From f3f8d64d7b1d9ff2789f74b16ec3755dbbc3db52 Mon Sep 17 00:00:00 2001 From: MK Date: Mon, 29 Jun 2026 23:49:49 +0800 Subject: [PATCH 1/3] Revert "Don't cache a packument that's missing npm time (#19)" This reverts commit 2165eeb625aec615dabb4373e5aa130207081bfe. --- src/app.ts | 8 +------ test/worker.test.ts | 53 +++++---------------------------------------- 2 files changed, 6 insertions(+), 55 deletions(-) diff --git a/src/app.ts b/src/app.ts index 095d60a..580bafd 100644 --- a/src/app.ts +++ b/src/app.ts @@ -348,16 +348,10 @@ app.get('*', async (c) => { }), ) - // If any served version lacks a `time` entry (e.g. the npm `time` fetch - // hiccupped), the response is degraded. Serve it, but `no-store` so it can't - // poison the edge/client caches for the full TTL and break time-based - // resolution (ERR_PNPM_MISSING_TIME) for everyone until it expires. - const timeComplete = Object.keys(packument.versions).every((v) => v in time) - return new Response(JSON.stringify(packument), { headers: { 'content-type': 'application/json; charset=utf-8', - 'cache-control': timeComplete ? packumentCacheControl() : 'no-store', + 'cache-control': packumentCacheControl(), }, }) }) diff --git a/test/worker.test.ts b/test/worker.test.ts index e77234a..0b577cd 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -46,14 +46,6 @@ function gzip(bytes: Uint8Array): Response { }) } -/** The `accept` header from a fetch init, whether a plain object or Headers. */ -function acceptOf(init?: RequestInit): string { - const h = init?.headers - return ( - (h instanceof Headers ? h.get('accept') : (h as Record)?.accept) ?? '' - ) -} - /** * The worker-under-test (reached via SELF.fetch) runs in this same isolate, so * a `vi.stubGlobal('fetch', ...)` mock intercepts its outbound calls to npm and @@ -61,13 +53,6 @@ function acceptOf(init?: RequestInit): string { */ const PLATFORM_SHA = '1234567890abcdef1234567890abcdef12345678' -// Assigned in beforeAll so a test can re-stub `fetch` and delegate the URLs it -// doesn't override back to the shared mock. -let baseFetchMock: ( - input: RequestInfo | URL, - init?: RequestInit, -) => Promise - beforeAll(async () => { const darwinBin = await makeTarball({ name: '@voidzero-dev/vite-plus-darwin-arm64', @@ -100,7 +85,11 @@ beforeAll(async () => { if (url === 'https://registry.npmjs.org/vite-plus') { // Mimic npm: `time` is present only in the full packument, not the // abbreviated (install-v1) form. Branch on the Accept header. - const abbreviated = acceptOf(init).includes('install-v1') + const h = init?.headers + const accept = ( + h instanceof Headers ? h.get('accept') : (h as Record)?.accept + ) ?? '' + const abbreviated = accept.includes('install-v1') const body = abbreviated ? { ...NPM_VITE_PLUS, modified: NPM_VITE_PLUS_TIME.modified } : { ...NPM_VITE_PLUS, time: NPM_VITE_PLUS_TIME } @@ -124,7 +113,6 @@ beforeAll(async () => { return Promise.reject(new Error(`unexpected fetch: ${url}`)) } - baseFetchMock = mockFetch vi.stubGlobal('fetch', mockFetch) }) @@ -219,37 +207,6 @@ describe('packument endpoint', () => { expect(Date.parse(t1)).toBeGreaterThanOrEqual(before) }) - it('marks the packument no-store when npm time could not be sourced', async () => { - // Simulate the separate full-packument (`time`) fetch failing: abbreviated - // versions are served but with no npm time. The response must still serve, - // but `no-store` so a transient hiccup can't poison the edge/client caches - // for the whole TTL and break time-based resolution. - vi.stubGlobal( - 'fetch', - (input: RequestInfo | URL, init?: RequestInit): Promise => { - const url = typeof input === 'string' ? input : input.toString() - if (url.startsWith('https://registry.npmjs.org/vite-plus')) { - return acceptOf(init).includes('install-v1') - ? Promise.resolve(json(NPM_VITE_PLUS)) // versions, no time - : Promise.resolve(json({ error: 'boom' }, 500)) // time fetch fails - } - return baseFetchMock(input, init) - }, - ) - try { - const res = await SELF.fetch(`${BASE}/vite-plus`, { - headers: { accept: 'application/json' }, - }) - expect(res.status).toBe(200) - const body = (await res.json()) as Record - expect(body.versions['0.2.1']).toBeTruthy() // still served - expect(body.time?.['0.2.1']).toBeFalsy() // npm time missing (degraded) - expect(res.headers.get('cache-control')).toBe('no-store') // so: not cached - } finally { - vi.stubGlobal('fetch', baseFetchMock) // restore for later tests - } - }) - it('synthesizes a preview-only packument when npm has no such package', async () => { const res = await SELF.fetch(`${BASE}/@voidzero-dev%2Fvite-plus-core`, { headers: { accept: 'application/json' }, From 91454ba21c4bc98d0d1da70a04b92601c0d4e723 Mon Sep 17 00:00:00 2001 From: MK Date: Mon, 29 Jun 2026 23:57:37 +0800 Subject: [PATCH 2/3] Surface npm registry non-200 responses as errors When the npm packument or time fetch returns a non-200 other than 404, throw npm's status + raw body instead of synthesizing a misleading packument (which drops the package's real versions and could be cached). 404 (not on npm) still synthesizes a preview-only packument. This supersedes the no-store guard (reverted above): on upstream failure the bridge errors out rather than serving a degraded packument. --- src/registry/fetchNpmPackument.ts | 46 +++++++++++++++---------------- test/worker.test.ts | 18 ++++++++++++ 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/src/registry/fetchNpmPackument.ts b/src/registry/fetchNpmPackument.ts index c770692..20de872 100644 --- a/src/registry/fetchNpmPackument.ts +++ b/src/registry/fetchNpmPackument.ts @@ -1,5 +1,6 @@ import type { Env } from '../config' import { encodeNpmPackageName } from './parsePackageName' +import { HttpError } from '../httpError' export interface NpmPackumentResult { status: number @@ -34,9 +35,11 @@ function npmFetch(env: Env, name: string, accept: string): Promise { } /** - * Fetch a packument from the npm registry. A 404 (package not published to - * npm) is returned as `{ status: 404, data: null }` so the caller can still - * synthesize a preview-only packument. + * Fetch a packument from the npm registry. A 404 (package not published to npm) + * is returned as `{ status: 404, data: null }` so the caller can still + * synthesize a preview-only packument. Any OTHER non-200 is an upstream failure: + * throw npm's status + raw body, rather than synthesize a misleading packument + * that drops the package's real versions. */ export async function fetchNpmPackument( env: Env, @@ -45,38 +48,33 @@ export async function fetchNpmPackument( const res = await npmFetch(env, name, ABBREVIATED_ACCEPT) if (res.status === 404) return { status: 404, data: null } - if (!res.ok) return { status: res.status, data: null } + if (!res.ok) throw new HttpError(res.status, await res.text()) const data = (await res.json()) as Record return { status: 200, data } } /** - * Fetch ONLY the per-version `time` map from npm's FULL packument. Returns null - * when the package is absent (404) or the upstream omits/has no usable `time`, - * so the caller can still serve a synthesized packument (with `time` entries it - * fills in for the injected preview versions). Keeping this separate from - * fetchNpmPackument lets the served response carry the compact abbreviated - * version docs while still preserving npm's real publish times. + * Fetch ONLY the per-version `time` map from npm's FULL packument. A 404 + * (package not on npm) returns null so the caller can still synthesize a + * preview-only packument; any OTHER non-200 is an upstream failure and throws + * npm's status + raw body (so a transient hiccup surfaces as an error instead of + * a packument missing npm's publish times). A 200 with no usable `time` returns + * null. Kept separate from fetchNpmPackument so the served response carries the + * compact abbreviated version docs while still preserving npm's real times. */ export async function fetchNpmTime( env: Env, name: string, ): Promise | null> { - // Fail soft: a hiccup sourcing `time` must not break the packument. On any - // error return null and serve without npm's times (the injected preview - // versions still get their own `time` entry from the caller). - try { - const res = await npmFetch(env, name, FULL_ACCEPT) + const res = await npmFetch(env, name, FULL_ACCEPT) - if (!res.ok) return null + if (res.status === 404) return null + if (!res.ok) throw new HttpError(res.status, await res.text()) - const data = (await res.json()) as Record - const time = data?.time - return time && typeof time === 'object' - ? (time as Record) - : null - } catch { - return null - } + const data = (await res.json()) as Record + const time = data?.time + return time && typeof time === 'object' + ? (time as Record) + : null } diff --git a/test/worker.test.ts b/test/worker.test.ts index 0b577cd..0c91ad8 100644 --- a/test/worker.test.ts +++ b/test/worker.test.ts @@ -227,6 +227,24 @@ describe('packument endpoint', () => { expect(body.time?.['0.0.0-commit.a832a55']).toBeTruthy() }) + it('surfaces an npm registry error (non-200, non-404) instead of synthesizing', async () => { + // 404 means "not on npm" and is synthesized (above). Any other upstream + // error must propagate npm's status, not hide behind a 200 packument that + // silently drops the package's real versions. + const saved = globalThis.fetch + vi.stubGlobal('fetch', () => + Promise.resolve(json({ error: 'upstream boom' }, 503)), + ) + try { + const res = await SELF.fetch(`${BASE}/vite-plus`, { + headers: { accept: 'application/json' }, + }) + expect(res.status).toBe(503) + } finally { + vi.stubGlobal('fetch', saved) + } + }) + it('rewrites pkg.pr.new optionalDependency URLs to version strings', async () => { const res = await SELF.fetch(`${BASE}/vite-plus`, { headers: { accept: 'application/json' }, From e4859f8b52798d2720952eec6d0285a62ce57a2a Mon Sep 17 00:00:00 2001 From: MK Date: Tue, 30 Jun 2026 00:03:11 +0800 Subject: [PATCH 3/3] Extract assertNpmOk; return the packument data directly (drop vestigial status) --- src/app.ts | 4 +--- src/registry/fetchNpmPackument.ts | 33 ++++++++++++++++--------------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/src/app.ts b/src/app.ts index 580bafd..5b8214b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -311,9 +311,7 @@ app.get('*', async (c) => { ]) const packument: Record = - base.status === 200 && base.data - ? base.data - : { name, 'dist-tags': {}, versions: {} } + base ?? { name, 'dist-tags': {}, versions: {} } packument.name = name packument['dist-tags'] ??= {} diff --git a/src/registry/fetchNpmPackument.ts b/src/registry/fetchNpmPackument.ts index 20de872..501d165 100644 --- a/src/registry/fetchNpmPackument.ts +++ b/src/registry/fetchNpmPackument.ts @@ -2,12 +2,6 @@ import type { Env } from '../config' import { encodeNpmPackageName } from './parsePackageName' import { HttpError } from '../httpError' -export interface NpmPackumentResult { - status: number - /** Parsed packument, or null when the upstream had no usable body. */ - data: Record | null -} - // Abbreviated packument format. Always request this from npm: it is an order // of magnitude smaller than the full packument (which some clients' Accept // headers, with q-values, otherwise coax npm into returning). A large response @@ -34,24 +28,31 @@ function npmFetch(env: Env, name: string, accept: string): Promise { }) } +/** + * Surface an npm upstream failure: throw npm's status + raw body on a non-2xx + * response. Callers handle 404 themselves first, since "not on npm" is not a + * failure. + */ +async function assertNpmOk(res: Response): Promise { + if (!res.ok) throw new HttpError(res.status, await res.text()) +} + /** * Fetch a packument from the npm registry. A 404 (package not published to npm) - * is returned as `{ status: 404, data: null }` so the caller can still - * synthesize a preview-only packument. Any OTHER non-200 is an upstream failure: - * throw npm's status + raw body, rather than synthesize a misleading packument - * that drops the package's real versions. + * returns null so the caller can still synthesize a preview-only packument. Any + * OTHER non-200 is an upstream failure: throw npm's status + raw body, rather + * than synthesize a misleading packument that drops the package's real versions. */ export async function fetchNpmPackument( env: Env, name: string, -): Promise { +): Promise | null> { const res = await npmFetch(env, name, ABBREVIATED_ACCEPT) - if (res.status === 404) return { status: 404, data: null } - if (!res.ok) throw new HttpError(res.status, await res.text()) + if (res.status === 404) return null + await assertNpmOk(res) - const data = (await res.json()) as Record - return { status: 200, data } + return (await res.json()) as Record } /** @@ -70,7 +71,7 @@ export async function fetchNpmTime( const res = await npmFetch(env, name, FULL_ACCEPT) if (res.status === 404) return null - if (!res.ok) throw new HttpError(res.status, await res.text()) + await assertNpmOk(res) const data = (await res.json()) as Record const time = data?.time