import { createGateway, type GatewayCache } from '@nibling/npm-gateway'; import type { ResponseCache } from './cache.ts'; import type { Gateway } from './context.ts'; /** The Workers Cache API as a GatewayCache. Keys become URLs under this worker's origin. */ function responseCache(cache: ResponseCache, origin: string, waitUntil: Gateway['waitUntil']): GatewayCache { const url = (key: string) => new URL(`/npm/cache/${encodeURIComponent(key)}`, origin).toString(); return { async get(key) { return (await cache.match(url(key)))?.text(); }, async put(key, value, ttl) { waitUntil(cache.put(url(key), new Response(value, { headers: { 'cache-control': `public, max-age=${ttl}` } }))); }, }; } /** dev.nibling.npm.getClosure and this worker's did:web document, answered by * @nibling/npm-gateway: this worker is one gateway among any that implement the query, and the * kernel works with none. */ export function handleNpm(g: Gateway, request: Request): Promise { return createGateway({ fetch: g.fetch, cache: responseCache(g.cache, g.origin, g.waitUntil), didWeb: true }).fetch(request); }