From e8ccb3a1a234c52565b5fb7686ff8d63bbae3829 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:46:17 +0000 Subject: [PATCH 01/16] fix: pass query to cached api routes that read it --- nuxt.config.ts | 30 ++++++ test/unit/config/route-rules.spec.ts | 133 +++++++++++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 test/unit/config/route-rules.spec.ts diff --git a/nuxt.config.ts b/nuxt.config.ts index a7688720aa..6fe283f870 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -147,6 +147,32 @@ export default defineNuxtConfig({ '/api/registry/provenance/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, '/api/registry/files/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, '/api/registry/package-meta/**': { isr: 300 }, + '/api/registry/install-size/**': { + isr: { + expiration: 300, + passQuery: true, + allowQuery: ['frozen-history'], + }, + }, + '/api/registry/license-change/**': { + isr: { + expiration: 300, + passQuery: true, + allowQuery: ['version'], + }, + }, + '/api/registry/compare-file/**': { + isr: { + expiration: 300, + passQuery: true, + allowQuery: [ + 'mergeModifiedLines', + 'maxChangeRatio', + 'maxDiffDistance', + 'inlineMaxCharEdits', + ], + }, + }, '/api/registry/packument/**': { isr: { expiration: 300, @@ -180,6 +206,10 @@ export default defineNuxtConfig({ 'locale', 'accent', 'yLabel', + 'width', + 'height', + 'weeks', + 'months', ], }, }, diff --git a/test/unit/config/route-rules.spec.ts b/test/unit/config/route-rules.spec.ts new file mode 100644 index 0000000000..067f697770 --- /dev/null +++ b/test/unit/config/route-rules.spec.ts @@ -0,0 +1,133 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { join, relative } from 'node:path' +import { describe, expect, it, vi } from 'vite-plus/test' + +vi.stubGlobal('defineNuxtConfig', (config: T) => config) + +const { default: config } = await import('../../../nuxt.config') + +interface ISRRule { + expiration?: number | false + passQuery?: boolean + allowQuery?: string[] +} + +const routeRules = config.routeRules as Record +const rootDir = join(import.meta.dirname, '../../..') + +const QUERY_HANDLERS: Record = { + 'server/api/atproto/bluesky-author-profiles.get.ts': { + rule: '/api/atproto/bluesky-author-profiles', + query: ['authors'], + }, + 'server/api/atproto/bluesky-comments.get.ts': { + rule: '/api/atproto/bluesky-comments', + query: ['uri'], + }, + 'server/api/auth/atproto.get.ts': { rule: '/api/auth/**', query: [] }, + 'server/api/changelog/md/[provider]/[owner]/[repo]/[...path].get.ts': { + rule: '/api/changelog/md/**', + query: ['host', 'raw'], + }, + 'server/api/changelog/releases/[provider]/[owner]/[repo].get.ts': { + rule: '/api/changelog/releases/**', + query: ['host'], + }, + 'server/api/changelog/releases/[provider]/[owner]/[repo]/raw/[tag].get.ts': { + rule: '/api/changelog/releases/**', + query: ['host'], + }, + 'server/api/embed/downloads.svg.get.ts': { + rule: '/api/embed/downloads.svg', + query: [ + 'packages', + 'package', + 'metric', + 'startDate', + 'start', + 'endDate', + 'end', + 'mode', + 'granularity', + 'locale', + 'accent', + 'yLabel', + 'width', + 'height', + 'weeks', + 'months', + ], + }, + 'server/api/opensearch/suggestions.get.ts': { rule: '/api/opensearch/suggestions', query: ['q'] }, + 'server/api/registry/badge/[type]/[...pkg].get.ts': { + rule: '/api/registry/badge/**', + query: ['color', 'labelColor', 'label', 'name', 'style', 'value'], + }, + 'server/api/registry/compare-file/[...pkg].get.ts': { + rule: '/api/registry/compare-file/**', + query: ['mergeModifiedLines', 'maxChangeRatio', 'maxDiffDistance', 'inlineMaxCharEdits'], + }, + 'server/api/registry/downloads/[...slug].get.ts': { + rule: '/api/registry/downloads/**', + query: ['mode', 'filterOldVersions', 'filterThreshold', 'packages'], + }, + 'server/api/registry/image-proxy/index.get.ts': { + rule: '/api/registry/image-proxy', + query: ['url', 'sig'], + }, + 'server/api/registry/install-size/[...pkg].get.ts': { + rule: '/api/registry/install-size/**', + query: ['frozen-history'], + }, + 'server/api/registry/license-change/[...pkg].get.ts': { + rule: '/api/registry/license-change/**', + query: ['version'], + }, + 'server/api/registry/packument/[...pkg].get.ts': { + rule: '/api/registry/packument/**', + query: ['version'], + }, + 'server/api/registry/timeline/[...pkg].get.ts': { + rule: '/api/registry/timeline/**', + query: ['offset', 'limit', 'sort', 'stable-only', 'around'], + }, + 'server/api/registry/timeline/sizes/[...pkg].get.ts': { + rule: '/api/registry/timeline/**', + query: ['offset', 'limit', 'sort', 'stable-only', 'frozen-history'], + }, + 'server/api/social/profile/[identifier]/likes.get.ts': { rule: '/api/social/**', query: [] }, +} + +const queryByRule: Record> = {} +for (const { rule, query } of Object.values(QUERY_HANDLERS)) { + queryByRule[rule] = new Set([...(queryByRule[rule] ?? []), ...query]) +} + +function listFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => + entry.isDirectory() ? listFiles(join(dir, entry.name)) : [join(dir, entry.name)], + ) +} + +describe('route rules', () => { + it('lists every server handler that reads the query string', () => { + const handlers = ['server/api', 'server/routes'] + .flatMap(dir => listFiles(join(rootDir, dir))) + .filter(file => readFileSync(file, 'utf-8').includes('getQuery(')) + .map(file => relative(rootDir, file).replaceAll('\\', '/')) + .sort() + + expect(handlers).toEqual(Object.keys(QUERY_HANDLERS).sort()) + }) + + it.each(Object.entries(queryByRule))( + 'caches %s by exactly the query params its handlers read', + (rule, query) => { + const isr = routeRules[rule]?.isr + if (isr === false) return + + expect(isr).toMatchObject({ passQuery: true }) + expect([...(isr as ISRRule).allowQuery!].sort()).toEqual([...query].sort()) + }, + ) +}) From 512e27508514083c8b1ccf382948a317734a1f5c Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:47:38 +0000 Subject: [PATCH 02/16] perf: ignore unread query params in isr cache keys --- nuxt.config.ts | 36 ++++++++++++++++++---------- test/unit/config/route-rules.spec.ts | 14 +++++++++++ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/nuxt.config.ts b/nuxt.config.ts index 6fe283f870..a50a478294 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -99,7 +99,7 @@ export default defineNuxtConfig({ routeRules: { // API routes - '/api/**': { isr: 300 }, + '/api/**': { isr: { expiration: 300, allowQuery: [] } }, '/api/registry/badge/**': { isr: { expiration: 60 * 60 /* one hour */, @@ -143,10 +143,19 @@ export default defineNuxtConfig({ }, }, '/api/registry/docs/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, - '/api/registry/file/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, - '/api/registry/provenance/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, - '/api/registry/files/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, - '/api/registry/package-meta/**': { isr: 300 }, + '/api/registry/file/**': { + isr: { expiration: false, allowQuery: [] }, + cache: { maxAge: 365 * 24 * 60 * 60 }, + }, + '/api/registry/provenance/**': { + isr: { expiration: false, allowQuery: [] }, + cache: { maxAge: 365 * 24 * 60 * 60 }, + }, + '/api/registry/files/**': { + isr: { expiration: false, allowQuery: [] }, + cache: { maxAge: 365 * 24 * 60 * 60 }, + }, + '/api/registry/package-meta/**': { isr: { expiration: 300, allowQuery: [] } }, '/api/registry/install-size/**': { isr: { expiration: 300, @@ -181,14 +190,17 @@ export default defineNuxtConfig({ allowQuery: ['version'], }, }, - '/:pkg/.well-known/skills/**': { isr: 3600 }, - '/:scope/:pkg/.well-known/skills/**': { isr: 3600 }, - '/_avatar/**': { isr: 3600, proxy: 'https://www.gravatar.com/avatar/**' }, - '/opensearch.xml': { isr: true }, + '/:pkg/.well-known/skills/**': { isr: { expiration: 3600, allowQuery: [] } }, + '/:scope/:pkg/.well-known/skills/**': { isr: { expiration: 3600, allowQuery: [] } }, + '/_avatar/**': { + isr: { expiration: 3600, allowQuery: [] }, + proxy: 'https://www.gravatar.com/avatar/**', + }, + '/opensearch.xml': { isr: { expiration: false, allowQuery: [] } }, '/oauth-client-metadata.json': { prerender: true }, '/.well-known/jwks.json': { prerender: true }, '/.well-known/site.standard.publication': { prerender: true }, - '/api/leaderboard/likes': { isr: 900 }, + '/api/leaderboard/likes': { isr: { expiration: 900, allowQuery: [] } }, '/api/embed/downloads.svg': { isr: { expiration: 60 * 60 /* one hour */, @@ -240,7 +252,7 @@ export default defineNuxtConfig({ }, }, // pages - '/leaderboard/likes': getISRConfig(900), + '/leaderboard/likes': getISRConfig(900, { allowQuery: [] }), '/package/**': getISRConfig(300, { fallback: 'html', passQuery: true, @@ -268,7 +280,7 @@ export default defineNuxtConfig({ '/settings': { prerender: true }, '/translation-status': { prerender: true }, '/recharging': { prerender: true }, - '/pds': { isr: 86400 }, // revalidate daily + '/pds': { isr: { expiration: 86400, allowQuery: [] } }, // revalidate daily '/blog/**': { prerender: true }, '/blog/rss.xml': { prerender: true, diff --git a/test/unit/config/route-rules.spec.ts b/test/unit/config/route-rules.spec.ts index 067f697770..77a8f2e230 100644 --- a/test/unit/config/route-rules.spec.ts +++ b/test/unit/config/route-rules.spec.ts @@ -103,6 +103,8 @@ for (const { rule, query } of Object.values(QUERY_HANDLERS)) { queryByRule[rule] = new Set([...(queryByRule[rule] ?? []), ...query]) } +const UNCHECKED_ISR_ROUTES = new Set(['/api/registry/docs/**']) + function listFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? listFiles(join(dir, entry.name)) : [join(dir, entry.name)], @@ -120,6 +122,18 @@ describe('route rules', () => { expect(handlers).toEqual(Object.keys(QUERY_HANDLERS).sort()) }) + it('limits the isr cache key of every cached route to the query params it reads', () => { + const unbounded = Object.entries(routeRules) + .filter( + ([route, { isr }]) => + isr !== undefined && isr !== false && !UNCHECKED_ISR_ROUTES.has(route), + ) + .filter(([, { isr }]) => typeof isr !== 'object' || !Array.isArray(isr.allowQuery)) + .map(([route]) => route) + + expect(unbounded).toEqual([]) + }) + it.each(Object.entries(queryByRule))( 'caches %s by exactly the query params its handlers read', (rule, query) => { From f005a42cf9b29a23bdbb1eabf07137fc64989642 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:48:23 +0000 Subject: [PATCH 03/16] perf: revalidate cached api routes in step with their data --- nuxt.config.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/nuxt.config.ts b/nuxt.config.ts index a50a478294..2267250cfc 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -158,21 +158,38 @@ export default defineNuxtConfig({ '/api/registry/package-meta/**': { isr: { expiration: 300, allowQuery: [] } }, '/api/registry/install-size/**': { isr: { - expiration: 300, + expiration: 60 * 60 /* one hour */, passQuery: true, allowQuery: ['frozen-history'], }, }, '/api/registry/license-change/**': { isr: { - expiration: 300, + expiration: 60 * 60 /* one hour */, passQuery: true, allowQuery: ['version'], }, }, + '/api/registry/analysis/**': getISRConfig(60 * 60 * 24 /* one day */, { allowQuery: [] }), + '/api/registry/vulnerabilities/**': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/registry/readme/**': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/registry/org/**': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/registry/compare/**': { isr: { expiration: false, allowQuery: [] } }, + '/api/changelog/info/**': getISRConfig(60 * 60 * 2 /* 2 hours */, { allowQuery: [] }), + '/api/jsr/**': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/github/issues/**': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/github/contributors-evolution/**': getISRConfig(60 * 60 * 24 /* one day */, { + allowQuery: [], + }), + '/api/gravatar/**': getISRConfig(60 * 60 * 24 /* one day */, { allowQuery: [] }), + '/api/contributors': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/repo-stats': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/atproto/pds-graphs': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/atproto/pds-users': getISRConfig(60 * 60 /* one hour */, { allowQuery: [] }), + '/api/atproto/tangled-stats/**': getISRConfig(60 * 10 /* ten minutes */, { allowQuery: [] }), '/api/registry/compare-file/**': { isr: { - expiration: 300, + expiration: false, passQuery: true, allowQuery: [ 'mergeModifiedLines', From e339e2104534ab261cbd0b556b5ff61f0f68abfa Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:49:58 +0000 Subject: [PATCH 04/16] perf: cache uncached package subpages at the cdn --- nuxt.config.ts | 16 ++++++++++++++++ test/e2e/cache-control.spec.ts | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 test/e2e/cache-control.spec.ts diff --git a/nuxt.config.ts b/nuxt.config.ts index 2267250cfc..59f36f68fd 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -286,6 +286,22 @@ export default defineNuxtConfig({ fallback: 'json', allowQuery: [], }), + // cdn cache + '/package-timeline/**': { + headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' }, + }, + '/package-stats/**': { + headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' }, + }, + '/org/**': { + headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' }, + }, + '/compare': { + headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' }, + }, + '/diff/**': { + headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=604800' }, + }, // static pages '/': { prerender: true }, '/200.html': { prerender: true }, diff --git a/test/e2e/cache-control.spec.ts b/test/e2e/cache-control.spec.ts new file mode 100644 index 0000000000..731ed695d7 --- /dev/null +++ b/test/e2e/cache-control.spec.ts @@ -0,0 +1,24 @@ +import { expect, test } from './test-utils' + +test.describe('cache control', () => { + for (const path of [ + '/org/nuxt', + '/package-stats/nuxt/v/4.3.1', + '/package-timeline/nuxt/v/4.3.1', + '/compare?packages=nuxt,vue', + ]) { + test(`caches ${path} at the CDN`, async ({ page }) => { + const response = await page.request.get(path) + + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toMatch(/\bs-maxage=\d+/) + }) + } + + test('does not cache error responses at the CDN', async ({ page }) => { + const response = await page.request.get('/org/this-org-does-not-exist') + + expect(response.status()).toBe(404) + expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) + }) +}) From 252b925b990c6f1922e9a1850554886485117135 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:55:47 +0000 Subject: [PATCH 05/16] perf: cache versioned package pages at the cdn instead of isr --- modules/isr-fallback.ts | 4 ---- nuxt.config.ts | 20 ++++++++++++-------- test/e2e/cache-control.spec.ts | 19 ++++++++++++++----- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/modules/isr-fallback.ts b/modules/isr-fallback.ts index a37c9fe0a4..ab35cff26e 100644 --- a/modules/isr-fallback.ts +++ b/modules/isr-fallback.ts @@ -31,12 +31,8 @@ export default defineNuxtModule({ for (const path of [ 'package', 'package/[name]', - 'package/[name]/v', - 'package/[name]/v/[version]', 'package/[org]', 'package/[org]/[name]', - 'package/[org]/[name]/v', - 'package/[org]/[name]/v/[version]', '', ]) { const outputPath = resolve(nitro.options.output.serverDir, '..', path, htmlFallback) diff --git a/nuxt.config.ts b/nuxt.config.ts index 59f36f68fd..598eeb0059 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -277,15 +277,19 @@ export default defineNuxtConfig({ }), // payloads do not depend on the query, including the `_b` build id '/package/:name/_payload.json': getISRConfig(300, { fallback: 'json', allowQuery: [] }), - '/package/:name/v/:version/_payload.json': getISRConfig(300, { - fallback: 'json', - allowQuery: [], - }), '/package/:org/:name/_payload.json': getISRConfig(300, { fallback: 'json', allowQuery: [] }), - '/package/:org/:name/v/:version/_payload.json': getISRConfig(300, { - fallback: 'json', - allowQuery: [], - }), + // versioned package pages are cached at the cdn + '/package/:name/v/:version': { + isr: false, + headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=604800' }, + }, + '/package/:org/:name/v/:version': { + isr: false, + headers: { 'Cache-Control': 'public, s-maxage=86400, stale-while-revalidate=604800' }, + }, + // no payload is rendered for these, so requests get an uncached 404 + '/package/:name/v/:version/_payload.json': { isr: false }, + '/package/:org/:name/v/:version/_payload.json': { isr: false }, // cdn cache '/package-timeline/**': { headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' }, diff --git a/test/e2e/cache-control.spec.ts b/test/e2e/cache-control.spec.ts index 731ed695d7..748fac0893 100644 --- a/test/e2e/cache-control.spec.ts +++ b/test/e2e/cache-control.spec.ts @@ -6,6 +6,8 @@ test.describe('cache control', () => { '/package-stats/nuxt/v/4.3.1', '/package-timeline/nuxt/v/4.3.1', '/compare?packages=nuxt,vue', + '/package/nuxt/v/4.3.1', + '/package/@nuxt/kit/v/4.3.0', ]) { test(`caches ${path} at the CDN`, async ({ page }) => { const response = await page.request.get(path) @@ -15,10 +17,17 @@ test.describe('cache control', () => { }) } - test('does not cache error responses at the CDN', async ({ page }) => { - const response = await page.request.get('/org/this-org-does-not-exist') + for (const path of [ + '/org/this-org-does-not-exist', + '/package/this-package-does-not-exist/v/1.0.0', + '/package/nuxt/v/4.3.1/_payload.json', + '/package/@nuxt/kit/v/4.3.0/_payload.json', + ]) { + test(`does not cache the ${path} error at the CDN`, async ({ page }) => { + const response = await page.request.get(path) - expect(response.status()).toBe(404) - expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) - }) + expect(response.status()).toBe(404) + expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) + }) + } }) From 238a6b6cb9c228f6382175512f9420bef1ab49e3 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 14:57:13 +0000 Subject: [PATCH 06/16] perf: drop fetch timestamp from download distribution responses --- server/api/registry/downloads/[...slug].get.ts | 11 ++--------- shared/types/version-downloads.ts | 2 -- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/server/api/registry/downloads/[...slug].get.ts b/server/api/registry/downloads/[...slug].get.ts index e4e052f1d4..0f6f436a84 100644 --- a/server/api/registry/downloads/[...slug].get.ts +++ b/server/api/registry/downloads/[...slug].get.ts @@ -71,10 +71,7 @@ export default defineCachedEventHandler( const packageNames = normalizePackages(parsed.packages) if (packageNames.length === 0) { - return { - packages: [], - timestamp: new Date().toISOString(), - } + return { packages: [] } } try { @@ -85,10 +82,7 @@ export default defineCachedEventHandler( })), ) - return { - packages, - timestamp: new Date().toISOString(), - } + return { packages } } catch (error: unknown) { handleApiError(error, { statusCode: 502, @@ -152,7 +146,6 @@ export default defineCachedEventHandler( mode, totalDownloads, groups, - timestamp: new Date().toISOString(), } if (filterOldVersionsBool) { diff --git a/shared/types/version-downloads.ts b/shared/types/version-downloads.ts index 203aed3d07..bec4f28691 100644 --- a/shared/types/version-downloads.ts +++ b/shared/types/version-downloads.ts @@ -53,8 +53,6 @@ export interface VersionDistributionResponse { totalDownloads: number /** Grouped version data */ groups: VersionGroupDownloads[] - /** ISO 8601 timestamp when data was fetched */ - timestamp: string /** List of version strings published within the last year (only present when filterOldVersions=true) */ recentVersions?: string[] } From a72a09e4fef554c0aeef3d4ac1fafd376ad15b53 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 15:28:54 +0000 Subject: [PATCH 07/16] fix: keep the fetch cache in instance memory on vercel --- modules/cache.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/modules/cache.ts b/modules/cache.ts index a2e7c3a410..3d781890bc 100644 --- a/modules/cache.ts +++ b/modules/cache.ts @@ -5,6 +5,8 @@ import { provider } from 'std-env' // Storage key for fetch cache - must match shared/utils/fetch-cache-config.ts const FETCH_CACHE_STORAGE_BASE = 'fetch-cache' +const MB = 1024 * 1024 + export default defineNuxtModule({ meta: { name: 'vercel-cache', @@ -37,6 +39,13 @@ export default defineNuxtModule({ ...nitroConfig.storage[FETCH_CACHE_STORAGE_BASE], driver: 'vercel-runtime-cache', } + } else { + // function filesystems are read-only + nitroConfig.storage[FETCH_CACHE_STORAGE_BASE] = { + driver: 'lru-cache', + max: 5_000, + maxSize: 32 * MB, + } } const env = process.env.VERCEL_ENV From 6df5b042b6dbf6508ffd6e0a0b9936d9e47d3326 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Wed, 25 Nov 2026 17:35:49 +0000 Subject: [PATCH 08/16] test: expect default prefetch for versioned package links --- test/nuxt/components/LinkBase.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/nuxt/components/LinkBase.spec.ts b/test/nuxt/components/LinkBase.spec.ts index 6dc240a1e8..99e7f24d1d 100644 --- a/test/nuxt/components/LinkBase.spec.ts +++ b/test/nuxt/components/LinkBase.spec.ts @@ -10,10 +10,11 @@ async function getPrefetchOn(to: string) { describe('LinkBase', () => { it('prefetches cached payload routes on interaction only', async () => { expect(await getPrefetchOn('/package/vue')).toBe('interaction') - expect(await getPrefetchOn('/package/@vue/core/v/3.5.0')).toBe('interaction') + expect(await getPrefetchOn('/package/@vue/core')).toBe('interaction') }) it('keeps the default prefetch behaviour for other routes', async () => { + expect(await getPrefetchOn('/package/@vue/core/v/3.5.0')).toBeUndefined() expect(await getPrefetchOn('/org/vue')).toBeUndefined() expect(await getPrefetchOn('/about')).toBeUndefined() }) From 52a29419d35a01b98398e2aeb680db6d1ca1c808 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Thu, 26 Nov 2026 10:22:46 +0000 Subject: [PATCH 09/16] fix: diff compare-file requests with the change ratio their cache key uses --- .../api/registry/compare-file/[...pkg].get.ts | 32 +++++++++---------- shared/utils/diff.ts | 16 ++++++++++ test/unit/shared/utils/diff.spec.ts | 22 ++++++++++++- 3 files changed, 52 insertions(+), 18 deletions(-) diff --git a/server/api/registry/compare-file/[...pkg].get.ts b/server/api/registry/compare-file/[...pkg].get.ts index 5f5504e01d..59746b85a5 100644 --- a/server/api/registry/compare-file/[...pkg].get.ts +++ b/server/api/registry/compare-file/[...pkg].get.ts @@ -1,6 +1,12 @@ import * as v from 'valibot' import { PackageFileDiffQuerySchema } from '#shared/schemas/package' -import { countDiffStats, createDiff, insertSkipBlocks, truncateDiffHunks } from '#shared/utils/diff' +import { + countDiffStats, + createDiff, + insertSkipBlocks, + parseDiffOptionsQuery, + truncateDiffHunks, +} from '#shared/utils/diff' import type { DiffHunk, DiffSkipBlock } from '#shared/types/compare' const CACHE_VERSION = 3 @@ -170,14 +176,7 @@ export default defineCachedEventHandler( const timeoutId = setTimeout(() => controller.abort(), DIFF_TIMEOUT) try { - // Get diff options from query params - const query = getQuery(event) - const diffOptions = { - mergeModifiedLines: query.mergeModifiedLines !== 'false', - maxChangeRatio: parseFloat(query.maxChangeRatio as string) || 0.45, - maxDiffDistance: parseInt(query.maxDiffDistance as string, 10) || 30, - inlineMaxCharEdits: parseInt(query.inlineMaxCharEdits as string, 10) || 2, - } + const diffOptions = parseDiffOptionsQuery(getQuery(event)) // Fetch file contents in parallel const [fromContent, toContent] = await Promise.all([ @@ -328,14 +327,13 @@ export default defineCachedEventHandler( swr: true, getKey: event => { const pkg = getRouterParam(event, 'pkg') ?? '' - const query = getQuery(event) - // Normalize option values to prevent cache pollution from arbitrary floats. - // These match the parsing logic used in the handler body. - const merge = query.mergeModifiedLines !== 'false' - const ratio = Math.round((parseFloat(query.maxChangeRatio as string) || 0.45) * 100) - const distance = parseInt(query.maxDiffDistance as string, 10) || 30 - const charEdits = parseInt(query.inlineMaxCharEdits as string, 10) || 2 - const optionsKey = `${merge}:${ratio}:${distance}:${charEdits}` + const options = parseDiffOptionsQuery(getQuery(event)) + const optionsKey = [ + options.mergeModifiedLines, + Math.round(options.maxChangeRatio * 100), + options.maxDiffDistance, + options.inlineMaxCharEdits, + ].join(':') return `compare-file:v${CACHE_VERSION}:${pkg.replace(/\/+$/, '').trim()}:${optionsKey}` }, }, diff --git a/shared/utils/diff.ts b/shared/utils/diff.ts index d1bc288d2b..ca6fe40260 100644 --- a/shared/utils/diff.ts +++ b/shared/utils/diff.ts @@ -22,6 +22,22 @@ const defaultOptions: ParseOptions = { inlineMaxCharEdits: 2, } +/** + * Read diff options from a request query. The change ratio is rounded to whole percent so that + * every value that shares a cache key produces the same diff. + */ +export function parseDiffOptionsQuery(query: Record): ParseOptions { + const ratio = parseFloat(query.maxChangeRatio as string) || defaultOptions.maxChangeRatio + return { + mergeModifiedLines: query.mergeModifiedLines !== 'false', + maxChangeRatio: Math.round(ratio * 100) / 100, + maxDiffDistance: + parseInt(query.maxDiffDistance as string, 10) || defaultOptions.maxDiffDistance, + inlineMaxCharEdits: + parseInt(query.inlineMaxCharEdits as string, 10) || defaultOptions.inlineMaxCharEdits, + } +} + interface RawChange { type: 'insert' | 'delete' | 'normal' content: string diff --git a/test/unit/shared/utils/diff.spec.ts b/test/unit/shared/utils/diff.spec.ts index fb1d6afa5a..e48a501e03 100644 --- a/test/unit/shared/utils/diff.spec.ts +++ b/test/unit/shared/utils/diff.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test' -import { truncateDiffHunks } from '#shared/utils/diff' +import { createDiff, parseDiffOptionsQuery, truncateDiffHunks } from '#shared/utils/diff' import type { DiffHunk, DiffSkipBlock } from '#shared/types/compare' function createHunk(lineCount: number): DiffHunk { @@ -66,3 +66,23 @@ describe('truncateDiffHunks', () => { expect(result.hunks).toEqual([hunk]) }) }) + +describe('parseDiffOptionsQuery', () => { + it('diffs with the same options for every query that shares a rounded change ratio', () => { + const oldContent = `${'a'.repeat(125)}\n` + const newContent = `${'b'.repeat(113)}${'a'.repeat(12)}\n` + const render = (query: Record) => + createDiff(oldContent, newContent, 'file.txt', parseDiffOptionsQuery(query)) + + expect(render({ maxChangeRatio: '0.454' })).toEqual(render({})) + }) + + it('uses the defaults for missing or invalid values', () => { + expect(parseDiffOptionsQuery({ maxDiffDistance: 'x' })).toEqual({ + mergeModifiedLines: true, + maxChangeRatio: 0.45, + maxDiffDistance: 30, + inlineMaxCharEdits: 2, + }) + }) +}) From 8a8f04186954a479e6fac264f6510901e636c759 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sat, 28 Nov 2026 21:28:58 +0000 Subject: [PATCH 10/16] perf: cache package file responses at the cdn instead of isr --- nuxt.config.ts | 5 +- server/api/registry/file/[...pkg].get.ts | 236 +++++++++++------------ shared/utils/npm.ts | 10 + 3 files changed, 127 insertions(+), 124 deletions(-) diff --git a/nuxt.config.ts b/nuxt.config.ts index 598eeb0059..d7223251a2 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -143,10 +143,7 @@ export default defineNuxtConfig({ }, }, '/api/registry/docs/**': { isr: true, cache: { maxAge: 365 * 24 * 60 * 60 } }, - '/api/registry/file/**': { - isr: { expiration: false, allowQuery: [] }, - cache: { maxAge: 365 * 24 * 60 * 60 }, - }, + '/api/registry/file/**': { isr: false }, '/api/registry/provenance/**': { isr: { expiration: false, allowQuery: [] }, cache: { maxAge: 365 * 24 * 60 * 60 }, diff --git a/server/api/registry/file/[...pkg].get.ts b/server/api/registry/file/[...pkg].get.ts index 2a717331b1..672beaf70f 100644 --- a/server/api/registry/file/[...pkg].get.ts +++ b/server/api/registry/file/[...pkg].get.ts @@ -3,12 +3,12 @@ import type { InternalImportsMap, PackageExportsMap } from '#server/utils/import import { publishedRevision } from '#server/utils/readme-loaders' import { PackageFileQuerySchema } from '#shared/schemas/package' import type { ReadmeResponse } from '#shared/types/readme' -import { - CACHE_MAX_AGE_ONE_YEAR, - ERROR_PACKAGE_VERSION_AND_FILE_FAILED, -} from '#shared/utils/constants' +import { ERROR_PACKAGE_VERSION_AND_FILE_FAILED } from '#shared/utils/constants' +import { isExactVersion } from '#shared/utils/npm' -const CACHE_VERSION = 3 +const CACHE_CONTROL_IMMUTABLE = + 'public, max-age=0, s-maxage=31536000, stale-while-revalidate=31536000' +const CACHE_CONTROL_MUTABLE_VERSION = 'public, max-age=0, s-maxage=300' // Maximum file size to fetch and highlight (500KB) const MAX_FILE_SIZE = 500 * 1024 @@ -99,129 +99,125 @@ async function fetchFileContent( * - /api/registry/file/packageName/v/1.2.3/path/to/file.ts * - /api/registry/file/@scope/packageName/v/1.2.3/path/to/file.ts */ -export default defineCachedEventHandler( - async event => { - // Parse: [pkg, 'v', version, ...filePath] or [@scope, pkg, 'v', version, ...filePath] - const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? [] - - const { rawPackageName, rawVersion: fullPathAfterV } = parsePackageParams(pkgParamSegments) - - // Since version AND path route are required, we split the remainder - // fullPathAfterV => "1.2.3/dist/index.mjs" - const versionSegments = fullPathAfterV?.split('/') ?? [] - - if (versionSegments.length < 2) { - throw createError({ - // TODO: throwing 404 rather than 400 as it's cacheable - statusCode: 404, - message: ERROR_PACKAGE_VERSION_AND_FILE_FAILED, - }) - } +export default defineEventHandler(async event => { + // Parse: [pkg, 'v', version, ...filePath] or [@scope, pkg, 'v', version, ...filePath] + const pkgParamSegments = getRouterParam(event, 'pkg')?.split('/') ?? [] - // The version is the first segment after 'v', and everything else is the file path - const rawVersion = versionSegments[0] - const rawFilePath = versionSegments.slice(1).join('/') - - try { - const { packageName, version, filePath } = v.parse(PackageFileQuerySchema, { - packageName: rawPackageName, - version: rawVersion, - filePath: rawFilePath, - }) - - const { content, contentType } = await fetchFileContent(packageName, version, filePath) - const language = getLanguageFromPath(filePath) - - // For JS/TS files, resolve dependency versions and relative imports for linking - let dependencies: Record | undefined - let resolveRelative: ((specifier: string) => string | null) | undefined - - if (IMPORT_LANGUAGES.has(language)) { - // Fetch package.json and file tree in parallel - const [pkgJson, fileTreeResponse] = await Promise.all([ - fetchPackageJson(packageName, version), - getPackageFileTree(packageName, version).catch(() => null), - ]) - - // Resolve npm dependency versions - if (pkgJson) { - // Merge all dependency types - const allDeps: Record = { - ...pkgJson.dependencies, - ...pkgJson.peerDependencies, - ...pkgJson.optionalDependencies, - // Note: excluding devDependencies as they're less likely to be imported in dist files - } + const { rawPackageName, rawVersion: fullPathAfterV } = parsePackageParams(pkgParamSegments) - if (Object.keys(allDeps).length > 0) { - const resolved: Record = await resolveDependencyVersions(allDeps) - dependencies = {} - for (const [name, ver] of Object.entries(resolved)) { - dependencies[name] = { version: ver } - } - } + // Since version AND path route are required, we split the remainder + // fullPathAfterV => "1.2.3/dist/index.mjs" + const versionSegments = fullPathAfterV?.split('/') ?? [] + + if (versionSegments.length < 2) { + throw createError({ + // TODO: throwing 404 rather than 400 as it's cacheable + statusCode: 404, + message: ERROR_PACKAGE_VERSION_AND_FILE_FAILED, + }) + } + + // The version is the first segment after 'v', and everything else is the file path + const rawVersion = versionSegments[0] + const rawFilePath = versionSegments.slice(1).join('/') + + try { + const { packageName, version, filePath } = v.parse(PackageFileQuerySchema, { + packageName: rawPackageName, + version: rawVersion, + filePath: rawFilePath, + }) + + const { content, contentType } = await fetchFileContent(packageName, version, filePath) + const language = getLanguageFromPath(filePath) + + // For JS/TS files, resolve dependency versions and relative imports for linking + let dependencies: Record | undefined + let resolveRelative: ((specifier: string) => string | null) | undefined + + if (IMPORT_LANGUAGES.has(language)) { + // Fetch package.json and file tree in parallel + const [pkgJson, fileTreeResponse] = await Promise.all([ + fetchPackageJson(packageName, version), + getPackageFileTree(packageName, version).catch(() => null), + ]) + + // Resolve npm dependency versions + if (pkgJson) { + // Merge all dependency types + const allDeps: Record = { + ...pkgJson.dependencies, + ...pkgJson.peerDependencies, + ...pkgJson.optionalDependencies, + // Note: excluding devDependencies as they're less likely to be imported in dist files } - // Create resolver for relative imports - if (fileTreeResponse) { - const files = flattenFileTree(fileTreeResponse.tree) - resolveRelative = createImportResolver( - files, - filePath, - packageName, - version, - pkgJson?.imports, - pkgJson?.exports, - ) + if (Object.keys(allDeps).length > 0) { + const resolved: Record = await resolveDependencyVersions(allDeps) + dependencies = {} + for (const [name, ver] of Object.entries(resolved)) { + dependencies[name] = { version: ver } + } } } - const html = await highlightCode(content, language, { - dependencies, - resolveRelative, - }) - - let markdownHtml: ReadmeResponse | undefined - if (language === 'markdown') { - // Best-effort: markdown preview is optional; never block code view - try { - const packageData = await fetchNpmPackage(rawPackageName) - const repoInfo = parseRepositoryInfo(packageData.repository) - markdownHtml = await renderReadmeHtml( - content, - rawPackageName, - repoInfo, - publishedRevision(packageData, version), - ) - } catch { - markdownHtml = undefined - } + // Create resolver for relative imports + if (fileTreeResponse) { + const files = flattenFileTree(fileTreeResponse.tree) + resolveRelative = createImportResolver( + files, + filePath, + packageName, + version, + pkgJson?.imports, + pkgJson?.exports, + ) } + } + + const html = await highlightCode(content, language, { + dependencies, + resolveRelative, + }) - return { - package: packageName, - version, - path: filePath, - language, - contentType, - content, - html, - lines: content.split('\n').length, - markdownHtml, + let markdownHtml: ReadmeResponse | undefined + if (language === 'markdown') { + // Best-effort: markdown preview is optional; never block code view + try { + const packageData = await fetchNpmPackage(rawPackageName) + const repoInfo = parseRepositoryInfo(packageData.repository) + markdownHtml = await renderReadmeHtml( + content, + rawPackageName, + repoInfo, + publishedRevision(packageData, version), + ) + } catch { + markdownHtml = undefined } - } catch (error: unknown) { - handleApiError(error, { - statusCode: 502, - message: 'Failed to fetch file content', - }) } - }, - { - // File content for a specific version never changes - cache permanently - maxAge: CACHE_MAX_AGE_ONE_YEAR, // 1 year - getKey: event => { - const pkg = getRouterParam(event, 'pkg') ?? '' - return `file:v${CACHE_VERSION}:${pkg.replace(/\/+$/, '').trim()}` - }, - }, -) + + setHeader( + event, + 'Cache-Control', + isExactVersion(version) ? CACHE_CONTROL_IMMUTABLE : CACHE_CONTROL_MUTABLE_VERSION, + ) + + return { + package: packageName, + version, + path: filePath, + language, + contentType, + content, + html, + lines: content.split('\n').length, + markdownHtml, + } + } catch (error: unknown) { + handleApiError(error, { + statusCode: 502, + message: 'Failed to fetch file content', + }) + } +}) diff --git a/shared/utils/npm.ts b/shared/utils/npm.ts index f71de75a10..8f8d7e900e 100644 --- a/shared/utils/npm.ts +++ b/shared/utils/npm.ts @@ -47,6 +47,16 @@ export function assertValidPackageName(name: string): void { } } +const EXACT_VERSION_RE = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/ + +/** + * Whether the version names one published release, rather than a dist-tag (`latest`) or a + * partial version (`1`, `1.2`), which resolve to whatever is tagged today. + */ +export function isExactVersion(version: string): boolean { + return EXACT_VERSION_RE.test(version) +} + /** Parsed result of an npm dependency version value */ export interface ParsedDependencyVersion { /** The real package name (different from the dependency key only for aliases) */ From f69a21ac78daf9f96dc8d2331ac4a6f89f62e54a Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sat, 28 Nov 2026 21:28:59 +0000 Subject: [PATCH 11/16] test: cover cdn caching for package file responses --- modules/runtime/server/cache.ts | 57 ++++++++++++++++++++++++++++++ test/e2e/cache-control.spec.ts | 43 ++++++++++++++++++++++ test/unit/nuxt-config.spec.ts | 13 +++++++ test/unit/shared/utils/npm.spec.ts | 23 +++++++++++- 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 test/unit/nuxt-config.spec.ts diff --git a/modules/runtime/server/cache.ts b/modules/runtime/server/cache.ts index 58415ff02e..f172e69019 100644 --- a/modules/runtime/server/cache.ts +++ b/modules/runtime/server/cache.ts @@ -1,5 +1,6 @@ import process from 'node:process' import type { CachedFetchResult } from '#shared/utils/fetch-cache-config' +import { isExactVersion } from '#shared/utils/npm' import { parsePackageSpec } from '#shared/utils/parse-package-param' import { createFetch } from 'ofetch' @@ -32,6 +33,7 @@ const FIXTURE_PATHS = { githubContributors: 'github:contributors.json', githubContributorsStats: 'github:contributors-stats.json', jsdelivr: 'jsdelivr', + jsdelivrCdn: 'jsdelivr-cdn', unghReleases: 'ungh:releases', } as const @@ -650,6 +652,56 @@ async function handleJsdelivrDataApi( } } +/** + * File contents are served from `test/fixtures/jsdelivr-cdn/@/`. + * A dist-tag or partial version resolves to the version of the jsDelivr data fixture, + * and anything without a fixture is a 404 so tests can cover the missing-file path. + */ +async function handleJsdelivrCdnFile( + url: string, + storage: ReturnType, +): Promise { + const urlObj = URL.parse(url) + if (urlObj?.host !== 'cdn.jsdelivr.net') return null + + const specMatch = decodeURIComponent(urlObj.pathname).match( + /^\/npm\/((?:@[^/]+\/)?[^/@]+)@([^/]+)\/(.+)$/, + ) + if (!specMatch?.[1] || !specMatch[2] || !specMatch[3]) { + return new Response(null, { status: 404 }) + } + + const [, name, requestedVersion, filePath] = specMatch + + const read = (version: string) => + storage + .getItemRaw( + `${FIXTURE_PATHS.jsdelivrCdn}:${name}@${version}/${filePath}`.replace(/\//g, ':'), + ) + .catch(() => null) + + let content = await read(requestedVersion) + if (content === null && !isExactVersion(requestedVersion)) { + const published = await storage + .getItem<{ version?: string }>(getFixturePath('jsdelivr', name)) + .catch(() => null) + if (published?.version) { + content = await read(published.version) + } + } + + if (content === null) { + if (VERBOSE) process.stdout.write(`[test-fixtures] jsDelivr CDN (missing): ${url}\n`) + return new Response(null, { status: 404 }) + } + + if (VERBOSE) process.stdout.write(`[test-fixtures] jsDelivr CDN: ${url}\n`) + return new Response(content, { + status: 200, + headers: { 'content-type': filePath.endsWith('.json') ? 'application/json' : 'text/plain' }, + }) +} + /** * Shared fixture-backed fetch implementation. * This is used by both cachedFetch and the global $fetch override. @@ -955,6 +1007,11 @@ export default defineNitroPlugin(nitroApp => { return await handleEsmShFetch(urlStr, init, storage) } + const jsdelivrCdnFile = await handleJsdelivrCdnFile(urlStr, storage) + if (jsdelivrCdnFile) { + return jsdelivrCdnFile + } + try { const res = await fetchFromFixtures(urlStr, storage) if (res.data) { diff --git a/test/e2e/cache-control.spec.ts b/test/e2e/cache-control.spec.ts index 748fac0893..ea49b019ee 100644 --- a/test/e2e/cache-control.spec.ts +++ b/test/e2e/cache-control.spec.ts @@ -30,4 +30,47 @@ test.describe('cache control', () => { expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) }) } + + const file = '/api/registry/file/empathic/v/2.0.0/package.json' + + test(`caches ${file} at the CDN for a year`, async ({ page }) => { + const response = await page.request.get(file) + + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toBe( + 'public, max-age=0, s-maxage=31536000, stale-while-revalidate=31536000', + ) + expect((await response.json()).content).toContain('"name": "empathic"') + }) + + test(`serves ${file} identically whatever the query string`, async ({ page }) => { + const clean = await page.request.get(file) + const tagged = await page.request.get(`${file}?utm_source=npmx&cachebust=1`) + + expect(tagged.status()).toBe(clean.status()) + expect(tagged.headers()['cache-control']).toBe(clean.headers()['cache-control']) + expect(tagged.headers()['set-cookie']).toBeUndefined() + expect(tagged.headers()['vary']).toBeUndefined() + expect(await tagged.text()).toBe(await clean.text()) + }) + + for (const version of ['latest', '2', '2.0']) { + test(`gives ${version} the short TTL instead of the immutable one`, async ({ page }) => { + const response = await page.request.get( + `/api/registry/file/empathic/v/${version}/package.json`, + ) + + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toBe('public, max-age=0, s-maxage=300') + }) + } + + for (const version of ['2.0.0', 'latest']) { + test(`does not cache a missing file in ${version} at the CDN`, async ({ page }) => { + const response = await page.request.get(`/api/registry/file/empathic/v/${version}/missing.js`) + + expect(response.status()).toBe(404) + expect(response.headers()['cache-control']).not.toMatch(/\bs-maxage=/) + }) + } }) diff --git a/test/unit/nuxt-config.spec.ts b/test/unit/nuxt-config.spec.ts new file mode 100644 index 0000000000..6bcbda7458 --- /dev/null +++ b/test/unit/nuxt-config.spec.ts @@ -0,0 +1,13 @@ +import { describe, expect, it, vi } from 'vite-plus/test' + +vi.stubGlobal('defineNuxtConfig', (config: unknown) => config) + +const { routeRules } = (await import('../../nuxt.config')).default as unknown as { + routeRules: Record> +} + +describe('route rules', () => { + it('takes the package file route off ISR without a cache-control header route', () => { + expect(routeRules['/api/registry/file/**']).toEqual({ isr: false }) + }) +}) diff --git a/test/unit/shared/utils/npm.spec.ts b/test/unit/shared/utils/npm.spec.ts index 5b4ec0aae9..72472eaeab 100644 --- a/test/unit/shared/utils/npm.spec.ts +++ b/test/unit/shared/utils/npm.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test' -import { normalizeLicense, parseDependencyVersion } from '#shared/utils/npm' +import { isExactVersion, normalizeLicense, parseDependencyVersion } from '#shared/utils/npm' import type { PackumentLicense } from '#shared/types/npm-registry' describe('normalizeLicense', () => { @@ -22,6 +22,27 @@ describe('normalizeLicense', () => { }) }) +describe('isExactVersion', () => { + it('accepts versions that name one release', () => { + for (const version of [ + '1.2.3', + 'v1.2.3', + '0.0.0', + '1.2.3-beta.1', + '1.2.3-rc.1+build.2', + '2024.01.01', + ]) { + expect(isExactVersion(version)).toBe(true) + } + }) + + it('rejects dist-tags and partial versions', () => { + for (const version of ['latest', 'next', '1', '1.2', '1.2.x', '*', '^1.2.3', '~1.2.3']) { + expect(isExactVersion(version)).toBe(false) + } + }) +}) + describe('parseDependencyVersion', () => { it('returns plain semver ranges without a name', () => { expect(parseDependencyVersion('^4.2.0')).toEqual({ name: null, range: '^4.2.0' }) From 731c95bfe9aa4c6e685c9013392f6b4a5a8a1863 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Sun, 29 Nov 2026 10:58:59 +0000 Subject: [PATCH 12/16] fix: only treat valid semver versions as exact --- shared/utils/npm.ts | 6 ++++-- test/unit/shared/utils/npm.spec.ts | 22 +++++++++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/shared/utils/npm.ts b/shared/utils/npm.ts index 8f8d7e900e..8c8ecc2296 100644 --- a/shared/utils/npm.ts +++ b/shared/utils/npm.ts @@ -47,11 +47,13 @@ export function assertValidPackageName(name: string): void { } } -const EXACT_VERSION_RE = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/ +const EXACT_VERSION_RE = + /^v?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/ /** * Whether the version names one published release, rather than a dist-tag (`latest`) or a - * partial version (`1`, `1.2`), which resolve to whatever is tagged today. + * partial version (`1`, `1.2`), which resolve to whatever is tagged today. Only SemVer is + * accepted, so a tag that merely looks like a version does not qualify. */ export function isExactVersion(version: string): boolean { return EXACT_VERSION_RE.test(version) diff --git a/test/unit/shared/utils/npm.spec.ts b/test/unit/shared/utils/npm.spec.ts index 72472eaeab..b81a8acfc4 100644 --- a/test/unit/shared/utils/npm.spec.ts +++ b/test/unit/shared/utils/npm.spec.ts @@ -29,15 +29,31 @@ describe('isExactVersion', () => { 'v1.2.3', '0.0.0', '1.2.3-beta.1', + '1.2.3-0.3.7', '1.2.3-rc.1+build.2', - '2024.01.01', + '1.2.3+build.2', + '2024.1.1', ]) { expect(isExactVersion(version)).toBe(true) } }) - it('rejects dist-tags and partial versions', () => { - for (const version of ['latest', 'next', '1', '1.2', '1.2.x', '*', '^1.2.3', '~1.2.3']) { + it('rejects dist-tags, partial versions and selectors that are not SemVer', () => { + for (const version of [ + 'latest', + 'next', + '1', + '1.2', + '1.2.x', + '*', + '^1.2.3', + '~1.2.3', + '2024.01.01', + '01.2.3', + '1.2.3-', + '1.2.3-a..b', + '1.2.3+abc..def', + ]) { expect(isExactVersion(version)).toBe(false) } }) From f9e510eee7510320625da64a282ba3f48c6b071a Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 30 Nov 2026 14:05:25 +0000 Subject: [PATCH 13/16] refactor: detect exact versions with verkit isValid --- shared/utils/npm.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/shared/utils/npm.ts b/shared/utils/npm.ts index 8c8ecc2296..8be6bd6c1d 100644 --- a/shared/utils/npm.ts +++ b/shared/utils/npm.ts @@ -1,6 +1,7 @@ import { getLatestVersion } from 'fast-npm-meta' import { createError } from 'h3' import validatePackageName from 'validate-npm-package-name' +import { isValid } from 'verkit' import type { PackumentLicense } from '#shared/types/npm-registry' /** @@ -47,16 +48,13 @@ export function assertValidPackageName(name: string): void { } } -const EXACT_VERSION_RE = - /^v?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/ - /** * Whether the version names one published release, rather than a dist-tag (`latest`) or a * partial version (`1`, `1.2`), which resolve to whatever is tagged today. Only SemVer is * accepted, so a tag that merely looks like a version does not qualify. */ export function isExactVersion(version: string): boolean { - return EXACT_VERSION_RE.test(version) + return isValid(version) } /** Parsed result of an npm dependency version value */ From 2efe505fdbc27f694179e9220ad6bace46e6ab3b Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 30 Nov 2026 14:05:25 +0000 Subject: [PATCH 14/16] fix: invalidate compare-file cache after diff ratio rounding --- server/api/registry/compare-file/[...pkg].get.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/api/registry/compare-file/[...pkg].get.ts b/server/api/registry/compare-file/[...pkg].get.ts index 59746b85a5..48155e8e42 100644 --- a/server/api/registry/compare-file/[...pkg].get.ts +++ b/server/api/registry/compare-file/[...pkg].get.ts @@ -9,7 +9,7 @@ import { } from '#shared/utils/diff' import type { DiffHunk, DiffSkipBlock } from '#shared/types/compare' -const CACHE_VERSION = 3 +const CACHE_VERSION = 4 const DIFF_TIMEOUT = 15000 // 15 sec /** Files above this size use a cheaper plain-text diff renderer. */ From b3243521f95811e4d53c321a84484aa0438d7c74 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 30 Nov 2026 15:03:35 +0000 Subject: [PATCH 15/16] fix: set page cdn cache headers per response --- app/composables/usePageCacheControl.ts | 9 ++++++ app/error.vue | 5 ++++ app/pages/compare.vue | 3 ++ .../[packageName]/v/[versionRange].vue | 10 +++++++ app/pages/org/[org].vue | 3 ++ .../package-stats/[[org]]/[packageName].vue | 7 +++++ .../[[org]]/[packageName].vue | 6 ++++ app/pages/package/[[org]]/[name].vue | 9 +++++- nuxt.config.ts | 28 ++----------------- shared/utils/constants.ts | 7 +++++ test/e2e/cache-control.spec.ts | 18 ++++++++++++ 11 files changed, 79 insertions(+), 26 deletions(-) create mode 100644 app/composables/usePageCacheControl.ts diff --git a/app/composables/usePageCacheControl.ts b/app/composables/usePageCacheControl.ts new file mode 100644 index 0000000000..dff395a30b --- /dev/null +++ b/app/composables/usePageCacheControl.ts @@ -0,0 +1,9 @@ +/** + * Give this page's HTML a CDN cache header. Only applied on the server, and only when the page + * renders, so pages that end up on an error never leave a cacheable response behind. + */ +export function usePageCacheControl(cacheControl: string | undefined) { + if (import.meta.server && cacheControl) { + useResponseHeader('cache-control').value = cacheControl + } +} diff --git a/app/error.vue b/app/error.vue index 2d0b949652..537ac3a1f1 100644 --- a/app/error.vue +++ b/app/error.vue @@ -5,6 +5,11 @@ const props = defineProps<{ error: NuxtError }>() +// a page can set a cdn cache header before it fails +if (import.meta.server) { + useResponseHeader('cache-control').value = 'no-store' +} + const status = computed(() => props.error.status || 500) const statusText = computed(() => { if (props.error.statusText) return props.error.statusText diff --git a/app/pages/compare.vue b/app/pages/compare.vue index 6b7394adf0..702bd4fa76 100644 --- a/app/pages/compare.vue +++ b/app/pages/compare.vue @@ -3,12 +3,15 @@ import { useRouteQuery } from '@vueuse/router' import FacetBarChart from '~/components/Compare/FacetBarChart.vue' import type { CommandPaletteContextCommandInput } from '~/types/command-palette' import FacetScatterChart from '~/components/Compare/FacetScatterChart.vue' +import { CACHE_CONTROL_PAGE_HOUR } from '#shared/utils/constants' definePageMeta({ name: 'compare', preserveScrollOnQuery: true, }) +usePageCacheControl(CACHE_CONTROL_PAGE_HOUR) + const { locale } = useI18n() const { copied, copy } = useClipboard({ copiedDuring: 2000 }) diff --git a/app/pages/diff/[[org]]/[packageName]/v/[versionRange].vue b/app/pages/diff/[[org]]/[packageName]/v/[versionRange].vue index 943ac57b72..ed7b7656be 100644 --- a/app/pages/diff/[[org]]/[packageName]/v/[versionRange].vue +++ b/app/pages/diff/[[org]]/[packageName]/v/[versionRange].vue @@ -1,5 +1,7 @@