vinext 0.0.37 → 0.0.39

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 (262) hide show
  1. package/README.md +33 -20
  2. package/dist/build/nitro-route-rules.d.ts +50 -0
  3. package/dist/build/nitro-route-rules.js +81 -0
  4. package/dist/build/nitro-route-rules.js.map +1 -0
  5. package/dist/build/precompress.d.ts +17 -0
  6. package/dist/build/precompress.js +102 -0
  7. package/dist/build/precompress.js.map +1 -0
  8. package/dist/build/prerender.d.ts +27 -22
  9. package/dist/build/prerender.js +17 -17
  10. package/dist/build/prerender.js.map +1 -1
  11. package/dist/build/report.d.ts +3 -4
  12. package/dist/build/report.js.map +1 -1
  13. package/dist/build/run-prerender.d.ts +3 -4
  14. package/dist/build/run-prerender.js.map +1 -1
  15. package/dist/build/standalone.d.ts +32 -0
  16. package/dist/build/standalone.js +199 -0
  17. package/dist/build/standalone.js.map +1 -0
  18. package/dist/build/static-export.d.ts +17 -29
  19. package/dist/build/static-export.js.map +1 -1
  20. package/dist/cache.d.ts +2 -0
  21. package/dist/cache.js +2 -0
  22. package/dist/check.d.ts +4 -4
  23. package/dist/check.js +1 -1
  24. package/dist/check.js.map +1 -1
  25. package/dist/cli.js +37 -26
  26. package/dist/cli.js.map +1 -1
  27. package/dist/client/empty-module.d.ts +1 -0
  28. package/dist/client/empty-module.js +1 -0
  29. package/dist/client/entry.js +2 -0
  30. package/dist/client/entry.js.map +1 -1
  31. package/dist/client/instrumentation-client-state.d.ts +10 -0
  32. package/dist/client/instrumentation-client-state.js +19 -0
  33. package/dist/client/instrumentation-client-state.js.map +1 -0
  34. package/dist/client/instrumentation-client.d.ts +8 -0
  35. package/dist/client/instrumentation-client.js +8 -0
  36. package/dist/client/instrumentation-client.js.map +1 -0
  37. package/dist/client/vinext-next-data.d.ts +5 -8
  38. package/dist/cloudflare/index.js +1 -1
  39. package/dist/cloudflare/kv-cache-handler.d.ts +5 -3
  40. package/dist/cloudflare/kv-cache-handler.js +1 -1
  41. package/dist/cloudflare/kv-cache-handler.js.map +1 -1
  42. package/dist/cloudflare/tpr.d.ts +35 -27
  43. package/dist/cloudflare/tpr.js +37 -15
  44. package/dist/cloudflare/tpr.js.map +1 -1
  45. package/dist/config/config-matchers.d.ts +2 -2
  46. package/dist/config/config-matchers.js +1 -1
  47. package/dist/config/config-matchers.js.map +1 -1
  48. package/dist/config/dotenv.d.ts +4 -4
  49. package/dist/config/dotenv.js.map +1 -1
  50. package/dist/config/next-config.d.ts +40 -61
  51. package/dist/config/next-config.js +5 -4
  52. package/dist/config/next-config.js.map +1 -1
  53. package/dist/deploy.d.ts +25 -41
  54. package/dist/deploy.js +10 -4
  55. package/dist/deploy.js.map +1 -1
  56. package/dist/entries/app-rsc-entry.d.ts +6 -10
  57. package/dist/entries/app-rsc-entry.js +31 -28
  58. package/dist/entries/app-rsc-entry.js.map +1 -1
  59. package/dist/entries/pages-client-entry.js +2 -0
  60. package/dist/entries/pages-client-entry.js.map +1 -1
  61. package/dist/entries/pages-server-entry.js +42 -263
  62. package/dist/entries/pages-server-entry.js.map +1 -1
  63. package/dist/entries/runtime-entry-module.d.ts +13 -1
  64. package/dist/entries/runtime-entry-module.js +18 -4
  65. package/dist/entries/runtime-entry-module.js.map +1 -1
  66. package/dist/index.d.ts +33 -41
  67. package/dist/index.js +263 -777
  68. package/dist/index.js.map +1 -1
  69. package/dist/init.d.ts +14 -26
  70. package/dist/init.js +8 -2
  71. package/dist/init.js.map +1 -1
  72. package/dist/plugins/client-reference-dedup.js.map +1 -1
  73. package/dist/plugins/fix-use-server-closure-collision.d.ts +29 -0
  74. package/dist/plugins/fix-use-server-closure-collision.js +204 -0
  75. package/dist/plugins/fix-use-server-closure-collision.js.map +1 -0
  76. package/dist/plugins/fonts.d.ts +56 -0
  77. package/dist/plugins/fonts.js +531 -0
  78. package/dist/plugins/fonts.js.map +1 -0
  79. package/dist/plugins/instrumentation-client.d.ts +7 -0
  80. package/dist/plugins/instrumentation-client.js +29 -0
  81. package/dist/plugins/instrumentation-client.js.map +1 -0
  82. package/dist/plugins/og-assets.d.ts +26 -0
  83. package/dist/plugins/og-assets.js +118 -0
  84. package/dist/plugins/og-assets.js.map +1 -0
  85. package/dist/plugins/optimize-imports.d.ts +2 -2
  86. package/dist/plugins/optimize-imports.js +4 -4
  87. package/dist/plugins/optimize-imports.js.map +1 -1
  88. package/dist/plugins/server-externals-manifest.d.ts +27 -0
  89. package/dist/plugins/server-externals-manifest.js +76 -0
  90. package/dist/plugins/server-externals-manifest.js.map +1 -0
  91. package/dist/routing/app-router.d.ts +29 -55
  92. package/dist/routing/app-router.js.map +1 -1
  93. package/dist/routing/file-matcher.d.ts +2 -2
  94. package/dist/routing/file-matcher.js.map +1 -1
  95. package/dist/routing/pages-router.d.ts +6 -11
  96. package/dist/routing/pages-router.js.map +1 -1
  97. package/dist/routing/route-trie.d.ts +2 -2
  98. package/dist/routing/route-trie.js.map +1 -1
  99. package/dist/server/api-handler.js +6 -23
  100. package/dist/server/api-handler.js.map +1 -1
  101. package/dist/server/app-browser-entry.js +274 -39
  102. package/dist/server/app-browser-entry.js.map +1 -1
  103. package/dist/server/app-browser-stream.d.ts +6 -6
  104. package/dist/server/app-browser-stream.js.map +1 -1
  105. package/dist/server/app-page-boundary-render.d.ts +8 -8
  106. package/dist/server/app-page-boundary-render.js +2 -2
  107. package/dist/server/app-page-boundary-render.js.map +1 -1
  108. package/dist/server/app-page-boundary.d.ts +13 -11
  109. package/dist/server/app-page-boundary.js +1 -1
  110. package/dist/server/app-page-boundary.js.map +1 -1
  111. package/dist/server/app-page-cache.d.ts +10 -10
  112. package/dist/server/app-page-cache.js.map +1 -1
  113. package/dist/server/app-page-execution.d.ts +10 -10
  114. package/dist/server/app-page-execution.js.map +1 -1
  115. package/dist/server/app-page-probe.d.ts +2 -2
  116. package/dist/server/app-page-probe.js.map +1 -1
  117. package/dist/server/app-page-render.d.ts +4 -4
  118. package/dist/server/app-page-render.js.map +1 -1
  119. package/dist/server/app-page-request.d.ts +12 -12
  120. package/dist/server/app-page-request.js.map +1 -1
  121. package/dist/server/app-page-response.d.ts +18 -18
  122. package/dist/server/app-page-response.js.map +1 -1
  123. package/dist/server/app-page-stream.d.ts +18 -18
  124. package/dist/server/app-page-stream.js.map +1 -1
  125. package/dist/server/app-route-handler-cache.d.ts +2 -2
  126. package/dist/server/app-route-handler-cache.js.map +1 -1
  127. package/dist/server/app-route-handler-execution.d.ts +6 -6
  128. package/dist/server/app-route-handler-execution.js.map +1 -1
  129. package/dist/server/app-route-handler-policy.d.ts +8 -8
  130. package/dist/server/app-route-handler-policy.js.map +1 -1
  131. package/dist/server/app-route-handler-response.d.ts +6 -6
  132. package/dist/server/app-route-handler-response.js.map +1 -1
  133. package/dist/server/app-route-handler-runtime.d.ts +4 -4
  134. package/dist/server/app-route-handler-runtime.js.map +1 -1
  135. package/dist/server/app-ssr-entry.d.ts +4 -4
  136. package/dist/server/app-ssr-entry.js.map +1 -1
  137. package/dist/server/app-ssr-stream.d.ts +2 -2
  138. package/dist/server/app-ssr-stream.js +1 -3
  139. package/dist/server/app-ssr-stream.js.map +1 -1
  140. package/dist/server/dev-module-runner.d.ts +2 -2
  141. package/dist/server/dev-module-runner.js.map +1 -1
  142. package/dist/server/dev-server.js +8 -8
  143. package/dist/server/dev-server.js.map +1 -1
  144. package/dist/server/image-optimization.d.ts +7 -12
  145. package/dist/server/image-optimization.js.map +1 -1
  146. package/dist/server/instrumentation.d.ts +13 -13
  147. package/dist/server/instrumentation.js +16 -7
  148. package/dist/server/instrumentation.js.map +1 -1
  149. package/dist/server/isr-cache.d.ts +2 -2
  150. package/dist/server/isr-cache.js.map +1 -1
  151. package/dist/server/metadata-routes.d.ts +14 -19
  152. package/dist/server/metadata-routes.js.map +1 -1
  153. package/dist/server/middleware.d.ts +10 -16
  154. package/dist/server/middleware.js +15 -8
  155. package/dist/server/middleware.js.map +1 -1
  156. package/dist/server/pages-api-route.d.ts +23 -0
  157. package/dist/server/pages-api-route.js +40 -0
  158. package/dist/server/pages-api-route.js.map +1 -0
  159. package/dist/server/pages-i18n.d.ts +4 -4
  160. package/dist/server/pages-i18n.js.map +1 -1
  161. package/dist/server/pages-media-type.d.ts +16 -0
  162. package/dist/server/pages-media-type.js +25 -0
  163. package/dist/server/pages-media-type.js.map +1 -0
  164. package/dist/server/pages-node-compat.d.ts +45 -0
  165. package/dist/server/pages-node-compat.js +148 -0
  166. package/dist/server/pages-node-compat.js.map +1 -0
  167. package/dist/server/pages-page-data.d.ts +22 -22
  168. package/dist/server/pages-page-data.js.map +1 -1
  169. package/dist/server/pages-page-response.d.ts +8 -8
  170. package/dist/server/pages-page-response.js.map +1 -1
  171. package/dist/server/prod-server.d.ts +20 -15
  172. package/dist/server/prod-server.js +171 -53
  173. package/dist/server/prod-server.js.map +1 -1
  174. package/dist/server/seed-cache.js.map +1 -1
  175. package/dist/server/static-file-cache.d.ts +57 -0
  176. package/dist/server/static-file-cache.js +219 -0
  177. package/dist/server/static-file-cache.js.map +1 -0
  178. package/dist/shims/app.d.ts +2 -2
  179. package/dist/shims/cache-for-request.d.ts +58 -0
  180. package/dist/shims/cache-for-request.js +74 -0
  181. package/dist/shims/cache-for-request.js.map +1 -0
  182. package/dist/shims/cache-runtime.d.ts +6 -9
  183. package/dist/shims/cache-runtime.js.map +1 -1
  184. package/dist/shims/cache.d.ts +28 -31
  185. package/dist/shims/cache.js.map +1 -1
  186. package/dist/shims/config.d.ts +2 -2
  187. package/dist/shims/config.js.map +1 -1
  188. package/dist/shims/dynamic.d.ts +2 -2
  189. package/dist/shims/dynamic.js +30 -17
  190. package/dist/shims/dynamic.js.map +1 -1
  191. package/dist/shims/error-boundary.d.ts +7 -7
  192. package/dist/shims/error-boundary.js.map +1 -1
  193. package/dist/shims/error.d.ts +2 -2
  194. package/dist/shims/error.js.map +1 -1
  195. package/dist/shims/fetch-cache.d.ts +4 -4
  196. package/dist/shims/fetch-cache.js.map +1 -1
  197. package/dist/shims/font-google-base.d.ts +4 -4
  198. package/dist/shims/font-google-base.js.map +1 -1
  199. package/dist/shims/font-local.d.ts +6 -6
  200. package/dist/shims/font-local.js.map +1 -1
  201. package/dist/shims/form.d.ts +4 -8
  202. package/dist/shims/form.js +4 -6
  203. package/dist/shims/form.js.map +1 -1
  204. package/dist/shims/head-state.d.ts +2 -2
  205. package/dist/shims/head-state.js.map +1 -1
  206. package/dist/shims/head.d.ts +2 -2
  207. package/dist/shims/head.js +18 -20
  208. package/dist/shims/head.js.map +1 -1
  209. package/dist/shims/headers.d.ts +4 -4
  210. package/dist/shims/headers.js +1 -1
  211. package/dist/shims/headers.js.map +1 -1
  212. package/dist/shims/i18n-context.d.ts +2 -2
  213. package/dist/shims/i18n-context.js.map +1 -1
  214. package/dist/shims/i18n-state.d.ts +2 -2
  215. package/dist/shims/i18n-state.js.map +1 -1
  216. package/dist/shims/image-config.d.ts +2 -2
  217. package/dist/shims/image-config.js.map +1 -1
  218. package/dist/shims/image.d.ts +5 -6
  219. package/dist/shims/image.js +24 -8
  220. package/dist/shims/image.js.map +1 -1
  221. package/dist/shims/internal/app-router-context.d.ts +6 -6
  222. package/dist/shims/internal/app-router-context.js.map +1 -1
  223. package/dist/shims/internal/utils.d.ts +2 -2
  224. package/dist/shims/internal/utils.js.map +1 -1
  225. package/dist/shims/layout-segment-context.d.ts +12 -5
  226. package/dist/shims/layout-segment-context.js +18 -7
  227. package/dist/shims/layout-segment-context.js.map +1 -1
  228. package/dist/shims/legacy-image.d.ts +5 -8
  229. package/dist/shims/legacy-image.js.map +1 -1
  230. package/dist/shims/link.d.ts +21 -31
  231. package/dist/shims/link.js +4 -56
  232. package/dist/shims/link.js.map +1 -1
  233. package/dist/shims/metadata.d.ts +23 -31
  234. package/dist/shims/metadata.js.map +1 -1
  235. package/dist/shims/navigation-state.d.ts +2 -2
  236. package/dist/shims/navigation-state.js.map +1 -1
  237. package/dist/shims/navigation.d.ts +102 -17
  238. package/dist/shims/navigation.js +361 -113
  239. package/dist/shims/navigation.js.map +1 -1
  240. package/dist/shims/request-context.d.ts +2 -2
  241. package/dist/shims/request-context.js.map +1 -1
  242. package/dist/shims/router-state.d.ts +4 -4
  243. package/dist/shims/router-state.js.map +1 -1
  244. package/dist/shims/router.d.ts +28 -47
  245. package/dist/shims/router.js.map +1 -1
  246. package/dist/shims/script.d.ts +16 -31
  247. package/dist/shims/script.js.map +1 -1
  248. package/dist/shims/server.d.ts +11 -10
  249. package/dist/shims/server.js +3 -0
  250. package/dist/shims/server.js.map +1 -1
  251. package/dist/shims/unified-request-context.d.ts +4 -4
  252. package/dist/shims/unified-request-context.js +1 -0
  253. package/dist/shims/unified-request-context.js.map +1 -1
  254. package/dist/shims/web-vitals.d.ts +2 -2
  255. package/dist/shims/web-vitals.js.map +1 -1
  256. package/dist/utils/lazy-chunks.d.ts +34 -0
  257. package/dist/utils/lazy-chunks.js +50 -0
  258. package/dist/utils/lazy-chunks.js.map +1 -0
  259. package/dist/utils/vinext-root.d.ts +24 -0
  260. package/dist/utils/vinext-root.js +31 -0
  261. package/dist/utils/vinext-root.js.map +1 -0
  262. package/package.json +8 -4
@@ -1 +1 @@
1
- {"version":3,"file":"tpr.js","names":[],"sources":["../../src/cloudflare/tpr.ts"],"sourcesContent":["/**\n * TPR: Traffic-aware Pre-Rendering\n *\n * Uses Cloudflare zone analytics to determine which pages actually get\n * traffic, and pre-renders only those during deploy. The pre-rendered\n * HTML is uploaded to KV in the same format ISR uses at runtime — no\n * runtime changes needed.\n *\n * Flow:\n * 1. Parse wrangler config to find custom domain and KV namespace\n * 2. Resolve the Cloudflare zone for the custom domain\n * 3. Query zone analytics (GraphQL) for top pages by request count\n * 4. Walk ranked list until coverage threshold is met\n * 5. Start the built production server locally\n * 6. Fetch each hot route to produce HTML\n * 7. Upload pre-rendered HTML to KV (same KVCacheEntry format ISR reads)\n *\n * TPR is an experimental feature enabled via --experimental-tpr. It\n * gracefully skips when no custom domain, no API token, no traffic data,\n * or no KV namespace is configured.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawn, type ChildProcess } from \"node:child_process\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface TPROptions {\n /** Project root directory. */\n root: string;\n /** Traffic coverage percentage (0–100). Default: 90. */\n coverage: number;\n /** Hard cap on number of pages to pre-render. Default: 1000. */\n limit: number;\n /** Analytics lookback window in hours. Default: 24. */\n window: number;\n}\n\nexport interface TPRResult {\n /** Total unique page paths found in analytics. */\n totalPaths: number;\n /** Number of pages successfully pre-rendered and uploaded. */\n prerenderedCount: number;\n /** Actual traffic coverage achieved (percentage). */\n coverageAchieved: number;\n /** Wall-clock duration of the TPR step in milliseconds. */\n durationMs: number;\n /** If TPR was skipped, the reason. */\n skipped?: string;\n}\n\ninterface TrafficEntry {\n path: string;\n requests: number;\n}\n\ninterface SelectedRoutes {\n routes: TrafficEntry[];\n totalRequests: number;\n coveredRequests: number;\n coveragePercent: number;\n}\n\ninterface PrerenderResult {\n html: string;\n status: number;\n headers: Record<string, string>;\n}\n\ninterface WranglerConfig {\n accountId?: string;\n kvNamespaceId?: string;\n customDomain?: string;\n}\n\n// ─── Wrangler Config Parsing ─────────────────────────────────────────────────\n\n/**\n * Parse wrangler config (JSONC or TOML) to extract the fields TPR needs:\n * account_id, VINEXT_CACHE KV namespace ID, and custom domain.\n */\nexport function parseWranglerConfig(root: string): WranglerConfig | null {\n // Try JSONC / JSON first\n for (const filename of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const filepath = path.join(root, filename);\n if (fs.existsSync(filepath)) {\n const content = fs.readFileSync(filepath, \"utf-8\");\n try {\n const json = JSON.parse(stripJsonComments(content));\n return extractFromJSON(json);\n } catch {\n continue;\n }\n }\n }\n\n // Try TOML\n const tomlPath = path.join(root, \"wrangler.toml\");\n if (fs.existsSync(tomlPath)) {\n const content = fs.readFileSync(tomlPath, \"utf-8\");\n return extractFromTOML(content);\n }\n\n return null;\n}\n\n/**\n * Strip single-line (//) and multi-line comments from JSONC while\n * preserving strings that contain slashes.\n */\nfunction stripJsonComments(str: string): string {\n let result = \"\";\n let inString = false;\n let inSingleLine = false;\n let inMultiLine = false;\n let escapeNext = false;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n const next = str[i + 1];\n\n if (escapeNext) {\n if (!inSingleLine && !inMultiLine) result += ch;\n escapeNext = false;\n continue;\n }\n\n if (ch === \"\\\\\" && inString) {\n result += ch;\n escapeNext = true;\n continue;\n }\n\n if (inSingleLine) {\n if (ch === \"\\n\") {\n inSingleLine = false;\n result += ch;\n }\n continue;\n }\n\n if (inMultiLine) {\n if (ch === \"*\" && next === \"/\") {\n inMultiLine = false;\n i++;\n }\n continue;\n }\n\n if (ch === '\"' && !inString) {\n inString = true;\n result += ch;\n continue;\n }\n\n if (ch === '\"' && inString) {\n inString = false;\n result += ch;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"/\") {\n inSingleLine = true;\n i++;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"*\") {\n inMultiLine = true;\n i++;\n continue;\n }\n\n result += ch;\n }\n\n return result;\n}\n\nfunction extractFromJSON(config: Record<string, unknown>): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id\n if (typeof config.account_id === \"string\") {\n result.accountId = config.account_id;\n }\n\n // KV namespace ID for VINEXT_CACHE\n if (Array.isArray(config.kv_namespaces)) {\n const vinextKV = config.kv_namespaces.find(\n (ns: Record<string, unknown>) =>\n ns && typeof ns === \"object\" && ns.binding === \"VINEXT_CACHE\",\n );\n if (vinextKV && typeof vinextKV.id === \"string\" && vinextKV.id !== \"<your-kv-namespace-id>\") {\n result.kvNamespaceId = vinextKV.id;\n }\n }\n\n // Custom domain — check routes[] and custom_domains[]\n const domain = extractDomainFromRoutes(config.routes) ?? extractDomainFromCustomDomains(config);\n if (domain) result.customDomain = domain;\n\n return result;\n}\n\nfunction extractDomainFromRoutes(routes: unknown): string | null {\n if (!Array.isArray(routes)) return null;\n\n for (const route of routes) {\n if (typeof route === \"string\") {\n const domain = cleanDomain(route);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n } else if (route && typeof route === \"object\") {\n const r = route as Record<string, unknown>;\n const pattern =\n typeof r.zone_name === \"string\"\n ? r.zone_name\n : typeof r.pattern === \"string\"\n ? r.pattern\n : null;\n if (pattern) {\n const domain = cleanDomain(pattern);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n }\n }\n }\n return null;\n}\n\nfunction extractDomainFromCustomDomains(config: Record<string, unknown>): string | null {\n // Workers Custom Domains: \"custom_domains\": [\"example.com\"]\n if (Array.isArray(config.custom_domains)) {\n for (const d of config.custom_domains) {\n if (typeof d === \"string\" && !d.includes(\"workers.dev\")) {\n return cleanDomain(d);\n }\n }\n }\n return null;\n}\n\n/** Strip protocol and trailing wildcards from a route pattern to get a bare domain. */\nfunction cleanDomain(raw: string): string | null {\n const cleaned = raw\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/\\*$/, \"\")\n .replace(/\\/+$/, \"\")\n .split(\"/\")[0]; // Take only the host part\n return cleaned || null;\n}\n\n/**\n * Simple extraction of specific fields from wrangler.toml content.\n * Not a full TOML parser — just enough for the fields we need.\n */\nfunction extractFromTOML(content: string): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id = \"...\"\n const accountMatch = content.match(/^account_id\\s*=\\s*\"([^\"]+)\"/m);\n if (accountMatch) result.accountId = accountMatch[1];\n\n // KV namespace with binding = \"VINEXT_CACHE\"\n // Look for [[kv_namespaces]] blocks\n const kvBlocks = content.split(/\\[\\[kv_namespaces\\]\\]/);\n for (let i = 1; i < kvBlocks.length; i++) {\n const block = kvBlocks[i].split(/\\[\\[/)[0]; // Take until next section\n const bindingMatch = block.match(/binding\\s*=\\s*\"([^\"]+)\"/);\n const idMatch = block.match(/\\bid\\s*=\\s*\"([^\"]+)\"/);\n if (\n bindingMatch?.[1] === \"VINEXT_CACHE\" &&\n idMatch?.[1] &&\n idMatch[1] !== \"<your-kv-namespace-id>\"\n ) {\n result.kvNamespaceId = idMatch[1];\n }\n }\n\n // routes — both string and table forms\n // route = \"example.com/*\"\n const routeMatch = content.match(/^route\\s*=\\s*\"([^\"]+)\"/m);\n if (routeMatch) {\n const domain = cleanDomain(routeMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n }\n }\n\n // [[routes]] blocks\n if (!result.customDomain) {\n const routeBlocks = content.split(/\\[\\[routes\\]\\]/);\n for (let i = 1; i < routeBlocks.length; i++) {\n const block = routeBlocks[i].split(/\\[\\[/)[0];\n const patternMatch = block.match(/pattern\\s*=\\s*\"([^\"]+)\"/);\n if (patternMatch) {\n const domain = cleanDomain(patternMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\n// ─── Cloudflare API ──────────────────────────────────────────────────────────\n\n/**\n * Generate zone lookup candidates from shortest (2-part) to longest.\n * Tries the most common case first (e.g., \"example.com\") and progressively\n * adds labels for multi-part TLDs (e.g., \"co.uk\" → \"example.co.uk\").\n *\n * \"shop.example.com\" → [\"example.com\", \"shop.example.com\"]\n * \"shop.example.co.uk\" → [\"co.uk\", \"example.co.uk\", \"shop.example.co.uk\"]\n * \"example.com\" → [\"example.com\"]\n */\nexport function domainCandidates(domain: string): string[] {\n const parts = domain.split(\".\");\n const candidates: string[] = [];\n for (let i = parts.length - 2; i >= 0; i--) {\n candidates.push(parts.slice(i).join(\".\"));\n }\n return candidates;\n}\n\n/** Resolve zone ID from a domain name via the Cloudflare API. */\nasync function resolveZoneId(domain: string, apiToken: string): Promise<string | null> {\n // Try progressively longer domain candidates until one matches a zone.\n // This handles all public suffixes without a hardcoded TLD list —\n // for simple TLDs (.com, .io) the 2-part candidate hits on the first try;\n // for multi-part TLDs (.co.uk, .com.au) it takes one extra call.\n for (const candidate of domainCandidates(domain)) {\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(candidate)}`,\n {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n if (!response.ok) continue;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (data.success && data.result?.length) {\n return data.result[0].id;\n }\n }\n\n return null;\n}\n\n/** Resolve the account ID associated with the API token. */\nasync function resolveAccountId(apiToken: string): Promise<string | null> {\n const response = await fetch(\"https://api.cloudflare.com/client/v4/accounts?per_page=1\", {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) return null;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (!data.success || !data.result?.length) return null;\n\n return data.result[0].id;\n}\n\n// ─── Traffic Querying ────────────────────────────────────────────────────────\n\n/**\n * Query Cloudflare zone analytics for top page paths by request count\n * over the given time window.\n */\nasync function queryTraffic(\n zoneTag: string,\n apiToken: string,\n windowHours: number,\n): Promise<TrafficEntry[]> {\n const now = new Date();\n const start = new Date(now.getTime() - windowHours * 60 * 60 * 1000);\n\n const query = `{\n viewer {\n zones(filter: { zoneTag: \"${zoneTag}\" }) {\n httpRequestsAdaptiveGroups(\n limit: 10000\n orderBy: [sum_requests_DESC]\n filter: {\n datetime_geq: \"${start.toISOString()}\"\n datetime_lt: \"${now.toISOString()}\"\n requestSource: \"eyeball\"\n }\n ) {\n sum { requests }\n dimensions { clientRequestPath }\n }\n }\n }\n }`;\n\n const response = await fetch(\"https://api.cloudflare.com/client/v4/graphql\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ query }),\n });\n\n if (!response.ok) {\n throw new Error(`Zone analytics query failed: ${response.status} ${response.statusText}`);\n }\n\n const data = (await response.json()) as {\n errors?: Array<{ message: string }>;\n data?: {\n viewer?: {\n zones?: Array<{\n httpRequestsAdaptiveGroups?: Array<{\n sum: { requests: number };\n dimensions: { clientRequestPath: string };\n }>;\n }>;\n };\n };\n };\n\n if (data.errors?.length) {\n throw new Error(`Zone analytics error: ${data.errors[0].message}`);\n }\n\n const groups = data.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups;\n if (!groups || groups.length === 0) return [];\n\n return filterTrafficPaths(\n groups.map((g) => ({\n path: g.dimensions.clientRequestPath,\n requests: g.sum.requests,\n })),\n );\n}\n\n/** Filter out non-page requests (static assets, API routes, internal routes). */\nfunction filterTrafficPaths(entries: TrafficEntry[]): TrafficEntry[] {\n return entries.filter((e) => {\n if (!e.path.startsWith(\"/\")) return false;\n // Static assets\n if (/\\.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|map|webp|avif)$/i.test(e.path))\n return false;\n // API routes\n if (e.path.startsWith(\"/api/\")) return false;\n // Internal routes\n if (e.path.startsWith(\"/_vinext/\") || e.path.startsWith(\"/_next/\")) return false;\n // RSC requests\n if (e.path.endsWith(\".rsc\")) return false;\n return true;\n });\n}\n\n// ─── Route Selection ─────────────────────────────────────────────────────────\n\n/**\n * Walk the ranked traffic list, accumulating request counts until the\n * coverage target is met or the hard cap is reached.\n */\nexport function selectRoutes(\n traffic: TrafficEntry[],\n coverageTarget: number,\n limit: number,\n): SelectedRoutes {\n const totalRequests = traffic.reduce((sum, e) => sum + e.requests, 0);\n if (totalRequests === 0) {\n return { routes: [], totalRequests: 0, coveredRequests: 0, coveragePercent: 0 };\n }\n\n const target = totalRequests * (coverageTarget / 100);\n const selected: TrafficEntry[] = [];\n let accumulated = 0;\n\n // Traffic is already sorted DESC by requests from the GraphQL query\n for (const entry of traffic) {\n if (accumulated >= target || selected.length >= limit) break;\n selected.push(entry);\n accumulated += entry.requests;\n }\n\n return {\n routes: selected,\n totalRequests,\n coveredRequests: accumulated,\n coveragePercent: (accumulated / totalRequests) * 100,\n };\n}\n\n// ─── Pre-rendering ───────────────────────────────────────────────────────────\n\n/** Pre-render port — high number to avoid collisions with dev servers. */\nconst PRERENDER_PORT = 19384;\n\n/** Max time to wait for the local server to start (ms). */\nconst SERVER_STARTUP_TIMEOUT = 30_000;\n\n/** Max concurrent fetch requests during pre-rendering. */\nconst FETCH_CONCURRENCY = 10;\n\n/**\n * Start a local production server, fetch each route to produce HTML,\n * and return the results. Pages that fail to render are skipped.\n */\nasync function prerenderRoutes(\n routes: string[],\n root: string,\n hostDomain?: string,\n): Promise<Map<string, PrerenderResult>> {\n const results = new Map<string, PrerenderResult>();\n let failedCount = 0;\n const port = PRERENDER_PORT;\n\n // Verify dist/ exists\n const distDir = path.join(root, \"dist\");\n if (!fs.existsSync(distDir)) {\n console.log(\" TPR: Skipping pre-render — dist/ directory not found\");\n return results;\n }\n\n // Start the local production server as a subprocess\n const serverProcess = startLocalServer(root, port);\n\n try {\n await waitForServer(port, SERVER_STARTUP_TIMEOUT);\n\n // Fetch routes in batches to limit concurrency\n for (let i = 0; i < routes.length; i += FETCH_CONCURRENCY) {\n const batch = routes.slice(i, i + FETCH_CONCURRENCY);\n const promises = batch.map(async (routePath) => {\n try {\n const response = await fetch(`http://127.0.0.1:${port}${routePath}`, {\n headers: {\n \"User-Agent\": \"vinext-tpr/1.0\",\n ...(hostDomain ? { Host: hostDomain } : {}),\n },\n redirect: \"manual\", // Don't follow redirects — cache the redirect itself\n });\n\n // Only cache successful responses (2xx and 3xx)\n if (response.status < 400) {\n const html = await response.text();\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n // Only keep relevant headers\n if (\n key === \"content-type\" ||\n key === \"cache-control\" ||\n key === \"x-vinext-revalidate\" ||\n key === \"location\"\n ) {\n headers[key] = value;\n }\n });\n results.set(routePath, {\n html,\n status: response.status,\n headers,\n });\n }\n } catch {\n // Skip pages that fail to render — they may depend on\n // request-specific data (cookies, headers, auth) that\n // isn't available during pre-rendering.\n failedCount++;\n }\n });\n\n await Promise.all(promises);\n }\n\n if (failedCount > 0) {\n console.log(` TPR: ${failedCount} page(s) failed to pre-render (skipped)`);\n }\n } finally {\n serverProcess.kill(\"SIGTERM\");\n // Give it a moment to clean up\n await new Promise<void>((resolve) => {\n serverProcess.on(\"exit\", resolve);\n setTimeout(resolve, 2000);\n });\n }\n\n return results;\n}\n\n/**\n * Spawn a subprocess running the vinext production server.\n * Uses the same Node.js binary and resolves prod-server.js relative\n * to the current module (works whether vinext is installed or linked).\n */\nfunction startLocalServer(root: string, port: number): ChildProcess {\n const thisDir = fileURLToPath(new URL(\".\", import.meta.url));\n const prodServerPath = path.resolve(thisDir, \"..\", \"server\", \"prod-server.js\");\n const outDir = path.join(root, \"dist\");\n\n // Escape backslashes for Windows paths inside the JS string\n const escapedProdServer = prodServerPath.replace(/\\\\/g, \"\\\\\\\\\");\n const escapedOutDir = outDir.replace(/\\\\/g, \"\\\\\\\\\");\n\n const script = [\n `import(\"file://${escapedProdServer}\")`,\n `.then(m => m.startProdServer({ port: ${port}, host: \"127.0.0.1\", outDir: \"${escapedOutDir}\" }))`,\n `.catch(e => { console.error(\"[vinext-tpr] Server failed to start:\", e); process.exit(1); });`,\n ].join(\"\");\n\n const proc = spawn(process.execPath, [\"--input-type=module\", \"-e\", script], {\n cwd: root,\n stdio: \"pipe\",\n env: { ...process.env, NODE_ENV: \"production\" },\n });\n\n // Forward server errors to the parent's stderr for debugging\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n const msg = chunk.toString().trim();\n if (msg) console.error(` [tpr-server] ${msg}`);\n });\n\n return proc;\n}\n\n/** Poll the local server until it responds or the timeout is reached. */\nasync function waitForServer(port: number, timeoutMs: number): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2000);\n const response = await fetch(`http://127.0.0.1:${port}/`, {\n redirect: \"manual\",\n signal: controller.signal,\n });\n clearTimeout(timer);\n // Any response means the server is up\n await response.text(); // consume body\n return;\n } catch {\n await new Promise<void>((r) => setTimeout(r, 300));\n }\n }\n throw new Error(`Local production server failed to start within ${timeoutMs / 1000}s`);\n}\n\n// ─── KV Upload ───────────────────────────────────────────────────────────────\n\n/**\n * Upload pre-rendered pages to KV using the Cloudflare REST API.\n * Writes in the same KVCacheEntry format that KVCacheHandler reads\n * at runtime, so ISR serves these entries without any code changes.\n */\nasync function uploadToKV(\n entries: Map<string, PrerenderResult>,\n namespaceId: string,\n accountId: string,\n apiToken: string,\n defaultRevalidateSeconds: number,\n): Promise<void> {\n const now = Date.now();\n\n // Build the bulk write payload\n const pairs: Array<{\n key: string;\n value: string;\n expiration_ttl?: number;\n }> = [];\n\n for (const [routePath, result] of entries) {\n // Determine revalidation window — use the page's revalidate header\n // if present, otherwise fall back to the default\n const revalidateHeader = result.headers[\"x-vinext-revalidate\"];\n const revalidateSeconds =\n revalidateHeader && !isNaN(Number(revalidateHeader))\n ? Number(revalidateHeader)\n : defaultRevalidateSeconds;\n\n const revalidateAt = revalidateSeconds > 0 ? now + revalidateSeconds * 1000 : null;\n\n // KV TTL: 10x the revalidation period, clamped to [60s, 30d]\n // (matches the logic in KVCacheHandler.set)\n const kvTtl =\n revalidateSeconds > 0\n ? Math.max(Math.min(revalidateSeconds * 10, 30 * 24 * 3600), 60)\n : 24 * 3600; // 24h fallback if no revalidation\n\n const entry = {\n value: {\n kind: \"APP_PAGE\" as const,\n html: result.html,\n headers: result.headers,\n status: result.status,\n },\n tags: [] as string[],\n lastModified: now,\n revalidateAt,\n };\n\n pairs.push({\n key: `cache:${routePath}`,\n value: JSON.stringify(entry),\n expiration_ttl: kvTtl,\n });\n }\n\n // Upload in batches (KV bulk API accepts up to 10,000 per request)\n const BATCH_SIZE = 10_000;\n for (let i = 0; i < pairs.length; i += BATCH_SIZE) {\n const batch = pairs.slice(i, i + BATCH_SIZE);\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,\n {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(batch),\n },\n );\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `KV bulk upload failed (batch ${Math.floor(i / BATCH_SIZE) + 1}): ${response.status} — ${text}`,\n );\n }\n }\n}\n\n// ─── Main Entry ──────────────────────────────────────────────────────────────\n\n/** Default revalidation TTL for pre-rendered pages (1 hour). */\nconst DEFAULT_REVALIDATE_SECONDS = 3600;\n\n/**\n * Run the TPR pipeline: query traffic, select routes, pre-render, upload.\n *\n * Designed to be called between the build step and wrangler deploy in\n * the `vinext deploy` pipeline. Gracefully skips (never errors) when\n * the prerequisites aren't met.\n */\nexport async function runTPR(options: TPROptions): Promise<TPRResult> {\n const startTime = Date.now();\n const { root, coverage, limit, window: windowHours } = options;\n\n const skip = (reason: string): TPRResult => ({\n totalPaths: 0,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: reason,\n });\n\n // ── 1. Check for API token ────────────────────────────────────\n const apiToken = process.env.CLOUDFLARE_API_TOKEN;\n if (!apiToken) {\n return skip(\"no CLOUDFLARE_API_TOKEN set\");\n }\n\n // ── 2. Parse wrangler config ──────────────────────────────────\n const wranglerConfig = parseWranglerConfig(root);\n if (!wranglerConfig) {\n return skip(\"could not parse wrangler config\");\n }\n\n // ── 3. Check for custom domain ────────────────────────────────\n if (!wranglerConfig.customDomain) {\n return skip(\"no custom domain — zone analytics unavailable\");\n }\n\n // ── 4. Check for KV namespace ─────────────────────────────────\n if (!wranglerConfig.kvNamespaceId) {\n return skip(\"no VINEXT_CACHE KV namespace configured\");\n }\n\n // ── 5. Resolve account ID ─────────────────────────────────────\n const accountId = wranglerConfig.accountId ?? (await resolveAccountId(apiToken));\n if (!accountId) {\n return skip(\"could not resolve Cloudflare account ID\");\n }\n\n // ── 6. Resolve zone ID ────────────────────────────────────────\n console.log(` TPR: Analyzing traffic for ${wranglerConfig.customDomain} (last ${windowHours}h)`);\n\n const zoneId = await resolveZoneId(wranglerConfig.customDomain, apiToken);\n if (!zoneId) {\n return skip(`could not resolve zone for ${wranglerConfig.customDomain}`);\n }\n\n // ── 7. Query traffic data ─────────────────────────────────────\n let traffic: TrafficEntry[];\n try {\n traffic = await queryTraffic(zoneId, apiToken, windowHours);\n } catch (err) {\n return skip(`analytics query failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (traffic.length === 0) {\n return skip(\"no traffic data available (first deploy?)\");\n }\n\n // ── 8. Select routes by coverage ──────────────────────────────\n const selection = selectRoutes(traffic, coverage, limit);\n\n console.log(\n ` TPR: ${traffic.length.toLocaleString()} unique paths — ` +\n `${selection.routes.length} pages cover ${Math.round(selection.coveragePercent)}% of traffic`,\n );\n\n if (selection.routes.length === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: \"no pre-renderable routes after filtering\",\n };\n }\n\n // ── 9. Pre-render selected routes ─────────────────────────────\n console.log(` TPR: Pre-rendering ${selection.routes.length} pages...`);\n\n const routePaths = selection.routes.map((r) => r.path);\n let rendered: Map<string, PrerenderResult>;\n try {\n rendered = await prerenderRoutes(routePaths, root, wranglerConfig.customDomain);\n } catch (err) {\n return skip(`pre-rendering failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (rendered.size === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: selection.coveragePercent,\n durationMs: Date.now() - startTime,\n skipped: \"all pages failed to pre-render (request-dependent?)\",\n };\n }\n\n // ── 10. Upload to KV ──────────────────────────────────────────\n try {\n await uploadToKV(\n rendered,\n wranglerConfig.kvNamespaceId,\n accountId,\n apiToken,\n DEFAULT_REVALIDATE_SECONDS,\n );\n } catch (err) {\n return skip(`KV upload failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const durationMs = Date.now() - startTime;\n console.log(\n ` TPR: Pre-rendered ${rendered.size} pages in ${(durationMs / 1000).toFixed(1)}s → KV cache`,\n );\n\n return {\n totalPaths: traffic.length,\n pr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Q,IAAI,UAAU,OAAO,IAAI,GAAG;;AAG1F,KAAI,SAAS,SAAS,EACpB,QAAO;EACL,YAAY,QAAQ;EACpB,kBAAkB;EAClB,kBAAkB,UAAU;EAC5B,YAAY,KAAK,KAAK,GAAG;EACzB,SAAS;EACV;AAIH,KAAI;AACF,QAAM,WACJ,UACA,eAAe,eACf,WACA,UACA,2BACD;UACM,KAAK;AACZ,SAAO,KAAK,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAAG;;CAGtF,MAAM,aAAa,KAAK,KAAK,GAAG;AAChC,SAAQ,IACN,uBAAuB,SAAS,KAAK,aAAa,aAAa,KAAM,QAAQ,EAAE,CAAC,cACjF;AAED,QAAO;EACL,YAAY,QAAQ;EACpB,kBAAkB,SAAS;EAC3B,kBAAkB,UAAU;EAC5B;EACD"}
1
+ {"version":3,"file":"tpr.js","names":[],"sources":["../../src/cloudflare/tpr.ts"],"sourcesContent":["/**\n * TPR: Traffic-aware Pre-Rendering\n *\n * Uses Cloudflare zone analytics to determine which pages actually get\n * traffic, and pre-renders only those during deploy. The pre-rendered\n * HTML is uploaded to KV in the same format ISR uses at runtime — no\n * runtime changes needed.\n *\n * Flow:\n * 1. Parse wrangler config to find custom domain and KV namespace\n * 2. Resolve the Cloudflare zone for the custom domain\n * 3. Query zone analytics (GraphQL) for top pages by request count\n * 4. Walk ranked list until coverage threshold is met\n * 5. Start the built production server locally\n * 6. Fetch each hot route to produce HTML\n * 7. Upload pre-rendered HTML to KV (same KVCacheEntry format ISR reads)\n *\n * TPR is an experimental feature enabled via --experimental-tpr. It\n * gracefully skips when no custom domain, no API token, no traffic data,\n * or no KV namespace is configured.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { isrCacheKey } from \"../server/isr-cache.js\";\nimport { ENTRY_PREFIX } from \"./kv-cache-handler.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type TPROptions = {\n /** Project root directory. */\n root: string;\n /** Traffic coverage percentage (0–100). Default: 90. */\n coverage: number;\n /** Hard cap on number of pages to pre-render. Default: 1000. */\n limit: number;\n /** Analytics lookback window in hours. Default: 24. */\n window: number;\n};\n\nexport type TPRResult = {\n /** Total unique page paths found in analytics. */\n totalPaths: number;\n /** Number of pages successfully pre-rendered and uploaded. */\n prerenderedCount: number;\n /** Actual traffic coverage achieved (percentage). */\n coverageAchieved: number;\n /** Wall-clock duration of the TPR step in milliseconds. */\n durationMs: number;\n /** If TPR was skipped, the reason. */\n skipped?: string;\n};\n\ntype TrafficEntry = {\n path: string;\n requests: number;\n};\n\ntype SelectedRoutes = {\n routes: TrafficEntry[];\n totalRequests: number;\n coveredRequests: number;\n coveragePercent: number;\n};\n\ntype PrerenderResult = {\n html: string;\n status: number;\n headers: Record<string, string>;\n};\n\ntype WranglerConfig = {\n accountId?: string;\n kvNamespaceId?: string;\n customDomain?: string;\n};\n\n// ─── Wrangler Config Parsing ─────────────────────────────────────────────────\n\n/**\n * Parse wrangler config (JSONC or TOML) to extract the fields TPR needs:\n * account_id, VINEXT_CACHE KV namespace ID, and custom domain.\n */\nexport function parseWranglerConfig(root: string): WranglerConfig | null {\n // Try JSONC / JSON first\n for (const filename of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const filepath = path.join(root, filename);\n if (fs.existsSync(filepath)) {\n const content = fs.readFileSync(filepath, \"utf-8\");\n try {\n const json = JSON.parse(stripJsonComments(content));\n return extractFromJSON(json);\n } catch {\n continue;\n }\n }\n }\n\n // Try TOML\n const tomlPath = path.join(root, \"wrangler.toml\");\n if (fs.existsSync(tomlPath)) {\n const content = fs.readFileSync(tomlPath, \"utf-8\");\n return extractFromTOML(content);\n }\n\n return null;\n}\n\n/**\n * Strip single-line (//) and multi-line comments from JSONC while\n * preserving strings that contain slashes.\n */\nfunction stripJsonComments(str: string): string {\n let result = \"\";\n let inString = false;\n let inSingleLine = false;\n let inMultiLine = false;\n let escapeNext = false;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n const next = str[i + 1];\n\n if (escapeNext) {\n if (!inSingleLine && !inMultiLine) result += ch;\n escapeNext = false;\n continue;\n }\n\n if (ch === \"\\\\\" && inString) {\n result += ch;\n escapeNext = true;\n continue;\n }\n\n if (inSingleLine) {\n if (ch === \"\\n\") {\n inSingleLine = false;\n result += ch;\n }\n continue;\n }\n\n if (inMultiLine) {\n if (ch === \"*\" && next === \"/\") {\n inMultiLine = false;\n i++;\n }\n continue;\n }\n\n if (ch === '\"' && !inString) {\n inString = true;\n result += ch;\n continue;\n }\n\n if (ch === '\"' && inString) {\n inString = false;\n result += ch;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"/\") {\n inSingleLine = true;\n i++;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"*\") {\n inMultiLine = true;\n i++;\n continue;\n }\n\n result += ch;\n }\n\n return result;\n}\n\nfunction extractFromJSON(config: Record<string, unknown>): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id\n if (typeof config.account_id === \"string\") {\n result.accountId = config.account_id;\n }\n\n // KV namespace ID for VINEXT_CACHE\n if (Array.isArray(config.kv_namespaces)) {\n const vinextKV = config.kv_namespaces.find(\n (ns: Record<string, unknown>) =>\n ns && typeof ns === \"object\" && ns.binding === \"VINEXT_CACHE\",\n );\n if (vinextKV && typeof vinextKV.id === \"string\" && vinextKV.id !== \"<your-kv-namespace-id>\") {\n result.kvNamespaceId = vinextKV.id;\n }\n }\n\n // Custom domain — check routes[] and custom_domains[]\n const domain = extractDomainFromRoutes(config.routes) ?? extractDomainFromCustomDomains(config);\n if (domain) result.customDomain = domain;\n\n return result;\n}\n\nfunction extractDomainFromRoutes(routes: unknown): string | null {\n if (!Array.isArray(routes)) return null;\n\n for (const route of routes) {\n if (typeof route === \"string\") {\n const domain = cleanDomain(route);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n } else if (route && typeof route === \"object\") {\n const r = route as Record<string, unknown>;\n const pattern =\n typeof r.zone_name === \"string\"\n ? r.zone_name\n : typeof r.pattern === \"string\"\n ? r.pattern\n : null;\n if (pattern) {\n const domain = cleanDomain(pattern);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n }\n }\n }\n return null;\n}\n\nfunction extractDomainFromCustomDomains(config: Record<string, unknown>): string | null {\n // Workers Custom Domains: \"custom_domains\": [\"example.com\"]\n if (Array.isArray(config.custom_domains)) {\n for (const d of config.custom_domains) {\n if (typeof d === \"string\" && !d.includes(\"workers.dev\")) {\n return cleanDomain(d);\n }\n }\n }\n return null;\n}\n\n/** Strip protocol and trailing wildcards from a route pattern to get a bare domain. */\nfunction cleanDomain(raw: string): string | null {\n const cleaned = raw\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/\\*$/, \"\")\n .replace(/\\/+$/, \"\")\n .split(\"/\")[0]; // Take only the host part\n return cleaned || null;\n}\n\n/**\n * Simple extraction of specific fields from wrangler.toml content.\n * Not a full TOML parser — just enough for the fields we need.\n */\nfunction extractFromTOML(content: string): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id = \"...\"\n const accountMatch = content.match(/^account_id\\s*=\\s*\"([^\"]+)\"/m);\n if (accountMatch) result.accountId = accountMatch[1];\n\n // KV namespace with binding = \"VINEXT_CACHE\"\n // Look for [[kv_namespaces]] blocks\n const kvBlocks = content.split(/\\[\\[kv_namespaces\\]\\]/);\n for (let i = 1; i < kvBlocks.length; i++) {\n const block = kvBlocks[i].split(/\\[\\[/)[0]; // Take until next section\n const bindingMatch = block.match(/binding\\s*=\\s*\"([^\"]+)\"/);\n const idMatch = block.match(/\\bid\\s*=\\s*\"([^\"]+)\"/);\n if (\n bindingMatch?.[1] === \"VINEXT_CACHE\" &&\n idMatch?.[1] &&\n idMatch[1] !== \"<your-kv-namespace-id>\"\n ) {\n result.kvNamespaceId = idMatch[1];\n }\n }\n\n // routes — both string and table forms\n // route = \"example.com/*\"\n const routeMatch = content.match(/^route\\s*=\\s*\"([^\"]+)\"/m);\n if (routeMatch) {\n const domain = cleanDomain(routeMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n }\n }\n\n // [[routes]] blocks\n if (!result.customDomain) {\n const routeBlocks = content.split(/\\[\\[routes\\]\\]/);\n for (let i = 1; i < routeBlocks.length; i++) {\n const block = routeBlocks[i].split(/\\[\\[/)[0];\n const patternMatch = block.match(/pattern\\s*=\\s*\"([^\"]+)\"/);\n if (patternMatch) {\n const domain = cleanDomain(patternMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\n// ─── Cloudflare API ──────────────────────────────────────────────────────────\n\n/**\n * Generate zone lookup candidates from shortest (2-part) to longest.\n * Tries the most common case first (e.g., \"example.com\") and progressively\n * adds labels for multi-part TLDs (e.g., \"co.uk\" → \"example.co.uk\").\n *\n * \"shop.example.com\" → [\"example.com\", \"shop.example.com\"]\n * \"shop.example.co.uk\" → [\"co.uk\", \"example.co.uk\", \"shop.example.co.uk\"]\n * \"example.com\" → [\"example.com\"]\n */\nexport function domainCandidates(domain: string): string[] {\n const parts = domain.split(\".\");\n const candidates: string[] = [];\n for (let i = parts.length - 2; i >= 0; i--) {\n candidates.push(parts.slice(i).join(\".\"));\n }\n return candidates;\n}\n\n/** Resolve zone ID from a domain name via the Cloudflare API. */\nasync function resolveZoneId(domain: string, apiToken: string): Promise<string | null> {\n // Try progressively longer domain candidates until one matches a zone.\n // This handles all public suffixes without a hardcoded TLD list —\n // for simple TLDs (.com, .io) the 2-part candidate hits on the first try;\n // for multi-part TLDs (.co.uk, .com.au) it takes one extra call.\n for (const candidate of domainCandidates(domain)) {\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(candidate)}`,\n {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n if (!response.ok) continue;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (data.success && data.result?.length) {\n return data.result[0].id;\n }\n }\n\n return null;\n}\n\n/** Resolve the account ID associated with the API token. */\nasync function resolveAccountId(apiToken: string): Promise<string | null> {\n const response = await fetch(\"https://api.cloudflare.com/client/v4/accounts?per_page=1\", {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) return null;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (!data.success || !data.result?.length) return null;\n\n return data.result[0].id;\n}\n\n// ─── Traffic Querying ────────────────────────────────────────────────────────\n\n/**\n * Query Cloudflare zone analytics for top page paths by request count\n * over the given time window.\n */\nasync function queryTraffic(\n zoneTag: string,\n apiToken: string,\n windowHours: number,\n): Promise<TrafficEntry[]> {\n const now = new Date();\n const start = new Date(now.getTime() - windowHours * 60 * 60 * 1000);\n\n const query = `{\n viewer {\n zones(filter: { zoneTag: \"${zoneTag}\" }) {\n httpRequestsAdaptiveGroups(\n limit: 10000\n orderBy: [sum_requests_DESC]\n filter: {\n datetime_geq: \"${start.toISOString()}\"\n datetime_lt: \"${now.toISOString()}\"\n requestSource: \"eyeball\"\n }\n ) {\n sum { requests }\n dimensions { clientRequestPath }\n }\n }\n }\n }`;\n\n const response = await fetch(\"https://api.cloudflare.com/client/v4/graphql\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ query }),\n });\n\n if (!response.ok) {\n throw new Error(`Zone analytics query failed: ${response.status} ${response.statusText}`);\n }\n\n const data = (await response.json()) as {\n errors?: Array<{ message: string }>;\n data?: {\n viewer?: {\n zones?: Array<{\n httpRequestsAdaptiveGroups?: Array<{\n sum: { requests: number };\n dimensions: { clientRequestPath: string };\n }>;\n }>;\n };\n };\n };\n\n if (data.errors?.length) {\n throw new Error(`Zone analytics error: ${data.errors[0].message}`);\n }\n\n const groups = data.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups;\n if (!groups || groups.length === 0) return [];\n\n return filterTrafficPaths(\n groups.map((g) => ({\n path: g.dimensions.clientRequestPath,\n requests: g.sum.requests,\n })),\n );\n}\n\n/** Filter out non-page requests (static assets, API routes, internal routes). */\nfunction filterTrafficPaths(entries: TrafficEntry[]): TrafficEntry[] {\n return entries.filter((e) => {\n if (!e.path.startsWith(\"/\")) return false;\n // Static assets\n if (/\\.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|map|webp|avif)$/i.test(e.path))\n return false;\n // API routes\n if (e.path.startsWith(\"/api/\")) return false;\n // Internal routes\n if (e.path.startsWith(\"/_vinext/\") || e.path.startsWith(\"/_next/\")) return false;\n // RSC requests\n if (e.path.endsWith(\".rsc\")) return false;\n return true;\n });\n}\n\n// ─── Route Selection ─────────────────────────────────────────────────────────\n\n/**\n * Walk the ranked traffic list, accumulating request counts until the\n * coverage target is met or the hard cap is reached.\n */\nexport function selectRoutes(\n traffic: TrafficEntry[],\n coverageTarget: number,\n limit: number,\n): SelectedRoutes {\n const totalRequests = traffic.reduce((sum, e) => sum + e.requests, 0);\n if (totalRequests === 0) {\n return { routes: [], totalRequests: 0, coveredRequests: 0, coveragePercent: 0 };\n }\n\n const target = totalRequests * (coverageTarget / 100);\n const selected: TrafficEntry[] = [];\n let accumulated = 0;\n\n // Traffic is already sorted DESC by requests from the GraphQL query\n for (const entry of traffic) {\n if (accumulated >= target || selected.length >= limit) break;\n selected.push(entry);\n accumulated += entry.requests;\n }\n\n return {\n routes: selected,\n totalRequests,\n coveredRequests: accumulated,\n coveragePercent: (accumulated / totalRequests) * 100,\n };\n}\n\n// ─── Pre-rendering ───────────────────────────────────────────────────────────\n\n/** Pre-render port — high number to avoid collisions with dev servers. */\nconst PRERENDER_PORT = 19384;\n\n/** Max time to wait for the local server to start (ms). */\nconst SERVER_STARTUP_TIMEOUT = 30_000;\n\n/** Max concurrent fetch requests during pre-rendering. */\nconst FETCH_CONCURRENCY = 10;\n\n/**\n * Start a local production server, fetch each route to produce HTML,\n * and return the results. Pages that fail to render are skipped.\n */\nasync function prerenderRoutes(\n routes: string[],\n root: string,\n hostDomain?: string,\n): Promise<Map<string, PrerenderResult>> {\n const results = new Map<string, PrerenderResult>();\n let failedCount = 0;\n const port = PRERENDER_PORT;\n\n // Verify dist/ exists\n const distDir = path.join(root, \"dist\");\n if (!fs.existsSync(distDir)) {\n console.log(\" TPR: Skipping pre-render — dist/ directory not found\");\n return results;\n }\n\n // Start the local production server as a subprocess\n const serverProcess = startLocalServer(root, port);\n\n try {\n await waitForServer(port, SERVER_STARTUP_TIMEOUT);\n\n // Fetch routes in batches to limit concurrency\n for (let i = 0; i < routes.length; i += FETCH_CONCURRENCY) {\n const batch = routes.slice(i, i + FETCH_CONCURRENCY);\n const promises = batch.map(async (routePath) => {\n try {\n const response = await fetch(`http://127.0.0.1:${port}${routePath}`, {\n headers: {\n \"User-Agent\": \"vinext-tpr/1.0\",\n ...(hostDomain ? { Host: hostDomain } : {}),\n },\n redirect: \"manual\", // Don't follow redirects — cache the redirect itself\n });\n\n // Only cache successful responses (2xx and 3xx)\n if (response.status < 400) {\n const html = await response.text();\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n // Only keep relevant headers\n if (\n key === \"content-type\" ||\n key === \"cache-control\" ||\n key === \"x-vinext-revalidate\" ||\n key === \"location\"\n ) {\n headers[key] = value;\n }\n });\n results.set(routePath, {\n html,\n status: response.status,\n headers,\n });\n }\n } catch {\n // Skip pages that fail to render — they may depend on\n // request-specific data (cookies, headers, auth) that\n // isn't available during pre-rendering.\n failedCount++;\n }\n });\n\n await Promise.all(promises);\n }\n\n if (failedCount > 0) {\n console.log(` TPR: ${failedCount} page(s) failed to pre-render (skipped)`);\n }\n } finally {\n serverProcess.kill(\"SIGTERM\");\n // Give it a moment to clean up\n await new Promise<void>((resolve) => {\n serverProcess.on(\"exit\", resolve);\n setTimeout(resolve, 2000);\n });\n }\n\n return results;\n}\n\n/**\n * Spawn a subprocess running the vinext production server.\n * Uses the same Node.js binary and resolves prod-server.js relative\n * to the current module (works whether vinext is installed or linked).\n */\nfunction startLocalServer(root: string, port: number): ChildProcess {\n const prodServerPath = path.resolve(import.meta.dirname, \"..\", \"server\", \"prod-server.js\");\n const outDir = path.join(root, \"dist\");\n\n // Escape backslashes for Windows paths inside the JS string\n const escapedProdServer = prodServerPath.replace(/\\\\/g, \"\\\\\\\\\");\n const escapedOutDir = outDir.replace(/\\\\/g, \"\\\\\\\\\");\n\n const script = [\n `import(\"file://${escapedProdServer}\")`,\n `.then(m => m.startProdServer({ port: ${port}, host: \"127.0.0.1\", outDir: \"${escapedOutDir}\" }))`,\n `.catch(e => { console.error(\"[vinext-tpr] Server failed to start:\", e); process.exit(1); });`,\n ].join(\"\");\n\n const proc = spawn(process.execPath, [\"--input-type=module\", \"-e\", script], {\n cwd: root,\n stdio: \"pipe\",\n env: { ...process.env, NODE_ENV: \"production\" },\n });\n\n // Forward server errors to the parent's stderr for debugging\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n const msg = chunk.toString().trim();\n if (msg) console.error(` [tpr-server] ${msg}`);\n });\n\n return proc;\n}\n\n/** Poll the local server until it responds or the timeout is reached. */\nasync function waitForServer(port: number, timeoutMs: number): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2000);\n const response = await fetch(`http://127.0.0.1:${port}/`, {\n redirect: \"manual\",\n signal: controller.signal,\n });\n clearTimeout(timer);\n // Any response means the server is up\n await response.text(); // consume body\n return;\n } catch {\n await new Promise<void>((r) => setTimeout(r, 300));\n }\n }\n throw new Error(`Local production server failed to start within ${timeoutMs / 1000}s`);\n}\n\n// ─── KV Upload ───────────────────────────────────────────────────────────────\n\n/** KV bulk API accepts up to 10,000 pairs per request */\nconst KV_BATCH_SIZE = 10_000;\n\n/** Maximum KV expiration TTL: 30 days */\nconst MAX_KV_TTL_SECONDS = 30 * 24 * 3600;\n\n/**\n * Build KV bulk API pairs from pre-rendered entries.\n *\n * Key format matches the runtime KVCacheHandler exactly:\n * ENTRY_PREFIX + isrCacheKey(\"app\", pathname, buildId) + \":html\"\n * → \"cache:app:<buildId>:<pathname>:html\"\n */\nexport function buildTprKVPairs(\n entries: Map<string, PrerenderResult>,\n buildId: string | undefined,\n defaultRevalidateSeconds: number,\n): Array<{ key: string; value: string; expiration_ttl: number }> {\n const now = Date.now();\n const pairs: Array<{ key: string; value: string; expiration_ttl: number }> = [];\n\n for (const [routePath, result] of entries) {\n const revalidateHeader = result.headers[\"x-vinext-revalidate\"];\n const revalidateSeconds =\n revalidateHeader && !isNaN(Number(revalidateHeader))\n ? Number(revalidateHeader)\n : defaultRevalidateSeconds;\n\n const revalidateAt = revalidateSeconds > 0 ? now + revalidateSeconds * 1000 : null;\n\n // For revalidating entries: 30-day TTL matches runtime KVCacheHandler.set().\n // For non-revalidating entries: runtime uses no TTL (entries persist indefinitely),\n // but TPR uses a 24h fallback so pre-warmed entries don't accumulate forever.\n const kvTtl = revalidateSeconds > 0 ? MAX_KV_TTL_SECONDS : 24 * 3600;\n\n const entry = {\n value: {\n kind: \"APP_PAGE\" as const,\n html: result.html,\n headers: result.headers,\n status: result.status,\n },\n tags: [] as string[],\n lastModified: now,\n revalidateAt,\n };\n\n const cacheKey = ENTRY_PREFIX + isrCacheKey(\"app\", routePath, buildId) + \":html\";\n\n pairs.push({\n key: cacheKey,\n value: JSON.stringify(entry),\n expiration_ttl: kvTtl,\n });\n }\n\n return pairs;\n}\n\n/**\n * Upload pre-rendered pages to KV using the Cloudflare REST API.\n * Writes in the same KVCacheEntry format that KVCacheHandler reads\n * at runtime, so ISR serves these entries without any code changes.\n */\nasync function uploadToKV(\n entries: Map<string, PrerenderResult>,\n namespaceId: string,\n accountId: string,\n apiToken: string,\n defaultRevalidateSeconds: number,\n buildId?: string,\n): Promise<void> {\n const pairs = buildTprKVPairs(entries, buildId, defaultRevalidateSeconds);\n for (let i = 0; i < pairs.length; i += KV_BATCH_SIZE) {\n const batch = pairs.slice(i, i + KV_BATCH_SIZE);\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,\n {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(batch),\n },\n );\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `KV bulk upload failed (batch ${Math.floor(i / KV_BATCH_SIZE) + 1}): ${response.status} — ${text}`,\n );\n }\n }\n}\n\n// ─── Main Entry ──────────────────────────────────────────────────────────────\n\n/** Default revalidation TTL for pre-rendered pages (1 hour). */\nconst DEFAULT_REVALIDATE_SECONDS = 3600;\n\n/**\n * Run the TPR pipeline: query traffic, select routes, pre-render, upload.\n *\n * Designed to be called between the build step and wrangler deploy in\n * the `vinext deploy` pipeline. Gracefully skips (never errors) when\n * the prerequisites aren't met.\n */\nexport async function runTPR(options: TPROptions): Promise<TPRResult> {\n const startTime = Date.now();\n const { root, coverage, limit, window: windowHours } = options;\n\n const skip = (reason: string): TPRResult => ({\n totalPaths: 0,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: reason,\n });\n\n // ── 1. Check for API token ────────────────────────────────────\n const apiToken = process.env.CLOUDFLARE_API_TOKEN;\n if (!apiToken) {\n return skip(\"no CLOUDFLARE_API_TOKEN set\");\n }\n\n // ── 2. Parse wrangler config ──────────────────────────────────\n const wranglerConfig = parseWranglerConfig(root);\n if (!wranglerConfig) {\n return skip(\"could not parse wrangler config\");\n }\n\n // ── 3. Check for custom domain ────────────────────────────────\n if (!wranglerConfig.customDomain) {\n return skip(\"no custom domain — zone analytics unavailable\");\n }\n\n // ── 4. Check for KV namespace ─────────────────────────────────\n if (!wranglerConfig.kvNamespaceId) {\n return skip(\"no VINEXT_CACHE KV namespace configured\");\n }\n\n // ── 5. Resolve account ID ─────────────────────────────────────\n const accountId = wranglerConfig.accountId ?? (await resolveAccountId(apiToken));\n if (!accountId) {\n return skip(\"could not resolve Cloudflare account ID\");\n }\n\n // ── 6. Resolve zone ID ────────────────────────────────────────\n console.log(` TPR: Analyzing traffic for ${wranglerConfig.customDomain} (last ${windowHours}h)`);\n\n const zoneId = await resolveZoneId(wranglerConfig.customDomain, apiToken);\n if (!zoneId) {\n return skip(`could not resolve zone for ${wranglerConfig.customDomain}`);\n }\n\n // ── 7. Query traffic data ─────────────────────────────────────\n let traffic: TrafficEntry[];\n try {\n traffic = await queryTraffic(zoneId, apiToken, windowHours);\n } catch (err) {\n return skip(`analytics query failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (traffic.length === 0) {\n return skip(\"no traffic data available (first deploy?)\");\n }\n\n // ── 8. Select routes by coverage ──────────────────────────────\n const selection = selectRoutes(traffic, coverage, limit);\n\n console.log(\n ` TPR: ${traffic.length.toLocaleString()} unique paths — ` +\n `${selection.routes.length} pages cover ${Math.round(selection.coveragePercent)}% of traffic`,\n );\n\n if (selection.routes.length === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: \"no pre-renderable routes after filtering\",\n };\n }\n\n // ── 9. Pre-render selected routes ─────────────────────────────\n console.log(` TPR: Pre-rendering ${selection.routes.length} pages...`);\n\n const routePaths = selection.routes.map((r) => r.path);\n let rendered: Map<string, PrerenderResult>;\n try {\n rendered = await prerenderRoutes(routePaths, root, wranglerConfig.customDomain);\n } catch (err) {\n return skip(`pre-rendering failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (rendered.size === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: selection.coveragePercent,\n durationMs: Date.now() - startTime,\n skipped: \"all pages failed to pre-render (request-dependent?)\",\n };\n }\n\n // ── 10. Upload to KV ──────────────────────────────────────────\n // Read buildId from the BUILD_ID file written by vinext:build-id plugin.\n let buildId: string;\n try {\n buildId = fs.readFileSync(path.join(root, \"dist\", \"server\", \"BUILD_ID\"), \"utf-8\").trim();\n } catch {\n // BUILD_ID is written by vinext:build-id during every production build.\n // If missing, the build output is likely corrupted or incomplete.\n // Proceeding without buildId would write keys that never match runtime.\n console.warn(\n \" TPR: Could not read BUILD_ID from dist/server/ — KV keys will not match runtime. Skipping KV upload.\",\n );\n return skip(\"BUILD_ID not found in dist/server/ — build output may be incomplete\");\n }\n\n try {\n await uploadToKV(\n rendered,\n wranglerConfig.kvNamespaceId,\n accountId,\n apiToken,\n DEFAULT_REVALIDATE_SECONDS,\n buildId,\n );\n } catch (err) {\n return skip(`KV upload failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const durationMs = Date.now() - startTime;\n console.log(\n ` TPR: Pre-rendered ${rendered.size} pages in ${(durationMs / 1000).toFixed(1)}s → KV cache`,\n );\n\n return {\n totalPaths: traffic.length,\n prerenderedCount: rendered.size,\n coverageAchieved: selection.coveragePercent,\n durationMs,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,SAAgB,oBAAoB,MAAqC;AAEvE,MAAK,MAAM,YAAY,CAAC,kBAAkB,gBAAgB,EAAE;EAC1D,MAAM,WAAW,KAAK,KAAK,MAAM,SAAS;AAC1C,MAAI,GAAG,WAAW,SAAS,EAAE;GAC3B,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,OAAI;AAEF,WAAO,gBADM,KAAK,MAAM,kBAAkB,QAAQ,CAAC,CACvB;WACtB;AACN;;;;CAMN,MAAM,WAAW,KAAK,KAAK,MAAM,gBAAgB;AACjD,KAAI,GAAG,WAAW,SAAS,CAEzB,QAAO,gBADS,GAAG,aAAa,UAAU,QAAQ,CACnB;AAGjC,QAAO;;;;;;AAOT,SAAS,kBAAkB,KAAqB;CAC9C,IAAI,SAAS;CACb,IAAI,WAAW;CACf,IAAI,eAAe;CACnB,IAAI,cAAc;CAClB,IAAI,aA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AAa,KAAM,QAAQ,EAAE,CAAC,cACjF;AAED,QAAO;EACL,YAAY,QAAQ;EACpB,kBAAkB,SAAS;EAC3B,kBAAkB,UAAU;EAC5B;EACD"}
@@ -31,12 +31,12 @@ declare function escapeHeaderSource(source: string): string;
31
31
  * Request context needed for evaluating has/missing conditions.
32
32
  * Callers extract the relevant parts from the incoming Request.
33
33
  */
34
- interface RequestContext {
34
+ type RequestContext = {
35
35
  headers: Headers;
36
36
  cookies: Record<string, string>;
37
37
  query: URLSearchParams;
38
38
  host: string;
39
- }
39
+ };
40
40
  /**
41
41
  * Parse a Cookie header string into a key-value record.
42
42
  */
@@ -728,7 +728,7 @@ async function proxyExternalRequest(request, externalUrl) {
728
728
  signal: controller.signal
729
729
  });
730
730
  } catch (e) {
731
- if (e?.name === "AbortError") {
731
+ if (e instanceof Error && e.name === "AbortError") {
732
732
  console.error("[vinext] External rewrite proxy timeout:", targetUrl.href);
733
733
  return new Response("Gateway Timeout", { status: 504 });
734
734
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config-matchers.js","names":[],"sources":["../../src/config/config-matchers.ts"],"sourcesContent":["/**\n * Config pattern matching and rule application utilities.\n *\n * Shared between the dev server (index.ts) and the production server\n * (prod-server.ts) so both apply next.config.js rules identically.\n */\n\nimport type { NextRedirect, NextRewrite, NextHeader, HasCondition } from \"./next-config.js\";\nimport { buildRequestHeadersFromMiddlewareResponse } from \"../server/middleware-request-headers.js\";\n\n/**\n * Cache for compiled regex patterns in matchConfigPattern.\n *\n * Redirect/rewrite patterns are static — they come from next.config.js and\n * never change at runtime. Without caching, every request that hits the regex\n * branch re-runs the full tokeniser walk + isSafeRegex + new RegExp() for\n * every rule in the array. On apps with many locale-prefixed rules (which all\n * contain `(` and therefore enter the regex branch) this dominated profiling\n * at ~2.4 seconds of CPU self-time.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk), so we\n * skip it on subsequent requests too without re-running the scanner.\n */\nconst _compiledPatternCache = new Map<string, { re: RegExp; paramNames: string[] } | null>();\n\n/**\n * Cache for compiled header source regexes in matchHeaders.\n *\n * Each NextHeader rule has a `source` that is run through escapeHeaderSource()\n * then safeRegExp() to produce a RegExp. Both are pure functions of the source\n * string and the result never changes. Without caching, every request\n * re-runs the full escapeHeaderSource tokeniser + isSafeRegex scan + new RegExp()\n * for every header rule.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk).\n */\nconst _compiledHeaderSourceCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for compiled has/missing condition value regexes in checkSingleCondition.\n *\n * Each has/missing condition may carry a `value` string that is passed directly\n * to safeRegExp() for matching against header/cookie/query/host values. The\n * condition objects are static (from next.config.js) so the compiled RegExp\n * never changes. Without caching, safeRegExp() is called on every request for\n * every condition on every rule.\n *\n * Value is `null` when safeRegExp rejected the pattern, or `false` when the\n * value string was undefined (no regex needed — use exact string comparison).\n */\nconst _compiledConditionCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for destination substitution regexes in substituteDestinationParams.\n *\n * The regex depends only on the set of param keys captured from the matched\n * source pattern. Caching by sorted key list avoids recompiling a new RegExp\n * for repeated redirect/rewrite calls that use the same param shape.\n */\nconst _compiledDestinationParamCache = new Map<string, RegExp>();\n\n/**\n * Redirect index for O(1) locale-static rule lookup.\n *\n * Many Next.js apps generate 50-100 redirect rules of the form:\n * /:locale(en|es|fr|...)?/some-static-path → /some-destination\n *\n * The compiled regex for each is like:\n * ^/(en|es|fr|...)?/some-static-path$\n *\n * When no redirect matches (the common case for ordinary page loads),\n * matchRedirect previously ran exec() on every one of those regexes —\n * ~2ms per call, ~2992ms total self-time in profiles.\n *\n * The index splits rules into two buckets:\n *\n * localeStatic — rules whose source is exactly /:paramName(alt1|alt2|...)?/suffix\n * where `suffix` is a static path with no further params or regex groups.\n * These are indexed in a Map<suffix, entry[]> for O(1) lookup after a\n * single fast strip of the optional locale prefix.\n *\n * linear — all other rules. Matched with the original O(n) loop.\n *\n * The index is stored in a WeakMap keyed by the redirects array so it is\n * computed once per config load and GC'd when the array is no longer live.\n *\n * ## Ordering invariant\n *\n * Redirect rules must be evaluated in their original order (first match wins).\n * Each locale-static entry stores its `originalIndex` so that, when a\n * locale-static fast-path match is found, any linear rules that appear earlier\n * in the array are still checked first.\n */\n\n/** Matches `/:param(alternation)?/static/suffix` — the locale-static pattern. */\nconst _LOCALE_STATIC_RE = /^\\/:[\\w-]+\\(([^)]+)\\)\\?\\/([a-zA-Z0-9_~.%@!$&'*+,;=:/-]+)$/;\n\ntype LocaleStaticEntry = {\n /** The param name extracted from the source (e.g. \"locale\"). */\n paramName: string;\n /** The compiled regex matching just the alternation, used at match time. */\n altRe: RegExp;\n /** The original redirect rule. */\n redirect: NextRedirect;\n /** Position of this rule in the original redirects array. */\n originalIndex: number;\n};\n\ntype RedirectIndex = {\n /** Fast-path map: strippedPath (e.g. \"/security\") → matching entries. */\n localeStatic: Map<string, LocaleStaticEntry[]>;\n /**\n * Linear fallback for rules that couldn't be indexed.\n * Each entry is [originalIndex, redirect].\n */\n linear: Array<[number, NextRedirect]>;\n};\n\nconst _redirectIndexCache = new WeakMap<NextRedirect[], RedirectIndex>();\n\n/**\n * Build (or retrieve from cache) the redirect index for a given redirects array.\n *\n * Called once per config load from matchRedirect. The WeakMap ensures the index\n * is recomputed if the config is reloaded (new array reference) and GC'd when\n * the array is collected.\n */\nfunction _getRedirectIndex(redirects: NextRedirect[]): RedirectIndex {\n let index = _redirectIndexCache.get(redirects);\n if (index !== undefined) return index;\n\n const localeStatic = new Map<string, LocaleStaticEntry[]>();\n const linear: Array<[number, NextRedirect]> = [];\n\n for (let i = 0; i < redirects.length; i++) {\n const redirect = redirects[i];\n const m = _LOCALE_STATIC_RE.exec(redirect.source);\n if (m) {\n const paramName = redirect.source.slice(2, redirect.source.indexOf(\"(\"));\n const alternation = m[1];\n const suffix = \"/\" + m[2]; // e.g. \"/security\"\n // Build a small regex to validate the captured locale value against the\n // alternation. Using anchored match to avoid partial matches.\n // The alternation comes from user config; run it through safeRegExp to\n // guard against ReDoS in pathological configs.\n const altRe = safeRegExp(\"^(?:\" + alternation + \")$\");\n if (!altRe) {\n // Unsafe alternation — fall back to linear scan for this rule.\n linear.push([i, redirect]);\n continue;\n }\n const entry: LocaleStaticEntry = { paramName, altRe, redirect, originalIndex: i };\n const bucket = localeStatic.get(suffix);\n if (bucket) {\n bucket.push(entry);\n } else {\n localeStatic.set(suffix, [entry]);\n }\n } else {\n linear.push([i, redirect]);\n }\n }\n\n index = { localeStatic, linear };\n _redirectIndexCache.set(redirects, index);\n return index;\n}\n\n/** Hop-by-hop headers that should not be forwarded through a proxy. */\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Request hop-by-hop headers to strip before proxying with fetch().\n * Intentionally narrower than HOP_BY_HOP_HEADERS: external rewrite proxying\n * still forwards proxy auth credentials, while response sanitization strips\n * them before returning data to the client.\n */\nconst REQUEST_HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\nfunction stripHopByHopRequestHeaders(headers: Headers): void {\n const connectionTokens = (headers.get(\"connection\") || \"\")\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean);\n\n for (const header of REQUEST_HOP_BY_HOP_HEADERS) {\n headers.delete(header);\n }\n\n for (const token of connectionTokens) {\n headers.delete(token);\n }\n}\n\n/**\n * Detect regex patterns vulnerable to catastrophic backtracking (ReDoS).\n *\n * Uses a lightweight heuristic: scans the pattern string for nested quantifiers\n * (a quantifier applied to a group that itself contains a quantifier). This\n * catches the most common pathological patterns like `(a+)+`, `(.*)*`,\n * `([^/]+)+`, `(a|a+)+` without needing a full regex parser.\n *\n * Returns true if the pattern appears safe, false if it's potentially dangerous.\n */\nexport function isSafeRegex(pattern: string): boolean {\n // Track parenthesis nesting depth and whether we've seen a quantifier\n // at each depth level.\n const quantifierAtDepth: boolean[] = [];\n let depth = 0;\n let i = 0;\n\n while (i < pattern.length) {\n const ch = pattern[i];\n\n // Skip escaped characters\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Skip character classes [...] — quantifiers inside them are literal\n if (ch === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++; // skip escaped char in class\n i++;\n }\n i++; // skip closing ]\n continue;\n }\n\n if (ch === \"(\") {\n depth++;\n // Initialize: no quantifier seen yet at this new depth\n if (quantifierAtDepth.length <= depth) {\n quantifierAtDepth.push(false);\n } else {\n quantifierAtDepth[depth] = false;\n }\n i++;\n continue;\n }\n\n if (ch === \")\") {\n const hadQuantifier = depth > 0 && quantifierAtDepth[depth];\n if (depth > 0) depth--;\n\n // Look ahead for a quantifier on this group: +, *, {n,m}\n // Note: '?' after ')' means \"zero or one\" which does NOT cause catastrophic\n // backtracking — it only allows 2 paths (match/skip), not exponential.\n // Only unbounded repetition (+, *, {n,}) on a group with inner quantifiers is dangerous.\n const next = pattern[i + 1];\n if (next === \"+\" || next === \"*\" || next === \"{\") {\n if (hadQuantifier) {\n // Nested quantifier detected: quantifier on a group that contains a quantifier\n return false;\n }\n // Mark the enclosing depth as having a quantifier\n if (depth >= 0 && depth < quantifierAtDepth.length) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n // Detect quantifiers: +, *, ?, {n,m}\n // '?' is a quantifier (optional) unless it follows another quantifier (+, *, ?, })\n // in which case it's a non-greedy modifier.\n if (ch === \"+\" || ch === \"*\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i++;\n continue;\n }\n\n if (ch === \"?\") {\n // '?' after +, *, ?, or } is a non-greedy modifier, not a quantifier\n const prev = i > 0 ? pattern[i - 1] : \"\";\n if (prev !== \"+\" && prev !== \"*\" && prev !== \"?\" && prev !== \"}\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n if (ch === \"{\") {\n // Check if this is a quantifier {n}, {n,}, {n,m}\n let j = i + 1;\n while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;\n if (j < pattern.length && pattern[j] === \"}\" && j > i + 1) {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i = j + 1;\n continue;\n }\n }\n\n i++;\n }\n\n return true;\n}\n\n/**\n * Compile a regex pattern safely. Returns the compiled RegExp or null if the\n * pattern is invalid or vulnerable to ReDoS.\n *\n * Logs a warning when a pattern is rejected so developers can fix their config.\n */\nexport function safeRegExp(pattern: string, flags?: string): RegExp | null {\n if (!isSafeRegex(pattern)) {\n console.warn(\n `[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): ${pattern}\\n` +\n ` Patterns with nested quantifiers (e.g. (a+)+) can cause catastrophic backtracking.\\n` +\n ` Simplify the pattern to avoid nested repetition.`,\n );\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a Next.js header/rewrite/redirect source pattern into a regex string.\n *\n * Regex groups in the source (e.g. `(\\d+)`) are extracted first, the remaining\n * text is escaped/converted in a **single pass** (avoiding chained `.replace()`\n * which CodeQL flags as incomplete sanitization), then groups are restored.\n */\nexport function escapeHeaderSource(source: string): string {\n // Sentinel character for group placeholders. Uses a Unicode private-use-area\n // codepoint that will never appear in real source patterns.\n const S = \"\\uE000\";\n\n // Step 1: extract regex groups and replace with numbered placeholders.\n const groups: string[] = [];\n const withPlaceholders = source.replace(/\\(([^)]+)\\)/g, (_m, inner) => {\n groups.push(inner);\n return `${S}G${groups.length - 1}${S}`;\n });\n\n // Step 2: single-pass conversion of the placeholder-bearing string.\n // Match named params (:[\\w-]+), sentinel group placeholders, metacharacters, and literal text.\n // The regex uses non-overlapping alternatives to avoid backtracking:\n // :[\\w-]+ — named parameter (constraint sentinel is checked procedurally;\n // param names may contain hyphens, e.g. :auth-method)\n // sentinel group — standalone regex group placeholder\n // [.+?*] — single metachar to escape/convert\n // [^.+?*:\\uE000]+ — literal text (excludes all chars that start other alternatives)\n let result = \"\";\n const re = new RegExp(\n `${S}G(\\\\d+)${S}|:[\\\\w-]+|[.+?*]|[^.+?*:\\\\uE000]+`, // lgtm[js/redos] — alternatives are non-overlapping\n \"g\",\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(withPlaceholders)) !== null) {\n if (m[1] !== undefined) {\n // Standalone regex group — restore as-is\n result += `(${groups[Number(m[1])]})`;\n } else if (m[0].startsWith(\":\")) {\n // Named parameter — check if followed by a constraint group placeholder\n const afterParam = withPlaceholders.slice(re.lastIndex);\n const constraintMatch = afterParam.match(new RegExp(`^${S}G(\\\\d+)${S}`));\n if (constraintMatch) {\n // :param(constraint) — use the constraint as the capture group\n re.lastIndex += constraintMatch[0].length;\n result += `(${groups[Number(constraintMatch[1])]})`;\n } else {\n // Plain named parameter → match one segment\n result += \"[^/]+\";\n }\n } else {\n switch (m[0]) {\n case \".\":\n result += \"\\\\.\";\n break;\n case \"+\":\n result += \"\\\\+\";\n break;\n case \"?\":\n result += \"\\\\?\";\n break;\n case \"*\":\n result += \".*\";\n break;\n default:\n result += m[0];\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Request context needed for evaluating has/missing conditions.\n * Callers extract the relevant parts from the incoming Request.\n */\nexport interface RequestContext {\n headers: Headers;\n cookies: Record<string, string>;\n query: URLSearchParams;\n host: string;\n}\n\n/**\n * Parse a Cookie header string into a key-value record.\n */\nexport function parseCookies(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) return {};\n const cookies: Record<string, string> = {};\n for (const part of cookieHeader.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key) cookies[key] = value;\n }\n return cookies;\n}\n\n/**\n * Build a RequestContext from a Web Request object.\n */\nexport function requestContextFromRequest(request: Request): RequestContext {\n const url = new URL(request.url);\n return {\n headers: request.headers,\n cookies: parseCookies(request.headers.get(\"cookie\")),\n query: url.searchParams,\n host: normalizeHost(request.headers.get(\"host\"), url.hostname),\n };\n}\n\nexport function normalizeHost(hostHeader: string | null, fallbackHostname: string): string {\n const host = hostHeader ?? fallbackHostname;\n return host.split(\":\", 1)[0].toLowerCase();\n}\n\n/**\n * Unpack `x-middleware-request-*` headers from the collected middleware\n * response headers into the actual request, and strip all `x-middleware-*`\n * internal signals so they never reach clients.\n *\n * `middlewareHeaders` is mutated in-place (matching keys are deleted).\n * Returns a (possibly cloned) `Request` with the unpacked headers applied,\n * and a fresh `RequestContext` built from it — ready for post-middleware\n * config rule matching (beforeFiles, afterFiles, fallback).\n *\n * Works for both Node.js requests (mutable headers) and Workers requests\n * (immutable — cloned only when there are headers to apply).\n *\n * `x-middleware-request-*` values are always plain strings (they carry\n * individual header values), so the wider `string | string[]` type of\n * `middlewareHeaders` is safe to cast here.\n */\nexport function applyMiddlewareRequestHeaders(\n middlewareHeaders: Record<string, string | string[]>,\n request: Request,\n): { request: Request; postMwReqCtx: RequestContext } {\n const nextHeaders = buildRequestHeadersFromMiddlewareResponse(request.headers, middlewareHeaders);\n\n for (const key of Object.keys(middlewareHeaders)) {\n if (key.startsWith(\"x-middleware-\")) {\n delete middlewareHeaders[key];\n }\n }\n\n if (nextHeaders) {\n // Headers may be immutable (Workers), so always clone via new Headers().\n request = new Request(request.url, {\n method: request.method,\n headers: nextHeaders,\n body: request.body,\n // @ts-expect-error — duplex needed for streaming request bodies\n duplex: request.body ? \"half\" : undefined,\n });\n }\n\n return { request, postMwReqCtx: requestContextFromRequest(request) };\n}\n\nfunction _emptyParams(): Record<string, string> {\n return Object.create(null) as Record<string, string>;\n}\n\nfunction _matchConditionValue(\n actualValue: string,\n expectedValue: string | undefined,\n): Record<string, string> | null {\n if (expectedValue === undefined) return _emptyParams();\n\n const re = _cachedConditionRegex(expectedValue);\n if (re) {\n const match = re.exec(actualValue);\n if (!match) return null;\n\n const params = _emptyParams();\n if (match.groups) {\n for (const [key, value] of Object.entries(match.groups)) {\n if (value !== undefined) params[key] = value;\n }\n }\n return params;\n }\n\n return actualValue === expectedValue ? _emptyParams() : null;\n}\n\n/**\n * Check a single has/missing condition against request context.\n * Returns captured params when the condition is satisfied, or null otherwise.\n */\nfunction matchSingleCondition(\n condition: HasCondition,\n ctx: RequestContext,\n): Record<string, string> | null {\n switch (condition.type) {\n case \"header\": {\n const headerValue = ctx.headers.get(condition.key);\n if (headerValue === null) return null;\n return _matchConditionValue(headerValue, condition.value);\n }\n case \"cookie\": {\n const cookieValue = ctx.cookies[condition.key];\n if (cookieValue === undefined) return null;\n return _matchConditionValue(cookieValue, condition.value);\n }\n case \"query\": {\n const queryValue = ctx.query.get(condition.key);\n if (queryValue === null) return null;\n return _matchConditionValue(queryValue, condition.value);\n }\n case \"host\": {\n if (condition.value !== undefined) return _matchConditionValue(ctx.host, condition.value);\n return ctx.host === condition.key ? _emptyParams() : null;\n }\n default:\n return null;\n }\n}\n\n/**\n * Return a cached RegExp for a has/missing condition value string, compiling\n * on first use. Returns null if safeRegExp rejected the pattern or if the\n * value is not a valid regex (fall back to exact string comparison).\n */\nfunction _cachedConditionRegex(value: string): RegExp | null {\n let re = _compiledConditionCache.get(value);\n if (re === undefined) {\n // Anchor the regex to match the full value, not a substring.\n // Matches Next.js: new RegExp(`^${hasItem.value}$`)\n // Without anchoring, has:[cookie:role=admin] would match \"not-admin\".\n re = safeRegExp(`^${value}$`);\n _compiledConditionCache.set(value, re);\n }\n return re;\n}\n\n/**\n * Check all has/missing conditions for a config rule.\n * Returns true if the rule should be applied (all has conditions pass, all missing conditions pass).\n *\n * - has: every condition must match (the request must have it)\n * - missing: every condition must NOT match (the request must not have it)\n */\nfunction collectConditionParams(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): Record<string, string> | null {\n const params = _emptyParams();\n\n if (has) {\n for (const condition of has) {\n const conditionParams = matchSingleCondition(condition, ctx);\n if (!conditionParams) return null;\n Object.assign(params, conditionParams);\n }\n }\n\n if (missing) {\n for (const condition of missing) {\n if (matchSingleCondition(condition, ctx)) return null;\n }\n }\n\n return params;\n}\n\nexport function checkHasConditions(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): boolean {\n return collectConditionParams(has, missing, ctx) !== null;\n}\n\n/**\n * If the current position in `str` starts with a parenthesized group, consume\n * it and advance `re.lastIndex` past the closing `)`. Returns the group\n * contents or null if no group is present.\n */\nfunction extractConstraint(str: string, re: RegExp): string | null {\n if (str[re.lastIndex] !== \"(\") return null;\n const start = re.lastIndex + 1;\n let depth = 1;\n let i = start;\n while (i < str.length && depth > 0) {\n if (str[i] === \"(\") depth++;\n else if (str[i] === \")\") depth--;\n i++;\n }\n if (depth !== 0) return null;\n re.lastIndex = i;\n return str.slice(start, i - 1);\n}\n\n/**\n * Match a Next.js config pattern (from redirects/rewrites sources) against a pathname.\n * Returns matched params or null.\n *\n * Supports:\n * :param - matches a single path segment\n * :param* - matches zero or more segments (catch-all)\n * :param+ - matches one or more segments\n * (regex) - inline regex patterns in the source\n * :param(constraint) - named param with inline regex constraint\n */\nexport function matchConfigPattern(\n pathname: string,\n pattern: string,\n): Record<string, string> | null {\n // If the pattern contains regex groups like (\\d+) or (.*), use regex matching.\n // Also enter this branch when a catch-all parameter (:param* or :param+) is\n // followed by a literal suffix (e.g. \"/:path*.md\"). Without this, the suffix\n // pattern falls through to the simple segment matcher which incorrectly treats\n // the whole segment (\":path*.md\") as a named parameter and matches everything.\n // The last condition catches simple params with literal suffixes (e.g. \"/:slug.md\")\n // where the param name is followed by a dot — the simple matcher would treat\n // \"slug.md\" as the param name and match any single segment regardless of suffix.\n if (\n pattern.includes(\"(\") ||\n pattern.includes(\"\\\\\") ||\n /:[\\w-]+[*+][^/]/.test(pattern) ||\n /:[\\w-]+\\./.test(pattern)\n ) {\n try {\n // Look up the compiled regex in the module-level cache. Patterns come\n // from next.config.js and are static, so we only need to compile each\n // one once across the lifetime of the worker/server process.\n let compiled = _compiledPatternCache.get(pattern);\n if (compiled === undefined) {\n // Cache miss — compile the pattern now and store the result.\n // Param names may contain hyphens (e.g. :auth-method, :sign-in).\n const paramNames: string[] = [];\n // Single-pass conversion with procedural suffix handling. The tokenizer\n // matches only simple, non-overlapping tokens; quantifier/constraint\n // suffixes after :param are consumed procedurally to avoid polynomial\n // backtracking in the regex engine.\n let regexStr = \"\";\n const tokenRe = /:([\\w-]+)|[.]|[^:.]+/g; // lgtm[js/redos] — alternatives are non-overlapping (`:` and `.` excluded from `[^:.]+`)\n let tok: RegExpExecArray | null;\n while ((tok = tokenRe.exec(pattern)) !== null) {\n if (tok[1] !== undefined) {\n const name = tok[1];\n const rest = pattern.slice(tokenRe.lastIndex);\n // Check for quantifier (* or +) with optional constraint\n if (rest.startsWith(\"*\") || rest.startsWith(\"+\")) {\n const quantifier = rest[0];\n tokenRe.lastIndex += 1;\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n if (constraint !== null) {\n regexStr += `(${constraint})`;\n } else {\n regexStr += quantifier === \"*\" ? \"(.*)\" : \"(.+)\";\n }\n } else {\n // Check for inline constraint without quantifier\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n regexStr += constraint !== null ? `(${constraint})` : \"([^/]+)\";\n }\n } else if (tok[0] === \".\") {\n regexStr += \"\\\\.\";\n } else {\n regexStr += tok[0];\n }\n }\n const re = safeRegExp(\"^\" + regexStr + \"$\");\n // Store null for rejected patterns so we don't re-run isSafeRegex.\n compiled = re ? { re, paramNames } : null;\n _compiledPatternCache.set(pattern, compiled);\n }\n if (!compiled) return null;\n const match = compiled.re.exec(pathname);\n if (!match) return null;\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = match[i + 1] ?? \"\";\n }\n return params;\n } catch {\n // Fall through to segment-based matching\n }\n }\n\n // Check for catch-all patterns (:param* or :param+) without regex groups\n // Param names may contain hyphens (e.g. :sign-in*, :sign-up+).\n const catchAllMatch = pattern.match(/:([\\w-]+)(\\*|\\+)$/);\n if (catchAllMatch) {\n const prefix = pattern.slice(0, pattern.lastIndexOf(\":\"));\n const paramName = catchAllMatch[1];\n const isPlus = catchAllMatch[2] === \"+\";\n\n const prefixNoSlash = prefix.replace(/\\/$/, \"\");\n if (!pathname.startsWith(prefixNoSlash)) return null;\n const charAfter = pathname[prefixNoSlash.length];\n if (charAfter !== undefined && charAfter !== \"/\") return null;\n\n const rest = pathname.slice(prefixNoSlash.length);\n if (isPlus && (!rest || rest === \"/\")) return null;\n let restValue = rest.startsWith(\"/\") ? rest.slice(1) : rest;\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the request entry point. Decoding again would produce incorrect param values.\n return { [paramName]: restValue };\n }\n\n // Simple segment-based matching for exact patterns and :param\n const parts = pattern.split(\"/\");\n const pathParts = pathname.split(\"/\");\n\n if (parts.length !== pathParts.length) return null;\n\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < parts.length; i++) {\n if (parts[i].startsWith(\":\")) {\n params[parts[i].slice(1)] = pathParts[i];\n } else if (parts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns the redirect info if a redirect was matched, or null.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating redirects, so this parameter is required.\n *\n * ## Performance\n *\n * Rules with a locale-capture-group prefix (the dominant pattern in large\n * Next.js apps — e.g. `/:locale(en|es|fr|...)?/some-path`) are handled via\n * a pre-built index. Instead of running exec() on each locale regex\n * individually, we:\n *\n * 1. Strip the optional locale prefix from the pathname with one cheap\n * string-slice check (no regex exec on the hot path).\n * 2. Look up the stripped suffix in a Map<suffix, entry[]>.\n * 3. For each matching entry, validate the captured locale string against\n * a small, anchored alternation regex.\n *\n * This reduces the per-request cost from O(n × regex) to O(1) map lookup +\n * O(matches × tiny-regex), eliminating the ~2992ms self-time reported in\n * profiles for apps with 63+ locale-prefixed rules.\n *\n * Rules that don't fit the locale-static pattern fall back to the original\n * linear matchConfigPattern scan.\n *\n * ## Ordering invariant\n *\n * First match wins, preserving the original redirect array order. When a\n * locale-static fast-path match is found at position N, all linear rules with\n * an original index < N are checked via matchConfigPattern first — they are\n * few in practice (typically zero) so this is not a hot-path concern.\n */\nexport function matchRedirect(\n pathname: string,\n redirects: NextRedirect[],\n ctx: RequestContext,\n): { destination: string; permanent: boolean } | null {\n if (redirects.length === 0) return null;\n\n const index = _getRedirectIndex(redirects);\n\n // --- Locate the best locale-static candidate ---\n //\n // We look for the locale-static entry with the LOWEST originalIndex that\n // matches this pathname (and passes has/missing conditions).\n //\n // Strategy: try both the full pathname (locale omitted, e.g. \"/security\")\n // and the pathname with the first segment stripped (locale present, e.g.\n // \"/en/security\" → suffix \"/security\", locale \"en\").\n //\n // We do NOT use a regex here — just a single indexOf('/') to locate the\n // second slash, which is O(n) on the path length but far cheaper than\n // running 63 compiled regexes.\n\n let localeMatch: { destination: string; permanent: boolean } | null = null;\n let localeMatchIndex = Infinity;\n\n if (index.localeStatic.size > 0) {\n // Case 1: no locale prefix — pathname IS the suffix.\n const noLocaleBucket = index.localeStatic.get(pathname);\n if (noLocaleBucket) {\n for (const entry of noLocaleBucket) {\n if (entry.originalIndex >= localeMatchIndex) continue; // already have a better match\n const redirect = entry.redirect;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n // Locale was omitted (the `?` made it optional) — param value is \"\".\n let dest = substituteDestinationParams(redirect.destination, {\n [entry.paramName]: \"\",\n ...conditionParams,\n });\n dest = sanitizeDestination(dest);\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n\n // Case 2: locale prefix present — first path segment is the locale.\n // Find the second slash: pathname = \"/locale/rest/of/path\"\n // ^--- slashTwo\n const slashTwo = pathname.indexOf(\"/\", 1);\n if (slashTwo !== -1) {\n const suffix = pathname.slice(slashTwo); // e.g. \"/security\"\n const localePart = pathname.slice(1, slashTwo); // e.g. \"en\"\n const localeBucket = index.localeStatic.get(suffix);\n if (localeBucket) {\n for (const entry of localeBucket) {\n if (entry.originalIndex >= localeMatchIndex) continue;\n // Validate that `localePart` is one of the allowed alternation values.\n if (!entry.altRe.test(localePart)) continue;\n const redirect = entry.redirect;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(redirect.destination, {\n [entry.paramName]: localePart,\n ...conditionParams,\n });\n dest = sanitizeDestination(dest);\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n }\n }\n\n // --- Linear fallback: all non-locale-static rules ---\n //\n // We only need to check linear rules whose originalIndex < localeMatchIndex.\n // If localeMatchIndex is Infinity (no locale match), we check all of them.\n for (const [origIdx, redirect] of index.linear) {\n if (origIdx >= localeMatchIndex) {\n // This linear rule comes after the best locale-static match —\n // the locale-static match wins. Stop scanning.\n break;\n }\n const params = matchConfigPattern(pathname, redirect.source);\n if (params) {\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(redirect.destination, {\n ...params,\n ...conditionParams,\n });\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return { destination: dest, permanent: redirect.permanent };\n }\n }\n\n // Return the locale-static match if found (no earlier linear rule matched).\n return localeMatch;\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating rewrites, so this parameter is required.\n */\nexport function matchRewrite(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n): string | null {\n for (const rewrite of rewrites) {\n const params = matchConfigPattern(pathname, rewrite.source);\n if (params) {\n const conditionParams =\n rewrite.has || rewrite.missing\n ? collectConditionParams(rewrite.has, rewrite.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(rewrite.destination, {\n ...params,\n ...conditionParams,\n });\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return dest;\n }\n }\n return null;\n}\n\n/**\n * Substitute all matched route params into a redirect/rewrite destination.\n *\n * Handles repeated params (e.g. `/api/:id/:id`) and catch-all suffix forms\n * (`:path*`, `:path+`) in a single pass. Unknown params are left intact.\n */\nfunction substituteDestinationParams(destination: string, params: Record<string, string>): string {\n const keys = Object.keys(params);\n if (keys.length === 0) return destination;\n\n // Match only the concrete param keys captured from the source pattern.\n // Sorting longest-first ensures hyphenated names like `auth-method`\n // win over shorter prefixes like `auth`. The negative lookahead keeps\n // alphanumeric/underscore suffixes attached, while allowing `-` to act\n // as a literal delimiter in destinations like `:year-:month`.\n const sortedKeys = [...keys].sort((a, b) => b.length - a.length);\n const cacheKey = sortedKeys.join(\"\\0\");\n let paramRe = _compiledDestinationParamCache.get(cacheKey);\n if (!paramRe) {\n const paramAlternation = sortedKeys\n .map((key) => key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\"|\");\n paramRe = new RegExp(`:(${paramAlternation})([+*])?(?![A-Za-z0-9_])`, \"g\");\n _compiledDestinationParamCache.set(cacheKey, paramRe);\n }\n\n return destination.replace(paramRe, (_token, key: string) => params[key]);\n}\n\n/**\n * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.\n *\n * After parameter substitution, a destination like `/:path*` can become\n * `//evil.com` if the catch-all captured a decoded `%2F` (`/evil.com`).\n * Browsers interpret `//evil.com` as a protocol-relative URL, redirecting\n * users off-site.\n *\n * This function collapses any leading double (or more) slashes to a single\n * slash for non-external (relative) destinations.\n */\nexport function sanitizeDestination(dest: string): string {\n // External URLs (http://, https://) are intentional — don't touch them\n if (dest.startsWith(\"http://\") || dest.startsWith(\"https://\")) {\n return dest;\n }\n // Normalize leading backslashes to forward slashes. Browsers interpret\n // backslash as forward slash in URL contexts, so \"\\/evil.com\" becomes\n // \"//evil.com\" (protocol-relative redirect). Replace any mix of leading\n // slashes and backslashes with a single forward slash.\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n return dest;\n}\n\n/**\n * Check if a URL is external (absolute URL or protocol-relative).\n * Detects any URL scheme (http:, https:, data:, javascript:, blob:, etc.)\n * per RFC 3986, plus protocol-relative URLs (//).\n */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/**\n * Proxy an incoming request to an external URL and return the upstream response.\n *\n * Used for external rewrites (e.g. `/ph/:path*` → `https://us.i.posthog.com/:path*`).\n * Next.js handles these as server-side reverse proxies, forwarding the request\n * method, headers, and body to the external destination.\n *\n * Works in all runtimes (Node.js, Cloudflare Workers) via the standard fetch() API.\n */\nexport async function proxyExternalRequest(\n request: Request,\n externalUrl: string,\n): Promise<Response> {\n // Build the full external URL, preserving query parameters from the original request\n const originalUrl = new URL(request.url);\n const targetUrl = new URL(externalUrl);\n const destinationKeys = new Set(targetUrl.searchParams.keys());\n\n // If the rewrite destination already has query params, merge them.\n // Destination params take precedence — original request params are only added\n // when the destination doesn't already specify that key.\n for (const [key, value] of originalUrl.searchParams) {\n if (!destinationKeys.has(key)) {\n targetUrl.searchParams.append(key, value);\n }\n }\n\n // Forward the request with appropriate headers\n const headers = new Headers(request.headers);\n // Set Host to the external target (required for correct routing)\n headers.set(\"host\", targetUrl.host);\n // Remove headers that should not be forwarded to external services.\n // fetch() handles framing independently, so hop-by-hop transport headers\n // from the client must not be forwarded upstream. In particular,\n // transfer-encoding could cause request boundary disagreement between the\n // proxy and backend (defense-in-depth against request smuggling,\n // ref: CVE GHSA-ggv3-7p47-pfv8).\n stripHopByHopRequestHeaders(headers);\n const keysToDelete: string[] = [];\n for (const key of headers.keys()) {\n if (key.startsWith(\"x-middleware-\")) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n headers.delete(key);\n }\n\n const method = request.method;\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n redirect: \"manual\", // Don't follow redirects — pass them through to the client\n };\n\n if (hasBody && request.body) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n\n // Enforce a timeout so slow/unresponsive upstreams don't hold connections\n // open indefinitely (DoS amplification risk on Node.js dev/prod servers).\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n let upstreamResponse: Response;\n try {\n upstreamResponse = await fetch(targetUrl.href, { ...init, signal: controller.signal });\n } catch (e: any) {\n if (e?.name === \"AbortError\") {\n console.error(\"[vinext] External rewrite proxy timeout:\", targetUrl.href);\n return new Response(\"Gateway Timeout\", { status: 504 });\n }\n console.error(\"[vinext] External rewrite proxy error:\", e);\n return new Response(\"Bad Gateway\", { status: 502 });\n } finally {\n clearTimeout(timeout);\n }\n\n // Build the response to return to the client.\n // Copy all upstream headers except hop-by-hop headers.\n // Node.js fetch() auto-decompresses responses (gzip, br, etc.), so the body\n // we receive is already plain text. Forwarding the original content-encoding\n // and content-length headers causes the browser to attempt a second\n // decompression on the already-decoded body, resulting in\n // ERR_CONTENT_DECODING_FAILED. Strip both headers on Node.js only.\n // On Workers, fetch() preserves wire encoding, so the headers stay accurate.\n const isNodeRuntime = typeof process !== \"undefined\" && !!process.versions?.node;\n const responseHeaders = new Headers();\n upstreamResponse.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (HOP_BY_HOP_HEADERS.has(lower)) return;\n if (isNodeRuntime && (lower === \"content-encoding\" || lower === \"content-length\")) return;\n responseHeaders.append(key, value);\n });\n\n return new Response(upstreamResponse.body, {\n status: upstreamResponse.status,\n statusText: upstreamResponse.statusText,\n headers: responseHeaders,\n });\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Returns an array of { key, value } pairs to set on the response.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating headers, so this parameter is required.\n */\nexport function matchHeaders(\n pathname: string,\n headers: NextHeader[],\n ctx: RequestContext,\n): Array<{ key: string; value: string }> {\n const result: Array<{ key: string; value: string }> = [];\n for (const rule of headers) {\n // Cache the compiled source regex — escapeHeaderSource() + safeRegExp() are\n // pure functions of rule.source and the result never changes between requests.\n let sourceRegex = _compiledHeaderSourceCache.get(rule.source);\n if (sourceRegex === undefined) {\n const escaped = escapeHeaderSource(rule.source);\n sourceRegex = safeRegExp(\"^\" + escaped + \"$\");\n _compiledHeaderSourceCache.set(rule.source, sourceRegex);\n }\n if (sourceRegex && sourceRegex.test(pathname)) {\n if (rule.has || rule.missing) {\n if (!checkHasConditions(rule.has, rule.missing, ctx)) {\n continue;\n }\n }\n result.push(...rule.headers);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,wCAAwB,IAAI,KAA0D;;;;;;;;;;;;AAa5F,MAAM,6CAA6B,IAAI,KAA4B;;;;;;;;;;;;;AAcnE,MAAM,0CAA0B,IAAI,KAA4B;;;;;;;;AAShE,MAAM,iDAAiC,IAAI,KAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoChE,MAAM,oBAAoB;AAuB1B,MAAM,sCAAsB,IAAI,SAAwC;;;;;;;;AASxE,SAAS,kBAAkB,WAA0C;CACnE,IAAI,QAAQ,oBAAoB,IAAI,UAAU;AAC9C,KAAI,UAAU,KAAA,EAAW,QAAO;CAEhC,MAAM,+BAAe,IAAI,KAAk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;;AAE1D,MAAI,eAAe,YAAY,KAAK,SAAS,EAAE;AAC7C,OAAI,KAAK,OAAO,KAAK;QACf,CAAC,mBAAmB,KAAK,KAAK,KAAK,SAAS,IAAI,CAClD;;AAGJ,UAAO,KAAK,GAAG,KAAK,QAAQ;;;AAGhC,QAAO"}
1
+ {"version":3,"file":"config-matchers.js","names":[],"sources":["../../src/config/config-matchers.ts"],"sourcesContent":["/**\n * Config pattern matching and rule application utilities.\n *\n * Shared between the dev server (index.ts) and the production server\n * (prod-server.ts) so both apply next.config.js rules identically.\n */\n\nimport type { NextRedirect, NextRewrite, NextHeader, HasCondition } from \"./next-config.js\";\nimport { buildRequestHeadersFromMiddlewareResponse } from \"../server/middleware-request-headers.js\";\n\n/**\n * Cache for compiled regex patterns in matchConfigPattern.\n *\n * Redirect/rewrite patterns are static — they come from next.config.js and\n * never change at runtime. Without caching, every request that hits the regex\n * branch re-runs the full tokeniser walk + isSafeRegex + new RegExp() for\n * every rule in the array. On apps with many locale-prefixed rules (which all\n * contain `(` and therefore enter the regex branch) this dominated profiling\n * at ~2.4 seconds of CPU self-time.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk), so we\n * skip it on subsequent requests too without re-running the scanner.\n */\nconst _compiledPatternCache = new Map<string, { re: RegExp; paramNames: string[] } | null>();\n\n/**\n * Cache for compiled header source regexes in matchHeaders.\n *\n * Each NextHeader rule has a `source` that is run through escapeHeaderSource()\n * then safeRegExp() to produce a RegExp. Both are pure functions of the source\n * string and the result never changes. Without caching, every request\n * re-runs the full escapeHeaderSource tokeniser + isSafeRegex scan + new RegExp()\n * for every header rule.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk).\n */\nconst _compiledHeaderSourceCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for compiled has/missing condition value regexes in checkSingleCondition.\n *\n * Each has/missing condition may carry a `value` string that is passed directly\n * to safeRegExp() for matching against header/cookie/query/host values. The\n * condition objects are static (from next.config.js) so the compiled RegExp\n * never changes. Without caching, safeRegExp() is called on every request for\n * every condition on every rule.\n *\n * Value is `null` when safeRegExp rejected the pattern, or `false` when the\n * value string was undefined (no regex needed — use exact string comparison).\n */\nconst _compiledConditionCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for destination substitution regexes in substituteDestinationParams.\n *\n * The regex depends only on the set of param keys captured from the matched\n * source pattern. Caching by sorted key list avoids recompiling a new RegExp\n * for repeated redirect/rewrite calls that use the same param shape.\n */\nconst _compiledDestinationParamCache = new Map<string, RegExp>();\n\n/**\n * Redirect index for O(1) locale-static rule lookup.\n *\n * Many Next.js apps generate 50-100 redirect rules of the form:\n * /:locale(en|es|fr|...)?/some-static-path → /some-destination\n *\n * The compiled regex for each is like:\n * ^/(en|es|fr|...)?/some-static-path$\n *\n * When no redirect matches (the common case for ordinary page loads),\n * matchRedirect previously ran exec() on every one of those regexes —\n * ~2ms per call, ~2992ms total self-time in profiles.\n *\n * The index splits rules into two buckets:\n *\n * localeStatic — rules whose source is exactly /:paramName(alt1|alt2|...)?/suffix\n * where `suffix` is a static path with no further params or regex groups.\n * These are indexed in a Map<suffix, entry[]> for O(1) lookup after a\n * single fast strip of the optional locale prefix.\n *\n * linear — all other rules. Matched with the original O(n) loop.\n *\n * The index is stored in a WeakMap keyed by the redirects array so it is\n * computed once per config load and GC'd when the array is no longer live.\n *\n * ## Ordering invariant\n *\n * Redirect rules must be evaluated in their original order (first match wins).\n * Each locale-static entry stores its `originalIndex` so that, when a\n * locale-static fast-path match is found, any linear rules that appear earlier\n * in the array are still checked first.\n */\n\n/** Matches `/:param(alternation)?/static/suffix` — the locale-static pattern. */\nconst _LOCALE_STATIC_RE = /^\\/:[\\w-]+\\(([^)]+)\\)\\?\\/([a-zA-Z0-9_~.%@!$&'*+,;=:/-]+)$/;\n\ntype LocaleStaticEntry = {\n /** The param name extracted from the source (e.g. \"locale\"). */\n paramName: string;\n /** The compiled regex matching just the alternation, used at match time. */\n altRe: RegExp;\n /** The original redirect rule. */\n redirect: NextRedirect;\n /** Position of this rule in the original redirects array. */\n originalIndex: number;\n};\n\ntype RedirectIndex = {\n /** Fast-path map: strippedPath (e.g. \"/security\") → matching entries. */\n localeStatic: Map<string, LocaleStaticEntry[]>;\n /**\n * Linear fallback for rules that couldn't be indexed.\n * Each entry is [originalIndex, redirect].\n */\n linear: Array<[number, NextRedirect]>;\n};\n\nconst _redirectIndexCache = new WeakMap<NextRedirect[], RedirectIndex>();\n\n/**\n * Build (or retrieve from cache) the redirect index for a given redirects array.\n *\n * Called once per config load from matchRedirect. The WeakMap ensures the index\n * is recomputed if the config is reloaded (new array reference) and GC'd when\n * the array is collected.\n */\nfunction _getRedirectIndex(redirects: NextRedirect[]): RedirectIndex {\n let index = _redirectIndexCache.get(redirects);\n if (index !== undefined) return index;\n\n const localeStatic = new Map<string, LocaleStaticEntry[]>();\n const linear: Array<[number, NextRedirect]> = [];\n\n for (let i = 0; i < redirects.length; i++) {\n const redirect = redirects[i];\n const m = _LOCALE_STATIC_RE.exec(redirect.source);\n if (m) {\n const paramName = redirect.source.slice(2, redirect.source.indexOf(\"(\"));\n const alternation = m[1];\n const suffix = \"/\" + m[2]; // e.g. \"/security\"\n // Build a small regex to validate the captured locale value against the\n // alternation. Using anchored match to avoid partial matches.\n // The alternation comes from user config; run it through safeRegExp to\n // guard against ReDoS in pathological configs.\n const altRe = safeRegExp(\"^(?:\" + alternation + \")$\");\n if (!altRe) {\n // Unsafe alternation — fall back to linear scan for this rule.\n linear.push([i, redirect]);\n continue;\n }\n const entry: LocaleStaticEntry = { paramName, altRe, redirect, originalIndex: i };\n const bucket = localeStatic.get(suffix);\n if (bucket) {\n bucket.push(entry);\n } else {\n localeStatic.set(suffix, [entry]);\n }\n } else {\n linear.push([i, redirect]);\n }\n }\n\n index = { localeStatic, linear };\n _redirectIndexCache.set(redirects, index);\n return index;\n}\n\n/** Hop-by-hop headers that should not be forwarded through a proxy. */\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Request hop-by-hop headers to strip before proxying with fetch().\n * Intentionally narrower than HOP_BY_HOP_HEADERS: external rewrite proxying\n * still forwards proxy auth credentials, while response sanitization strips\n * them before returning data to the client.\n */\nconst REQUEST_HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\nfunction stripHopByHopRequestHeaders(headers: Headers): void {\n const connectionTokens = (headers.get(\"connection\") || \"\")\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean);\n\n for (const header of REQUEST_HOP_BY_HOP_HEADERS) {\n headers.delete(header);\n }\n\n for (const token of connectionTokens) {\n headers.delete(token);\n }\n}\n\n/**\n * Detect regex patterns vulnerable to catastrophic backtracking (ReDoS).\n *\n * Uses a lightweight heuristic: scans the pattern string for nested quantifiers\n * (a quantifier applied to a group that itself contains a quantifier). This\n * catches the most common pathological patterns like `(a+)+`, `(.*)*`,\n * `([^/]+)+`, `(a|a+)+` without needing a full regex parser.\n *\n * Returns true if the pattern appears safe, false if it's potentially dangerous.\n */\nexport function isSafeRegex(pattern: string): boolean {\n // Track parenthesis nesting depth and whether we've seen a quantifier\n // at each depth level.\n const quantifierAtDepth: boolean[] = [];\n let depth = 0;\n let i = 0;\n\n while (i < pattern.length) {\n const ch = pattern[i];\n\n // Skip escaped characters\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Skip character classes [...] — quantifiers inside them are literal\n if (ch === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++; // skip escaped char in class\n i++;\n }\n i++; // skip closing ]\n continue;\n }\n\n if (ch === \"(\") {\n depth++;\n // Initialize: no quantifier seen yet at this new depth\n if (quantifierAtDepth.length <= depth) {\n quantifierAtDepth.push(false);\n } else {\n quantifierAtDepth[depth] = false;\n }\n i++;\n continue;\n }\n\n if (ch === \")\") {\n const hadQuantifier = depth > 0 && quantifierAtDepth[depth];\n if (depth > 0) depth--;\n\n // Look ahead for a quantifier on this group: +, *, {n,m}\n // Note: '?' after ')' means \"zero or one\" which does NOT cause catastrophic\n // backtracking — it only allows 2 paths (match/skip), not exponential.\n // Only unbounded repetition (+, *, {n,}) on a group with inner quantifiers is dangerous.\n const next = pattern[i + 1];\n if (next === \"+\" || next === \"*\" || next === \"{\") {\n if (hadQuantifier) {\n // Nested quantifier detected: quantifier on a group that contains a quantifier\n return false;\n }\n // Mark the enclosing depth as having a quantifier\n if (depth >= 0 && depth < quantifierAtDepth.length) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n // Detect quantifiers: +, *, ?, {n,m}\n // '?' is a quantifier (optional) unless it follows another quantifier (+, *, ?, })\n // in which case it's a non-greedy modifier.\n if (ch === \"+\" || ch === \"*\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i++;\n continue;\n }\n\n if (ch === \"?\") {\n // '?' after +, *, ?, or } is a non-greedy modifier, not a quantifier\n const prev = i > 0 ? pattern[i - 1] : \"\";\n if (prev !== \"+\" && prev !== \"*\" && prev !== \"?\" && prev !== \"}\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n if (ch === \"{\") {\n // Check if this is a quantifier {n}, {n,}, {n,m}\n let j = i + 1;\n while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;\n if (j < pattern.length && pattern[j] === \"}\" && j > i + 1) {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i = j + 1;\n continue;\n }\n }\n\n i++;\n }\n\n return true;\n}\n\n/**\n * Compile a regex pattern safely. Returns the compiled RegExp or null if the\n * pattern is invalid or vulnerable to ReDoS.\n *\n * Logs a warning when a pattern is rejected so developers can fix their config.\n */\nexport function safeRegExp(pattern: string, flags?: string): RegExp | null {\n if (!isSafeRegex(pattern)) {\n console.warn(\n `[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): ${pattern}\\n` +\n ` Patterns with nested quantifiers (e.g. (a+)+) can cause catastrophic backtracking.\\n` +\n ` Simplify the pattern to avoid nested repetition.`,\n );\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a Next.js header/rewrite/redirect source pattern into a regex string.\n *\n * Regex groups in the source (e.g. `(\\d+)`) are extracted first, the remaining\n * text is escaped/converted in a **single pass** (avoiding chained `.replace()`\n * which CodeQL flags as incomplete sanitization), then groups are restored.\n */\nexport function escapeHeaderSource(source: string): string {\n // Sentinel character for group placeholders. Uses a Unicode private-use-area\n // codepoint that will never appear in real source patterns.\n const S = \"\\uE000\";\n\n // Step 1: extract regex groups and replace with numbered placeholders.\n const groups: string[] = [];\n const withPlaceholders = source.replace(/\\(([^)]+)\\)/g, (_m, inner) => {\n groups.push(inner);\n return `${S}G${groups.length - 1}${S}`;\n });\n\n // Step 2: single-pass conversion of the placeholder-bearing string.\n // Match named params (:[\\w-]+), sentinel group placeholders, metacharacters, and literal text.\n // The regex uses non-overlapping alternatives to avoid backtracking:\n // :[\\w-]+ — named parameter (constraint sentinel is checked procedurally;\n // param names may contain hyphens, e.g. :auth-method)\n // sentinel group — standalone regex group placeholder\n // [.+?*] — single metachar to escape/convert\n // [^.+?*:\\uE000]+ — literal text (excludes all chars that start other alternatives)\n let result = \"\";\n const re = new RegExp(\n `${S}G(\\\\d+)${S}|:[\\\\w-]+|[.+?*]|[^.+?*:\\\\uE000]+`, // lgtm[js/redos] — alternatives are non-overlapping\n \"g\",\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(withPlaceholders)) !== null) {\n if (m[1] !== undefined) {\n // Standalone regex group — restore as-is\n result += `(${groups[Number(m[1])]})`;\n } else if (m[0].startsWith(\":\")) {\n // Named parameter — check if followed by a constraint group placeholder\n const afterParam = withPlaceholders.slice(re.lastIndex);\n const constraintMatch = afterParam.match(new RegExp(`^${S}G(\\\\d+)${S}`));\n if (constraintMatch) {\n // :param(constraint) — use the constraint as the capture group\n re.lastIndex += constraintMatch[0].length;\n result += `(${groups[Number(constraintMatch[1])]})`;\n } else {\n // Plain named parameter → match one segment\n result += \"[^/]+\";\n }\n } else {\n switch (m[0]) {\n case \".\":\n result += \"\\\\.\";\n break;\n case \"+\":\n result += \"\\\\+\";\n break;\n case \"?\":\n result += \"\\\\?\";\n break;\n case \"*\":\n result += \".*\";\n break;\n default:\n result += m[0];\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Request context needed for evaluating has/missing conditions.\n * Callers extract the relevant parts from the incoming Request.\n */\nexport type RequestContext = {\n headers: Headers;\n cookies: Record<string, string>;\n query: URLSearchParams;\n host: string;\n};\n\n/**\n * Parse a Cookie header string into a key-value record.\n */\nexport function parseCookies(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) return {};\n const cookies: Record<string, string> = {};\n for (const part of cookieHeader.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key) cookies[key] = value;\n }\n return cookies;\n}\n\n/**\n * Build a RequestContext from a Web Request object.\n */\nexport function requestContextFromRequest(request: Request): RequestContext {\n const url = new URL(request.url);\n return {\n headers: request.headers,\n cookies: parseCookies(request.headers.get(\"cookie\")),\n query: url.searchParams,\n host: normalizeHost(request.headers.get(\"host\"), url.hostname),\n };\n}\n\nexport function normalizeHost(hostHeader: string | null, fallbackHostname: string): string {\n const host = hostHeader ?? fallbackHostname;\n return host.split(\":\", 1)[0].toLowerCase();\n}\n\n/**\n * Unpack `x-middleware-request-*` headers from the collected middleware\n * response headers into the actual request, and strip all `x-middleware-*`\n * internal signals so they never reach clients.\n *\n * `middlewareHeaders` is mutated in-place (matching keys are deleted).\n * Returns a (possibly cloned) `Request` with the unpacked headers applied,\n * and a fresh `RequestContext` built from it — ready for post-middleware\n * config rule matching (beforeFiles, afterFiles, fallback).\n *\n * Works for both Node.js requests (mutable headers) and Workers requests\n * (immutable — cloned only when there are headers to apply).\n *\n * `x-middleware-request-*` values are always plain strings (they carry\n * individual header values), so the wider `string | string[]` type of\n * `middlewareHeaders` is safe to cast here.\n */\nexport function applyMiddlewareRequestHeaders(\n middlewareHeaders: Record<string, string | string[]>,\n request: Request,\n): { request: Request; postMwReqCtx: RequestContext } {\n const nextHeaders = buildRequestHeadersFromMiddlewareResponse(request.headers, middlewareHeaders);\n\n for (const key of Object.keys(middlewareHeaders)) {\n if (key.startsWith(\"x-middleware-\")) {\n delete middlewareHeaders[key];\n }\n }\n\n if (nextHeaders) {\n // Headers may be immutable (Workers), so always clone via new Headers().\n request = new Request(request.url, {\n method: request.method,\n headers: nextHeaders,\n body: request.body,\n // @ts-expect-error — duplex needed for streaming request bodies\n duplex: request.body ? \"half\" : undefined,\n });\n }\n\n return { request, postMwReqCtx: requestContextFromRequest(request) };\n}\n\nfunction _emptyParams(): Record<string, string> {\n return Object.create(null) as Record<string, string>;\n}\n\nfunction _matchConditionValue(\n actualValue: string,\n expectedValue: string | undefined,\n): Record<string, string> | null {\n if (expectedValue === undefined) return _emptyParams();\n\n const re = _cachedConditionRegex(expectedValue);\n if (re) {\n const match = re.exec(actualValue);\n if (!match) return null;\n\n const params = _emptyParams();\n if (match.groups) {\n for (const [key, value] of Object.entries(match.groups)) {\n if (value !== undefined) params[key] = value;\n }\n }\n return params;\n }\n\n return actualValue === expectedValue ? _emptyParams() : null;\n}\n\n/**\n * Check a single has/missing condition against request context.\n * Returns captured params when the condition is satisfied, or null otherwise.\n */\nfunction matchSingleCondition(\n condition: HasCondition,\n ctx: RequestContext,\n): Record<string, string> | null {\n switch (condition.type) {\n case \"header\": {\n const headerValue = ctx.headers.get(condition.key);\n if (headerValue === null) return null;\n return _matchConditionValue(headerValue, condition.value);\n }\n case \"cookie\": {\n const cookieValue = ctx.cookies[condition.key];\n if (cookieValue === undefined) return null;\n return _matchConditionValue(cookieValue, condition.value);\n }\n case \"query\": {\n const queryValue = ctx.query.get(condition.key);\n if (queryValue === null) return null;\n return _matchConditionValue(queryValue, condition.value);\n }\n case \"host\": {\n if (condition.value !== undefined) return _matchConditionValue(ctx.host, condition.value);\n return ctx.host === condition.key ? _emptyParams() : null;\n }\n default:\n return null;\n }\n}\n\n/**\n * Return a cached RegExp for a has/missing condition value string, compiling\n * on first use. Returns null if safeRegExp rejected the pattern or if the\n * value is not a valid regex (fall back to exact string comparison).\n */\nfunction _cachedConditionRegex(value: string): RegExp | null {\n let re = _compiledConditionCache.get(value);\n if (re === undefined) {\n // Anchor the regex to match the full value, not a substring.\n // Matches Next.js: new RegExp(`^${hasItem.value}$`)\n // Without anchoring, has:[cookie:role=admin] would match \"not-admin\".\n re = safeRegExp(`^${value}$`);\n _compiledConditionCache.set(value, re);\n }\n return re;\n}\n\n/**\n * Check all has/missing conditions for a config rule.\n * Returns true if the rule should be applied (all has conditions pass, all missing conditions pass).\n *\n * - has: every condition must match (the request must have it)\n * - missing: every condition must NOT match (the request must not have it)\n */\nfunction collectConditionParams(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): Record<string, string> | null {\n const params = _emptyParams();\n\n if (has) {\n for (const condition of has) {\n const conditionParams = matchSingleCondition(condition, ctx);\n if (!conditionParams) return null;\n Object.assign(params, conditionParams);\n }\n }\n\n if (missing) {\n for (const condition of missing) {\n if (matchSingleCondition(condition, ctx)) return null;\n }\n }\n\n return params;\n}\n\nexport function checkHasConditions(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): boolean {\n return collectConditionParams(has, missing, ctx) !== null;\n}\n\n/**\n * If the current position in `str` starts with a parenthesized group, consume\n * it and advance `re.lastIndex` past the closing `)`. Returns the group\n * contents or null if no group is present.\n */\nfunction extractConstraint(str: string, re: RegExp): string | null {\n if (str[re.lastIndex] !== \"(\") return null;\n const start = re.lastIndex + 1;\n let depth = 1;\n let i = start;\n while (i < str.length && depth > 0) {\n if (str[i] === \"(\") depth++;\n else if (str[i] === \")\") depth--;\n i++;\n }\n if (depth !== 0) return null;\n re.lastIndex = i;\n return str.slice(start, i - 1);\n}\n\n/**\n * Match a Next.js config pattern (from redirects/rewrites sources) against a pathname.\n * Returns matched params or null.\n *\n * Supports:\n * :param - matches a single path segment\n * :param* - matches zero or more segments (catch-all)\n * :param+ - matches one or more segments\n * (regex) - inline regex patterns in the source\n * :param(constraint) - named param with inline regex constraint\n */\nexport function matchConfigPattern(\n pathname: string,\n pattern: string,\n): Record<string, string> | null {\n // If the pattern contains regex groups like (\\d+) or (.*), use regex matching.\n // Also enter this branch when a catch-all parameter (:param* or :param+) is\n // followed by a literal suffix (e.g. \"/:path*.md\"). Without this, the suffix\n // pattern falls through to the simple segment matcher which incorrectly treats\n // the whole segment (\":path*.md\") as a named parameter and matches everything.\n // The last condition catches simple params with literal suffixes (e.g. \"/:slug.md\")\n // where the param name is followed by a dot — the simple matcher would treat\n // \"slug.md\" as the param name and match any single segment regardless of suffix.\n if (\n pattern.includes(\"(\") ||\n pattern.includes(\"\\\\\") ||\n /:[\\w-]+[*+][^/]/.test(pattern) ||\n /:[\\w-]+\\./.test(pattern)\n ) {\n try {\n // Look up the compiled regex in the module-level cache. Patterns come\n // from next.config.js and are static, so we only need to compile each\n // one once across the lifetime of the worker/server process.\n let compiled = _compiledPatternCache.get(pattern);\n if (compiled === undefined) {\n // Cache miss — compile the pattern now and store the result.\n // Param names may contain hyphens (e.g. :auth-method, :sign-in).\n const paramNames: string[] = [];\n // Single-pass conversion with procedural suffix handling. The tokenizer\n // matches only simple, non-overlapping tokens; quantifier/constraint\n // suffixes after :param are consumed procedurally to avoid polynomial\n // backtracking in the regex engine.\n let regexStr = \"\";\n const tokenRe = /:([\\w-]+)|[.]|[^:.]+/g; // lgtm[js/redos] — alternatives are non-overlapping (`:` and `.` excluded from `[^:.]+`)\n let tok: RegExpExecArray | null;\n while ((tok = tokenRe.exec(pattern)) !== null) {\n if (tok[1] !== undefined) {\n const name = tok[1];\n const rest = pattern.slice(tokenRe.lastIndex);\n // Check for quantifier (* or +) with optional constraint\n if (rest.startsWith(\"*\") || rest.startsWith(\"+\")) {\n const quantifier = rest[0];\n tokenRe.lastIndex += 1;\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n if (constraint !== null) {\n regexStr += `(${constraint})`;\n } else {\n regexStr += quantifier === \"*\" ? \"(.*)\" : \"(.+)\";\n }\n } else {\n // Check for inline constraint without quantifier\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n regexStr += constraint !== null ? `(${constraint})` : \"([^/]+)\";\n }\n } else if (tok[0] === \".\") {\n regexStr += \"\\\\.\";\n } else {\n regexStr += tok[0];\n }\n }\n const re = safeRegExp(\"^\" + regexStr + \"$\");\n // Store null for rejected patterns so we don't re-run isSafeRegex.\n compiled = re ? { re, paramNames } : null;\n _compiledPatternCache.set(pattern, compiled);\n }\n if (!compiled) return null;\n const match = compiled.re.exec(pathname);\n if (!match) return null;\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = match[i + 1] ?? \"\";\n }\n return params;\n } catch {\n // Fall through to segment-based matching\n }\n }\n\n // Check for catch-all patterns (:param* or :param+) without regex groups\n // Param names may contain hyphens (e.g. :sign-in*, :sign-up+).\n const catchAllMatch = pattern.match(/:([\\w-]+)(\\*|\\+)$/);\n if (catchAllMatch) {\n const prefix = pattern.slice(0, pattern.lastIndexOf(\":\"));\n const paramName = catchAllMatch[1];\n const isPlus = catchAllMatch[2] === \"+\";\n\n const prefixNoSlash = prefix.replace(/\\/$/, \"\");\n if (!pathname.startsWith(prefixNoSlash)) return null;\n const charAfter = pathname[prefixNoSlash.length];\n if (charAfter !== undefined && charAfter !== \"/\") return null;\n\n const rest = pathname.slice(prefixNoSlash.length);\n if (isPlus && (!rest || rest === \"/\")) return null;\n let restValue = rest.startsWith(\"/\") ? rest.slice(1) : rest;\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the request entry point. Decoding again would produce incorrect param values.\n return { [paramName]: restValue };\n }\n\n // Simple segment-based matching for exact patterns and :param\n const parts = pattern.split(\"/\");\n const pathParts = pathname.split(\"/\");\n\n if (parts.length !== pathParts.length) return null;\n\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < parts.length; i++) {\n if (parts[i].startsWith(\":\")) {\n params[parts[i].slice(1)] = pathParts[i];\n } else if (parts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns the redirect info if a redirect was matched, or null.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating redirects, so this parameter is required.\n *\n * ## Performance\n *\n * Rules with a locale-capture-group prefix (the dominant pattern in large\n * Next.js apps — e.g. `/:locale(en|es|fr|...)?/some-path`) are handled via\n * a pre-built index. Instead of running exec() on each locale regex\n * individually, we:\n *\n * 1. Strip the optional locale prefix from the pathname with one cheap\n * string-slice check (no regex exec on the hot path).\n * 2. Look up the stripped suffix in a Map<suffix, entry[]>.\n * 3. For each matching entry, validate the captured locale string against\n * a small, anchored alternation regex.\n *\n * This reduces the per-request cost from O(n × regex) to O(1) map lookup +\n * O(matches × tiny-regex), eliminating the ~2992ms self-time reported in\n * profiles for apps with 63+ locale-prefixed rules.\n *\n * Rules that don't fit the locale-static pattern fall back to the original\n * linear matchConfigPattern scan.\n *\n * ## Ordering invariant\n *\n * First match wins, preserving the original redirect array order. When a\n * locale-static fast-path match is found at position N, all linear rules with\n * an original index < N are checked via matchConfigPattern first — they are\n * few in practice (typically zero) so this is not a hot-path concern.\n */\nexport function matchRedirect(\n pathname: string,\n redirects: NextRedirect[],\n ctx: RequestContext,\n): { destination: string; permanent: boolean } | null {\n if (redirects.length === 0) return null;\n\n const index = _getRedirectIndex(redirects);\n\n // --- Locate the best locale-static candidate ---\n //\n // We look for the locale-static entry with the LOWEST originalIndex that\n // matches this pathname (and passes has/missing conditions).\n //\n // Strategy: try both the full pathname (locale omitted, e.g. \"/security\")\n // and the pathname with the first segment stripped (locale present, e.g.\n // \"/en/security\" → suffix \"/security\", locale \"en\").\n //\n // We do NOT use a regex here — just a single indexOf('/') to locate the\n // second slash, which is O(n) on the path length but far cheaper than\n // running 63 compiled regexes.\n\n let localeMatch: { destination: string; permanent: boolean } | null = null;\n let localeMatchIndex = Infinity;\n\n if (index.localeStatic.size > 0) {\n // Case 1: no locale prefix — pathname IS the suffix.\n const noLocaleBucket = index.localeStatic.get(pathname);\n if (noLocaleBucket) {\n for (const entry of noLocaleBucket) {\n if (entry.originalIndex >= localeMatchIndex) continue; // already have a better match\n const redirect = entry.redirect;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n // Locale was omitted (the `?` made it optional) — param value is \"\".\n let dest = substituteDestinationParams(redirect.destination, {\n [entry.paramName]: \"\",\n ...conditionParams,\n });\n dest = sanitizeDestination(dest);\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n\n // Case 2: locale prefix present — first path segment is the locale.\n // Find the second slash: pathname = \"/locale/rest/of/path\"\n // ^--- slashTwo\n const slashTwo = pathname.indexOf(\"/\", 1);\n if (slashTwo !== -1) {\n const suffix = pathname.slice(slashTwo); // e.g. \"/security\"\n const localePart = pathname.slice(1, slashTwo); // e.g. \"en\"\n const localeBucket = index.localeStatic.get(suffix);\n if (localeBucket) {\n for (const entry of localeBucket) {\n if (entry.originalIndex >= localeMatchIndex) continue;\n // Validate that `localePart` is one of the allowed alternation values.\n if (!entry.altRe.test(localePart)) continue;\n const redirect = entry.redirect;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(redirect.destination, {\n [entry.paramName]: localePart,\n ...conditionParams,\n });\n dest = sanitizeDestination(dest);\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n }\n }\n\n // --- Linear fallback: all non-locale-static rules ---\n //\n // We only need to check linear rules whose originalIndex < localeMatchIndex.\n // If localeMatchIndex is Infinity (no locale match), we check all of them.\n for (const [origIdx, redirect] of index.linear) {\n if (origIdx >= localeMatchIndex) {\n // This linear rule comes after the best locale-static match —\n // the locale-static match wins. Stop scanning.\n break;\n }\n const params = matchConfigPattern(pathname, redirect.source);\n if (params) {\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(redirect.destination, {\n ...params,\n ...conditionParams,\n });\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return { destination: dest, permanent: redirect.permanent };\n }\n }\n\n // Return the locale-static match if found (no earlier linear rule matched).\n return localeMatch;\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating rewrites, so this parameter is required.\n */\nexport function matchRewrite(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n): string | null {\n for (const rewrite of rewrites) {\n const params = matchConfigPattern(pathname, rewrite.source);\n if (params) {\n const conditionParams =\n rewrite.has || rewrite.missing\n ? collectConditionParams(rewrite.has, rewrite.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n let dest = substituteDestinationParams(rewrite.destination, {\n ...params,\n ...conditionParams,\n });\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return dest;\n }\n }\n return null;\n}\n\n/**\n * Substitute all matched route params into a redirect/rewrite destination.\n *\n * Handles repeated params (e.g. `/api/:id/:id`) and catch-all suffix forms\n * (`:path*`, `:path+`) in a single pass. Unknown params are left intact.\n */\nfunction substituteDestinationParams(destination: string, params: Record<string, string>): string {\n const keys = Object.keys(params);\n if (keys.length === 0) return destination;\n\n // Match only the concrete param keys captured from the source pattern.\n // Sorting longest-first ensures hyphenated names like `auth-method`\n // win over shorter prefixes like `auth`. The negative lookahead keeps\n // alphanumeric/underscore suffixes attached, while allowing `-` to act\n // as a literal delimiter in destinations like `:year-:month`.\n const sortedKeys = [...keys].sort((a, b) => b.length - a.length);\n const cacheKey = sortedKeys.join(\"\\0\");\n let paramRe = _compiledDestinationParamCache.get(cacheKey);\n if (!paramRe) {\n const paramAlternation = sortedKeys\n .map((key) => key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\"|\");\n paramRe = new RegExp(`:(${paramAlternation})([+*])?(?![A-Za-z0-9_])`, \"g\");\n _compiledDestinationParamCache.set(cacheKey, paramRe);\n }\n\n return destination.replace(paramRe, (_token, key: string) => params[key]);\n}\n\n/**\n * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.\n *\n * After parameter substitution, a destination like `/:path*` can become\n * `//evil.com` if the catch-all captured a decoded `%2F` (`/evil.com`).\n * Browsers interpret `//evil.com` as a protocol-relative URL, redirecting\n * users off-site.\n *\n * This function collapses any leading double (or more) slashes to a single\n * slash for non-external (relative) destinations.\n */\nexport function sanitizeDestination(dest: string): string {\n // External URLs (http://, https://) are intentional — don't touch them\n if (dest.startsWith(\"http://\") || dest.startsWith(\"https://\")) {\n return dest;\n }\n // Normalize leading backslashes to forward slashes. Browsers interpret\n // backslash as forward slash in URL contexts, so \"\\/evil.com\" becomes\n // \"//evil.com\" (protocol-relative redirect). Replace any mix of leading\n // slashes and backslashes with a single forward slash.\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n return dest;\n}\n\n/**\n * Check if a URL is external (absolute URL or protocol-relative).\n * Detects any URL scheme (http:, https:, data:, javascript:, blob:, etc.)\n * per RFC 3986, plus protocol-relative URLs (//).\n */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/**\n * Proxy an incoming request to an external URL and return the upstream response.\n *\n * Used for external rewrites (e.g. `/ph/:path*` → `https://us.i.posthog.com/:path*`).\n * Next.js handles these as server-side reverse proxies, forwarding the request\n * method, headers, and body to the external destination.\n *\n * Works in all runtimes (Node.js, Cloudflare Workers) via the standard fetch() API.\n */\nexport async function proxyExternalRequest(\n request: Request,\n externalUrl: string,\n): Promise<Response> {\n // Build the full external URL, preserving query parameters from the original request\n const originalUrl = new URL(request.url);\n const targetUrl = new URL(externalUrl);\n const destinationKeys = new Set(targetUrl.searchParams.keys());\n\n // If the rewrite destination already has query params, merge them.\n // Destination params take precedence — original request params are only added\n // when the destination doesn't already specify that key.\n for (const [key, value] of originalUrl.searchParams) {\n if (!destinationKeys.has(key)) {\n targetUrl.searchParams.append(key, value);\n }\n }\n\n // Forward the request with appropriate headers\n const headers = new Headers(request.headers);\n // Set Host to the external target (required for correct routing)\n headers.set(\"host\", targetUrl.host);\n // Remove headers that should not be forwarded to external services.\n // fetch() handles framing independently, so hop-by-hop transport headers\n // from the client must not be forwarded upstream. In particular,\n // transfer-encoding could cause request boundary disagreement between the\n // proxy and backend (defense-in-depth against request smuggling,\n // ref: CVE GHSA-ggv3-7p47-pfv8).\n stripHopByHopRequestHeaders(headers);\n const keysToDelete: string[] = [];\n for (const key of headers.keys()) {\n if (key.startsWith(\"x-middleware-\")) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n headers.delete(key);\n }\n\n const method = request.method;\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n redirect: \"manual\", // Don't follow redirects — pass them through to the client\n };\n\n if (hasBody && request.body) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n\n // Enforce a timeout so slow/unresponsive upstreams don't hold connections\n // open indefinitely (DoS amplification risk on Node.js dev/prod servers).\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n let upstreamResponse: Response;\n try {\n upstreamResponse = await fetch(targetUrl.href, { ...init, signal: controller.signal });\n } catch (e) {\n if (e instanceof Error && e.name === \"AbortError\") {\n console.error(\"[vinext] External rewrite proxy timeout:\", targetUrl.href);\n return new Response(\"Gateway Timeout\", { status: 504 });\n }\n console.error(\"[vinext] External rewrite proxy error:\", e);\n return new Response(\"Bad Gateway\", { status: 502 });\n } finally {\n clearTimeout(timeout);\n }\n\n // Build the response to return to the client.\n // Copy all upstream headers except hop-by-hop headers.\n // Node.js fetch() auto-decompresses responses (gzip, br, etc.), so the body\n // we receive is already plain text. Forwarding the original content-encoding\n // and content-length headers causes the browser to attempt a second\n // decompression on the already-decoded body, resulting in\n // ERR_CONTENT_DECODING_FAILED. Strip both headers on Node.js only.\n // On Workers, fetch() preserves wire encoding, so the headers stay accurate.\n const isNodeRuntime = typeof process !== \"undefined\" && !!process.versions?.node;\n const responseHeaders = new Headers();\n upstreamResponse.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (HOP_BY_HOP_HEADERS.has(lower)) return;\n if (isNodeRuntime && (lower === \"content-encoding\" || lower === \"content-length\")) return;\n responseHeaders.append(key, value);\n });\n\n return new Response(upstreamResponse.body, {\n status: upstreamResponse.status,\n statusText: upstreamResponse.statusText,\n headers: responseHeaders,\n });\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Returns an array of { key, value } pairs to set on the response.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating headers, so this parameter is required.\n */\nexport function matchHeaders(\n pathname: string,\n headers: NextHeader[],\n ctx: RequestContext,\n): Array<{ key: string; value: string }> {\n const result: Array<{ key: string; value: string }> = [];\n for (const rule of headers) {\n // Cache the compiled source regex — escapeHeaderSource() + safeRegExp() are\n // pure functions of rule.source and the result never changes between requests.\n let sourceRegex = _compiledHeaderSourceCache.get(rule.source);\n if (sourceRegex === undefined) {\n const escaped = escapeHeaderSource(rule.source);\n sourceRegex = safeRegExp(\"^\" + escaped + \"$\");\n _compiledHeaderSourceCache.set(rule.source, sourceRegex);\n }\n if (sourceRegex && sourceRegex.test(pathname)) {\n if (rule.has || rule.missing) {\n if (!checkHasConditions(rule.has, rule.missing, ctx)) {\n continue;\n }\n }\n result.push(...rule.headers);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,wCAAwB,IAAI,KAA0D;;;;;;;;;;;;AAa5F,MAAM,6CAA6B,IAAI,KAA4B;;;;;;;;;;;;;AAcnE,MAAM,0CAA0B,IAAI,KAA4B;;;;;;;;AAShE,MAAM,iDAAiC,IAAI,KAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoChE,MAAM,oBAAoB;AAuB1B,MAAM,sCAAsB,IAAI,SAAwC;;;;;;;;AASxE,SAAS,kBAAkB,WAA0C;CACnE,IAAI,QAAQ,oBAAoB,IAAI,UAAU;AAC9C,KAAI,UAAU,KAAA,EAAW,QAAO;CAEhC,MAAM,+BAAe,IAAI,KAAkC;CAC3D,MAAM,SAAwC,EAAE;AAEhD,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;EACzC,MAAM,WAAW,UAAU;EAC3B,MAAM,IAAI,kBAAkB,KAAK,SAAS,OAAO;AACjD,MAAI,GAAG;GACL,MAAM,YAAY,SAAS,OAAO,MAAM,GAAG,SAAS,OAAO,QAAQ,IAAI,CAAC;GACxE,MAAM,cAAc,EAAE;GACtB,MAAM,SAAS,MAAM,EAAE;GAKvB,MAAM,QAAQ,WAAW,SAAS,cAAc,KAAK;AACrD,OAAI,CAAC,OAAO;AAEV,WAAO,KAAK,CAAC,GAAG,SAAS,CAAC;AAC1B;;GAEF,MAAM,QAA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CAAC;;AAEzD,UAAQ,MAAM,0CAA0C,EAAE;AAC1D,SAAO,IAAI,SAAS,eAAe,EAAE,QAAQ,KAAK,CAAC;WAC3C;AACR,eAAa,QAAQ;;CAWvB,MAAM,gBAAgB,OAAO,YAAY,eAAe,CAAC,CAAC,QAAQ,UAAU;CAC5E,MAAM,kBAAkB,IAAI,SAAS;AACrC,kBAAiB,QAAQ,SAAS,OAAO,QAAQ;EAC/C,MAAM,QAAQ,IAAI,aAAa;AAC/B,MAAI,mBAAmB,IAAI,MAAM,CAAE;AACnC,MAAI,kBAAkB,UAAU,sBAAsB,UAAU,kBAAmB;AACnF,kBAAgB,OAAO,KAAK,MAAM;GAClC;AAEF,QAAO,IAAI,SAAS,iBAAiB,MAAM;EACzC,QAAQ,iBAAiB;EACzB,YAAY,iBAAiB;EAC7B,SAAS;EACV,CAAC;;;;;;;;;;AAWJ,SAAgB,aACd,UACA,SACA,KACuC;CACvC,MAAM,SAAgD,EAAE;AACxD,MAAK,MAAM,QAAQ,SAAS;EAG1B,IAAI,cAAc,2BAA2B,IAAI,KAAK,OAAO;AAC7D,MAAI,gBAAgB,KAAA,GAAW;AAE7B,iBAAc,WAAW,MADT,mBAAmB,KAAK,OAAO,GACN,IAAI;AAC7C,8BAA2B,IAAI,KAAK,QAAQ,YAAY;;AAE1D,MAAI,eAAe,YAAY,KAAK,SAAS,EAAE;AAC7C,OAAI,KAAK,OAAO,KAAK;QACf,CAAC,mBAAmB,KAAK,KAAK,KAAK,SAAS,IAAI,CAClD;;AAGJ,UAAO,KAAK,GAAG,KAAK,QAAQ;;;AAGhC,QAAO"}
@@ -1,15 +1,15 @@
1
1
  //#region src/config/dotenv.d.ts
2
2
  type VinextEnvMode = "development" | "production" | "test";
3
- interface LoadDotenvOptions {
3
+ type LoadDotenvOptions = {
4
4
  root: string;
5
5
  mode: VinextEnvMode;
6
6
  processEnv?: NodeJS.ProcessEnv;
7
- }
8
- interface LoadDotenvResult {
7
+ };
8
+ type LoadDotenvResult = {
9
9
  mode: VinextEnvMode;
10
10
  loadedFiles: string[];
11
11
  loadedEnv: Record<string, string>;
12
- }
12
+ };
13
13
  /**
14
14
  * Next.js-compatible dotenv lookup order (highest priority first).
15
15
  */
@@ -1 +1 @@
1
- {"version":3,"file":"dotenv.js","names":[],"sources":["../../src/config/dotenv.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseEnv } from \"node:util\";\n\nexport type VinextEnvMode = \"development\" | \"production\" | \"test\";\n\nexport interface LoadDotenvOptions {\n root: string;\n mode: VinextEnvMode;\n processEnv?: NodeJS.ProcessEnv;\n}\n\nexport interface LoadDotenvResult {\n mode: VinextEnvMode;\n loadedFiles: string[];\n loadedEnv: Record<string, string>;\n}\n\n/**\n * Next.js-compatible dotenv lookup order (highest priority first).\n */\nexport function getDotenvFiles(mode: VinextEnvMode): string[] {\n return [`.env.${mode}.local`, ...(mode === \"test\" ? [] : [\".env.local\"]), `.env.${mode}`, \".env\"];\n}\n\n/**\n * Load .env files into processEnv with Next.js-like precedence:\n * process.env > .env.<mode>.local > .env.local > .env.<mode> > .env.\n *\n * This mutates processEnv (defaults to process.env).\n *\n * ## Interaction with Vite's own .env loading\n *\n * Vite also loads .env files internally during createServer()/build(). That's\n * fine — the two systems serve different purposes and don't conflict:\n *\n * - **vinext** populates `process.env` so that server-side code (SSR, API\n * routes, Server Components) can read env vars at runtime, and so the Vite\n * plugin's `config()` hook can scan `process.env` for `NEXT_PUBLIC_*` vars\n * to inline via `define`.\n *\n * - **Vite** loads .env files to populate `import.meta.env.VITE_*` for its\n * own client exposure mechanism (which Next.js apps don't use).\n *\n * Because we load first and neither system overwrites existing keys, Vite's\n * pass is effectively a no-op for overlapping keys. For `start` and `deploy`\n * commands (which don't go through Vite at all), this is the only loading.\n */\nexport function loadDotenv({\n root,\n mode,\n processEnv = process.env,\n}: LoadDotenvOptions): LoadDotenvResult {\n const loadedFiles: string[] = [];\n const loadedEnv: Record<string, string> = {};\n\n for (const relativeFile of getDotenvFiles(mode)) {\n const filePath = path.join(root, relativeFile);\n if (!fs.existsSync(filePath)) continue;\n\n const fileContent = fs.readFileSync(filePath, \"utf-8\");\n const parsed = parseEnv(fileContent) as Record<string, string>;\n const expanded = expandEnv(parsed, processEnv);\n\n for (const [key, value] of Object.entries(expanded)) {\n if (processEnv[key] !== undefined) continue;\n processEnv[key] = value;\n loadedEnv[key] = value;\n }\n\n loadedFiles.push(relativeFile);\n }\n\n return {\n mode,\n loadedFiles,\n loadedEnv,\n };\n}\n\nconst ENV_REF_RE = /(\\\\)?\\$(?:\\{([A-Za-z_][A-Za-z0-9_]*)\\}|([A-Za-z_][A-Za-z0-9_]*))/g;\n\nfunction expandEnv(\n parsed: Record<string, string>,\n processEnv: NodeJS.ProcessEnv,\n): Record<string, string> {\n const expanded: Record<string, string> = {};\n const resolving = new Set<string>();\n const context: Record<string, string | undefined> = {\n ...parsed,\n ...processEnv,\n };\n\n function resolveValue(key: string): string {\n const cached = expanded[key];\n if (cached !== undefined) return cached;\n\n if (resolving.has(key)) {\n return context[key] ?? \"\";\n }\n\n const raw = context[key];\n if (raw === undefined) return \"\";\n\n resolving.add(key);\n let value = raw.replace(ENV_REF_RE, (match, escaped, braced, bare) => {\n if (escaped) return match.slice(1);\n\n const refKey = (braced || bare) as string;\n return resolveValue(refKey);\n });\n // Strip remaining \\$ escapes not caught by the regex (e.g. \\$100 where\n // what follows $ isn't a valid variable name).\n value = value.replace(/\\\\\\$/g, \"$\");\n resolving.delete(key);\n\n expanded[key] = value;\n context[key] = value;\n return value;\n }\n\n for (const key of Object.keys(parsed)) {\n resolveValue(key);\n }\n\n return expanded;\n}\n"],"mappings":";;;;;;;AAqBA,SAAgB,eAAe,MAA+B;AAC5D,QAAO;EAAC,QAAQ,KAAK;EAAS,GAAI,SAAS,SAAS,EAAE,GAAG,CAAC,aAAa;EAAG,QAAQ;EAAQ;EAAO;;;;;;;;;;;;;;;;;;;;;;;;;AA0BnG,SAAgB,WAAW,EACz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../src/config/dotenv.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseEnv } from \"node:util\";\n\nexport type VinextEnvMode = \"development\" | \"production\" | \"test\";\n\nexport type LoadDotenvOptions = {\n root: string;\n mode: VinextEnvMode;\n processEnv?: NodeJS.ProcessEnv;\n};\n\nexport type LoadDotenvResult = {\n mode: VinextEnvMode;\n loadedFiles: string[];\n loadedEnv: Record<string, string>;\n};\n\n/**\n * Next.js-compatible dotenv lookup order (highest priority first).\n */\nexport function getDotenvFiles(mode: VinextEnvMode): string[] {\n return [`.env.${mode}.local`, ...(mode === \"test\" ? [] : [\".env.local\"]), `.env.${mode}`, \".env\"];\n}\n\n/**\n * Load .env files into processEnv with Next.js-like precedence:\n * process.env > .env.<mode>.local > .env.local > .env.<mode> > .env.\n *\n * This mutates processEnv (defaults to process.env).\n *\n * ## Interaction with Vite's own .env loading\n *\n * Vite also loads .env files internally during createServer()/build(). That's\n * fine — the two systems serve different purposes and don't conflict:\n *\n * - **vinext** populates `process.env` so that server-side code (SSR, API\n * routes, Server Components) can read env vars at runtime, and so the Vite\n * plugin's `config()` hook can scan `process.env` for `NEXT_PUBLIC_*` vars\n * to inline via `define`.\n *\n * - **Vite** loads .env files to populate `import.meta.env.VITE_*` for its\n * own client exposure mechanism (which Next.js apps don't use).\n *\n * Because we load first and neither system overwrites existing keys, Vite's\n * pass is effectively a no-op for overlapping keys. For `start` and `deploy`\n * commands (which don't go through Vite at all), this is the only loading.\n */\nexport function loadDotenv({\n root,\n mode,\n processEnv = process.env,\n}: LoadDotenvOptions): LoadDotenvResult {\n const loadedFiles: string[] = [];\n const loadedEnv: Record<string, string> = {};\n\n for (const relativeFile of getDotenvFiles(mode)) {\n const filePath = path.join(root, relativeFile);\n if (!fs.existsSync(filePath)) continue;\n\n const fileContent = fs.readFileSync(filePath, \"utf-8\");\n const parsed = parseEnv(fileContent) as Record<string, string>;\n const expanded = expandEnv(parsed, processEnv);\n\n for (const [key, value] of Object.entries(expanded)) {\n if (processEnv[key] !== undefined) continue;\n processEnv[key] = value;\n loadedEnv[key] = value;\n }\n\n loadedFiles.push(relativeFile);\n }\n\n return {\n mode,\n loadedFiles,\n loadedEnv,\n };\n}\n\nconst ENV_REF_RE = /(\\\\)?\\$(?:\\{([A-Za-z_][A-Za-z0-9_]*)\\}|([A-Za-z_][A-Za-z0-9_]*))/g;\n\nfunction expandEnv(\n parsed: Record<string, string>,\n processEnv: NodeJS.ProcessEnv,\n): Record<string, string> {\n const expanded: Record<string, string> = {};\n const resolving = new Set<string>();\n const context: Record<string, string | undefined> = {\n ...parsed,\n ...processEnv,\n };\n\n function resolveValue(key: string): string {\n const cached = expanded[key];\n if (cached !== undefined) return cached;\n\n if (resolving.has(key)) {\n return context[key] ?? \"\";\n }\n\n const raw = context[key];\n if (raw === undefined) return \"\";\n\n resolving.add(key);\n let value = raw.replace(ENV_REF_RE, (match, escaped, braced, bare) => {\n if (escaped) return match.slice(1);\n\n const refKey = (braced || bare) as string;\n return resolveValue(refKey);\n });\n // Strip remaining \\$ escapes not caught by the regex (e.g. \\$100 where\n // what follows $ isn't a valid variable name).\n value = value.replace(/\\\\\\$/g, \"$\");\n resolving.delete(key);\n\n expanded[key] = value;\n context[key] = value;\n return value;\n }\n\n for (const key of Object.keys(parsed)) {\n resolveValue(key);\n }\n\n return expanded;\n}\n"],"mappings":";;;;;;;AAqBA,SAAgB,eAAe,MAA+B;AAC5D,QAAO;EAAC,QAAQ,KAAK;EAAS,GAAI,SAAS,SAAS,EAAE,GAAG,CAAC,aAAa;EAAG,QAAQ;EAAQ;EAAO;;;;;;;;;;;;;;;;;;;;;;;;;AA0BnG,SAAgB,WAAW,EACzB,MACA,MACA,aAAa,QAAQ,OACiB;CACtC,MAAM,cAAwB,EAAE;CAChC,MAAM,YAAoC,EAAE;AAE5C,MAAK,MAAM,gBAAgB,eAAe,KAAK,EAAE;EAC/C,MAAM,WAAW,KAAK,KAAK,MAAM,aAAa;AAC9C,MAAI,CAA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