vinext 0.0.22 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/build/static-export.d.ts.map +1 -1
  2. package/dist/build/static-export.js +9 -7
  3. package/dist/build/static-export.js.map +1 -1
  4. package/dist/config/next-config.d.ts +4 -1
  5. package/dist/config/next-config.d.ts.map +1 -1
  6. package/dist/config/next-config.js +10 -5
  7. package/dist/config/next-config.js.map +1 -1
  8. package/dist/deploy.d.ts.map +1 -1
  9. package/dist/deploy.js +11 -1
  10. package/dist/deploy.js.map +1 -1
  11. package/dist/index.d.ts +25 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +202 -28
  14. package/dist/index.js.map +1 -1
  15. package/dist/routing/app-router.d.ts +2 -1
  16. package/dist/routing/app-router.d.ts.map +1 -1
  17. package/dist/routing/app-router.js +73 -66
  18. package/dist/routing/app-router.js.map +1 -1
  19. package/dist/routing/file-matcher.d.ts +24 -0
  20. package/dist/routing/file-matcher.d.ts.map +1 -0
  21. package/dist/routing/file-matcher.js +75 -0
  22. package/dist/routing/file-matcher.js.map +1 -0
  23. package/dist/routing/pages-router.d.ts +3 -2
  24. package/dist/routing/pages-router.d.ts.map +1 -1
  25. package/dist/routing/pages-router.js +24 -17
  26. package/dist/routing/pages-router.js.map +1 -1
  27. package/dist/server/app-dev-server.d.ts.map +1 -1
  28. package/dist/server/app-dev-server.js +54 -45
  29. package/dist/server/app-dev-server.js.map +1 -1
  30. package/dist/server/dev-server.d.ts +2 -1
  31. package/dist/server/dev-server.d.ts.map +1 -1
  32. package/dist/server/dev-server.js +16 -14
  33. package/dist/server/dev-server.js.map +1 -1
  34. package/dist/server/prod-server.d.ts.map +1 -1
  35. package/dist/server/prod-server.js +26 -2
  36. package/dist/server/prod-server.js.map +1 -1
  37. package/dist/shims/cache.d.ts +1 -1
  38. package/dist/shims/cache.d.ts.map +1 -1
  39. package/dist/shims/cache.js +8 -3
  40. package/dist/shims/cache.js.map +1 -1
  41. package/dist/shims/metadata.d.ts +1 -0
  42. package/dist/shims/metadata.d.ts.map +1 -1
  43. package/dist/shims/metadata.js +5 -1
  44. package/dist/shims/metadata.js.map +1 -1
  45. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"prod-server.js","sourceRoot":"","sources":["../../src/server/prod-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,yBAAyB,EAAE,aAAa,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAE9K,OAAO,EAAE,uBAAuB,EAAE,6BAA6B,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,mBAAmB,EAAoB,MAAM,yBAAyB,CAAC;AACxM,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,oFAAoF;AACpF,SAAS,cAAc,CAAC,GAAoB;IAC1C,OAAO,IAAI,cAAc,CAAC;QACxB,KAAK,CAAC,UAAU;YACd,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAC7E,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,UAAU,C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C,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE;YAC7B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YACvE,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,IAAI,UAAU,EAAE,CAAC,CAAC;YAClF,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,6BAA6B;AAC7B,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Production server for vinext.\n *\n * Serves the built output from `vinext build`. Handles:\n * - Static asset serving from client build output\n * - Pages Router: SSR rendering + API route handling\n * - App Router: RSC/SSR rendering, route handlers, server actions\n * - Gzip/Brotli compression for text-based responses\n * - Streaming SSR for App Router\n *\n * Build output for Pages Router:\n * - dist/client/ — static assets (JS, CSS, images) + .vite/ssr-manifest.json\n * - dist/server/entry.js — SSR entry point (virtual:vinext-server-entry)\n *\n * Build output for App Router:\n * - dist/client/ — static assets (JS, CSS, images)\n * - dist/server/index.js — RSC entry (default export: handler(Request) → Response)\n * - dist/server/ssr/index.js — SSR entry (imported by RSC entry at runtime)\n */\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { Readable, pipeline } from \"node:stream\";\nimport { pathToFileURL } from \"node:url\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport zlib from \"node:zlib\";\nimport { matchRedirect, matchRewrite, matchHeaders, requestContextFromRequest, isExternalUrl, proxyExternalRequest, sanitizeDestination } from \"../config/config-matchers.js\";\nimport type { RequestContext } from \"../config/config-matchers.js\";\nimport { IMAGE_OPTIMIZATION_PATH, IMAGE_CONTENT_SECURITY_POLICY, parseImageParams, isSafeImageContentType, DEFAULT_DEVICE_SIZES, DEFAULT_IMAGE_SIZES, type ImageConfig } from \"./image-optimization.js\";\nimport { normalizePath } from \"./normalize-path.js\";\nimport { computeLazyChunks } from \"../index.js\";\n\n/** Convert a Node.js IncomingMessage into a ReadableStream for Web Request body. */\nfunction readNodeStream(req: IncomingMessage): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n req.on(\"data\", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));\n req.on(\"end\", () => controller.close());\n req.on(\"error\", (err) => controller.error(err));\n },\n });\n}\n\nexport interface ProdServerOptions {\n /** Port to listen on */\n port?: number;\n /** Host to bind to */\n host?: string;\n /** Path to the build output directory */\n outDir?: string;\n /** Disable compression (default: false) */\n noCompression?: boolean;\n}\n\n/** Content types that benefit from compression. */\nconst COMPRESSIBLE_TYPES = new Set([\n \"text/html\",\n \"text/css\",\n \"text/plain\",\n \"text/xml\",\n \"text/javascript\",\n \"application/javascript\",\n \"application/json\",\n \"application/xml\",\n \"application/xhtml+xml\",\n \"application/rss+xml\",\n \"application/atom+xml\",\n \"image/svg+xml\",\n \"application/manifest+json\",\n \"application/wasm\",\n]);\n\n/** Minimum size threshold for compression (in bytes). Below this, compression overhead isn't worth it. */\nconst COMPRESS_THRESHOLD = 1024;\n\n/**\n * Parse the Accept-Encoding header and return the best supported encoding.\n * Preference order: br > gzip > deflate > identity.\n */\nfunction negotiateEncoding(req: IncomingMessage): \"br\" | \"gzip\" | \"deflate\" | null {\n const accept = req.headers[\"accept-encoding\"];\n if (!accept || typeof accept !== \"string\") return null;\n const lower = accept.toLowerCase();\n if (lower.includes(\"br\")) return \"br\";\n if (lower.includes(\"gzip\")) return \"gzip\";\n if (lower.includes(\"deflate\")) return \"deflate\";\n return null;\n}\n\n/**\n * Create a compression stream for the given encoding.\n */\nfunction createCompressor(encoding: \"br\" | \"gzip\" | \"deflate\"): zlib.BrotliCompress | zlib.Gzip | zlib.Deflate {\n switch (encoding) {\n case \"br\":\n return zlib.createBrotliCompress({\n params: {\n [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // Fast compression (1-11, 4 is a good balance)\n },\n });\n case \"gzip\":\n return zlib.createGzip({ level: 6 }); // Default level, good balance\n case \"deflate\":\n return zlib.createDeflate({ level: 6 });\n }\n}\n\n/**\n * Send a compressed response if the content type is compressible and the\n * client supports compression. Otherwise send uncompressed.\n */\nfunction sendCompressed(\n req: IncomingMessage,\n res: ServerResponse,\n body: string | Buffer,\n contentType: string,\n statusCode: number,\n extraHeaders: Record<string, string> = {},\n compress: boolean = true,\n): void {\n const buf = typeof body === \"string\" ? Buffer.from(body) : body;\n const baseType = contentType.split(\";\")[0].trim();\n const encoding = compress ? negotiateEncoding(req) : null;\n\n if (encoding && COMPRESSIBLE_TYPES.has(baseType) && buf.length >= COMPRESS_THRESHOLD) {\n const compressor = createCompressor(encoding);\n // Merge Accept-Encoding into existing Vary header from extraHeaders instead\n // of overwriting. Preserves Vary values set by the App Router for content\n // negotiation (e.g. \"RSC, Accept\").\n const existingVary = extraHeaders[\"Vary\"] ?? extraHeaders[\"vary\"];\n let varyValue: string;\n if (existingVary) {\n const existing = String(existingVary).toLowerCase();\n varyValue = existing.includes(\"accept-encoding\") ? String(existingVary) : existingVary + \", Accept-Encoding\";\n } else {\n varyValue = \"Accept-Encoding\";\n }\n res.writeHead(statusCode, {\n ...extraHeaders,\n \"Content-Type\": contentType,\n \"Content-Encoding\": encoding,\n Vary: varyValue,\n });\n compressor.end(buf);\n pipeline(compressor, res, () => { /* ignore pipeline errors on closed connections */ });\n } else {\n res.writeHead(statusCode, {\n ...extraHeaders,\n \"Content-Type\": contentType,\n \"Content-Length\": String(buf.length),\n });\n res.end(buf);\n }\n}\n\n/** Content-type lookup for static assets. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"application/javascript\",\n \".mjs\": \"application/javascript\",\n \".css\": \"text/css\",\n \".html\": \"text/html\",\n \".json\": \"application/json\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".map\": \"application/json\",\n};\n\n/**\n * Try to serve a static file from the client build directory.\n * Returns true if the file was served, false otherwise.\n */\nfunction tryServeStatic(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n pathname: string,\n compress: boolean,\n extraHeaders?: Record<string, string>,\n): boolean {\n // Resolve the path and guard against directory traversal (e.g. /../../../etc/passwd)\n const resolvedClient = path.resolve(clientDir);\n let decodedPathname: string;\n try {\n decodedPathname = decodeURIComponent(pathname);\n } catch {\n return false;\n }\n\n // Block access to internal build metadata directories. The .vite/\n // directory contains manifests and other build artifacts that should\n // not be publicly served. Check after decoding to catch encoded\n // variants like /%2Evite/manifest.json.\n if (decodedPathname.startsWith(\"/.vite/\") || decodedPathname === \"/.vite\") {\n return false;\n }\n const staticFile = path.resolve(clientDir, \".\" + decodedPathname);\n if (!staticFile.startsWith(resolvedClient + path.sep) && staticFile !== resolvedClient) {\n return false;\n }\n if (\n pathname === \"/\" ||\n !fs.existsSync(staticFile) ||\n !fs.statSync(staticFile).isFile()\n ) {\n return false;\n }\n\n const ext = path.extname(staticFile);\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n const isHashed = pathname.startsWith(\"/assets/\");\n const cacheControl = isHashed\n ? \"public, max-age=31536000, immutable\"\n : \"public, max-age=3600\";\n\n const baseHeaders = {\n \"Content-Type\": ct,\n \"Cache-Control\": cacheControl,\n ...extraHeaders,\n };\n\n const baseType = ct.split(\";\")[0].trim();\n if (compress && COMPRESSIBLE_TYPES.has(baseType)) {\n const encoding = negotiateEncoding(req);\n if (encoding) {\n const fileStream = fs.createReadStream(staticFile);\n const compressor = createCompressor(encoding);\n res.writeHead(200, {\n ...baseHeaders,\n \"Content-Encoding\": encoding,\n Vary: \"Accept-Encoding\",\n });\n pipeline(fileStream, compressor, res, () => { /* ignore */ });\n return true;\n }\n }\n\n res.writeHead(200, baseHeaders);\n fs.createReadStream(staticFile).pipe(res);\n return true;\n}\n\n/**\n * Resolve the host for a request, ignoring X-Forwarded-Host to prevent\n * host header poisoning attacks (open redirects, cache poisoning).\n *\n * X-Forwarded-Host is only trusted when the VINEXT_TRUSTED_HOSTS env var\n * lists the forwarded host value. Without this, an attacker can send\n * X-Forwarded-Host: evil.com and poison any redirect that resolves\n * against request.url.\n *\n * On Cloudflare Workers, X-Forwarded-Host is always set by Cloudflare\n * itself, so this is only a concern for the Node.js prod-server.\n */\nfunction resolveHost(req: IncomingMessage, fallback: string): string {\n const rawForwarded = req.headers[\"x-forwarded-host\"] as string | undefined;\n const hostHeader = req.headers.host;\n\n if (rawForwarded) {\n // X-Forwarded-Host can be comma-separated when passing through\n // multiple proxies — take only the first (client-facing) value.\n const forwardedHost = rawForwarded.split(\",\")[0].trim().toLowerCase();\n if (forwardedHost && trustedHosts.has(forwardedHost)) {\n return forwardedHost;\n }\n }\n\n return hostHeader || fallback;\n}\n\n/** Hosts that are allowed as X-Forwarded-Host values (stored lowercase). */\nconst trustedHosts: Set<string> = new Set(\n (process.env.VINEXT_TRUSTED_HOSTS ?? \"\")\n .split(\",\")\n .map((h) => h.trim().toLowerCase())\n .filter(Boolean),\n);\n\n/**\n * Whether to trust X-Forwarded-Proto from upstream proxies.\n * Enabled when VINEXT_TRUST_PROXY=1 or when VINEXT_TRUSTED_HOSTS is set\n * (having trusted hosts implies a trusted proxy).\n */\nconst trustProxy = process.env.VINEXT_TRUST_PROXY === \"1\" || trustedHosts.size > 0;\n\n/**\n * Convert a Node.js IncomingMessage to a Web Request object.\n */\nfunction nodeToWebRequest(req: IncomingMessage): Request {\n const rawProto = trustProxy\n ? (req.headers[\"x-forwarded-proto\"] as string)?.split(\",\")[0]?.trim()\n : undefined;\n const proto = rawProto === \"https\" || rawProto === \"http\" ? rawProto : \"http\";\n const host = resolveHost(req, \"localhost\");\n const origin = `${proto}://${host}`;\n const url = new URL(req.url ?? \"/\", origin);\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n };\n\n if (hasBody) {\n // Convert Node.js readable stream to Web ReadableStream for request body.\n // Readable.toWeb() is available since Node.js 17.\n init.body = Readable.toWeb(req) as ReadableStream;\n init.duplex = \"half\"; // Required for streaming request bodies\n }\n\n return new Request(url, init);\n}\n\n/**\n * Stream a Web Response back to a Node.js ServerResponse.\n * Supports streaming compression for SSR responses.\n */\nasync function sendWebResponse(\n webResponse: Response,\n req: IncomingMessage,\n res: ServerResponse,\n compress: boolean,\n): Promise<void> {\n const status = webResponse.status;\n\n // Collect headers, handling multi-value headers (e.g. Set-Cookie)\n const nodeHeaders: Record<string, string | string[]> = {};\n webResponse.headers.forEach((value, key) => {\n const existing = nodeHeaders[key];\n if (existing !== undefined) {\n nodeHeaders[key] = Array.isArray(existing)\n ? [...existing, value]\n : [existing, value];\n } else {\n nodeHeaders[key] = value;\n }\n });\n\n if (!webResponse.body) {\n res.writeHead(status, nodeHeaders);\n res.end();\n return;\n }\n\n // Check if we should compress the response.\n // Skip if the upstream already compressed (avoid double-compression).\n const alreadyEncoded = webResponse.headers.has(\"content-encoding\");\n const contentType = webResponse.headers.get(\"content-type\") ?? \"\";\n const baseType = contentType.split(\";\")[0].trim();\n const encoding = (compress && !alreadyEncoded) ? negotiateEncoding(req) : null;\n const shouldCompress = !!(encoding && COMPRESSIBLE_TYPES.has(baseType));\n\n if (shouldCompress) {\n delete nodeHeaders[\"content-length\"];\n delete nodeHeaders[\"Content-Length\"];\n nodeHeaders[\"Content-Encoding\"] = encoding!;\n // Merge Accept-Encoding into existing Vary header (e.g. \"RSC, Accept\") instead\n // of overwriting. This prevents stripping the Vary values that the App Router\n // sets for content negotiation (RSC stream vs HTML).\n const existingVary = nodeHeaders[\"Vary\"] ?? nodeHeaders[\"vary\"];\n if (existingVary) {\n const existing = String(existingVary).toLowerCase();\n if (!existing.includes(\"accept-encoding\")) {\n nodeHeaders[\"Vary\"] = existingVary + \", Accept-Encoding\";\n }\n } else {\n nodeHeaders[\"Vary\"] = \"Accept-Encoding\";\n }\n }\n\n res.writeHead(status, nodeHeaders);\n\n // HEAD requests: send headers only, skip the body\n if (req.method === \"HEAD\") {\n res.end();\n return;\n }\n\n // Convert Web ReadableStream to Node.js Readable and pipe to response.\n // Readable.fromWeb() is available since Node.js 17.\n const nodeStream = Readable.fromWeb(webResponse.body as import(\"stream/web\").ReadableStream);\n\n if (shouldCompress) {\n const compressor = createCompressor(encoding!);\n pipeline(nodeStream, compressor, res, () => { /* ignore pipeline errors on closed connections */ });\n } else {\n pipeline(nodeStream, res, () => { /* ignore pipeline errors on closed connections */ });\n }\n}\n\n/**\n * Start the production server.\n *\n * Automatically detects whether the build is App Router (dist/server/index.js) or\n * Pages Router (dist/server/entry.js) and configures the appropriate handler.\n */\nexport async function startProdServer(options: ProdServerOptions = {}) {\n const {\n port = process.env.PORT ? parseInt(process.env.PORT) : 3000,\n host = \"0.0.0.0\",\n outDir = path.resolve(\"dist\"),\n noCompression = false,\n } = options;\n\n const compress = !noCompression;\n // Always resolve outDir to absolute to ensure dynamic import() works\n const resolvedOutDir = path.resolve(outDir);\n const clientDir = path.join(resolvedOutDir, \"client\");\n\n // Detect build type\n const rscEntryPath = path.join(resolvedOutDir, \"server\", \"index.js\");\n const serverEntryPath = path.join(resolvedOutDir, \"server\", \"entry.js\");\n const isAppRouter = fs.existsSync(rscEntryPath);\n\n if (!isAppRouter && !fs.existsSync(serverEntryPath)) {\n console.error(`[vinext] No build output found in ${outDir}`);\n console.error(\"Run `vinext build` first.\");\n process.exit(1);\n }\n\n if (isAppRouter) {\n return startAppRouterServer({ port, host, clientDir, rscEntryPath, compress });\n }\n\n return startPagesRouterServer({ port, host, clientDir, serverEntryPath, compress });\n}\n\n// ─── App Router Production Server ─────────────────────────────────────────────\n\ninterface AppRouterServerOptions {\n port: number;\n host: string;\n clientDir: string;\n rscEntryPath: string;\n compress: boolean;\n}\n\n/**\n * Start the App Router production server.\n *\n * The RSC entry (dist/server/index.js) exports a default handler function:\n * handler(request: Request) → Promise<Response>\n *\n * This handler already does everything: route matching, RSC rendering,\n * SSR HTML generation (via import(\"./ssr/index.js\")), route handlers,\n * server actions, ISR caching, 404s, redirects, etc.\n *\n * The production server's job is simply to:\n * 1. Serve static assets from dist/client/\n * 2. Convert Node.js IncomingMessage → Web Request\n * 3. Call the RSC handler\n * 4. Stream the Web Response back (with optional compression)\n */\nasync function startAppRouterServer(options: AppRouterServerOptions) {\n const { port, host, clientDir, rscEntryPath, compress } = options;\n\n // Load image config written at build time by vinext:image-config plugin.\n // This provides SVG/security header settings for the image optimization endpoint.\n let imageConfig: ImageConfig | undefined;\n const imageConfigPath = path.join(path.dirname(rscEntryPath), \"image-config.json\");\n if (fs.existsSync(imageConfigPath)) {\n try {\n imageConfig = JSON.parse(fs.readFileSync(imageConfigPath, \"utf-8\"));\n } catch { /* ignore parse errors */ }\n }\n\n // Import the RSC handler (use file:// URL for reliable dynamic import)\n const rscModule = await import(pathToFileURL(rscEntryPath).href);\n const rscHandler: (request: Request) => Promise<Response> = rscModule.default;\n\n if (typeof rscHandler !== \"function\") {\n console.error(\"[vinext] RSC entry does not export a default handler function\");\n process.exit(1);\n }\n\n const server = createServer(async (req, res) => {\n const url = req.url ?? \"/\";\n // Normalize backslashes (browsers treat /\\ as //), then decode and normalize path.\n const rawPathname = url.split(\"?\")[0].replaceAll(\"\\\\\", \"/\");\n let pathname: string;\n try {\n pathname = normalizePath(decodeURIComponent(rawPathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n\n // Guard against protocol-relative URL open redirect attacks.\n // Check rawPathname before normalizePath collapses //.\n if (rawPathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // Serve static assets from client build\n if (pathname !== \"/\" && tryServeStatic(req, res, clientDir, pathname, compress)) {\n return;\n }\n\n // Image optimization passthrough (Node.js prod server has no Images binding;\n // serves the original file with cache headers and security headers)\n if (pathname === IMAGE_OPTIMIZATION_PATH) {\n const parsedUrl = new URL(url, \"http://localhost\");\n const defaultAllowedWidths = [...DEFAULT_DEVICE_SIZES, ...DEFAULT_IMAGE_SIZES];\n const params = parseImageParams(parsedUrl, defaultAllowedWidths);\n if (!params) {\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n // Block SVG and other unsafe content types by checking the file extension.\n // SVG is only allowed when dangerouslyAllowSVG is enabled in next.config.js.\n const ext = path.extname(params.imageUrl).toLowerCase();\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n if (!isSafeImageContentType(ct, imageConfig?.dangerouslyAllowSVG)) {\n res.writeHead(400);\n res.end(\"The requested resource is not an allowed image type\");\n return;\n }\n // Serve the original image with CSP and security headers\n const imageSecurityHeaders: Record<string, string> = {\n \"Content-Security-Policy\": imageConfig?.contentSecurityPolicy ?? IMAGE_CONTENT_SECURITY_POLICY,\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Disposition\": imageConfig?.contentDispositionType ?? \"inline\",\n };\n if (tryServeStatic(req, res, clientDir, params.imageUrl, false, imageSecurityHeaders)) {\n return;\n }\n res.writeHead(404);\n res.end(\"Image not found\");\n return;\n }\n\n try {\n // Convert Node.js request to Web Request and call the RSC handler\n const request = nodeToWebRequest(req);\n const response = await rscHandler(request);\n\n // Stream the Web Response back to the Node.js response\n await sendWebResponse(response, req, res, compress);\n } catch (e) {\n console.error(\"[vinext] Server error:\", e);\n if (!res.headersSent) {\n res.writeHead(500);\n res.end(\"Internal Server Error\");\n }\n }\n });\n\n await new Promise<void>((resolve) => {\n server.listen(port, host, () => {\n const addr = server.address();\n const actualPort = typeof addr === \"object\" && addr ? addr.port : port;\n console.log(`[vinext] Production server running at http://${host}:${actualPort}`);\n resolve();\n });\n });\n\n return server;\n}\n\n// ─── Pages Router Production Server ───────────────────────────────────────────\n\ninterface PagesRouterServerOptions {\n port: number;\n host: string;\n clientDir: string;\n serverEntryPath: string;\n compress: boolean;\n}\n\n/**\n * Start the Pages Router production server.\n *\n * Uses the server entry (dist/server/entry.js) which exports:\n * - renderPage(request, url, manifest) — SSR rendering (Web Request → Response)\n * - handleApiRoute(request, url) — API route handling (Web Request → Response)\n * - runMiddleware(request) — middleware execution\n * - vinextConfig — embedded next.config.js settings\n */\nasync function startPagesRouterServer(options: PagesRouterServerOptions) {\n const { port, host, clientDir, serverEntryPath, compress } = options;\n\n // Load the SSR manifest (maps module URLs to client asset URLs)\n let ssrManifest: Record<string, string[]> = {};\n const manifestPath = path.join(clientDir, \".vite\", \"ssr-manifest.json\");\n if (fs.existsSync(manifestPath)) {\n ssrManifest = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n }\n\n // Load the build manifest to compute lazy chunks — chunks only reachable via\n // dynamic imports (React.lazy, next/dynamic). These should not be\n // modulepreloaded since they are fetched on demand.\n const buildManifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n if (fs.existsSync(buildManifestPath)) {\n try {\n const buildManifest = JSON.parse(fs.readFileSync(buildManifestPath, \"utf-8\"));\n const lazyChunks = computeLazyChunks(buildManifest);\n if (lazyChunks.length > 0) {\n (globalThis as any).__VINEXT_LAZY_CHUNKS__ = lazyChunks;\n }\n } catch { /* ignore parse errors */ }\n }\n\n // Import the server entry module (use file:// URL for reliable dynamic import)\n const serverEntry = await import(pathToFileURL(serverEntryPath).href);\n const { renderPage, handleApiRoute: handleApi, runMiddleware, vinextConfig } = serverEntry;\n\n // Extract config values (embedded at build time in the server entry)\n const basePath: string = vinextConfig?.basePath ?? \"\";\n const trailingSlash: boolean = vinextConfig?.trailingSlash ?? false;\n const configRedirects = vinextConfig?.redirects ?? [];\n const configRewrites = vinextConfig?.rewrites ?? { beforeFiles: [], afterFiles: [], fallback: [] };\n const configHeaders = vinextConfig?.headers ?? [];\n // Compute allowed image widths from config (union of deviceSizes + imageSizes)\n const allowedImageWidths: number[] = [\n ...(vinextConfig?.images?.deviceSizes ?? DEFAULT_DEVICE_SIZES),\n ...(vinextConfig?.images?.imageSizes ?? DEFAULT_IMAGE_SIZES),\n ];\n // Extract image security config for SVG handling and security headers\n const pagesImageConfig: ImageConfig | undefined = vinextConfig?.images ? {\n dangerouslyAllowSVG: vinextConfig.images.dangerouslyAllowSVG,\n contentDispositionType: vinextConfig.images.contentDispositionType,\n contentSecurityPolicy: vinextConfig.images.contentSecurityPolicy,\n } : undefined;\n\n const server = createServer(async (req, res) => {\n const rawUrl = req.url ?? \"/\";\n // Normalize backslashes (browsers treat /\\ as //), then decode and normalize path.\n // Rebuild `url` from the decoded pathname + original query string so all\n // downstream consumers (resolvedUrl, resolvedPathname, config matchers)\n // always work with the decoded, canonical path.\n const rawPagesPathname = rawUrl.split(\"?\")[0].replaceAll(\"\\\\\", \"/\");\n const rawQs = rawUrl.includes(\"?\") ? rawUrl.slice(rawUrl.indexOf(\"?\")) : \"\";\n let pathname: string;\n try {\n pathname = normalizePath(decodeURIComponent(rawPagesPathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n let url = pathname + rawQs;\n\n // Guard against protocol-relative URL open redirect attacks.\n // Check rawPagesPathname before normalizePath collapses //.\n if (rawPagesPathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // ── 1. Static assets ──────────────────────────────────────────\n // Serve static files from client build. When basePath is configured,\n // Vite's `base` config ensures assets are under basePath/assets/.\n // We check both with and without basePath.\n const staticLookupPath = basePath && pathname.startsWith(basePath)\n ? pathname.slice(basePath.length) || \"/\"\n : pathname;\n if (\n staticLookupPath !== \"/\" &&\n !staticLookupPath.startsWith(\"/api/\") &&\n tryServeStatic(req, res, clientDir, staticLookupPath, compress)\n ) {\n return;\n }\n\n // ── Image optimization passthrough ──────────────────────────────\n if (pathname === IMAGE_OPTIMIZATION_PATH || staticLookupPath === IMAGE_OPTIMIZATION_PATH) {\n const parsedUrl = new URL(rawUrl, \"http://localhost\");\n const params = parseImageParams(parsedUrl, allowedImageWidths);\n if (!params) {\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n // Block SVG and other unsafe content types.\n // SVG is only allowed when dangerouslyAllowSVG is enabled.\n const ext = path.extname(params.imageUrl).toLowerCase();\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n if (!isSafeImageContentType(ct, pagesImageConfig?.dangerouslyAllowSVG)) {\n res.writeHead(400);\n res.end(\"The requested resource is not an allowed image type\");\n return;\n }\n const imageSecurityHeaders: Record<string, string> = {\n \"Content-Security-Policy\": pagesImageConfig?.contentSecurityPolicy ?? IMAGE_CONTENT_SECURITY_POLICY,\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Disposition\": pagesImageConfig?.contentDispositionType ?? \"inline\",\n };\n if (tryServeStatic(req, res, clientDir, params.imageUrl, false, imageSecurityHeaders)) {\n return;\n }\n res.writeHead(404);\n res.end(\"Image not found\");\n return;\n }\n\n try {\n // ── 2. Strip basePath ─────────────────────────────────────────\n if (basePath && pathname.startsWith(basePath)) {\n const stripped = pathname.slice(basePath.length) || \"/\";\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = stripped + qs;\n pathname = stripped;\n }\n\n // ── 3. Trailing slash normalization ───────────────────────────\n if (pathname !== \"/\" && !pathname.startsWith(\"/api\")) {\n const hasTrailing = pathname.endsWith(\"/\");\n if (trailingSlash && !hasTrailing) {\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n res.writeHead(308, { Location: basePath + pathname + \"/\" + qs });\n res.end();\n return;\n } else if (!trailingSlash && hasTrailing) {\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n res.writeHead(308, { Location: basePath + pathname.replace(/\\/+$/, \"\") + qs });\n res.end();\n return;\n }\n }\n\n // Convert Node.js req to Web Request for the server entry\n const rawProtocol = trustProxy\n ? (req.headers[\"x-forwarded-proto\"] as string)?.split(\",\")[0]?.trim()\n : undefined;\n const protocol = rawProtocol === \"https\" || rawProtocol === \"http\" ? rawProtocol : \"http\";\n const hostHeader = resolveHost(req, `${host}:${port}`);\n const reqHeaders = Object.entries(req.headers).reduce((h, [k, v]) => {\n if (v) h.set(k, Array.isArray(v) ? v.join(\", \") : v);\n return h;\n }, new Headers());\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const webRequest = new Request(`${protocol}://${hostHeader}${url}`, {\n method,\n headers: reqHeaders,\n body: hasBody ? readNodeStream(req) : undefined,\n // @ts-expect-error — duplex needed for streaming request bodies\n duplex: hasBody ? \"half\" : undefined,\n });\n\n // Build request context for has/missing condition matching\n const reqCtx: RequestContext = requestContextFromRequest(webRequest);\n\n // ── 4. Run middleware ─────────────────────────────────────────\n let resolvedUrl = url;\n const middlewareHeaders: Record<string, string> = {};\n let middlewareRewriteStatus: number | undefined;\n if (typeof runMiddleware === \"function\") {\n const result = await runMiddleware(webRequest);\n\n if (!result.continue) {\n if (result.redirectUrl) {\n res.writeHead(result.redirectStatus ?? 307, {\n Location: result.redirectUrl,\n });\n res.end();\n return;\n }\n if (result.response) {\n // Use arrayBuffer() to handle binary response bodies correctly\n const body = Buffer.from(await result.response.arrayBuffer());\n // Preserve multi-value headers (especially Set-Cookie) by\n // using getSetCookie() for cookies and forEach for the rest.\n const respHeaders: Record<string, string | string[]> = {};\n result.response.headers.forEach((value: string, key: string) => {\n if (key.toLowerCase() === \"set-cookie\") return; // handled below\n respHeaders[key] = value;\n });\n const setCookies = result.response.headers.getSetCookie?.() ?? [];\n if (setCookies.length > 0) respHeaders[\"set-cookie\"] = setCookies;\n res.writeHead(result.response.status, respHeaders);\n res.end(body);\n return;\n }\n }\n\n // Collect middleware response headers to merge into final response.\n // Use an array for Set-Cookie to preserve multiple values.\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n const existing = middlewareHeaders[key];\n if (Array.isArray(existing)) {\n existing.push(value);\n } else if (existing) {\n (middlewareHeaders as any)[key] = [existing, value];\n } else {\n (middlewareHeaders as any)[key] = [value];\n }\n } else {\n middlewareHeaders[key] = value;\n }\n }\n }\n\n // Apply middleware rewrite\n if (result.rewriteUrl) {\n resolvedUrl = result.rewriteUrl;\n }\n\n // Apply custom status code from middleware rewrite\n // (e.g. NextResponse.rewrite(url, { status: 403 }))\n middlewareRewriteStatus = result.rewriteStatus;\n }\n\n // Unpack x-middleware-request-* headers into the actual request so that\n // renderPage / handleApiRoute see the middleware-modified headers.\n // Strip ALL x-middleware-* headers from the response — this prefix is\n // reserved for internal routing signals and must never reach clients.\n // (Matches Next.js behavior where x-middleware-* headers are internal.)\n const mwReqPrefix = \"x-middleware-request-\";\n for (const key of Object.keys(middlewareHeaders)) {\n if (key.startsWith(mwReqPrefix)) {\n const realName = key.slice(mwReqPrefix.length);\n webRequest.headers.set(realName, middlewareHeaders[key]);\n delete middlewareHeaders[key];\n } else if (key.startsWith(\"x-middleware-\")) {\n delete middlewareHeaders[key];\n }\n }\n\n let resolvedPathname = resolvedUrl.split(\"?\")[0];\n\n // ── 5. Apply custom headers from next.config.js ───────────────\n if (configHeaders.length) {\n const matched = matchHeaders(resolvedPathname, configHeaders, reqCtx);\n for (const h of matched) {\n middlewareHeaders[h.key.toLowerCase()] = h.value;\n }\n }\n\n // ── 6. Apply redirects from next.config.js ────────────────────\n if (configRedirects.length) {\n const redirect = matchRedirect(resolvedPathname, configRedirects, reqCtx);\n if (redirect) {\n // Guard against double-prefixing: only add basePath if destination\n // doesn't already start with it.\n // Sanitize the final destination to prevent protocol-relative URL open redirects.\n const dest = sanitizeDestination(\n basePath && !redirect.destination.startsWith(basePath)\n ? basePath + redirect.destination\n : redirect.destination,\n );\n res.writeHead(redirect.permanent ? 308 : 307, { Location: dest });\n res.end();\n return;\n }\n }\n\n // ── 7. Apply beforeFiles rewrites from next.config.js ─────────\n if (configRewrites.beforeFiles?.length) {\n const rewritten = matchRewrite(resolvedPathname, configRewrites.beforeFiles, reqCtx);\n if (rewritten) {\n if (isExternalUrl(rewritten)) {\n const proxyResponse = await proxyExternalRequest(webRequest, rewritten);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n resolvedUrl = rewritten;\n resolvedPathname = rewritten.split(\"?\")[0];\n }\n }\n\n // ── 8. API routes ─────────────────────────────────────────────\n if (resolvedPathname.startsWith(\"/api/\") || resolvedPathname === \"/api\") {\n let response: Response;\n if (typeof handleApi === \"function\") {\n response = await handleApi(webRequest, resolvedUrl);\n } else {\n response = new Response(\"404 - API route not found\", { status: 404 });\n }\n\n // Merge middleware + config headers into the response\n const responseBody = Buffer.from(await response.arrayBuffer());\n const ct = response.headers.get(\"content-type\") ?? \"text/html\";\n const responseHeaders: Record<string, string> = { ...middlewareHeaders };\n response.headers.forEach((v, k) => { responseHeaders[k] = v; });\n\n sendCompressed(req, res, responseBody, ct, middlewareRewriteStatus ?? response.status, responseHeaders, compress);\n return;\n }\n\n // ── 9. Apply afterFiles rewrites from next.config.js ──────────\n if (configRewrites.afterFiles?.length) {\n const rewritten = matchRewrite(resolvedPathname, configRewrites.afterFiles, reqCtx);\n if (rewritten) {\n if (isExternalUrl(rewritten)) {\n const proxyResponse = await proxyExternalRequest(webRequest, rewritten);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n resolvedUrl = rewritten;\n resolvedPathname = rewritten.split(\"?\")[0];\n }\n }\n\n // ── 10. SSR page rendering ────────────────────────────────────\n let response: Response | undefined;\n if (typeof renderPage === \"function\") {\n response = await renderPage(webRequest, resolvedUrl, ssrManifest);\n\n // ── 11. Fallback rewrites (if SSR returned 404) ─────────────\n if (response && response.status === 404 && configRewrites.fallback?.length) {\n const fallbackRewrite = matchRewrite(resolvedPathname, configRewrites.fallback, reqCtx);\n if (fallbackRewrite) {\n if (isExternalUrl(fallbackRewrite)) {\n const proxyResponse = await proxyExternalRequest(webRequest, fallbackRewrite);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n response = await renderPage(webRequest, fallbackRewrite, ssrManifest);\n }\n }\n }\n\n if (!response) {\n res.writeHead(404);\n res.end(\"404 - Not found\");\n return;\n }\n\n // Merge middleware + config headers into the response\n const responseBody = Buffer.from(await response.arrayBuffer());\n const ct = response.headers.get(\"content-type\") ?? \"text/html\";\n const responseHeaders: Record<string, string> = { ...middlewareHeaders };\n response.headers.forEach((v, k) => { responseHeaders[k] = v; });\n\n sendCompressed(req, res, responseBody, ct, middlewareRewriteStatus ?? response.status, responseHeaders, compress);\n } catch (e) {\n console.error(\"[vinext] Server error:\", e);\n res.writeHead(500);\n res.end(\"Internal Server Error\");\n }\n });\n\n await new Promise<void>((resolve) => {\n server.listen(port, host, () => {\n const addr = server.address();\n const actualPort = typeof addr === \"object\" && addr ? addr.port : port;\n console.log(`[vinext] Production server running at http://${host}:${actualPort}`);\n resolve();\n });\n });\n\n return server;\n}\n\n// Export helpers for testing\nexport { sendCompressed, negotiateEncoding, COMPRESSIBLE_TYPES, COMPRESS_THRESHOLD, resolveHost, trustedHosts, trustProxy, nodeToWebRequest };\n"]}
1
+ {"version":3,"file":"prod-server.js","sourceRoot":"","sources":["../../src/server/prod-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;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C,EAAE,EAAE,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAEhE,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,EAAE,uBAAuB,IAAI,QAAQ,CAAC,MAAM,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC;QACpH,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,CAAC,CAAC,CAAC;YAC3C,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACnB,GAAG,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;QACnC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QAClC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE;YAC7B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YACvE,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,IAAI,UAAU,EAAE,CAAC,CAAC;YAClF,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,6BAA6B;AAC7B,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,CAAC","sourcesContent":["/**\n * Production server for vinext.\n *\n * Serves the built output from `vinext build`. Handles:\n * - Static asset serving from client build output\n * - Pages Router: SSR rendering + API route handling\n * - App Router: RSC/SSR rendering, route handlers, server actions\n * - Gzip/Brotli compression for text-based responses\n * - Streaming SSR for App Router\n *\n * Build output for Pages Router:\n * - dist/client/ — static assets (JS, CSS, images) + .vite/ssr-manifest.json\n * - dist/server/entry.js — SSR entry point (virtual:vinext-server-entry)\n *\n * Build output for App Router:\n * - dist/client/ — static assets (JS, CSS, images)\n * - dist/server/index.js — RSC entry (default export: handler(Request) → Response)\n * - dist/server/ssr/index.js — SSR entry (imported by RSC entry at runtime)\n */\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { Readable, pipeline } from \"node:stream\";\nimport { pathToFileURL } from \"node:url\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport zlib from \"node:zlib\";\nimport { matchRedirect, matchRewrite, matchHeaders, requestContextFromRequest, isExternalUrl, proxyExternalRequest, sanitizeDestination } from \"../config/config-matchers.js\";\nimport type { RequestContext } from \"../config/config-matchers.js\";\nimport { IMAGE_OPTIMIZATION_PATH, IMAGE_CONTENT_SECURITY_POLICY, parseImageParams, isSafeImageContentType, DEFAULT_DEVICE_SIZES, DEFAULT_IMAGE_SIZES, type ImageConfig } from \"./image-optimization.js\";\nimport { normalizePath } from \"./normalize-path.js\";\nimport { computeLazyChunks } from \"../index.js\";\n\n/** Convert a Node.js IncomingMessage into a ReadableStream for Web Request body. */\nfunction readNodeStream(req: IncomingMessage): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n req.on(\"data\", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));\n req.on(\"end\", () => controller.close());\n req.on(\"error\", (err) => controller.error(err));\n },\n });\n}\n\nexport interface ProdServerOptions {\n /** Port to listen on */\n port?: number;\n /** Host to bind to */\n host?: string;\n /** Path to the build output directory */\n outDir?: string;\n /** Disable compression (default: false) */\n noCompression?: boolean;\n}\n\n/** Content types that benefit from compression. */\nconst COMPRESSIBLE_TYPES = new Set([\n \"text/html\",\n \"text/css\",\n \"text/plain\",\n \"text/xml\",\n \"text/javascript\",\n \"application/javascript\",\n \"application/json\",\n \"application/xml\",\n \"application/xhtml+xml\",\n \"application/rss+xml\",\n \"application/atom+xml\",\n \"image/svg+xml\",\n \"application/manifest+json\",\n \"application/wasm\",\n]);\n\n/** Minimum size threshold for compression (in bytes). Below this, compression overhead isn't worth it. */\nconst COMPRESS_THRESHOLD = 1024;\n\n/**\n * Parse the Accept-Encoding header and return the best supported encoding.\n * Preference order: br > gzip > deflate > identity.\n */\nfunction negotiateEncoding(req: IncomingMessage): \"br\" | \"gzip\" | \"deflate\" | null {\n const accept = req.headers[\"accept-encoding\"];\n if (!accept || typeof accept !== \"string\") return null;\n const lower = accept.toLowerCase();\n if (lower.includes(\"br\")) return \"br\";\n if (lower.includes(\"gzip\")) return \"gzip\";\n if (lower.includes(\"deflate\")) return \"deflate\";\n return null;\n}\n\n/**\n * Create a compression stream for the given encoding.\n */\nfunction createCompressor(encoding: \"br\" | \"gzip\" | \"deflate\"): zlib.BrotliCompress | zlib.Gzip | zlib.Deflate {\n switch (encoding) {\n case \"br\":\n return zlib.createBrotliCompress({\n params: {\n [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // Fast compression (1-11, 4 is a good balance)\n },\n });\n case \"gzip\":\n return zlib.createGzip({ level: 6 }); // Default level, good balance\n case \"deflate\":\n return zlib.createDeflate({ level: 6 });\n }\n}\n\n/**\n * Send a compressed response if the content type is compressible and the\n * client supports compression. Otherwise send uncompressed.\n */\nfunction sendCompressed(\n req: IncomingMessage,\n res: ServerResponse,\n body: string | Buffer,\n contentType: string,\n statusCode: number,\n extraHeaders: Record<string, string> = {},\n compress: boolean = true,\n): void {\n const buf = typeof body === \"string\" ? Buffer.from(body) : body;\n const baseType = contentType.split(\";\")[0].trim();\n const encoding = compress ? negotiateEncoding(req) : null;\n\n if (encoding && COMPRESSIBLE_TYPES.has(baseType) && buf.length >= COMPRESS_THRESHOLD) {\n const compressor = createCompressor(encoding);\n // Merge Accept-Encoding into existing Vary header from extraHeaders instead\n // of overwriting. Preserves Vary values set by the App Router for content\n // negotiation (e.g. \"RSC, Accept\").\n const existingVary = extraHeaders[\"Vary\"] ?? extraHeaders[\"vary\"];\n let varyValue: string;\n if (existingVary) {\n const existing = String(existingVary).toLowerCase();\n varyValue = existing.includes(\"accept-encoding\") ? String(existingVary) : existingVary + \", Accept-Encoding\";\n } else {\n varyValue = \"Accept-Encoding\";\n }\n res.writeHead(statusCode, {\n ...extraHeaders,\n \"Content-Type\": contentType,\n \"Content-Encoding\": encoding,\n Vary: varyValue,\n });\n compressor.end(buf);\n pipeline(compressor, res, () => { /* ignore pipeline errors on closed connections */ });\n } else {\n res.writeHead(statusCode, {\n ...extraHeaders,\n \"Content-Type\": contentType,\n \"Content-Length\": String(buf.length),\n });\n res.end(buf);\n }\n}\n\n/** Content-type lookup for static assets. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"application/javascript\",\n \".mjs\": \"application/javascript\",\n \".css\": \"text/css\",\n \".html\": \"text/html\",\n \".json\": \"application/json\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".map\": \"application/json\",\n};\n\n/**\n * Try to serve a static file from the client build directory.\n * Returns true if the file was served, false otherwise.\n */\nfunction tryServeStatic(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n pathname: string,\n compress: boolean,\n extraHeaders?: Record<string, string>,\n): boolean {\n // Resolve the path and guard against directory traversal (e.g. /../../../etc/passwd)\n const resolvedClient = path.resolve(clientDir);\n let decodedPathname: string;\n try {\n decodedPathname = decodeURIComponent(pathname);\n } catch {\n return false;\n }\n\n // Block access to internal build metadata directories. The .vite/\n // directory contains manifests and other build artifacts that should\n // not be publicly served. Check after decoding to catch encoded\n // variants like /%2Evite/manifest.json.\n if (decodedPathname.startsWith(\"/.vite/\") || decodedPathname === \"/.vite\") {\n return false;\n }\n const staticFile = path.resolve(clientDir, \".\" + decodedPathname);\n if (!staticFile.startsWith(resolvedClient + path.sep) && staticFile !== resolvedClient) {\n return false;\n }\n if (\n pathname === \"/\" ||\n !fs.existsSync(staticFile) ||\n !fs.statSync(staticFile).isFile()\n ) {\n return false;\n }\n\n const ext = path.extname(staticFile);\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n const isHashed = pathname.startsWith(\"/assets/\");\n const cacheControl = isHashed\n ? \"public, max-age=31536000, immutable\"\n : \"public, max-age=3600\";\n\n const baseHeaders = {\n \"Content-Type\": ct,\n \"Cache-Control\": cacheControl,\n ...extraHeaders,\n };\n\n const baseType = ct.split(\";\")[0].trim();\n if (compress && COMPRESSIBLE_TYPES.has(baseType)) {\n const encoding = negotiateEncoding(req);\n if (encoding) {\n const fileStream = fs.createReadStream(staticFile);\n const compressor = createCompressor(encoding);\n res.writeHead(200, {\n ...baseHeaders,\n \"Content-Encoding\": encoding,\n Vary: \"Accept-Encoding\",\n });\n pipeline(fileStream, compressor, res, () => { /* ignore */ });\n return true;\n }\n }\n\n res.writeHead(200, baseHeaders);\n fs.createReadStream(staticFile).pipe(res);\n return true;\n}\n\n/**\n * Resolve the host for a request, ignoring X-Forwarded-Host to prevent\n * host header poisoning attacks (open redirects, cache poisoning).\n *\n * X-Forwarded-Host is only trusted when the VINEXT_TRUSTED_HOSTS env var\n * lists the forwarded host value. Without this, an attacker can send\n * X-Forwarded-Host: evil.com and poison any redirect that resolves\n * against request.url.\n *\n * On Cloudflare Workers, X-Forwarded-Host is always set by Cloudflare\n * itself, so this is only a concern for the Node.js prod-server.\n */\nfunction resolveHost(req: IncomingMessage, fallback: string): string {\n const rawForwarded = req.headers[\"x-forwarded-host\"] as string | undefined;\n const hostHeader = req.headers.host;\n\n if (rawForwarded) {\n // X-Forwarded-Host can be comma-separated when passing through\n // multiple proxies — take only the first (client-facing) value.\n const forwardedHost = rawForwarded.split(\",\")[0].trim().toLowerCase();\n if (forwardedHost && trustedHosts.has(forwardedHost)) {\n return forwardedHost;\n }\n }\n\n return hostHeader || fallback;\n}\n\n/** Hosts that are allowed as X-Forwarded-Host values (stored lowercase). */\nconst trustedHosts: Set<string> = new Set(\n (process.env.VINEXT_TRUSTED_HOSTS ?? \"\")\n .split(\",\")\n .map((h) => h.trim().toLowerCase())\n .filter(Boolean),\n);\n\n/**\n * Whether to trust X-Forwarded-Proto from upstream proxies.\n * Enabled when VINEXT_TRUST_PROXY=1 or when VINEXT_TRUSTED_HOSTS is set\n * (having trusted hosts implies a trusted proxy).\n */\nconst trustProxy = process.env.VINEXT_TRUST_PROXY === \"1\" || trustedHosts.size > 0;\n\n/**\n * Convert a Node.js IncomingMessage to a Web Request object.\n */\nfunction nodeToWebRequest(req: IncomingMessage): Request {\n const rawProto = trustProxy\n ? (req.headers[\"x-forwarded-proto\"] as string)?.split(\",\")[0]?.trim()\n : undefined;\n const proto = rawProto === \"https\" || rawProto === \"http\" ? rawProto : \"http\";\n const host = resolveHost(req, \"localhost\");\n const origin = `${proto}://${host}`;\n const url = new URL(req.url ?? \"/\", origin);\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n };\n\n if (hasBody) {\n // Convert Node.js readable stream to Web ReadableStream for request body.\n // Readable.toWeb() is available since Node.js 17.\n init.body = Readable.toWeb(req) as ReadableStream;\n init.duplex = \"half\"; // Required for streaming request bodies\n }\n\n return new Request(url, init);\n}\n\n/**\n * Stream a Web Response back to a Node.js ServerResponse.\n * Supports streaming compression for SSR responses.\n */\nasync function sendWebResponse(\n webResponse: Response,\n req: IncomingMessage,\n res: ServerResponse,\n compress: boolean,\n): Promise<void> {\n const status = webResponse.status;\n\n // Collect headers, handling multi-value headers (e.g. Set-Cookie)\n const nodeHeaders: Record<string, string | string[]> = {};\n webResponse.headers.forEach((value, key) => {\n const existing = nodeHeaders[key];\n if (existing !== undefined) {\n nodeHeaders[key] = Array.isArray(existing)\n ? [...existing, value]\n : [existing, value];\n } else {\n nodeHeaders[key] = value;\n }\n });\n\n if (!webResponse.body) {\n res.writeHead(status, nodeHeaders);\n res.end();\n return;\n }\n\n // Check if we should compress the response.\n // Skip if the upstream already compressed (avoid double-compression).\n const alreadyEncoded = webResponse.headers.has(\"content-encoding\");\n const contentType = webResponse.headers.get(\"content-type\") ?? \"\";\n const baseType = contentType.split(\";\")[0].trim();\n const encoding = (compress && !alreadyEncoded) ? negotiateEncoding(req) : null;\n const shouldCompress = !!(encoding && COMPRESSIBLE_TYPES.has(baseType));\n\n if (shouldCompress) {\n delete nodeHeaders[\"content-length\"];\n delete nodeHeaders[\"Content-Length\"];\n nodeHeaders[\"Content-Encoding\"] = encoding!;\n // Merge Accept-Encoding into existing Vary header (e.g. \"RSC, Accept\") instead\n // of overwriting. This prevents stripping the Vary values that the App Router\n // sets for content negotiation (RSC stream vs HTML).\n const existingVary = nodeHeaders[\"Vary\"] ?? nodeHeaders[\"vary\"];\n if (existingVary) {\n const existing = String(existingVary).toLowerCase();\n if (!existing.includes(\"accept-encoding\")) {\n nodeHeaders[\"Vary\"] = existingVary + \", Accept-Encoding\";\n }\n } else {\n nodeHeaders[\"Vary\"] = \"Accept-Encoding\";\n }\n }\n\n res.writeHead(status, nodeHeaders);\n\n // HEAD requests: send headers only, skip the body\n if (req.method === \"HEAD\") {\n res.end();\n return;\n }\n\n // Convert Web ReadableStream to Node.js Readable and pipe to response.\n // Readable.fromWeb() is available since Node.js 17.\n const nodeStream = Readable.fromWeb(webResponse.body as import(\"stream/web\").ReadableStream);\n\n if (shouldCompress) {\n const compressor = createCompressor(encoding!);\n pipeline(nodeStream, compressor, res, () => { /* ignore pipeline errors on closed connections */ });\n } else {\n pipeline(nodeStream, res, () => { /* ignore pipeline errors on closed connections */ });\n }\n}\n\n/**\n * Start the production server.\n *\n * Automatically detects whether the build is App Router (dist/server/index.js) or\n * Pages Router (dist/server/entry.js) and configures the appropriate handler.\n */\nexport async function startProdServer(options: ProdServerOptions = {}) {\n const {\n port = process.env.PORT ? parseInt(process.env.PORT) : 3000,\n host = \"0.0.0.0\",\n outDir = path.resolve(\"dist\"),\n noCompression = false,\n } = options;\n\n const compress = !noCompression;\n // Always resolve outDir to absolute to ensure dynamic import() works\n const resolvedOutDir = path.resolve(outDir);\n const clientDir = path.join(resolvedOutDir, \"client\");\n\n // Detect build type\n const rscEntryPath = path.join(resolvedOutDir, \"server\", \"index.js\");\n const serverEntryPath = path.join(resolvedOutDir, \"server\", \"entry.js\");\n const isAppRouter = fs.existsSync(rscEntryPath);\n\n if (!isAppRouter && !fs.existsSync(serverEntryPath)) {\n console.error(`[vinext] No build output found in ${outDir}`);\n console.error(\"Run `vinext build` first.\");\n process.exit(1);\n }\n\n if (isAppRouter) {\n return startAppRouterServer({ port, host, clientDir, rscEntryPath, compress });\n }\n\n return startPagesRouterServer({ port, host, clientDir, serverEntryPath, compress });\n}\n\n// ─── App Router Production Server ─────────────────────────────────────────────\n\ninterface AppRouterServerOptions {\n port: number;\n host: string;\n clientDir: string;\n rscEntryPath: string;\n compress: boolean;\n}\n\n/**\n * Start the App Router production server.\n *\n * The RSC entry (dist/server/index.js) exports a default handler function:\n * handler(request: Request) → Promise<Response>\n *\n * This handler already does everything: route matching, RSC rendering,\n * SSR HTML generation (via import(\"./ssr/index.js\")), route handlers,\n * server actions, ISR caching, 404s, redirects, etc.\n *\n * The production server's job is simply to:\n * 1. Serve static assets from dist/client/\n * 2. Convert Node.js IncomingMessage → Web Request\n * 3. Call the RSC handler\n * 4. Stream the Web Response back (with optional compression)\n */\nasync function startAppRouterServer(options: AppRouterServerOptions) {\n const { port, host, clientDir, rscEntryPath, compress } = options;\n\n // Load image config written at build time by vinext:image-config plugin.\n // This provides SVG/security header settings for the image optimization endpoint.\n let imageConfig: ImageConfig | undefined;\n const imageConfigPath = path.join(path.dirname(rscEntryPath), \"image-config.json\");\n if (fs.existsSync(imageConfigPath)) {\n try {\n imageConfig = JSON.parse(fs.readFileSync(imageConfigPath, \"utf-8\"));\n } catch { /* ignore parse errors */ }\n }\n\n // Import the RSC handler (use file:// URL for reliable dynamic import)\n const rscModule = await import(pathToFileURL(rscEntryPath).href);\n const rscHandler: (request: Request) => Promise<Response> = rscModule.default;\n\n if (typeof rscHandler !== \"function\") {\n console.error(\"[vinext] RSC entry does not export a default handler function\");\n process.exit(1);\n }\n\n const server = createServer(async (req, res) => {\n const url = req.url ?? \"/\";\n // Normalize backslashes (browsers treat /\\ as //), then decode and normalize path.\n const rawPathname = url.split(\"?\")[0].replaceAll(\"\\\\\", \"/\");\n let pathname: string;\n try {\n pathname = normalizePath(decodeURIComponent(rawPathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n\n // Guard against protocol-relative URL open redirect attacks.\n // Check rawPathname before normalizePath collapses //.\n if (rawPathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // Serve static assets from client build\n if (pathname !== \"/\" && tryServeStatic(req, res, clientDir, pathname, compress)) {\n return;\n }\n\n // Image optimization passthrough (Node.js prod server has no Images binding;\n // serves the original file with cache headers and security headers)\n if (pathname === IMAGE_OPTIMIZATION_PATH) {\n const parsedUrl = new URL(url, \"http://localhost\");\n const defaultAllowedWidths = [...DEFAULT_DEVICE_SIZES, ...DEFAULT_IMAGE_SIZES];\n const params = parseImageParams(parsedUrl, defaultAllowedWidths);\n if (!params) {\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n // Block SVG and other unsafe content types by checking the file extension.\n // SVG is only allowed when dangerouslyAllowSVG is enabled in next.config.js.\n const ext = path.extname(params.imageUrl).toLowerCase();\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n if (!isSafeImageContentType(ct, imageConfig?.dangerouslyAllowSVG)) {\n res.writeHead(400);\n res.end(\"The requested resource is not an allowed image type\");\n return;\n }\n // Serve the original image with CSP and security headers\n const imageSecurityHeaders: Record<string, string> = {\n \"Content-Security-Policy\": imageConfig?.contentSecurityPolicy ?? IMAGE_CONTENT_SECURITY_POLICY,\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Disposition\": imageConfig?.contentDispositionType ?? \"inline\",\n };\n if (tryServeStatic(req, res, clientDir, params.imageUrl, false, imageSecurityHeaders)) {\n return;\n }\n res.writeHead(404);\n res.end(\"Image not found\");\n return;\n }\n\n try {\n // Convert Node.js request to Web Request and call the RSC handler\n const request = nodeToWebRequest(req);\n const response = await rscHandler(request);\n\n // Stream the Web Response back to the Node.js response\n await sendWebResponse(response, req, res, compress);\n } catch (e) {\n console.error(\"[vinext] Server error:\", e);\n if (!res.headersSent) {\n res.writeHead(500);\n res.end(\"Internal Server Error\");\n }\n }\n });\n\n await new Promise<void>((resolve) => {\n server.listen(port, host, () => {\n const addr = server.address();\n const actualPort = typeof addr === \"object\" && addr ? addr.port : port;\n console.log(`[vinext] Production server running at http://${host}:${actualPort}`);\n resolve();\n });\n });\n\n return server;\n}\n\n// ─── Pages Router Production Server ───────────────────────────────────────────\n\ninterface PagesRouterServerOptions {\n port: number;\n host: string;\n clientDir: string;\n serverEntryPath: string;\n compress: boolean;\n}\n\n/**\n * Start the Pages Router production server.\n *\n * Uses the server entry (dist/server/entry.js) which exports:\n * - renderPage(request, url, manifest) — SSR rendering (Web Request → Response)\n * - handleApiRoute(request, url) — API route handling (Web Request → Response)\n * - runMiddleware(request) — middleware execution\n * - vinextConfig — embedded next.config.js settings\n */\nasync function startPagesRouterServer(options: PagesRouterServerOptions) {\n const { port, host, clientDir, serverEntryPath, compress } = options;\n\n // Load the SSR manifest (maps module URLs to client asset URLs)\n let ssrManifest: Record<string, string[]> = {};\n const manifestPath = path.join(clientDir, \".vite\", \"ssr-manifest.json\");\n if (fs.existsSync(manifestPath)) {\n ssrManifest = JSON.parse(fs.readFileSync(manifestPath, \"utf-8\"));\n }\n\n // Load the build manifest to compute lazy chunks — chunks only reachable via\n // dynamic imports (React.lazy, next/dynamic). These should not be\n // modulepreloaded since they are fetched on demand.\n const buildManifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n if (fs.existsSync(buildManifestPath)) {\n try {\n const buildManifest = JSON.parse(fs.readFileSync(buildManifestPath, \"utf-8\"));\n const lazyChunks = computeLazyChunks(buildManifest);\n if (lazyChunks.length > 0) {\n (globalThis as any).__VINEXT_LAZY_CHUNKS__ = lazyChunks;\n }\n } catch { /* ignore parse errors */ }\n }\n\n // Import the server entry module (use file:// URL for reliable dynamic import)\n const serverEntry = await import(pathToFileURL(serverEntryPath).href);\n const { renderPage, handleApiRoute: handleApi, runMiddleware, vinextConfig } = serverEntry;\n\n // Extract config values (embedded at build time in the server entry)\n const basePath: string = vinextConfig?.basePath ?? \"\";\n const trailingSlash: boolean = vinextConfig?.trailingSlash ?? false;\n const configRedirects = vinextConfig?.redirects ?? [];\n const configRewrites = vinextConfig?.rewrites ?? { beforeFiles: [], afterFiles: [], fallback: [] };\n const configHeaders = vinextConfig?.headers ?? [];\n // Compute allowed image widths from config (union of deviceSizes + imageSizes)\n const allowedImageWidths: number[] = [\n ...(vinextConfig?.images?.deviceSizes ?? DEFAULT_DEVICE_SIZES),\n ...(vinextConfig?.images?.imageSizes ?? DEFAULT_IMAGE_SIZES),\n ];\n // Extract image security config for SVG handling and security headers\n const pagesImageConfig: ImageConfig | undefined = vinextConfig?.images ? {\n dangerouslyAllowSVG: vinextConfig.images.dangerouslyAllowSVG,\n contentDispositionType: vinextConfig.images.contentDispositionType,\n contentSecurityPolicy: vinextConfig.images.contentSecurityPolicy,\n } : undefined;\n\n const server = createServer(async (req, res) => {\n const rawUrl = req.url ?? \"/\";\n // Normalize backslashes (browsers treat /\\ as //), then decode and normalize path.\n // Rebuild `url` from the decoded pathname + original query string so all\n // downstream consumers (resolvedUrl, resolvedPathname, config matchers)\n // always work with the decoded, canonical path.\n const rawPagesPathname = rawUrl.split(\"?\")[0].replaceAll(\"\\\\\", \"/\");\n const rawQs = rawUrl.includes(\"?\") ? rawUrl.slice(rawUrl.indexOf(\"?\")) : \"\";\n let pathname: string;\n try {\n pathname = normalizePath(decodeURIComponent(rawPagesPathname));\n } catch {\n // Malformed percent-encoding (e.g. /%E0%A4%A) — return 400 instead of crashing.\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n let url = pathname + rawQs;\n\n // Guard against protocol-relative URL open redirect attacks.\n // Check rawPagesPathname before normalizePath collapses //.\n if (rawPagesPathname.startsWith(\"//\")) {\n res.writeHead(404);\n res.end(\"404 Not Found\");\n return;\n }\n\n // ── 1. Static assets ──────────────────────────────────────────\n // Serve static files from client build. When basePath is configured,\n // Vite's `base` config ensures assets are under basePath/assets/.\n // We check both with and without basePath.\n const staticLookupPath = basePath && pathname.startsWith(basePath)\n ? pathname.slice(basePath.length) || \"/\"\n : pathname;\n if (\n staticLookupPath !== \"/\" &&\n !staticLookupPath.startsWith(\"/api/\") &&\n tryServeStatic(req, res, clientDir, staticLookupPath, compress)\n ) {\n return;\n }\n\n // ── Image optimization passthrough ──────────────────────────────\n if (pathname === IMAGE_OPTIMIZATION_PATH || staticLookupPath === IMAGE_OPTIMIZATION_PATH) {\n const parsedUrl = new URL(rawUrl, \"http://localhost\");\n const params = parseImageParams(parsedUrl, allowedImageWidths);\n if (!params) {\n res.writeHead(400);\n res.end(\"Bad Request\");\n return;\n }\n // Block SVG and other unsafe content types.\n // SVG is only allowed when dangerouslyAllowSVG is enabled.\n const ext = path.extname(params.imageUrl).toLowerCase();\n const ct = CONTENT_TYPES[ext] ?? \"application/octet-stream\";\n if (!isSafeImageContentType(ct, pagesImageConfig?.dangerouslyAllowSVG)) {\n res.writeHead(400);\n res.end(\"The requested resource is not an allowed image type\");\n return;\n }\n const imageSecurityHeaders: Record<string, string> = {\n \"Content-Security-Policy\": pagesImageConfig?.contentSecurityPolicy ?? IMAGE_CONTENT_SECURITY_POLICY,\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Disposition\": pagesImageConfig?.contentDispositionType ?? \"inline\",\n };\n if (tryServeStatic(req, res, clientDir, params.imageUrl, false, imageSecurityHeaders)) {\n return;\n }\n res.writeHead(404);\n res.end(\"Image not found\");\n return;\n }\n\n try {\n // ── 2. Strip basePath ─────────────────────────────────────────\n if (basePath && pathname.startsWith(basePath)) {\n const stripped = pathname.slice(basePath.length) || \"/\";\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = stripped + qs;\n pathname = stripped;\n }\n\n // ── 3. Trailing slash normalization ───────────────────────────\n if (pathname !== \"/\" && !pathname.startsWith(\"/api\")) {\n const hasTrailing = pathname.endsWith(\"/\");\n if (trailingSlash && !hasTrailing) {\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n res.writeHead(308, { Location: basePath + pathname + \"/\" + qs });\n res.end();\n return;\n } else if (!trailingSlash && hasTrailing) {\n const qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n res.writeHead(308, { Location: basePath + pathname.replace(/\\/+$/, \"\") + qs });\n res.end();\n return;\n }\n }\n\n // Convert Node.js req to Web Request for the server entry\n const rawProtocol = trustProxy\n ? (req.headers[\"x-forwarded-proto\"] as string)?.split(\",\")[0]?.trim()\n : undefined;\n const protocol = rawProtocol === \"https\" || rawProtocol === \"http\" ? rawProtocol : \"http\";\n const hostHeader = resolveHost(req, `${host}:${port}`);\n const reqHeaders = Object.entries(req.headers).reduce((h, [k, v]) => {\n if (v) h.set(k, Array.isArray(v) ? v.join(\", \") : v);\n return h;\n }, new Headers());\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const webRequest = new Request(`${protocol}://${hostHeader}${url}`, {\n method,\n headers: reqHeaders,\n body: hasBody ? readNodeStream(req) : undefined,\n // @ts-expect-error — duplex needed for streaming request bodies\n duplex: hasBody ? \"half\" : undefined,\n });\n\n // Build request context for has/missing condition matching\n const reqCtx: RequestContext = requestContextFromRequest(webRequest);\n\n // ── 4. Run middleware ─────────────────────────────────────────\n let resolvedUrl = url;\n const middlewareHeaders: Record<string, string> = {};\n let middlewareRewriteStatus: number | undefined;\n if (typeof runMiddleware === \"function\") {\n const result = await runMiddleware(webRequest);\n\n if (!result.continue) {\n if (result.redirectUrl) {\n res.writeHead(result.redirectStatus ?? 307, {\n Location: result.redirectUrl,\n });\n res.end();\n return;\n }\n if (result.response) {\n // Use arrayBuffer() to handle binary response bodies correctly\n const body = Buffer.from(await result.response.arrayBuffer());\n // Preserve multi-value headers (especially Set-Cookie) by\n // using getSetCookie() for cookies and forEach for the rest.\n const respHeaders: Record<string, string | string[]> = {};\n result.response.headers.forEach((value: string, key: string) => {\n if (key.toLowerCase() === \"set-cookie\") return; // handled below\n respHeaders[key] = value;\n });\n const setCookies = result.response.headers.getSetCookie?.() ?? [];\n if (setCookies.length > 0) respHeaders[\"set-cookie\"] = setCookies;\n res.writeHead(result.response.status, respHeaders);\n res.end(body);\n return;\n }\n }\n\n // Collect middleware response headers to merge into final response.\n // Use an array for Set-Cookie to preserve multiple values.\n if (result.responseHeaders) {\n for (const [key, value] of result.responseHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n const existing = middlewareHeaders[key];\n if (Array.isArray(existing)) {\n existing.push(value);\n } else if (existing) {\n (middlewareHeaders as any)[key] = [existing, value];\n } else {\n (middlewareHeaders as any)[key] = [value];\n }\n } else {\n middlewareHeaders[key] = value;\n }\n }\n }\n\n // Apply middleware rewrite\n if (result.rewriteUrl) {\n resolvedUrl = result.rewriteUrl;\n }\n\n // Apply custom status code from middleware rewrite\n // (e.g. NextResponse.rewrite(url, { status: 403 }))\n middlewareRewriteStatus = result.rewriteStatus;\n }\n\n // Unpack x-middleware-request-* headers into the actual request so that\n // renderPage / handleApiRoute see the middleware-modified headers.\n // Strip ALL x-middleware-* headers from the response — this prefix is\n // reserved for internal routing signals and must never reach clients.\n // (Matches Next.js behavior where x-middleware-* headers are internal.)\n const mwReqPrefix = \"x-middleware-request-\";\n for (const key of Object.keys(middlewareHeaders)) {\n if (key.startsWith(mwReqPrefix)) {\n const realName = key.slice(mwReqPrefix.length);\n webRequest.headers.set(realName, middlewareHeaders[key]);\n delete middlewareHeaders[key];\n } else if (key.startsWith(\"x-middleware-\")) {\n delete middlewareHeaders[key];\n }\n }\n\n let resolvedPathname = resolvedUrl.split(\"?\")[0];\n\n // ── 5. Apply custom headers from next.config.js ───────────────\n // Config headers are additive for multi-value headers (Vary,\n // Set-Cookie) and override for everything else. Set-Cookie values\n // are stored as arrays (RFC 6265 forbids comma-joining cookies).\n if (configHeaders.length) {\n const matched = matchHeaders(resolvedPathname, configHeaders, reqCtx);\n for (const h of matched) {\n const lk = h.key.toLowerCase();\n if (lk === \"set-cookie\") {\n const existing = middlewareHeaders[lk];\n if (Array.isArray(existing)) {\n existing.push(h.value);\n } else if (existing) {\n (middlewareHeaders as any)[lk] = [existing, h.value];\n } else {\n (middlewareHeaders as any)[lk] = [h.value];\n }\n } else if (lk === \"vary\" && middlewareHeaders[lk]) {\n middlewareHeaders[lk] += \", \" + h.value;\n } else {\n middlewareHeaders[lk] = h.value;\n }\n }\n }\n\n // ── 6. Apply redirects from next.config.js ────────────────────\n if (configRedirects.length) {\n const redirect = matchRedirect(resolvedPathname, configRedirects, reqCtx);\n if (redirect) {\n // Guard against double-prefixing: only add basePath if destination\n // doesn't already start with it.\n // Sanitize the final destination to prevent protocol-relative URL open redirects.\n const dest = sanitizeDestination(\n basePath && !redirect.destination.startsWith(basePath)\n ? basePath + redirect.destination\n : redirect.destination,\n );\n res.writeHead(redirect.permanent ? 308 : 307, { Location: dest });\n res.end();\n return;\n }\n }\n\n // ── 7. Apply beforeFiles rewrites from next.config.js ─────────\n if (configRewrites.beforeFiles?.length) {\n const rewritten = matchRewrite(resolvedPathname, configRewrites.beforeFiles, reqCtx);\n if (rewritten) {\n if (isExternalUrl(rewritten)) {\n const proxyResponse = await proxyExternalRequest(webRequest, rewritten);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n resolvedUrl = rewritten;\n resolvedPathname = rewritten.split(\"?\")[0];\n }\n }\n\n // ── 8. API routes ─────────────────────────────────────────────\n if (resolvedPathname.startsWith(\"/api/\") || resolvedPathname === \"/api\") {\n let response: Response;\n if (typeof handleApi === \"function\") {\n response = await handleApi(webRequest, resolvedUrl);\n } else {\n response = new Response(\"404 - API route not found\", { status: 404 });\n }\n\n // Merge middleware + config headers into the response\n const responseBody = Buffer.from(await response.arrayBuffer());\n // API routes may return arbitrary data (JSON, binary, etc.), so\n // default to application/octet-stream rather than text/html when\n // the handler doesn't set an explicit Content-Type.\n const ct = response.headers.get(\"content-type\") ?? \"application/octet-stream\";\n const responseHeaders: Record<string, string> = { ...middlewareHeaders };\n response.headers.forEach((v, k) => { responseHeaders[k] = v; });\n\n sendCompressed(req, res, responseBody, ct, middlewareRewriteStatus ?? response.status, responseHeaders, compress);\n return;\n }\n\n // ── 9. Apply afterFiles rewrites from next.config.js ──────────\n if (configRewrites.afterFiles?.length) {\n const rewritten = matchRewrite(resolvedPathname, configRewrites.afterFiles, reqCtx);\n if (rewritten) {\n if (isExternalUrl(rewritten)) {\n const proxyResponse = await proxyExternalRequest(webRequest, rewritten);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n resolvedUrl = rewritten;\n resolvedPathname = rewritten.split(\"?\")[0];\n }\n }\n\n // ── 10. SSR page rendering ────────────────────────────────────\n let response: Response | undefined;\n if (typeof renderPage === \"function\") {\n response = await renderPage(webRequest, resolvedUrl, ssrManifest);\n\n // ── 11. Fallback rewrites (if SSR returned 404) ─────────────\n if (response && response.status === 404 && configRewrites.fallback?.length) {\n const fallbackRewrite = matchRewrite(resolvedPathname, configRewrites.fallback, reqCtx);\n if (fallbackRewrite) {\n if (isExternalUrl(fallbackRewrite)) {\n const proxyResponse = await proxyExternalRequest(webRequest, fallbackRewrite);\n await sendWebResponse(proxyResponse, req, res, compress);\n return;\n }\n response = await renderPage(webRequest, fallbackRewrite, ssrManifest);\n }\n }\n }\n\n if (!response) {\n res.writeHead(404);\n res.end(\"404 - Not found\");\n return;\n }\n\n // Merge middleware + config headers into the response\n const responseBody = Buffer.from(await response.arrayBuffer());\n const ct = response.headers.get(\"content-type\") ?? \"text/html\";\n const responseHeaders: Record<string, string> = { ...middlewareHeaders };\n response.headers.forEach((v, k) => { responseHeaders[k] = v; });\n\n sendCompressed(req, res, responseBody, ct, middlewareRewriteStatus ?? response.status, responseHeaders, compress);\n } catch (e) {\n console.error(\"[vinext] Server error:\", e);\n res.writeHead(500);\n res.end(\"Internal Server Error\");\n }\n });\n\n await new Promise<void>((resolve) => {\n server.listen(port, host, () => {\n const addr = server.address();\n const actualPort = typeof addr === \"object\" && addr ? addr.port : port;\n console.log(`[vinext] Production server running at http://${host}:${actualPort}`);\n resolve();\n });\n });\n\n return server;\n}\n\n// Export helpers for testing\nexport { sendCompressed, negotiateEncoding, COMPRESSIBLE_TYPES, COMPRESS_THRESHOLD, resolveHost, trustedHosts, trustProxy, nodeToWebRequest };\n"]}
@@ -43,7 +43,7 @@ export interface CachedFetchValue {
43
43
  status?: number;
44
44
  };
45
45
  tags?: string[];
46
- revalidate: number;
46
+ revalidate: number | false;
47
47
  }
48
48
  export interface CachedAppPageValue {
49
49
  kind: "APP_PAGE";
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/shims/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAWH,UAAU,gBAAgB;IACxB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,WAAW,EAAE,OAAO,oBAAoB,EAAE,YAAY,C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AM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAQ7D,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,eAAe,GAAG,IAAI,CA2CjE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAShD;AAgBD;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,OAAO,CAEpD;AAED,UAAU,oBAAoB;IAC5B,UAAU,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC5B,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EACvE,EAAE,EAAE,CAAC,EACL,QAAQ,CAAC,EAAE,MAAM,EAAE,EACnB,OAAO,CAAC,EAAE,oBAAoB,GAC7B,CAAC,CAwDH"}
@@ -400,12 +400,13 @@ export function unstable_cache(fn, keyParts, options) {
400
400
  const cachedFn = async (...args) => {
401
401
  const argsKey = JSON.stringify(args);
402
402
  const cacheKey = `unstable_cache:${baseKey}:${argsKey}`;
403
- // Try to get from cache
403
+ // Try to get from cache. Check cacheState so time-expired entries
404
+ // trigger a re-fetch instead of being served indefinitely.
404
405
  const existing = await activeHandler.get(cacheKey, {
405
406
  kind: "FETCH",
406
407
  tags,
407
408
  });
408
- if (existing?.value && existing.value.kind === "FETCH") {
409
+ if (existing?.value && existing.value.kind === "FETCH" && existing.cacheState !== "stale") {
409
410
  try {
410
411
  return JSON.parse(existing.value.data.body);
411
412
  }
@@ -426,7 +427,11 @@ export function unstable_cache(fn, keyParts, options) {
426
427
  url: cacheKey,
427
428
  },
428
429
  tags,
429
- revalidate: typeof revalidateSeconds === "number" ? revalidateSeconds : 0,
430
+ // revalidate: false means "cache indefinitely" (no time-based expiry).
431
+ // A positive number means time-based revalidation in seconds.
432
+ // When unset (undefined), default to false (indefinite) matching
433
+ // Next.js behavior for unstable_cache without explicit revalidate.
434
+ revalidate: typeof revalidateSeconds === "number" ? revalidateSeconds : false,
430
435
  };
431
436
  await activeHandler.set(cacheKey, cacheValue, {
432
437
  fetchCache: true,
@@ -1 +1 @@
1
- {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/shims/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,gBAAgB,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAa3C,+EAA+E;AAC/E,IAAI,kBAAkB,GAA2C,IAAI,CAAC;AAEtE;;;GAGG;AACH,MAAM,UAAU,6BAA6B,CAAC,EAAiC;IAC7E,kBAAkB,GAAG,EAAE,CAAC;AAC1B,CAAC;AA+GD,MAAM,OAAO,kBAAkB;IACrB,KAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;IACvC,gBAAgB,GAAG,IAAI,GAAG,EAAkB,CAAC;IAErD,KAAK,CAAC,GAAG,CACP,GAAW,EACX,IAA8B;QAE9B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,kFAAkF;QAClF,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;YAC7B,MAAM,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACrD,IAAI,aAAa,IAAI,aAAa,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;gBACzD,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACvB,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AC;SAC1E,CAAC;QAEF,MAAM,aAAa,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,EAAE;YAC5C,UAAU,EAAE,IAAI;YAChB,IAAI;YACJ,UAAU,EAAE,iBAAiB;SAC9B,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,QAAa,CAAC;AACvB,CAAC","sourcesContent":["/**\n * next/cache shim\n *\n * Provides the Next.js caching API surface: revalidateTag, revalidatePath,\n * unstable_cache. Backed by a pluggable CacheHandler that defaults to\n * in-memory but can be swapped for Cloudflare KV, Redis, DynamoDB, etc.\n *\n * The CacheHandler interface matches Next.js 16's CacheHandler class, so\n * existing community adapters (@neshca/cache-handler, @opennextjs/aws, etc.)\n * can be used directly.\n *\n * Configuration (in vite.config.ts or next.config.js):\n * vinext({ cacheHandler: './my-cache-handler.ts' })\n *\n * Or set at runtime:\n * import { setCacheHandler } from 'next/cache';\n * setCacheHandler(new MyCacheHandler());\n */\n\nimport { markDynamicUsage as _markDynamic } from \"./headers.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { fnv1a64 } from \"../utils/hash.js\";\n\n// ---------------------------------------------------------------------------\n// Lazy accessor for cache context — avoids circular imports with cache-runtime.\n// The cache-runtime module sets this on load.\n// ---------------------------------------------------------------------------\n\ninterface CacheContextLike {\n tags: string[];\n lifeConfigs: import(\"./cache-runtime.js\").CacheContext[\"lifeConfigs\"];\n variant: string;\n}\n\n/** @internal Set by cache-runtime.ts on import to avoid circular dependency */\nlet _getCacheContextFn: (() => CacheContextLike | null) | null = null;\n\n/**\n * Register the cache context accessor. Called by cache-runtime.ts on load.\n * @internal\n */\nexport function _registerCacheContextAccessor(fn: () => CacheContextLike | null): void {\n _getCacheContextFn = fn;\n}\n\n// ---------------------------------------------------------------------------\n// CacheHandler interface — matches Next.js 16's CacheHandler class shape.\n// Implement this to provide a custom cache backend.\n// ---------------------------------------------------------------------------\n\nexport interface CacheHandlerValue {\n lastModified: number;\n age?: number;\n cacheState?: string;\n value: IncrementalCacheValue | null;\n}\n\n/** Discriminated union of cache value types. */\nexport type IncrementalCacheValue =\n | CachedFetchValue\n | CachedAppPageValue\n | CachedPagesValue\n | CachedRouteValue\n | CachedRedirectValue\n | CachedImageValue;\n\nexport interface CachedFetchValue {\n kind: \"FETCH\";\n data: {\n headers: Record<string, string>;\n body: string;\n url: string;\n status?: number;\n };\n tags?: string[];\n revalidate: number;\n}\n\nexport interface CachedAppPageValue {\n kind: \"APP_PAGE\";\n html: string;\n rscData: ArrayBuffer | undefined;\n headers: Record<string, string | string[]> | undefined;\n postponed: string | undefined;\n status: number | undefined;\n}\n\nexport interface CachedPagesValue {\n kind: \"PAGES\";\n html: string;\n pageData: object;\n headers: Record<string, string | string[]> | undefined;\n status: number | undefined;\n}\n\nexport interface CachedRouteValue {\n kind: \"APP_ROUTE\";\n body: ArrayBuffer;\n status: number;\n headers: Record<string, string | string[]>;\n}\n\nexport interface CachedRedirectValue {\n kind: \"REDIRECT\";\n props: object;\n}\n\nexport interface CachedImageValue {\n kind: \"IMAGE\";\n etag: string;\n buffer: ArrayBuffer;\n extension: string;\n revalidate?: number;\n}\n\nexport interface CacheHandlerContext {\n dev?: boolean;\n maxMemoryCacheSize?: number;\n revalidatedTags?: string[];\n [key: string]: unknown;\n}\n\nexport interface CacheHandler {\n get(\n key: string,\n ctx?: Record<string, unknown>,\n ): Promise<CacheHandlerValue | null>;\n\n set(\n key: string,\n data: IncrementalCacheValue | null,\n ctx?: Record<string, unknown>,\n ): Promise<void>;\n\n revalidateTag(\n tags: string | string[],\n durations?: { expire?: number },\n ): Promise<void>;\n\n resetRequestCache?(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Default in-memory adapter — works everywhere, suitable for dev and\n// single-process production. Not shared across workers/instances.\n// ---------------------------------------------------------------------------\n\ninterface MemoryEntry {\n value: IncrementalCacheValue | null;\n tags: string[];\n lastModified: number;\n revalidateAt: number | null;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<string, MemoryEntry>();\n private tagRevalidatedAt = new Map<string, number>();\n\n async get(\n key: string,\n _ctx?: Record<string, unknown>,\n ): Promise<CacheHandlerValue | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Check tag-based invalidation first — if tag was invalidated, treat as hard miss\n for (const tag of entry.tags) {\n const revalidatedAt = this.tagRevalidatedAt.get(tag);\n if (revalidatedAt && revalidatedAt >= entry.lastModified) {\n this.store.delete(key);\n return null;\n }\n }\n\n // Check time-based expiry — return stale entry with cacheState=\"stale\"\n // instead of deleting, so ISR can serve stale-while-revalidate\n if (entry.revalidateAt !== null && Date.now() > entry.revalidateAt) {\n return {\n lastModified: entry.lastModified,\n value: entry.value,\n cacheState: \"stale\",\n };\n }\n\n return {\n lastModified: entry.lastModified,\n value: entry.value,\n };\n }\n\n async set(\n key: string,\n data: IncrementalCacheValue | null,\n ctx?: Record<string, unknown>,\n ): Promise<void> {\n const tags: string[] = [];\n if (data && \"tags\" in data && Array.isArray(data.tags)) {\n tags.push(...data.tags);\n }\n if (ctx && \"tags\" in ctx && Array.isArray(ctx.tags)) {\n tags.push(...(ctx.tags as string[]));\n }\n\n let revalidateAt: number | null = null;\n if (ctx) {\n // Handle both old-style { revalidate } and new-style { cacheControl: { revalidate } }\n const revalidate =\n (ctx as any).cacheControl?.revalidate ?? (ctx as any).revalidate;\n if (typeof revalidate === \"number\" && revalidate > 0) {\n revalidateAt = Date.now() + revalidate * 1000;\n }\n }\n if (data && \"revalidate\" in data && typeof data.revalidate === \"number\") {\n revalidateAt = Date.now() + data.revalidate * 1000;\n }\n\n this.store.set(key, {\n value: data,\n tags,\n lastModified: Date.now(),\n revalidateAt,\n });\n }\n\n async revalidateTag(\n tags: string | string[],\n _durations?: { expire?: number },\n ): Promise<void> {\n const tagList = Array.isArray(tags) ? tags : [tags];\n const now = Date.now();\n for (const tag of tagList) {\n this.tagRevalidatedAt.set(tag, now);\n }\n }\n\n resetRequestCache(): void {\n // No-op for the simple memory cache. In a production adapter,\n // this would clear per-request caches (e.g., dedup fetch calls).\n }\n}\n\n// ---------------------------------------------------------------------------\n// Active cache handler — the singleton used by next/cache API functions.\n// Defaults to MemoryCacheHandler, can be swapped at runtime.\n// ---------------------------------------------------------------------------\n\nlet activeHandler: CacheHandler = new MemoryCacheHandler();\n\n/**\n * Set a custom CacheHandler. Call this during server startup to\n * plug in Cloudflare KV, Redis, DynamoDB, or any other backend.\n *\n * The handler must implement the CacheHandler interface (same shape\n * as Next.js 16's CacheHandler class).\n */\nexport function setCacheHandler(handler: CacheHandler): void {\n activeHandler = handler;\n}\n\n/**\n * Get the active CacheHandler (for internal use or testing).\n */\nexport function getCacheHandler(): CacheHandler {\n return activeHandler;\n}\n\n// ---------------------------------------------------------------------------\n// Public API — what app code imports from 'next/cache'\n// ---------------------------------------------------------------------------\n\n/**\n * Revalidate cached data associated with a specific cache tag.\n *\n * Works with both `fetch(..., { next: { tags: ['myTag'] } })` and\n * `unstable_cache(fn, keys, { tags: ['myTag'] })`.\n */\n/**\n * Revalidate cached data associated with a specific cache tag.\n *\n * Next.js 16 updated signature: requires a cacheLife profile as second argument\n * for stale-while-revalidate (SWR) behavior. The single-argument form is\n * deprecated but still supported for backward compatibility.\n *\n * @param tag - Cache tag to revalidate\n * @param profile - cacheLife profile name (e.g. 'max', 'hours') or inline { expire: number }\n */\nexport async function revalidateTag(\n tag: string,\n profile?: string | { expire?: number },\n): Promise<void> {\n // Resolve the profile to durations for the handler\n let durations: { expire?: number } | undefined;\n if (typeof profile === \"string\") {\n const resolved = cacheLifeProfiles[profile];\n if (resolved) {\n durations = { expire: resolved.expire };\n }\n } else if (profile && typeof profile === \"object\") {\n durations = profile;\n }\n await activeHandler.revalidateTag(tag, durations);\n}\n\n/**\n * Revalidate cached data associated with a specific path.\n *\n * Under the hood, Next.js converts paths to internal tags.\n * We use a `_N_T_/path` prefix convention for path-based tags.\n */\nexport async function revalidatePath(\n path: string,\n _type?: \"page\" | \"layout\",\n): Promise<void> {\n // Next.js internally converts paths to tags with a prefix\n const pathTag = `_N_T_${path}`;\n await activeHandler.revalidateTag([path, pathTag]);\n}\n\n/**\n * Expire and immediately refresh cached data for a tag (Next.js 16).\n *\n * Server Actions-only API that provides read-your-writes semantics:\n * the cache entry is expired and fresh data is read within the same request,\n * so the user immediately sees their changes.\n *\n * Use this for interactive features (forms, user settings) where users\n * expect to see their updates instantly.\n *\n * @param tag - Cache tag to expire and refresh\n */\nexport async function updateTag(tag: string): Promise<void> {\n // Expire the tag immediately (same as revalidateTag without SWR)\n await activeHandler.revalidateTag(tag);\n}\n\n/**\n * Refresh uncached data on the page (Next.js 16).\n *\n * Server Actions-only API that signals the client to re-fetch dynamic\n * (uncached) data without touching the cache. Complementary to the\n * client-side router.refresh().\n *\n * Use this when you need to refresh data like notification counts,\n * live metrics, or status indicators after performing a server action.\n */\nexport function refresh(): void {\n // In our implementation, this is a signal that the client should\n // refresh dynamic data. The actual refresh happens on the client side\n // via the RSC protocol — the server action response triggers a\n // client-side navigation refresh.\n // For now, this is a no-op on the server; the Server Action response\n // mechanism already handles re-rendering the affected RSC tree.\n}\n\n/**\n * Opt out of static rendering and indicate a particular component should not be cached.\n *\n * In Next.js, calling noStore() inside a Server Component ensures the component\n * is dynamically rendered. In our implementation, this is a no-op since we don't\n * have the same static/dynamic rendering split — all server rendering is on-demand.\n * It's provided for API compatibility so apps importing it don't break.\n */\nexport function unstable_noStore(): void {\n // Signal dynamic usage so ISR-configured routes bypass the cache\n _markDynamic();\n}\n\n// Also export as `noStore` (Next.js 15+ naming)\nexport { unstable_noStore as noStore };\n\n// ---------------------------------------------------------------------------\n// Request-scoped cacheLife for page-level \"use cache\" directives.\n// When cacheLife() is called outside a \"use cache\" function context (e.g.,\n// in a page component with file-level \"use cache\"), the resolved config is\n// stored here so the server can read it after rendering and apply ISR caching.\n//\n// Uses AsyncLocalStorage for request isolation on concurrent workers.\n// ---------------------------------------------------------------------------\ninterface CacheState {\n requestScopedCacheLife: CacheLifeConfig | null;\n}\n\nconst _ALS_KEY = Symbol.for(\"vinext.cache.als\");\nconst _FALLBACK_KEY = Symbol.for(\"vinext.cache.fallback\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\nconst _cacheAls = (_g[_ALS_KEY] ??= new AsyncLocalStorage<CacheState>()) as AsyncLocalStorage<CacheState>;\n\nconst _cacheFallbackState = (_g[_FALLBACK_KEY] ??= {\n requestScopedCacheLife: null,\n} satisfies CacheState) as CacheState;\n\nfunction _getCacheState(): CacheState {\n return _cacheAls.getStore() ?? _cacheFallbackState;\n}\n\n/**\n * Run a function within a cache state ALS scope.\n * Ensures per-request isolation for request-scoped cacheLife config\n * on concurrent runtimes.\n * @internal\n */\nexport function _runWithCacheState<T>(fn: () => T | Promise<T>): T | Promise<T> {\n const state: CacheState = {\n requestScopedCacheLife: null,\n };\n return _cacheAls.run(state, fn);\n}\n\n/**\n * Initialize cache ALS for a new request. Call at request entry.\n * Only needed when not using _runWithCacheState() (legacy path).\n * @internal\n */\nexport function _initRequestScopedCacheState(): void {\n const state = _cacheAls.getStore();\n if (state) {\n state.requestScopedCacheLife = null;\n } else {\n _cacheFallbackState.requestScopedCacheLife = null;\n }\n}\n\n/**\n * Set a request-scoped cache life config. Called by cacheLife() when outside\n * a \"use cache\" function context.\n * @internal\n */\nexport function _setRequestScopedCacheLife(config: CacheLifeConfig): void {\n const state = _getCacheState();\n if (state.requestScopedCacheLife === null) {\n state.requestScopedCacheLife = { ...config };\n } else {\n // Minimum-wins rule\n if (config.stale !== undefined) {\n state.requestScopedCacheLife.stale = state.requestScopedCacheLife.stale !== undefined\n ? Math.min(state.requestScopedCacheLife.stale, config.stale)\n : config.stale;\n }\n if (config.revalidate !== undefined) {\n state.requestScopedCacheLife.revalidate = state.requestScopedCacheLife.revalidate !== undefined\n ? Math.min(state.requestScopedCacheLife.revalidate, config.revalidate)\n : config.revalidate;\n }\n if (config.expire !== undefined) {\n state.requestScopedCacheLife.expire = state.requestScopedCacheLife.expire !== undefined\n ? Math.min(state.requestScopedCacheLife.expire, config.expire)\n : config.expire;\n }\n }\n}\n\n/**\n * Consume and reset the request-scoped cache life. Returns null if none was set.\n * @internal\n */\nexport function _consumeRequestScopedCacheLife(): CacheLifeConfig | null {\n const state = _getCacheState();\n const config = state.requestScopedCacheLife;\n state.requestScopedCacheLife = null;\n return config;\n}\n\n// ---------------------------------------------------------------------------\n// cacheLife / cacheTag — Next.js 15+ \"use cache\" APIs\n// ---------------------------------------------------------------------------\n\n/**\n * Cache life configuration. Controls stale-while-revalidate behavior.\n */\nexport interface CacheLifeConfig {\n /** How long (seconds) the client can cache without checking the server */\n stale?: number;\n /** How frequently (seconds) the server cache refreshes */\n revalidate?: number;\n /** Max staleness (seconds) before deoptimizing to dynamic */\n expire?: number;\n}\n\n/**\n * Built-in cache life profiles matching Next.js 16.\n */\nexport const cacheLifeProfiles: Record<string, CacheLifeConfig> = {\n default: { revalidate: 900, expire: 4294967294 },\n seconds: { stale: 30, revalidate: 1, expire: 60 },\n minutes: { stale: 300, revalidate: 60, expire: 3600 },\n hours: { stale: 300, revalidate: 3600, expire: 86400 },\n days: { stale: 300, revalidate: 86400, expire: 604800 },\n weeks: { stale: 300, revalidate: 604800, expire: 2592000 },\n max: { stale: 300, revalidate: 2592000, expire: 31536000 },\n};\n\n/**\n * Set the cache lifetime for a \"use cache\" function.\n *\n * Accepts either a built-in profile name (e.g., \"hours\", \"days\") or a custom\n * configuration object. In Next.js, this only works inside \"use cache\" functions.\n *\n * When called inside a \"use cache\" function, this sets the cache TTL.\n * The \"minimum-wins\" rule applies: if called multiple times, the shortest\n * duration for each field wins.\n *\n * When called outside a \"use cache\" context, this is a validated no-op.\n */\nexport function cacheLife(profile: string | CacheLifeConfig): void {\n let resolvedConfig: CacheLifeConfig;\n\n if (typeof profile === \"string\") {\n // Validate the profile name exists\n if (!cacheLifeProfiles[profile]) {\n console.warn(\n `[vinext] cacheLife: unknown profile \"${profile}\". ` +\n `Available profiles: ${Object.keys(cacheLifeProfiles).join(\", \")}`,\n );\n return;\n }\n resolvedConfig = { ...cacheLifeProfiles[profile] };\n } else if (typeof profile === \"object\" && profile !== null) {\n // Validate the config shape\n if (\n profile.expire !== undefined &&\n profile.revalidate !== undefined &&\n profile.expire < profile.revalidate\n ) {\n console.warn(\n \"[vinext] cacheLife: expire must be >= revalidate\",\n );\n }\n resolvedConfig = { ...profile };\n } else {\n return;\n }\n\n // If we're inside a \"use cache\" context, push the config\n try {\n const ctx = _getCacheContextFn?.();\n if (ctx) {\n ctx.lifeConfigs.push(resolvedConfig);\n return;\n }\n } catch {\n // Fall through to request-scoped\n }\n\n // Outside a \"use cache\" context (e.g., page component with file-level \"use cache\"):\n // store as request-scoped so the server can read it after rendering.\n _setRequestScopedCacheLife(resolvedConfig);\n}\n\n/**\n * Tag a \"use cache\" function's cached result for on-demand revalidation.\n *\n * Tags set here can be invalidated via revalidateTag(). In Next.js, this only\n * works inside \"use cache\" functions.\n *\n * When called inside a \"use cache\" function, tags are attached to the cached\n * entry. They can later be invalidated via revalidateTag().\n *\n * When called outside a \"use cache\" context, this is a no-op.\n */\nexport function cacheTag(...tags: string[]): void {\n try {\n const ctx = _getCacheContextFn?.();\n if (ctx) {\n ctx.tags.push(...tags);\n }\n } catch {\n // Not in a cache context — no-op\n }\n}\n\n// ---------------------------------------------------------------------------\n// unstable_cache — the older caching API\n// ---------------------------------------------------------------------------\n\n/**\n * AsyncLocalStorage to track whether we're inside an unstable_cache() callback.\n * Stored on globalThis via Symbol so headers.ts can detect the scope without\n * a direct import (avoiding circular dependencies).\n */\nconst _UNSTABLE_CACHE_ALS_KEY = Symbol.for(\"vinext.unstableCache.als\");\nconst _unstableCacheAls = (\n (_g[_UNSTABLE_CACHE_ALS_KEY] ??= new AsyncLocalStorage<boolean>()) as AsyncLocalStorage<boolean>\n);\n\n/**\n * Check if the current execution context is inside an unstable_cache() callback.\n * Used by headers(), cookies(), and connection() to throw errors when\n * dynamic request APIs are called inside a cache scope.\n */\nexport function isInsideUnstableCacheScope(): boolean {\n return _unstableCacheAls.getStore() === true;\n}\n\ninterface UnstableCacheOptions {\n revalidate?: number | false;\n tags?: string[];\n}\n\n/**\n * Wrap an async function with caching.\n *\n * Returns a new function that caches results. The cache key is derived\n * from keyParts + serialized arguments.\n */\nexport function unstable_cache<T extends (...args: any[]) => Promise<any>>(\n fn: T,\n keyParts?: string[],\n options?: UnstableCacheOptions,\n): T {\n const baseKey = keyParts\n ? keyParts.join(\":\")\n : fnv1a64(fn.toString());\n const tags = options?.tags ?? [];\n const revalidateSeconds = options?.revalidate;\n\n const cachedFn = async (...args: any[]): Promise<any> => {\n const argsKey = JSON.stringify(args);\n const cacheKey = `unstable_cache:${baseKey}:${argsKey}`;\n\n // Try to get from cache\n const existing = await activeHandler.get(cacheKey, {\n kind: \"FETCH\",\n tags,\n });\n if (existing?.value && existing.value.kind === \"FETCH\") {\n try {\n return JSON.parse(existing.value.data.body);\n } catch {\n // Corrupted entry, fall through to re-fetch\n }\n }\n\n // Cache miss — call the function inside the unstable_cache ALS scope\n // so that headers()/cookies()/connection() can detect they're in a\n // cache scope and throw an appropriate error.\n const result = await _unstableCacheAls.run(true, () => fn(...args));\n\n // Store in cache using the FETCH kind\n const cacheValue: CachedFetchValue = {\n kind: \"FETCH\",\n data: {\n headers: {},\n body: JSON.stringify(result),\n url: cacheKey,\n },\n tags,\n revalidate: typeof revalidateSeconds === \"number\" ? revalidateSeconds : 0,\n };\n\n await activeHandler.set(cacheKey, cacheValue, {\n fetchCache: true,\n tags,\n revalidate: revalidateSeconds,\n });\n\n return result;\n };\n\n return cachedFn as T;\n}\n"]}
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/shims/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,gBAAgB,IAAI,YAAY,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC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AAQ,EAAE;YACjD,IAAI,EAAE,OAAO;YACb,IAAI;SACL,CAAC,CAAC;QACH,IAAI,QAAQ,EAAE,KAAK,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;YAC1F,IAAI,CAAC;gBACH,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC9C,CAAC;YAAC,MAAM,CAAC;gBACP,4CAA4C;YAC9C,CAAC;QACH,CAAC;QAED,qEAAqE;QACrE,mEAAmE;QACnE,8CAA8C;QAC9C,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QAEpE,sCAAsC;QACtC,MAAM,UAAU,GAAqB;YACnC,IAAI,EAAE,OAAO;YACb,IAAI,EAAE;gBACJ,OAAO,EAAE,EAAE;gBACX,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;gBAC5B,GAAG,EAAE,QAAQ;aACd;YACD,IAAI;YACJ,uEAAuE;YACvE,8DAA8D;YAC9D,iEAAiE;YACjE,mEAAmE;YACnE,UAAU,EAAE,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,KAAK;SAC9E,CAAC;QAEF,MAAM,aAAa,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,EAAE;YAC5C,UAAU,EAAE,IAAI;YAChB,IAAI;YACJ,UAAU,EAAE,iBAAiB;SAC9B,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,QAAa,CAAC;AACvB,CAAC","sourcesContent":["/**\n * next/cache shim\n *\n * Provides the Next.js caching API surface: revalidateTag, revalidatePath,\n * unstable_cache. Backed by a pluggable CacheHandler that defaults to\n * in-memory but can be swapped for Cloudflare KV, Redis, DynamoDB, etc.\n *\n * The CacheHandler interface matches Next.js 16's CacheHandler class, so\n * existing community adapters (@neshca/cache-handler, @opennextjs/aws, etc.)\n * can be used directly.\n *\n * Configuration (in vite.config.ts or next.config.js):\n * vinext({ cacheHandler: './my-cache-handler.ts' })\n *\n * Or set at runtime:\n * import { setCacheHandler } from 'next/cache';\n * setCacheHandler(new MyCacheHandler());\n */\n\nimport { markDynamicUsage as _markDynamic } from \"./headers.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { fnv1a64 } from \"../utils/hash.js\";\n\n// ---------------------------------------------------------------------------\n// Lazy accessor for cache context — avoids circular imports with cache-runtime.\n// The cache-runtime module sets this on load.\n// ---------------------------------------------------------------------------\n\ninterface CacheContextLike {\n tags: string[];\n lifeConfigs: import(\"./cache-runtime.js\").CacheContext[\"lifeConfigs\"];\n variant: string;\n}\n\n/** @internal Set by cache-runtime.ts on import to avoid circular dependency */\nlet _getCacheContextFn: (() => CacheContextLike | null) | null = null;\n\n/**\n * Register the cache context accessor. Called by cache-runtime.ts on load.\n * @internal\n */\nexport function _registerCacheContextAccessor(fn: () => CacheContextLike | null): void {\n _getCacheContextFn = fn;\n}\n\n// ---------------------------------------------------------------------------\n// CacheHandler interface — matches Next.js 16's CacheHandler class shape.\n// Implement this to provide a custom cache backend.\n// ---------------------------------------------------------------------------\n\nexport interface CacheHandlerValue {\n lastModified: number;\n age?: number;\n cacheState?: string;\n value: IncrementalCacheValue | null;\n}\n\n/** Discriminated union of cache value types. */\nexport type IncrementalCacheValue =\n | CachedFetchValue\n | CachedAppPageValue\n | CachedPagesValue\n | CachedRouteValue\n | CachedRedirectValue\n | CachedImageValue;\n\nexport interface CachedFetchValue {\n kind: \"FETCH\";\n data: {\n headers: Record<string, string>;\n body: string;\n url: string;\n status?: number;\n };\n tags?: string[];\n revalidate: number | false;\n}\n\nexport interface CachedAppPageValue {\n kind: \"APP_PAGE\";\n html: string;\n rscData: ArrayBuffer | undefined;\n headers: Record<string, string | string[]> | undefined;\n postponed: string | undefined;\n status: number | undefined;\n}\n\nexport interface CachedPagesValue {\n kind: \"PAGES\";\n html: string;\n pageData: object;\n headers: Record<string, string | string[]> | undefined;\n status: number | undefined;\n}\n\nexport interface CachedRouteValue {\n kind: \"APP_ROUTE\";\n body: ArrayBuffer;\n status: number;\n headers: Record<string, string | string[]>;\n}\n\nexport interface CachedRedirectValue {\n kind: \"REDIRECT\";\n props: object;\n}\n\nexport interface CachedImageValue {\n kind: \"IMAGE\";\n etag: string;\n buffer: ArrayBuffer;\n extension: string;\n revalidate?: number;\n}\n\nexport interface CacheHandlerContext {\n dev?: boolean;\n maxMemoryCacheSize?: number;\n revalidatedTags?: string[];\n [key: string]: unknown;\n}\n\nexport interface CacheHandler {\n get(\n key: string,\n ctx?: Record<string, unknown>,\n ): Promise<CacheHandlerValue | null>;\n\n set(\n key: string,\n data: IncrementalCacheValue | null,\n ctx?: Record<string, unknown>,\n ): Promise<void>;\n\n revalidateTag(\n tags: string | string[],\n durations?: { expire?: number },\n ): Promise<void>;\n\n resetRequestCache?(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Default in-memory adapter — works everywhere, suitable for dev and\n// single-process production. Not shared across workers/instances.\n// ---------------------------------------------------------------------------\n\ninterface MemoryEntry {\n value: IncrementalCacheValue | null;\n tags: string[];\n lastModified: number;\n revalidateAt: number | null;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<string, MemoryEntry>();\n private tagRevalidatedAt = new Map<string, number>();\n\n async get(\n key: string,\n _ctx?: Record<string, unknown>,\n ): Promise<CacheHandlerValue | null> {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Check tag-based invalidation first — if tag was invalidated, treat as hard miss\n for (const tag of entry.tags) {\n const revalidatedAt = this.tagRevalidatedAt.get(tag);\n if (revalidatedAt && revalidatedAt >= entry.lastModified) {\n this.store.delete(key);\n return null;\n }\n }\n\n // Check time-based expiry — return stale entry with cacheState=\"stale\"\n // instead of deleting, so ISR can serve stale-while-revalidate\n if (entry.revalidateAt !== null && Date.now() > entry.revalidateAt) {\n return {\n lastModified: entry.lastModified,\n value: entry.value,\n cacheState: \"stale\",\n };\n }\n\n return {\n lastModified: entry.lastModified,\n value: entry.value,\n };\n }\n\n async set(\n key: string,\n data: IncrementalCacheValue | null,\n ctx?: Record<string, unknown>,\n ): Promise<void> {\n const tags: string[] = [];\n if (data && \"tags\" in data && Array.isArray(data.tags)) {\n tags.push(...data.tags);\n }\n if (ctx && \"tags\" in ctx && Array.isArray(ctx.tags)) {\n tags.push(...(ctx.tags as string[]));\n }\n\n let revalidateAt: number | null = null;\n if (ctx) {\n // Handle both old-style { revalidate } and new-style { cacheControl: { revalidate } }\n const revalidate =\n (ctx as any).cacheControl?.revalidate ?? (ctx as any).revalidate;\n if (typeof revalidate === \"number\" && revalidate > 0) {\n revalidateAt = Date.now() + revalidate * 1000;\n }\n }\n if (data && \"revalidate\" in data && typeof data.revalidate === \"number\") {\n revalidateAt = Date.now() + data.revalidate * 1000;\n }\n\n this.store.set(key, {\n value: data,\n tags,\n lastModified: Date.now(),\n revalidateAt,\n });\n }\n\n async revalidateTag(\n tags: string | string[],\n _durations?: { expire?: number },\n ): Promise<void> {\n const tagList = Array.isArray(tags) ? tags : [tags];\n const now = Date.now();\n for (const tag of tagList) {\n this.tagRevalidatedAt.set(tag, now);\n }\n }\n\n resetRequestCache(): void {\n // No-op for the simple memory cache. In a production adapter,\n // this would clear per-request caches (e.g., dedup fetch calls).\n }\n}\n\n// ---------------------------------------------------------------------------\n// Active cache handler — the singleton used by next/cache API functions.\n// Defaults to MemoryCacheHandler, can be swapped at runtime.\n// ---------------------------------------------------------------------------\n\nlet activeHandler: CacheHandler = new MemoryCacheHandler();\n\n/**\n * Set a custom CacheHandler. Call this during server startup to\n * plug in Cloudflare KV, Redis, DynamoDB, or any other backend.\n *\n * The handler must implement the CacheHandler interface (same shape\n * as Next.js 16's CacheHandler class).\n */\nexport function setCacheHandler(handler: CacheHandler): void {\n activeHandler = handler;\n}\n\n/**\n * Get the active CacheHandler (for internal use or testing).\n */\nexport function getCacheHandler(): CacheHandler {\n return activeHandler;\n}\n\n// ---------------------------------------------------------------------------\n// Public API — what app code imports from 'next/cache'\n// ---------------------------------------------------------------------------\n\n/**\n * Revalidate cached data associated with a specific cache tag.\n *\n * Works with both `fetch(..., { next: { tags: ['myTag'] } })` and\n * `unstable_cache(fn, keys, { tags: ['myTag'] })`.\n */\n/**\n * Revalidate cached data associated with a specific cache tag.\n *\n * Next.js 16 updated signature: requires a cacheLife profile as second argument\n * for stale-while-revalidate (SWR) behavior. The single-argument form is\n * deprecated but still supported for backward compatibility.\n *\n * @param tag - Cache tag to revalidate\n * @param profile - cacheLife profile name (e.g. 'max', 'hours') or inline { expire: number }\n */\nexport async function revalidateTag(\n tag: string,\n profile?: string | { expire?: number },\n): Promise<void> {\n // Resolve the profile to durations for the handler\n let durations: { expire?: number } | undefined;\n if (typeof profile === \"string\") {\n const resolved = cacheLifeProfiles[profile];\n if (resolved) {\n durations = { expire: resolved.expire };\n }\n } else if (profile && typeof profile === \"object\") {\n durations = profile;\n }\n await activeHandler.revalidateTag(tag, durations);\n}\n\n/**\n * Revalidate cached data associated with a specific path.\n *\n * Under the hood, Next.js converts paths to internal tags.\n * We use a `_N_T_/path` prefix convention for path-based tags.\n */\nexport async function revalidatePath(\n path: string,\n _type?: \"page\" | \"layout\",\n): Promise<void> {\n // Next.js internally converts paths to tags with a prefix\n const pathTag = `_N_T_${path}`;\n await activeHandler.revalidateTag([path, pathTag]);\n}\n\n/**\n * Expire and immediately refresh cached data for a tag (Next.js 16).\n *\n * Server Actions-only API that provides read-your-writes semantics:\n * the cache entry is expired and fresh data is read within the same request,\n * so the user immediately sees their changes.\n *\n * Use this for interactive features (forms, user settings) where users\n * expect to see their updates instantly.\n *\n * @param tag - Cache tag to expire and refresh\n */\nexport async function updateTag(tag: string): Promise<void> {\n // Expire the tag immediately (same as revalidateTag without SWR)\n await activeHandler.revalidateTag(tag);\n}\n\n/**\n * Refresh uncached data on the page (Next.js 16).\n *\n * Server Actions-only API that signals the client to re-fetch dynamic\n * (uncached) data without touching the cache. Complementary to the\n * client-side router.refresh().\n *\n * Use this when you need to refresh data like notification counts,\n * live metrics, or status indicators after performing a server action.\n */\nexport function refresh(): void {\n // In our implementation, this is a signal that the client should\n // refresh dynamic data. The actual refresh happens on the client side\n // via the RSC protocol — the server action response triggers a\n // client-side navigation refresh.\n // For now, this is a no-op on the server; the Server Action response\n // mechanism already handles re-rendering the affected RSC tree.\n}\n\n/**\n * Opt out of static rendering and indicate a particular component should not be cached.\n *\n * In Next.js, calling noStore() inside a Server Component ensures the component\n * is dynamically rendered. In our implementation, this is a no-op since we don't\n * have the same static/dynamic rendering split — all server rendering is on-demand.\n * It's provided for API compatibility so apps importing it don't break.\n */\nexport function unstable_noStore(): void {\n // Signal dynamic usage so ISR-configured routes bypass the cache\n _markDynamic();\n}\n\n// Also export as `noStore` (Next.js 15+ naming)\nexport { unstable_noStore as noStore };\n\n// ---------------------------------------------------------------------------\n// Request-scoped cacheLife for page-level \"use cache\" directives.\n// When cacheLife() is called outside a \"use cache\" function context (e.g.,\n// in a page component with file-level \"use cache\"), the resolved config is\n// stored here so the server can read it after rendering and apply ISR caching.\n//\n// Uses AsyncLocalStorage for request isolation on concurrent workers.\n// ---------------------------------------------------------------------------\ninterface CacheState {\n requestScopedCacheLife: CacheLifeConfig | null;\n}\n\nconst _ALS_KEY = Symbol.for(\"vinext.cache.als\");\nconst _FALLBACK_KEY = Symbol.for(\"vinext.cache.fallback\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\nconst _cacheAls = (_g[_ALS_KEY] ??= new AsyncLocalStorage<CacheState>()) as AsyncLocalStorage<CacheState>;\n\nconst _cacheFallbackState = (_g[_FALLBACK_KEY] ??= {\n requestScopedCacheLife: null,\n} satisfies CacheState) as CacheState;\n\nfunction _getCacheState(): CacheState {\n return _cacheAls.getStore() ?? _cacheFallbackState;\n}\n\n/**\n * Run a function within a cache state ALS scope.\n * Ensures per-request isolation for request-scoped cacheLife config\n * on concurrent runtimes.\n * @internal\n */\nexport function _runWithCacheState<T>(fn: () => T | Promise<T>): T | Promise<T> {\n const state: CacheState = {\n requestScopedCacheLife: null,\n };\n return _cacheAls.run(state, fn);\n}\n\n/**\n * Initialize cache ALS for a new request. Call at request entry.\n * Only needed when not using _runWithCacheState() (legacy path).\n * @internal\n */\nexport function _initRequestScopedCacheState(): void {\n const state = _cacheAls.getStore();\n if (state) {\n state.requestScopedCacheLife = null;\n } else {\n _cacheFallbackState.requestScopedCacheLife = null;\n }\n}\n\n/**\n * Set a request-scoped cache life config. Called by cacheLife() when outside\n * a \"use cache\" function context.\n * @internal\n */\nexport function _setRequestScopedCacheLife(config: CacheLifeConfig): void {\n const state = _getCacheState();\n if (state.requestScopedCacheLife === null) {\n state.requestScopedCacheLife = { ...config };\n } else {\n // Minimum-wins rule\n if (config.stale !== undefined) {\n state.requestScopedCacheLife.stale = state.requestScopedCacheLife.stale !== undefined\n ? Math.min(state.requestScopedCacheLife.stale, config.stale)\n : config.stale;\n }\n if (config.revalidate !== undefined) {\n state.requestScopedCacheLife.revalidate = state.requestScopedCacheLife.revalidate !== undefined\n ? Math.min(state.requestScopedCacheLife.revalidate, config.revalidate)\n : config.revalidate;\n }\n if (config.expire !== undefined) {\n state.requestScopedCacheLife.expire = state.requestScopedCacheLife.expire !== undefined\n ? Math.min(state.requestScopedCacheLife.expire, config.expire)\n : config.expire;\n }\n }\n}\n\n/**\n * Consume and reset the request-scoped cache life. Returns null if none was set.\n * @internal\n */\nexport function _consumeRequestScopedCacheLife(): CacheLifeConfig | null {\n const state = _getCacheState();\n const config = state.requestScopedCacheLife;\n state.requestScopedCacheLife = null;\n return config;\n}\n\n// ---------------------------------------------------------------------------\n// cacheLife / cacheTag — Next.js 15+ \"use cache\" APIs\n// ---------------------------------------------------------------------------\n\n/**\n * Cache life configuration. Controls stale-while-revalidate behavior.\n */\nexport interface CacheLifeConfig {\n /** How long (seconds) the client can cache without checking the server */\n stale?: number;\n /** How frequently (seconds) the server cache refreshes */\n revalidate?: number;\n /** Max staleness (seconds) before deoptimizing to dynamic */\n expire?: number;\n}\n\n/**\n * Built-in cache life profiles matching Next.js 16.\n */\nexport const cacheLifeProfiles: Record<string, CacheLifeConfig> = {\n default: { revalidate: 900, expire: 4294967294 },\n seconds: { stale: 30, revalidate: 1, expire: 60 },\n minutes: { stale: 300, revalidate: 60, expire: 3600 },\n hours: { stale: 300, revalidate: 3600, expire: 86400 },\n days: { stale: 300, revalidate: 86400, expire: 604800 },\n weeks: { stale: 300, revalidate: 604800, expire: 2592000 },\n max: { stale: 300, revalidate: 2592000, expire: 31536000 },\n};\n\n/**\n * Set the cache lifetime for a \"use cache\" function.\n *\n * Accepts either a built-in profile name (e.g., \"hours\", \"days\") or a custom\n * configuration object. In Next.js, this only works inside \"use cache\" functions.\n *\n * When called inside a \"use cache\" function, this sets the cache TTL.\n * The \"minimum-wins\" rule applies: if called multiple times, the shortest\n * duration for each field wins.\n *\n * When called outside a \"use cache\" context, this is a validated no-op.\n */\nexport function cacheLife(profile: string | CacheLifeConfig): void {\n let resolvedConfig: CacheLifeConfig;\n\n if (typeof profile === \"string\") {\n // Validate the profile name exists\n if (!cacheLifeProfiles[profile]) {\n console.warn(\n `[vinext] cacheLife: unknown profile \"${profile}\". ` +\n `Available profiles: ${Object.keys(cacheLifeProfiles).join(\", \")}`,\n );\n return;\n }\n resolvedConfig = { ...cacheLifeProfiles[profile] };\n } else if (typeof profile === \"object\" && profile !== null) {\n // Validate the config shape\n if (\n profile.expire !== undefined &&\n profile.revalidate !== undefined &&\n profile.expire < profile.revalidate\n ) {\n console.warn(\n \"[vinext] cacheLife: expire must be >= revalidate\",\n );\n }\n resolvedConfig = { ...profile };\n } else {\n return;\n }\n\n // If we're inside a \"use cache\" context, push the config\n try {\n const ctx = _getCacheContextFn?.();\n if (ctx) {\n ctx.lifeConfigs.push(resolvedConfig);\n return;\n }\n } catch {\n // Fall through to request-scoped\n }\n\n // Outside a \"use cache\" context (e.g., page component with file-level \"use cache\"):\n // store as request-scoped so the server can read it after rendering.\n _setRequestScopedCacheLife(resolvedConfig);\n}\n\n/**\n * Tag a \"use cache\" function's cached result for on-demand revalidation.\n *\n * Tags set here can be invalidated via revalidateTag(). In Next.js, this only\n * works inside \"use cache\" functions.\n *\n * When called inside a \"use cache\" function, tags are attached to the cached\n * entry. They can later be invalidated via revalidateTag().\n *\n * When called outside a \"use cache\" context, this is a no-op.\n */\nexport function cacheTag(...tags: string[]): void {\n try {\n const ctx = _getCacheContextFn?.();\n if (ctx) {\n ctx.tags.push(...tags);\n }\n } catch {\n // Not in a cache context — no-op\n }\n}\n\n// ---------------------------------------------------------------------------\n// unstable_cache — the older caching API\n// ---------------------------------------------------------------------------\n\n/**\n * AsyncLocalStorage to track whether we're inside an unstable_cache() callback.\n * Stored on globalThis via Symbol so headers.ts can detect the scope without\n * a direct import (avoiding circular dependencies).\n */\nconst _UNSTABLE_CACHE_ALS_KEY = Symbol.for(\"vinext.unstableCache.als\");\nconst _unstableCacheAls = (\n (_g[_UNSTABLE_CACHE_ALS_KEY] ??= new AsyncLocalStorage<boolean>()) as AsyncLocalStorage<boolean>\n);\n\n/**\n * Check if the current execution context is inside an unstable_cache() callback.\n * Used by headers(), cookies(), and connection() to throw errors when\n * dynamic request APIs are called inside a cache scope.\n */\nexport function isInsideUnstableCacheScope(): boolean {\n return _unstableCacheAls.getStore() === true;\n}\n\ninterface UnstableCacheOptions {\n revalidate?: number | false;\n tags?: string[];\n}\n\n/**\n * Wrap an async function with caching.\n *\n * Returns a new function that caches results. The cache key is derived\n * from keyParts + serialized arguments.\n */\nexport function unstable_cache<T extends (...args: any[]) => Promise<any>>(\n fn: T,\n keyParts?: string[],\n options?: UnstableCacheOptions,\n): T {\n const baseKey = keyParts\n ? keyParts.join(\":\")\n : fnv1a64(fn.toString());\n const tags = options?.tags ?? [];\n const revalidateSeconds = options?.revalidate;\n\n const cachedFn = async (...args: any[]): Promise<any> => {\n const argsKey = JSON.stringify(args);\n const cacheKey = `unstable_cache:${baseKey}:${argsKey}`;\n\n // Try to get from cache. Check cacheState so time-expired entries\n // trigger a re-fetch instead of being served indefinitely.\n const existing = await activeHandler.get(cacheKey, {\n kind: \"FETCH\",\n tags,\n });\n if (existing?.value && existing.value.kind === \"FETCH\" && existing.cacheState !== \"stale\") {\n try {\n return JSON.parse(existing.value.data.body);\n } catch {\n // Corrupted entry, fall through to re-fetch\n }\n }\n\n // Cache miss — call the function inside the unstable_cache ALS scope\n // so that headers()/cookies()/connection() can detect they're in a\n // cache scope and throw an appropriate error.\n const result = await _unstableCacheAls.run(true, () => fn(...args));\n\n // Store in cache using the FETCH kind\n const cacheValue: CachedFetchValue = {\n kind: \"FETCH\",\n data: {\n headers: {},\n body: JSON.stringify(result),\n url: cacheKey,\n },\n tags,\n // revalidate: false means \"cache indefinitely\" (no time-based expiry).\n // A positive number means time-based revalidation in seconds.\n // When unset (undefined), default to false (indefinite) matching\n // Next.js behavior for unstable_cache without explicit revalidate.\n revalidate: typeof revalidateSeconds === \"number\" ? revalidateSeconds : false,\n };\n\n await activeHandler.set(cacheKey, cacheValue, {\n fetchCache: true,\n tags,\n revalidate: revalidateSeconds,\n });\n\n return result;\n };\n\n return cachedFn as T;\n}\n"]}
@@ -28,6 +28,7 @@ export declare function resolveModuleViewport(mod: Record<string, unknown>, para
28
28
  * Merge viewport configs from multiple sources (layouts + page).
29
29
  * Later entries override earlier ones.
30
30
  */
31
+ export declare const DEFAULT_VIEWPORT: Viewport;
31
32
  export declare function mergeViewport(viewportList: Viewport[]): Viewport;
32
33
  /**
33
34
  * React component that renders viewport meta tags into <head>.