Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,7 @@ app.get('*', async (c) => {
])

const packument: Record<string, any> =
base.status === 200 && base.data
? base.data
: { name, 'dist-tags': {}, versions: {} }
base ?? { name, 'dist-tags': {}, versions: {} }

packument.name = name
packument['dist-tags'] ??= {}
Expand Down Expand Up @@ -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(),
},
})
})
Expand Down
67 changes: 33 additions & 34 deletions src/registry/fetchNpmPackument.ts
Original file line number Diff line number Diff line change
@@ -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<string, any> | 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
Expand Down Expand Up @@ -34,49 +29,53 @@ function npmFetch(env: Env, name: string, accept: string): Promise<Response> {
}

/**
* 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<void> {
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<NpmPackumentResult> {
): Promise<Record<string, any> | 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<string, any>
return { status: 200, data }
return (await res.json()) as Record<string, any>
}

/**
* 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<Record<string, string> | 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<string, any>
const time = data?.time
return time && typeof time === 'object'
? (time as Record<string, string>)
: null
} catch {
return null
}
const data = (await res.json()) as Record<string, any>
const time = data?.time
return time && typeof time === 'object'
? (time as Record<string, string>)
: null
}
71 changes: 23 additions & 48 deletions test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,28 +46,13 @@ 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<string, string>)?.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
* pkg.pr.new, while SELF.fetch (a service binding) still routes normally.
*/
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<Response>

beforeAll(async () => {
const darwinBin = await makeTarball({
name: '@voidzero-dev/vite-plus-darwin-arm64',
Expand Down Expand Up @@ -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<string, string>)?.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 }
Expand All @@ -124,7 +113,6 @@ beforeAll(async () => {
return Promise.reject(new Error(`unexpected fetch: ${url}`))
}

baseFetchMock = mockFetch
vi.stubGlobal('fetch', mockFetch)
})

Expand Down Expand Up @@ -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<Response> => {
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<string, any>
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' },
Expand All @@ -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' },
Expand Down