diff --git a/src/app.ts b/src/app.ts index 095d60a..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'] ??= {} @@ -348,16 +346,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/src/registry/fetchNpmPackument.ts b/src/registry/fetchNpmPackument.ts index c770692..501d165 100644 --- a/src/registry/fetchNpmPackument.ts +++ b/src/registry/fetchNpmPackument.ts @@ -1,11 +1,6 @@ import type { Env } from '../config' import { encodeNpmPackageName } from './parsePackageName' - -export interface NpmPackumentResult { - status: number - /** Parsed packument, or null when the upstream had no usable body. */ - data: Record | null -} +import { HttpError } from '../httpError' // Abbreviated packument format. Always request this from npm: it is an order // of magnitude smaller than the full packument (which some clients' Accept @@ -34,49 +29,53 @@ 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. + * 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) + * 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) return { status: res.status, data: null } + 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 } /** - * 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 + await assertNpmOk(res) - 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 e77234a..0c91ad8 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' }, @@ -270,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' },