From 47c193fd6b6946c1c8056088d82ff241b7bfcb06 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Thu, 26 Nov 2026 14:08:25 +0100 Subject: [PATCH 1/2] fix bookmarks limit, owner filter and data cleanups - detect bookmarks cookie writes dropped by the browser size limit and show it in the tooltip - match the whole owner name (case-insensitive) in the owner filter, fix "More packages" counter - keep case-sensitive versions in the code browser and unpkg proxy - don't show "no results" in QuickSearch while results are loading - use a fixed 30-day downloads period for npm-stat, matching npm `last-month` - count topics across all libraries when refreshing a single package - remove the unused cron refresh API route --- components/BookmarkButton.tsx | 13 +++- .../CommunitySection/MorePackagesSection.tsx | 2 +- components/QuickSearch.tsx | 2 +- context/BookmarksContext.test.ts | 58 ++++++++++++++ context/BookmarksContext.tsx | 19 ++++- pages/api/cron/refresh/index.ts | 77 ------------------- pages/api/proxy/unpkg.ts | 2 +- scenes/PackageCodeScene.tsx | 4 +- scripts/build-and-score-data.ts | 30 ++++---- scripts/fetch-npm-stat-data.ts | 17 ++-- util/search.ts | 13 +++- 11 files changed, 127 insertions(+), 110 deletions(-) create mode 100644 context/BookmarksContext.test.ts delete mode 100644 pages/api/cron/refresh/index.ts diff --git a/components/BookmarkButton.tsx b/components/BookmarkButton.tsx index 6b921cc72..a2eb9ac60 100644 --- a/components/BookmarkButton.tsx +++ b/components/BookmarkButton.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react'; import { type StyleProp, type ViewStyle } from 'react-native'; import { HoverEffect } from '~/common/styleguide'; @@ -14,10 +15,18 @@ type BookmarkButtonProps = { export default function BookmarkButton({ bookmarkId, style, iconStyle }: BookmarkButtonProps) { const { checkIsBookmarked, toggleBookmark } = useBookmarks(); + const [hasSaveFailed, setSaveFailed] = useState(false); const isBookmarked = checkIsBookmarked(bookmarkId); function handleToggleBookmark() { - toggleBookmark(bookmarkId); + setSaveFailed(!toggleBookmark(bookmarkId)); + } + + function getTooltipContent() { + if (hasSaveFailed) { + return 'Bookmarks limit reached, remove some bookmarks to add more'; + } + return isBookmarked ? 'Remove from bookmarks' : 'Add to bookmarks'; } return ( @@ -35,7 +44,7 @@ export default function BookmarkButton({ bookmarkId, style, iconStyle }: Bookmar )} }> - {isBookmarked ? 'Remove from bookmarks' : 'Add to bookmarks'} + {getTooltipContent()} ); } diff --git a/components/Package/CommunitySection/MorePackagesSection.tsx b/components/Package/CommunitySection/MorePackagesSection.tsx index 0f02947aa..541e286a9 100644 --- a/components/Package/CommunitySection/MorePackagesSection.tsx +++ b/components/Package/CommunitySection/MorePackagesSection.tsx @@ -51,7 +51,7 @@ export default function MorePackagesSection({ library }: Props) { More packages from {startCase(owner)} {!isLoading && data?.total && data.total > 0 ? ( - LIMIT ? data.total : data.total - 1} /> + ) : null} {!isSmallScreen && data?.total && data.total > LIMIT && ( diff --git a/components/QuickSearch.tsx b/components/QuickSearch.tsx index 188382937..54fbc8489 100644 --- a/components/QuickSearch.tsx +++ b/components/QuickSearch.tsx @@ -250,7 +250,7 @@ export default function QuickSearch({ focusOnMount = false, style }: Props) { )} - {!hasResults && ( + {!hasResults && !isLoading && data && ( There are no results for "{search}" query. diff --git a/context/BookmarksContext.test.ts b/context/BookmarksContext.test.ts new file mode 100644 index 000000000..db794818c --- /dev/null +++ b/context/BookmarksContext.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; + +import { getBookmarksFromCookie, saveBookmarksToCookie } from '~/context/BookmarksContext'; + +// Browsers ignore cookies with name and value longer than 4096 bytes +const COOKIE_SIZE_LIMIT = 4096; + +function installCookieJar() { + const jar = new Map(); + + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { + get cookie() { + return [...jar].map(([name, value]) => `${name}=${value}`).join('; '); + }, + set cookie(cookie: string) { + const [pair] = cookie.split(';'); + const separatorIndex = pair.indexOf('='); + + if (pair.length > COOKIE_SIZE_LIMIT) { + return; + } + + jar.set(pair.slice(0, separatorIndex), pair.slice(separatorIndex + 1)); + }, + }, + }); +} + +function createPackageNames(count: number) { + return new Set( + Array.from({ length: count }, (_, index) => `@some-scope/react-native-package-${index}`) + ); +} + +describe('saveBookmarksToCookie', () => { + beforeEach(installCookieJar); + + afterEach(() => { + Reflect.deleteProperty(globalThis, 'document'); + }); + + test('saves bookmarks which fit in the cookie', () => { + const bookmarks = createPackageNames(10); + + expect(saveBookmarksToCookie(bookmarks)).toBe(true); + expect(getBookmarksFromCookie()).toEqual([...bookmarks]); + }); + + test('reports a failed save and keeps previous bookmarks when cookie is too large', () => { + const bookmarks = createPackageNames(10); + saveBookmarksToCookie(bookmarks); + + expect(saveBookmarksToCookie(createPackageNames(200))).toBe(false); + expect(getBookmarksFromCookie()).toEqual([...bookmarks]); + }); +}); diff --git a/context/BookmarksContext.tsx b/context/BookmarksContext.tsx index 4ce09a367..a029e7d74 100644 --- a/context/BookmarksContext.tsx +++ b/context/BookmarksContext.tsx @@ -8,7 +8,8 @@ const COOKIE_MAX_AGE = TimeRange.YEAR; type BookmarksContextType = { bookmarkedIds: Set; checkIsBookmarked: (id: string) => boolean; - toggleBookmark: (id: string) => void; + /** Returns `false` when the change could not be saved, e.g. bookmarks cookie size limit was hit. */ + toggleBookmark: (id: string) => boolean; isLoading: boolean; }; @@ -29,6 +30,16 @@ function setCookie(name: string, value: string, maxAge: number) { document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`; } +/** + * Save bookmarks to the cookie and check that the browser has stored it. Browsers silently + * ignore cookies over the size limit (about 4 KB), which is reached with around 120 bookmarks. + */ +export function saveBookmarksToCookie(ids: Set): boolean { + const serializedIds = JSON.stringify([...ids]); + setCookie(BOOKMARK_COOKIE_NAME, serializedIds, COOKIE_MAX_AGE); + return getCookie(BOOKMARK_COOKIE_NAME) === serializedIds; +} + export function getBookmarksFromCookie(cookieString?: string): string[] { if (typeof cookieString === 'string') { const match = cookieString.match(new RegExp(`(^| )${BOOKMARK_COOKIE_NAME}=([^;]+)`)); @@ -70,8 +81,12 @@ export function BookmarksProvider({ children }: PropsWithChildren) { newSet.add(id); } - setCookie(BOOKMARK_COOKIE_NAME, JSON.stringify([...newSet]), COOKIE_MAX_AGE); + if (!saveBookmarksToCookie(newSet)) { + return false; + } + setBookmarkedIds(newSet); + return true; }, isLoading, }; diff --git a/pages/api/cron/refresh/index.ts b/pages/api/cron/refresh/index.ts deleted file mode 100644 index 6d3869b9f..000000000 --- a/pages/api/cron/refresh/index.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { NextResponse } from 'next/server'; - -import { buildAndScoreData } from '~/scripts/build-and-score-data'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -export async function GET(request: Request) { - if (!isAuthorized(request)) { - return NextResponse.json( - { - ok: false, - error: - process.env.CRON_SECRET == null - ? 'CRON_SECRET is not configured.' - : 'Unauthorized cron request.', - }, - { status: process.env.CRON_SECRET == null ? 500 : 401 } - ); - } - - if (!process.env.BLOB_READ_WRITE_TOKEN) { - return NextResponse.json( - { - ok: false, - error: 'BLOB_READ_WRITE_TOKEN is not configured.', - }, - { status: 500 } - ); - } - - try { - await buildAndScoreData(); - - let deployTriggered = false; - - if (process.env.VERCEL_DEPLOY_HOOK_URL) { - const deployResponse = await fetch(process.env.VERCEL_DEPLOY_HOOK_URL, { method: 'POST' }); - - if (!deployResponse.ok) { - console.error( - '[cron] failed to trigger deploy hook', - deployResponse.status, - deployResponse.statusText - ); - } else { - deployTriggered = true; - console.log('[cron] deploy hook triggered successfully'); - } - } - - return NextResponse.json({ - ok: true, - deployTriggered, - }); - } catch (error) { - console.error('[cron] refresh failed', error); - - return NextResponse.json( - { - ok: false, - error: error instanceof Error ? error.message : 'Unknown cron failure.', - }, - { status: 500 } - ); - } -} - -function isAuthorized(request: Request): boolean { - const cronSecret = process.env.CRON_SECRET; - - if (!cronSecret) { - return process.env.VERCEL !== '1'; - } - - return request.headers.get('authorization') === `Bearer ${cronSecret}`; -} diff --git a/pages/api/proxy/unpkg.ts b/pages/api/proxy/unpkg.ts index ec22beebf..2d41a8350 100644 --- a/pages/api/proxy/unpkg.ts +++ b/pages/api/proxy/unpkg.ts @@ -9,7 +9,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const { name, version, path } = parseQueryParams(req.query); const packageName = name ? name.toString().toLowerCase().trim() : undefined; - const packageVersion = version ? version.toString().toLowerCase().trim() : 'latest'; + const packageVersion = version ? version.toString().trim() : 'latest'; const apiPath = path ? path.toString().trim() : undefined; if (!packageName || !apiPath) { diff --git a/scenes/PackageCodeScene.tsx b/scenes/PackageCodeScene.tsx index 41f4bddc9..cfbf9208d 100644 --- a/scenes/PackageCodeScene.tsx +++ b/scenes/PackageCodeScene.tsx @@ -34,8 +34,8 @@ export default function PackageCodeScene({ apiData, packageName }: PackageCodePa const { isSmallScreen } = useLayout(); const activeFileStorageKey = `${ACTIVE_FILE_STORAGE_KEY_PREFIX}:${packageName}`; - const selectedVersionParam = - parseQueryParams(router.query).selectedVersion?.toLowerCase() ?? 'latest'; + // Versions are case-sensitive, e.g. `1.1.2-TEST.1`, so the param can't be lowercased + const selectedVersionParam = parseQueryParams(router.query).selectedVersion ?? 'latest'; const compareVersion = parseQueryParams(router.query).compareVersion; const selectedVersion = selectedVersionParam; diff --git a/scripts/build-and-score-data.ts b/scripts/build-and-score-data.ts index 96d0f9b4d..73dece554 100644 --- a/scripts/build-and-score-data.ts +++ b/scripts/build-and-score-data.ts @@ -271,20 +271,22 @@ export async function buildAndScoreData() { const hasEntry = libraries.some(lib => lib.npmPkg === wantedPackageName); const newDataEntry = data.find(entry => entry.npmPkg === wantedPackageName); - const content = hasEntry - ? { - libraries: libraries.map(library => { - if (newDataEntry && library.npmPkg === wantedPackageName) { - return newDataEntry; - } - return library; - }), - topics: sortTopics(topicCounts), - } - : { - libraries: newDataEntry ? [...libraries, newDataEntry] : libraries, - topics: sortTopics(topicCounts), - }; + const updatedLibraries = hasEntry + ? libraries.map(library => { + if (newDataEntry && library.npmPkg === wantedPackageName) { + return newDataEntry; + } + return library; + }) + : newDataEntry + ? [...libraries, newDataEntry] + : libraries; + + // Count topics across all libraries, not only the single refreshed package + const content = { + libraries: updatedLibraries, + topics: sortTopics(getTopicCounts(updatedLibraries)), + }; finalLibraries = content.libraries; fileContent = JSON.stringify(content, null, 2); diff --git a/scripts/fetch-npm-stat-data.ts b/scripts/fetch-npm-stat-data.ts index d9be10ef9..c76c3c9ae 100644 --- a/scripts/fetch-npm-stat-data.ts +++ b/scripts/fetch-npm-stat-data.ts @@ -7,6 +7,8 @@ import { REQUEST_SLEEP, sleep } from './helpers'; const ATTEMPTS_LIMIT = 2; const REQUEST_TIMEOUT = 5000; +const DAY_IN_MS = 864e5; +const DOWNLOADS_PERIOD_DAYS = 30; export async function fetchNpmStatDataBulk(namesArray: string[], attemptsCount = 0) { try { @@ -89,17 +91,14 @@ function formatDownloadData(downloadData: Record) { } function formattedDate(date: Date) { - const year = date.getFullYear(); - const month = String(date.getMonth() + 1).padStart(2, '0'); - const day = String(date.getDate()).padStart(2, '0'); - - return `${year}-${month}-${day}`; + return date.toISOString().slice(0, 10); } function urlForPackages(packagesList: string) { - const now = new Date(); - const fromDate = new Date(now); - fromDate.setMonth(fromDate.getMonth() - 1); + // Use a fixed period of full days, matching the npm downloads API `last-month` period, + // so the monthly downloads (and the Trending Score) don't depend on the current month length + const untilDate = new Date(Date.now() - DAY_IN_MS); + const fromDate = new Date(untilDate.getTime() - (DOWNLOADS_PERIOD_DAYS - 1) * DAY_IN_MS); - return `https://npm-stat.com/api/download-counts?package=${packagesList}&from=${formattedDate(fromDate)}&until=${formattedDate(now)}`; + return `https://npm-stat.com/api/download-counts?package=${packagesList}&from=${formattedDate(fromDate)}&until=${formattedDate(untilDate)}`; } diff --git a/util/search.ts b/util/search.ts index d008eabdb..166cffb26 100644 --- a/util/search.ts +++ b/util/search.ts @@ -105,6 +105,17 @@ function calculateMatchScore( } } +/** + * Match the whole owner name (so `expo` doesn't match `exponotify`), case-insensitively, + * against the owner from the entry GitHub URL and the current owner reported by GitHub. + */ +function isOwnedBy({ githubUrl, github }: LibraryType, owner: string) { + const ownerName = owner.toLowerCase(); + const libraryOwners = [githubUrl.split('/')[3], github.fullName?.split('/')[0]]; + + return libraryOwners.some(libraryOwner => libraryOwner?.toLowerCase() === ownerName); +} + export function handleFilterLibraries({ libraries, sortBy, @@ -255,7 +266,7 @@ export function handleFilterLibraries({ return false; } - if (owner && !library.githubUrl.startsWith(`https://github.com/${owner}`)) { + if (owner && !isOwnedBy(library, owner)) { return false; } From 8f35411d99efe2ecd4f6441d265f3be7d8e9b2e1 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Thu, 26 Nov 2026 15:21:55 +0100 Subject: [PATCH 2/2] address review: drop unrelated changes, use TimeRange --- .../CommunitySection/MorePackagesSection.tsx | 2 +- components/QuickSearch.tsx | 2 +- pages/api/cron/refresh/index.ts | 77 +++++++++++++++++++ pages/api/proxy/unpkg.ts | 2 +- scenes/PackageCodeScene.tsx | 4 +- scripts/fetch-npm-stat-data.ts | 10 +-- 6 files changed, 87 insertions(+), 10 deletions(-) create mode 100644 pages/api/cron/refresh/index.ts diff --git a/components/Package/CommunitySection/MorePackagesSection.tsx b/components/Package/CommunitySection/MorePackagesSection.tsx index 541e286a9..0f02947aa 100644 --- a/components/Package/CommunitySection/MorePackagesSection.tsx +++ b/components/Package/CommunitySection/MorePackagesSection.tsx @@ -51,7 +51,7 @@ export default function MorePackagesSection({ library }: Props) { More packages from {startCase(owner)} {!isLoading && data?.total && data.total > 0 ? ( - + LIMIT ? data.total : data.total - 1} /> ) : null} {!isSmallScreen && data?.total && data.total > LIMIT && ( diff --git a/components/QuickSearch.tsx b/components/QuickSearch.tsx index 54fbc8489..188382937 100644 --- a/components/QuickSearch.tsx +++ b/components/QuickSearch.tsx @@ -250,7 +250,7 @@ export default function QuickSearch({ focusOnMount = false, style }: Props) { )} - {!hasResults && !isLoading && data && ( + {!hasResults && ( There are no results for "{search}" query. diff --git a/pages/api/cron/refresh/index.ts b/pages/api/cron/refresh/index.ts new file mode 100644 index 000000000..6d3869b9f --- /dev/null +++ b/pages/api/cron/refresh/index.ts @@ -0,0 +1,77 @@ +import { NextResponse } from 'next/server'; + +import { buildAndScoreData } from '~/scripts/build-and-score-data'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +export async function GET(request: Request) { + if (!isAuthorized(request)) { + return NextResponse.json( + { + ok: false, + error: + process.env.CRON_SECRET == null + ? 'CRON_SECRET is not configured.' + : 'Unauthorized cron request.', + }, + { status: process.env.CRON_SECRET == null ? 500 : 401 } + ); + } + + if (!process.env.BLOB_READ_WRITE_TOKEN) { + return NextResponse.json( + { + ok: false, + error: 'BLOB_READ_WRITE_TOKEN is not configured.', + }, + { status: 500 } + ); + } + + try { + await buildAndScoreData(); + + let deployTriggered = false; + + if (process.env.VERCEL_DEPLOY_HOOK_URL) { + const deployResponse = await fetch(process.env.VERCEL_DEPLOY_HOOK_URL, { method: 'POST' }); + + if (!deployResponse.ok) { + console.error( + '[cron] failed to trigger deploy hook', + deployResponse.status, + deployResponse.statusText + ); + } else { + deployTriggered = true; + console.log('[cron] deploy hook triggered successfully'); + } + } + + return NextResponse.json({ + ok: true, + deployTriggered, + }); + } catch (error) { + console.error('[cron] refresh failed', error); + + return NextResponse.json( + { + ok: false, + error: error instanceof Error ? error.message : 'Unknown cron failure.', + }, + { status: 500 } + ); + } +} + +function isAuthorized(request: Request): boolean { + const cronSecret = process.env.CRON_SECRET; + + if (!cronSecret) { + return process.env.VERCEL !== '1'; + } + + return request.headers.get('authorization') === `Bearer ${cronSecret}`; +} diff --git a/pages/api/proxy/unpkg.ts b/pages/api/proxy/unpkg.ts index 2d41a8350..ec22beebf 100644 --- a/pages/api/proxy/unpkg.ts +++ b/pages/api/proxy/unpkg.ts @@ -9,7 +9,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const { name, version, path } = parseQueryParams(req.query); const packageName = name ? name.toString().toLowerCase().trim() : undefined; - const packageVersion = version ? version.toString().trim() : 'latest'; + const packageVersion = version ? version.toString().toLowerCase().trim() : 'latest'; const apiPath = path ? path.toString().trim() : undefined; if (!packageName || !apiPath) { diff --git a/scenes/PackageCodeScene.tsx b/scenes/PackageCodeScene.tsx index cfbf9208d..41f4bddc9 100644 --- a/scenes/PackageCodeScene.tsx +++ b/scenes/PackageCodeScene.tsx @@ -34,8 +34,8 @@ export default function PackageCodeScene({ apiData, packageName }: PackageCodePa const { isSmallScreen } = useLayout(); const activeFileStorageKey = `${ACTIVE_FILE_STORAGE_KEY_PREFIX}:${packageName}`; - // Versions are case-sensitive, e.g. `1.1.2-TEST.1`, so the param can't be lowercased - const selectedVersionParam = parseQueryParams(router.query).selectedVersion ?? 'latest'; + const selectedVersionParam = + parseQueryParams(router.query).selectedVersion?.toLowerCase() ?? 'latest'; const compareVersion = parseQueryParams(router.query).compareVersion; const selectedVersion = selectedVersionParam; diff --git a/scripts/fetch-npm-stat-data.ts b/scripts/fetch-npm-stat-data.ts index c76c3c9ae..42500364f 100644 --- a/scripts/fetch-npm-stat-data.ts +++ b/scripts/fetch-npm-stat-data.ts @@ -2,13 +2,12 @@ import { fetch } from 'bun'; import { sum } from 'es-toolkit/math'; import { fallbackFetchNpmDownloadData } from '~/scripts/fetch-npm-download-data'; +import { TimeRange } from '~/util/datetime'; import { REQUEST_SLEEP, sleep } from './helpers'; const ATTEMPTS_LIMIT = 2; const REQUEST_TIMEOUT = 5000; -const DAY_IN_MS = 864e5; -const DOWNLOADS_PERIOD_DAYS = 30; export async function fetchNpmStatDataBulk(namesArray: string[], attemptsCount = 0) { try { @@ -95,10 +94,11 @@ function formattedDate(date: Date) { } function urlForPackages(packagesList: string) { - // Use a fixed period of full days, matching the npm downloads API `last-month` period, + // Use 30 full days ending yesterday, the same period as the npm downloads API `last-month`, // so the monthly downloads (and the Trending Score) don't depend on the current month length - const untilDate = new Date(Date.now() - DAY_IN_MS); - const fromDate = new Date(untilDate.getTime() - (DOWNLOADS_PERIOD_DAYS - 1) * DAY_IN_MS); + const now = Date.now(); + const fromDate = new Date(now - TimeRange.MONTH * 1000); + const untilDate = new Date(now - TimeRange.DAY * 1000); return `https://npm-stat.com/api/download-counts?package=${packagesList}&from=${formattedDate(fromDate)}&until=${formattedDate(untilDate)}`; }