@timber-js/app 0.2.0-alpha.145 → 0.2.0-alpha.147

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 (183) hide show
  1. package/dist/_chunks/{actions-DzFMnUAR.js → actions-OIZ8siQu.js} +28 -43
  2. package/dist/_chunks/actions-OIZ8siQu.js.map +1 -0
  3. package/dist/_chunks/{cli-schema-sync-DH-M8Poy.js → cli-schema-sync-CBiMEtqa.js} +1 -1
  4. package/dist/_chunks/{cli-schema-sync-D2IpXicg.js → cli-schema-sync-CQaxupHv.js} +47 -54
  5. package/dist/_chunks/cli-schema-sync-CQaxupHv.js.map +1 -0
  6. package/dist/_chunks/{handler-store-DjISKYEB.js → handler-store-BVDgyTh7.js} +26 -2
  7. package/dist/_chunks/handler-store-BVDgyTh7.js.map +1 -0
  8. package/dist/_chunks/{href-validation-EZktELp8.js → href-validation-DyZIzfMJ.js} +18 -2
  9. package/dist/_chunks/{href-validation-EZktELp8.js.map → href-validation-DyZIzfMJ.js.map} +1 -1
  10. package/dist/_chunks/{navigation-root-DLc4s4ZC.js → navigation-root-bUDZLw74.js} +23 -2
  11. package/dist/_chunks/navigation-root-bUDZLw74.js.map +1 -0
  12. package/dist/_chunks/tracing-M_zKubhk.js.map +1 -1
  13. package/dist/_chunks/{walkers-7FBPM-hX.js → walkers-Ck4Y45XN.js} +49 -8
  14. package/dist/_chunks/walkers-Ck4Y45XN.js.map +1 -0
  15. package/dist/adapters/cloudflare.d.ts +1 -15
  16. package/dist/adapters/cloudflare.d.ts.map +1 -1
  17. package/dist/adapters/cloudflare.js +10 -28
  18. package/dist/adapters/cloudflare.js.map +1 -1
  19. package/dist/adapters/compress-module.d.ts.map +1 -1
  20. package/dist/adapters/nitro.d.ts.map +1 -1
  21. package/dist/adapters/nitro.js +18 -5
  22. package/dist/adapters/nitro.js.map +1 -1
  23. package/dist/cache/index.js +39 -12
  24. package/dist/cache/index.js.map +1 -1
  25. package/dist/cache/redis-handler.d.ts +72 -8
  26. package/dist/cache/redis-handler.d.ts.map +1 -1
  27. package/dist/cache/stable-stringify.d.ts +9 -0
  28. package/dist/cache/stable-stringify.d.ts.map +1 -1
  29. package/dist/cache/timber-cache.d.ts +3 -1
  30. package/dist/cache/timber-cache.d.ts.map +1 -1
  31. package/dist/cli.js +1 -1
  32. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
  33. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  34. package/dist/client/browser-entry/scroll.d.ts +9 -0
  35. package/dist/client/browser-entry/scroll.d.ts.map +1 -1
  36. package/dist/client/error-boundary.d.ts.map +1 -1
  37. package/dist/client/error-boundary.js +24 -10
  38. package/dist/client/error-boundary.js.map +1 -1
  39. package/dist/client/error-reconstituter.d.ts +8 -1
  40. package/dist/client/error-reconstituter.d.ts.map +1 -1
  41. package/dist/client/index.js +3 -3
  42. package/dist/client/index.js.map +1 -1
  43. package/dist/client/internal.js +99 -24
  44. package/dist/client/internal.js.map +1 -1
  45. package/dist/client/link.d.ts.map +1 -1
  46. package/dist/client/navigation-api.d.ts.map +1 -1
  47. package/dist/client/navigation-root.d.ts +13 -0
  48. package/dist/client/navigation-root.d.ts.map +1 -1
  49. package/dist/client/router.d.ts +7 -0
  50. package/dist/client/router.d.ts.map +1 -1
  51. package/dist/client/rsc-fetch.d.ts.map +1 -1
  52. package/dist/dev-tools/404-page.d.ts +6 -2
  53. package/dist/dev-tools/404-page.d.ts.map +1 -1
  54. package/dist/dev-tools/dev-page-shell.d.ts +77 -0
  55. package/dist/dev-tools/dev-page-shell.d.ts.map +1 -0
  56. package/dist/dev-tools/error-page.d.ts +4 -30
  57. package/dist/dev-tools/error-page.d.ts.map +1 -1
  58. package/dist/dev-tools/index.d.ts +2 -1
  59. package/dist/dev-tools/index.d.ts.map +1 -1
  60. package/dist/dev-tools/instrumentation.d.ts +11 -1
  61. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +432 -255
  64. package/dist/index.js.map +1 -1
  65. package/dist/plugins/cache.d.ts +43 -9
  66. package/dist/plugins/cache.d.ts.map +1 -1
  67. package/dist/plugins/cloudflare-wasm.d.ts +4 -1
  68. package/dist/plugins/cloudflare-wasm.d.ts.map +1 -1
  69. package/dist/plugins/dev-server.d.ts +16 -0
  70. package/dist/plugins/dev-server.d.ts.map +1 -1
  71. package/dist/plugins/server-bundle.d.ts.map +1 -1
  72. package/dist/plugins/shims.d.ts +23 -0
  73. package/dist/plugins/shims.d.ts.map +1 -1
  74. package/dist/routing/codegen-types.d.ts +4 -0
  75. package/dist/routing/codegen-types.d.ts.map +1 -1
  76. package/dist/routing/index.js +2 -2
  77. package/dist/server/action-handler.d.ts.map +1 -1
  78. package/dist/server/actions.d.ts +3 -2
  79. package/dist/server/actions.d.ts.map +1 -1
  80. package/dist/server/cookie-context.d.ts.map +1 -1
  81. package/dist/server/cookie-parsing.d.ts.map +1 -1
  82. package/dist/server/deny-boundary.d.ts +27 -2
  83. package/dist/server/deny-boundary.d.ts.map +1 -1
  84. package/dist/server/deny-renderer.d.ts.map +1 -1
  85. package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
  86. package/dist/server/fallback-error.d.ts +2 -2
  87. package/dist/server/fallback-error.d.ts.map +1 -1
  88. package/dist/server/index.js +1 -1
  89. package/dist/server/internal.js +227 -179
  90. package/dist/server/internal.js.map +1 -1
  91. package/dist/server/node-stream-transforms.d.ts +24 -6
  92. package/dist/server/node-stream-transforms.d.ts.map +1 -1
  93. package/dist/server/pipeline.d.ts +11 -0
  94. package/dist/server/pipeline.d.ts.map +1 -1
  95. package/dist/server/primitives.d.ts +1 -11
  96. package/dist/server/primitives.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  98. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  99. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  100. package/dist/server/slot-resolver.d.ts +6 -4
  101. package/dist/server/slot-resolver.d.ts.map +1 -1
  102. package/dist/server/ssr-entry.d.ts.map +1 -1
  103. package/dist/server/status-code-resolver.d.ts +6 -0
  104. package/dist/server/status-code-resolver.d.ts.map +1 -1
  105. package/dist/server/tracing.d.ts +2 -1
  106. package/dist/server/tracing.d.ts.map +1 -1
  107. package/dist/server/utils/mdx-file.d.ts +15 -0
  108. package/dist/server/utils/mdx-file.d.ts.map +1 -0
  109. package/dist/shared/head-header.d.ts +54 -0
  110. package/dist/shared/head-header.d.ts.map +1 -0
  111. package/dist/shared/href-validation.d.ts +11 -0
  112. package/dist/shared/href-validation.d.ts.map +1 -1
  113. package/dist/shared/redirect-type.d.ts +17 -0
  114. package/dist/shared/redirect-type.d.ts.map +1 -0
  115. package/dist/shims/headers.d.ts +52 -1
  116. package/dist/shims/headers.d.ts.map +1 -1
  117. package/dist/shims/navigation-client.d.ts +33 -11
  118. package/dist/shims/navigation-client.d.ts.map +1 -1
  119. package/package.json +11 -10
  120. package/src/adapters/cloudflare.ts +13 -47
  121. package/src/adapters/compress-module.ts +9 -3
  122. package/src/adapters/nitro.ts +9 -2
  123. package/src/cache/redis-handler.ts +77 -13
  124. package/src/cache/stable-stringify.ts +65 -2
  125. package/src/cache/timber-cache.ts +25 -13
  126. package/src/cli.ts +0 -0
  127. package/src/client/browser-entry/action-dispatch.ts +7 -2
  128. package/src/client/browser-entry/router-init.ts +2 -1
  129. package/src/client/browser-entry/scroll.ts +23 -0
  130. package/src/client/error-boundary.tsx +33 -5
  131. package/src/client/error-reconstituter.tsx +15 -1
  132. package/src/client/link.tsx +4 -1
  133. package/src/client/navigation-api.ts +5 -1
  134. package/src/client/navigation-root.tsx +16 -0
  135. package/src/client/router.ts +107 -29
  136. package/src/client/rsc-fetch.ts +6 -6
  137. package/src/dev-tools/404-page.ts +22 -123
  138. package/src/dev-tools/dev-page-shell.ts +256 -0
  139. package/src/dev-tools/error-page.ts +27 -203
  140. package/src/dev-tools/index.ts +7 -1
  141. package/src/dev-tools/instrumentation.ts +39 -2
  142. package/src/index.ts +1 -0
  143. package/src/plugins/cache.ts +79 -21
  144. package/src/plugins/cloudflare-wasm.ts +48 -10
  145. package/src/plugins/dev-server.ts +32 -8
  146. package/src/plugins/server-bundle.ts +25 -9
  147. package/src/plugins/shims.ts +94 -52
  148. package/src/routing/codegen-types.ts +4 -0
  149. package/src/routing/codegen.ts +63 -6
  150. package/src/routing/scanner.ts +80 -63
  151. package/src/server/action-handler.ts +10 -2
  152. package/src/server/actions.ts +3 -2
  153. package/src/server/compress.ts +11 -2
  154. package/src/server/cookie-context.ts +11 -0
  155. package/src/server/cookie-parsing.ts +16 -4
  156. package/src/server/deny-boundary.ts +106 -13
  157. package/src/server/deny-renderer.ts +40 -10
  158. package/src/server/error-boundary-wrapper.ts +1 -14
  159. package/src/server/fallback-error.ts +9 -4
  160. package/src/server/node-stream-transforms.ts +61 -24
  161. package/src/server/pipeline.ts +12 -0
  162. package/src/server/primitives.ts +10 -31
  163. package/src/server/route-matcher.ts +22 -6
  164. package/src/server/rsc-entry/error-renderer.ts +1 -12
  165. package/src/server/rsc-entry/index.ts +7 -2
  166. package/src/server/rsc-entry/rsc-payload.ts +4 -3
  167. package/src/server/slot-resolver.ts +27 -14
  168. package/src/server/ssr-entry.ts +17 -28
  169. package/src/server/status-code-resolver.ts +3 -2
  170. package/src/server/tracing.ts +17 -1
  171. package/src/server/tree-match.ts +15 -5
  172. package/src/server/utils/mdx-file.ts +22 -0
  173. package/src/shared/head-header.ts +69 -0
  174. package/src/shared/href-validation.ts +24 -0
  175. package/src/shared/redirect-type.ts +17 -0
  176. package/src/shims/headers.ts +119 -2
  177. package/src/shims/navigation-client.ts +48 -27
  178. package/LICENSE +0 -8
  179. package/dist/_chunks/actions-DzFMnUAR.js.map +0 -1
  180. package/dist/_chunks/cli-schema-sync-D2IpXicg.js.map +0 -1
  181. package/dist/_chunks/handler-store-DjISKYEB.js.map +0 -1
  182. package/dist/_chunks/navigation-root-DLc4s4ZC.js.map +0 -1
  183. package/dist/_chunks/walkers-7FBPM-hX.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { n as classifyUrlSegment } from "./segment-classify-CDDRVKs7.js";
2
- import { i as parseExistingSchemaKeys, r as findSchemaFile } from "./cli-schema-sync-D2IpXicg.js";
2
+ import { i as parseExistingSchemaKeys, r as findSchemaFile } from "./cli-schema-sync-CQaxupHv.js";
3
3
  import { join, posix, relative } from "node:path";
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  //#region src/routing/codegen-shared.ts
@@ -241,7 +241,7 @@ function formatTypedLinkOverloads(routes, importBase, hasSchema) {
241
241
  function generateRouteMap(tree, options = {}) {
242
242
  const hasSchema = options.hasSchema ?? detectSchema(options.appDir);
243
243
  const routes = [];
244
- collectRoutes(tree.root, [], [], "", routes, hasSchema);
244
+ collectRoutes(tree.root, [], [], "", routes, hasSchema, false);
245
245
  routes.sort((a, b) => a.urlPath.localeCompare(b.urlPath));
246
246
  return formatDeclarationFile(routes, options.outputDir ?? options.appDir, hasSchema, options.appDir);
247
247
  }
@@ -265,7 +265,7 @@ function detectSchema(appDir) {
265
265
  * A route entry is created for any segment that has a `page` or `route` file.
266
266
  * Params accumulate from ancestor dynamic segments.
267
267
  */
268
- function collectRoutes(node, ancestorParams, ancestorParamsFiles, parentTreePath, routes, hasSchema) {
268
+ function collectRoutes(node, ancestorParams, ancestorParamsFiles, parentTreePath, routes, hasSchema, insideSlot) {
269
269
  const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;
270
270
  const ownParamsFile = node.params && fileHasExport(node.params.filePath, "segmentParams") ? node.params.filePath : void 0;
271
271
  const params = [...ancestorParams];
@@ -298,6 +298,7 @@ function collectRoutes(node, ancestorParams, ancestorParamsFiles, parentTreePath
298
298
  params: resolvedParams,
299
299
  hasSearchParams: false,
300
300
  isApiRoute,
301
+ isSlotRoute: insideSlot,
301
302
  hasSchema
302
303
  };
303
304
  if (isPage) {
@@ -311,8 +312,47 @@ function collectRoutes(node, ancestorParams, ancestorParamsFiles, parentTreePath
311
312
  }
312
313
  routes.push(entry);
313
314
  }
314
- for (const child of node.children) collectRoutes(child, params, nextAncestorFiles, treePath, routes, hasSchema);
315
- for (const slot of Object.values(node.slots)) collectRoutes(slot, params, nextAncestorFiles, treePath, routes, hasSchema);
315
+ for (const child of node.children) collectRoutes(child, params, nextAncestorFiles, treePath, routes, hasSchema, insideSlot);
316
+ for (const slot of Object.values(node.slots)) collectRoutes(slot, params, nextAncestorFiles, treePath, routes, hasSchema, true);
317
+ }
318
+ /**
319
+ * Dedupe route entries by urlPath for urlPath-keyed emissions (the Routes
320
+ * interface, useQueryStates overloads, and typed Link variants).
321
+ *
322
+ * Parallel-slot pages share their parent's urlPath; emitting one entry per
323
+ * slot page produced duplicate interface keys (TS2300/TS2717 under
324
+ * skipLibCheck:false) and duplicate overloads. The non-slot entry is the
325
+ * canonical one; when only slot entries exist (parent has no page), the
326
+ * lexicographically smallest segmentPath wins so output is independent of
327
+ * slot scan order. A slot's searchParams definition is carried onto the
328
+ * merged entry when the canonical entry has none — never silently dropped.
329
+ *
330
+ * segmentPath-keyed emissions (getSegmentParams, useSegmentParams,
331
+ * TimberSegmentParams) must NOT use this — segmentPaths are already unique
332
+ * and slot entries feed those APIs directly.
333
+ */
334
+ function dedupeRoutesByUrlPath(routes) {
335
+ const byPath = /* @__PURE__ */ new Map();
336
+ for (const route of routes) {
337
+ const existing = byPath.get(route.urlPath);
338
+ if (!existing) {
339
+ byPath.set(route.urlPath, route);
340
+ continue;
341
+ }
342
+ let winner = existing;
343
+ let loser = route;
344
+ if (existing.isSlotRoute && !route.isSlotRoute || !!existing.isSlotRoute === !!route.isSlotRoute && route.segmentPath.localeCompare(existing.segmentPath) < 0) {
345
+ winner = route;
346
+ loser = existing;
347
+ }
348
+ if (!winner.hasSearchParams && loser.hasSearchParams) winner = {
349
+ ...winner,
350
+ hasSearchParams: true,
351
+ searchParamsPagePath: loser.searchParamsPagePath
352
+ };
353
+ byPath.set(route.urlPath, winner);
354
+ }
355
+ return [...byPath.values()];
316
356
  }
317
357
  /**
318
358
  * Determine the TypeScript type for a segment's param.
@@ -425,9 +465,10 @@ function formatDeclarationFile(routes, importBase, hasSchema, appDir) {
425
465
  lines.push(emitResolveSegmentFieldHelper());
426
466
  lines.push("");
427
467
  }
468
+ const uniqueByUrlPath = dedupeRoutesByUrlPath(routes);
428
469
  lines.push("declare module '@timber-js/app' {");
429
470
  lines.push(" interface Routes {");
430
- for (const route of routes) {
471
+ for (const route of uniqueByUrlPath) {
431
472
  const paramsType = formatParamsType(route.params, importBase, hasSchema);
432
473
  const searchParamsType = formatSearchParamsType(route, importBase);
433
474
  lines.push(` '${route.urlPath}': {`);
@@ -442,7 +483,7 @@ function formatDeclarationFile(routes, importBase, hasSchema, appDir) {
442
483
  }
443
484
  lines.push("}");
444
485
  lines.push("");
445
- const pageRoutes = routes.filter((r) => !r.isApiRoute);
486
+ const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);
446
487
  const dynamicRoutes = routes.filter((r) => r.params.length > 0);
447
488
  if (dynamicRoutes.length > 0) {
448
489
  lines.push("declare module '@timber-js/app/server' {");
@@ -721,4 +762,4 @@ function walk(node, chain, result, includeSlots) {
721
762
  //#endregion
722
763
  export { generateRouteMap as a, collectInterceptionRewrites as i, collectDynamicSegmentsFromTree as n, validateSchemaAgainstRoutes as r, collectLeafRoutes as t };
723
764
 
724
- //# sourceMappingURL=walkers-7FBPM-hX.js.map
765
+ //# sourceMappingURL=walkers-Ck4Y45XN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walkers-Ck4Y45XN.js","names":[],"sources":["../../src/routing/codegen-shared.ts","../../src/routing/link-codegen.ts","../../src/routing/codegen.ts","../../src/routing/interception.ts","../../src/routing/schema-validation.ts","../../src/routing/walkers.ts"],"sourcesContent":["/**\n * Shared codegen helpers — import-path computation, codec chain type\n * builder, and searchParams type formatter.\n *\n * Extracted from `codegen.ts` so `link-codegen.ts` can use the same\n * helpers without a cyclic import.\n */\n\nimport { relative, posix } from 'node:path';\nimport type { ParamEntry, RouteEntry } from './codegen-types.js';\n\n/**\n * Compute a relative import specifier for a codec/page file, stripping\n * the .ts/.tsx extension and resolving against the codegen output dir.\n */\nexport function codecImportPath(codecFilePath: string, importBase: string | undefined): string {\n const absPath = codecFilePath.replace(/\\.(ts|tsx)$/, '');\n if (importBase) {\n return './' + relative(importBase, absPath).replace(/\\\\/g, '/');\n }\n return './' + posix.basename(absPath);\n}\n\n/** Name of the shared helper type emitted at the top of the .d.ts. */\nexport const RESOLVE_SEGMENT_FIELD_TYPE_NAME = '_TimberResolveSegmentField';\n\n/**\n * Helper type emitted once at the top of the generated `.d.ts` and\n * referenced by every codec-chain conditional. Without this shared\n * helper, the inline expansion would duplicate the fallback branch on\n * every step and grow O(2^N) in chain depth (a single deep nested route\n * could blow up the file size and TS performance). With the helper,\n * each step reuses the named type and growth is O(N).\n *\n * The helper is a 2-arg conditional: given a typeof import expression\n * (`Def`), a key (`K`), and a fallback (`F`), it returns `T[K]` if\n * `Def extends ParamsDefinition<T>` and `K extends keyof T`, otherwise\n * `F`. The codec chain composes calls to this helper.\n */\nexport function emitResolveSegmentFieldHelper(): string {\n return [\n `type ${RESOLVE_SEGMENT_FIELD_TYPE_NAME}<Def, K extends string, F> =`,\n ` Def extends import('@timber-js/app/segment-params').ParamsDefinition<infer T>`,\n ` ? K extends keyof T ? T[K] : F`,\n ` : F;`,\n ].join('\\n');\n}\n\n/**\n * Build a TypeScript type expression that resolves a single param's\n * codec by walking a chain of params.ts files in priority order.\n *\n * Each entry in the chain emits one application of the shared\n * `_TimberResolveSegmentField` helper type. Composing N applications\n * grows linearly with chain depth (O(N) characters), unlike an inline\n * conditional that would duplicate the fallback in each branch and\n * grow O(2^N).\n *\n * The closest match (position 0 in the chain) is checked first; if its\n * `segmentParams` definition declares the key, its inferred type wins.\n * Otherwise we fall through to the next entry, and finally to the\n * provided fallback. See TIM-834.\n */\nexport function buildCodecChainType(\n p: ParamEntry,\n importBase: string | undefined,\n fallback: string\n): string {\n const files = p.codecFilePaths;\n if (!files || files.length === 0) return fallback;\n const key = JSON.stringify(p.name);\n // Compose helper applications inside-out so the closest entry\n // (files[0]) ends up as the OUTERMOST application. Each application\n // adds a constant-size wrapper around the running fallback.\n let inner = fallback;\n for (let i = files.length - 1; i >= 0; i--) {\n const importPath = codecImportPath(files[i], importBase);\n inner = `${RESOLVE_SEGMENT_FIELD_TYPE_NAME}<(typeof import('${importPath}'))['segmentParams'], ${key}, ${inner}>`;\n }\n return inner;\n}\n\n/**\n * Build a TypeScript type expression for a single param using the global\n * schema's InferCodecType. Falls back to the param's base type when\n * schema doesn't declare this param (schemas are opt-in per key).\n *\n * Uses `infer` to extract the codec value rather than direct indexing\n * because TypeScript doesn't narrow index validity inside a conditional\n * type's true branch — `typeof schema.segmentParams[K]` produces TS2538\n * even when the condition proves K is a valid key. In .d.ts files that\n * error is suppressed and the type silently becomes `any`.\n */\nexport function buildSchemaParamType(p: ParamEntry, fallback?: string): string {\n const key = JSON.stringify(p.bracketName);\n const fb = fallback ?? p.type;\n return `typeof schema['segmentParams'] extends Record<${key}, infer V> ? InferCodecType<V> : ${fb}`;\n}\n\n/**\n * Format the searchParams type for a route entry.\n *\n * When a page.tsx (or params.ts) exports searchParams, we reference its\n * inferred type via an import type. The import path is relative to\n * `importBase` (the directory where the .d.ts will be written). When\n * importBase is undefined, falls back to a bare relative path.\n */\nexport function formatSearchParamsType(route: RouteEntry, importBase?: string): string {\n if (route.hasSearchParams && route.searchParamsPagePath) {\n const importPath = codecImportPath(route.searchParamsPagePath, importBase);\n // Extract the type from the named 'searchParams' export of the page module.\n return `(typeof import('${importPath}'))['searchParams'] extends import('@timber-js/app/search-params').SearchParamsDefinition<infer T> ? T : never`;\n }\n return '{}';\n}\n","/**\n * Typed `<Link>` codegen — interface augmentation generation.\n *\n * Extracted from `codegen.ts` to keep that file under the project's\n * 500-line cap. This module owns everything that emits the\n * `interface LinkFunction { ... }` augmentation blocks in the generated\n * `.timber/timber-routes.d.ts`.\n *\n * Two augmentation blocks are emitted:\n *\n * 1. **Per-route discriminated union** (`formatTypedLinkOverloads`) —\n * one call signature whose props is a union keyed on `href`. TS\n * narrows by literal href and reports prop errors against the\n * matched variant. See TIM-835 and `design/09-typescript.md`.\n *\n * 2. **Catch-all overloads** (`formatLinkCatchAllOverloads`) — external\n * href literals (`http://`, `mailto:`, etc.) and a computed-string\n * `<H extends string>` signature for runtime-computed paths.\n *\n * Block ordering is critical for error UX: per-route is emitted FIRST\n * so that, after TS's \"later overload set ordered first\" merge rule,\n * the discriminated union ends up LAST in resolution order — the\n * overload TS reports against on failure.\n */\n\nimport type { ParamEntry, RouteEntry } from './codegen-types.js';\nimport {\n buildCodecChainType,\n buildSchemaParamType,\n formatSearchParamsType,\n} from './codegen-shared.js';\n\n/** Shared Link base-props type literal used in every emitted call signature. */\nexport const LINK_BASE_PROPS_TYPE =\n \"Omit<import('react').AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> & { prefetch?: boolean; scroll?: boolean; preserveSearchParams?: true | string[]; onNavigate?: import('./client/link.js').OnNavigateHandler; children?: import('react').ReactNode }\";\n\n/**\n * Build a TypeScript template literal pattern for a dynamic route.\n * e.g. '/products/[id]' → '/products/${string}'\n * '/blog/[...slug]' → '/blog/${string}'\n * '/docs/[[...path]]' → '/docs/${string}' (also matches /docs)\n * '/[org]/[repo]' → '/${string}/${string}'\n */\nexport function buildResolvedPattern(route: RouteEntry): string | null {\n const parts = route.urlPath.split('/');\n const templateParts = parts.map((part) => {\n if (part.startsWith('[[...') && part.endsWith(']]')) {\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return '${string}';\n }\n if (part.startsWith('[...') && part.endsWith(']')) {\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return '${string}';\n }\n if (part.startsWith('[') && part.endsWith(']')) {\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return '${string}';\n }\n return part;\n });\n return templateParts.join('/');\n}\n\n/**\n * Format the segmentParams type for Link overloads.\n *\n * Link params accept `string | number` for single dynamic segments\n * (convenience — values are stringified at runtime). Catch-all and\n * optional catch-all remain `string[]` / `string[] | undefined`.\n *\n * When the segment's params chain (TIM-834) declares a typed codec, the\n * inferred type from the codec wins via a nested conditional.\n */\nexport function formatLinkParamsType(\n params: ParamEntry[],\n importBase?: string,\n hasSchema?: boolean\n): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const fields = params.map((p) => {\n const fallback = p.type === 'string' ? 'string | number' : p.type;\n const codecType = hasSchema\n ? buildSchemaParamType(p, fallback)\n : buildCodecChainType(p, importBase, fallback);\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * Catch-all call signatures for `<Link>` — external hrefs and computed\n * `string` variables. Emitted from codegen in a SEPARATE\n * `declare module` block (declared AFTER the per-route block) so the TS\n * \"later overload set ordered first\" rule places these catch-all\n * signatures ahead of per-route in resolution order, leaving per-route\n * as the final overload whose error message is reported on failure.\n *\n * The conditional `string extends H ? ... : never` protection preserves\n * TIM-624's guarantee that unknown internal path literals don't match\n * the catch-all — typos like `<Link href=\"/typo\" />` still error.\n */\nexport function formatLinkCatchAllOverloads(): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n // TIM-830: the catch-all signatures accept EITHER the legacy\n // `{ definition, values }` wrapper OR a flat `Record<string, unknown>`\n // values object. External/computed hrefs can't be looked up in the\n // runtime registry, so the wrapped form is still the reliable path;\n // the flat form is kept permissive for callers migrating from typed-\n // route hrefs to computed strings. `resolveHref` discriminates at\n // runtime via the presence of a `definition` key.\n const catchAllSearchParams =\n '{ definition: SearchParamsDefinition<Record<string, unknown>>; values: Record<string, unknown> } | Record<string, unknown>';\n\n // ExternalHref inlined here rather than referenced as an exported\n // alias so the generated .d.ts stands alone without source imports.\n /* eslint-disable no-template-curly-in-string -- codegen output */\n const externalHref =\n '`http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`';\n /* eslint-enable no-template-curly-in-string */\n\n lines.push(' // Typed Link overloads — catch-all (block 2 / emitted second)');\n lines.push(' interface LinkFunction {');\n\n // (1) External/literal-protocol hrefs.\n //\n // TIM-833: `segmentParams` is permissively typed as\n // `Record<string, unknown>` (not `never`) so generic wrappers that\n // forward a `LinkProps`-shaped object can compile when the wrapper\n // happens to bottom out at an external href. There are no dynamic\n // segments to interpolate for an external href, so this prop is\n // ignored at runtime — accepting an open-shape object instead of\n // forbidding it removes a footgun without changing behavior.\n lines.push(` (props: ${baseProps} & {`);\n lines.push(` href: ${externalHref}`);\n lines.push(` segmentParams?: Record<string, unknown>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }): import('react').JSX.Element`);\n\n // (2) Computed/variable href — non-literal `string` only.\n //\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. For literal hrefs, this overload must NOT\n // be selectable so the per-route discriminated union (block 1) is\n // the resolution target.\n //\n // TIM-833 follow-up: the previous shape used `string extends H ? {...} : never`\n // on the WHOLE props type. For literal H, that collapsed `props` to\n // `never`, and JSX type inference then read `(never).children` as\n // `never` — producing the misleading\n // `'children' prop expects type 'never' which requires multiple\n // children, but only a single child was provided` (TS2745) error,\n // which buried the actual prop-mismatch message under a noise diagnostic.\n //\n // Fix: move the `: never` from the whole props onto just the `href`\n // field. The overload remains uncallable for literal H (since `\"/x\"`\n // is not assignable to `never`), but `children` retains its real\n // `ReactNode` type so JSX inference no longer collapses to never.\n // The diagnostic surface becomes: TS reports the per-route block's\n // error chain (the helpful \"Type 'number' is not assignable to type\n // 'string'\" message) WITHOUT a leading TS2745 noise line.\n lines.push(` <H extends string>(`);\n lines.push(` props: ${baseProps} & {`);\n lines.push(` href: string extends H ? H : never`);\n lines.push(` segmentParams?: Record<string, string | number | string[]>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }`);\n lines.push(` ): import('react').JSX.Element`);\n\n lines.push(' }');\n return lines;\n}\n\n/**\n * Generate typed per-route Link call signatures via LinkFunction\n * interface merging.\n *\n * TIM-835: This emits a SINGLE call signature whose props is a\n * discriminated union keyed on `href`. TypeScript narrows the union by\n * the literal `href` at the call site, then checks the rest of the\n * props against the matched variant. When `segmentParams` or\n * `searchParams` is wrong, TS reports the error against the matched\n * variant — naming the user's actual `href` and the offending field.\n *\n * Before TIM-835, this function emitted N separate per-route overloads\n * (one per route, sometimes two for dynamic routes). When ALL overloads\n * failed, TS would pick an arbitrary failed overload (heuristically the\n * \"last tried\") to render the diagnostic, often pointing at a route\n * completely unrelated to the one the user wrote. The discriminated\n * union sidesteps overload-resolution heuristics entirely.\n *\n * Open property shapes (`Record<string, unknown>` instead of `never`)\n * for `segmentParams` on routes that don't declare them keep generic\n * `LinkProps`-spreading wrappers compiling. (Aligned with TIM-833.)\n *\n * TIM-832: this function still emits the per-route block FIRST and the\n * catch-all block follows, so per-route remains the LAST overload set in\n * resolution order — the one TS reports against on failure. With a\n * discriminated union there is only one call signature in this block,\n * so the resolved-template-vs-pattern ordering reduces to placing the\n * pattern variant before the resolved-template variant inside the union.\n */\nexport function formatTypedLinkOverloads(\n routes: RouteEntry[],\n importBase?: string,\n hasSchema?: boolean\n): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n // Build the union variants. Each route contributes one variant for the\n // pattern href (e.g. '/products/[id]') and, for dynamic routes, an\n // additional variant for the resolved-template href (e.g.\n // `/products/${string}`).\n //\n // The PATTERN variant must be listed BEFORE the resolved-template\n // variant for the same route so that when the user writes the literal\n // pattern href (`<Link href=\"/products/[id]\" />`), TS narrows to the\n // pattern variant (which carries the typed `segmentParams` shape)\n // rather than the looser resolved-template variant. Without this\n // ordering, TS would silently match the resolved-template variant\n // first — swallowing typed-segmentParams type errors.\n const variants: string[] = [];\n for (const route of routes) {\n const hasDynamicParams = route.params.length > 0;\n // For routes with no dynamic params, accept an absent OR open-shape\n // segmentParams. `Record<string, unknown>` keeps generic spreads\n // compiling and gives a readable error if a non-object is passed.\n const paramsProp = hasDynamicParams\n ? `segmentParams: ${formatLinkParamsType(route.params, importBase, hasSchema)}`\n : 'segmentParams?: Record<string, unknown>';\n\n const searchParamsType = route.hasSearchParams\n ? formatSearchParamsType(route, importBase)\n : null;\n // TIM-830: pattern href uses the FLAT `Partial<T>` shape — the\n // runtime registry is keyed by the un-interpolated pattern.\n //\n // TIM-833: when the route has NO searchParams definition, use\n // `Record<string, unknown>` (open shape) instead of\n // `Record<string, never>` so generic `LinkProps`-spreading wrappers\n // compile. The trade-off vs the original TIM-835 strict shape is\n // that excess searchParams keys on a no-def route no longer raise\n // a type error — but those keys are runtime no-ops anyway, and\n // wrapper compatibility is the more common pain point. Routes WITH\n // a searchParams definition still get strict `Partial<T>` typing.\n const patternSearchParamsProp = searchParamsType\n ? `searchParams?: Partial<${searchParamsType}>`\n : 'searchParams?: Record<string, unknown>';\n\n // Pattern variant FIRST (more specific).\n variants.push(\n `${baseProps} & { href: '${route.urlPath}'; ${paramsProp}; ${patternSearchParamsProp} }`\n );\n\n // Resolved-template variant SECOND (looser, matches interpolated hrefs).\n if (hasDynamicParams) {\n const templatePattern = buildResolvedPattern(route);\n if (templatePattern) {\n // TIM-830: resolved-template href keeps the WRAPPED\n // `{ definition, values }` shape — the registry can't be looked\n // up by an already-interpolated href.\n //\n // TIM-833: searchParams falls back to `Record<string, unknown>`\n // (was `Record<string, never>`) when the route has no\n // definition, mirroring the pattern-variant change above. The\n // resolved-template `segmentParams` is intentionally KEPT as\n // `Record<string, never>` below to preserve TIM-835's\n // pattern-variant typo detection: loosening segmentParams here\n // would let the resolved-template variant shadow the pattern\n // variant on literal pattern hrefs and silently swallow keyed\n // typos like `<Link href=\"/[id]\" segmentParams={{ idz: 1 }} />`.\n const resolvedSearchParamsProp = searchParamsType\n ? `searchParams?: { definition: SearchParamsDefinition<${searchParamsType}>; values: Partial<${searchParamsType}> }`\n : 'searchParams?: Record<string, unknown>';\n // TIM-835: `Record<string, never>` for segmentParams forbids ANY\n // provided keys on the resolved-template variant. Without this,\n // the resolved-template would shadow the pattern variant for\n // literal pattern hrefs (`<Link href=\"/products/[id]\" segmentParams={...} />`)\n // because both variants accept the literal `'/products/[id]'`\n // and the looser variant would silently swallow segmentParams\n // type errors.\n variants.push(\n `${baseProps} & { href: \\`${templatePattern}\\`; segmentParams?: Record<string, never>; ${resolvedSearchParamsProp} }`\n );\n }\n }\n }\n\n lines.push(' interface LinkFunction {');\n if (variants.length === 0) {\n // No page routes — emit nothing. The catch-all block in the second\n // augmentation still provides external/computed-string signatures.\n lines.push(' }');\n return lines;\n }\n lines.push(' (');\n lines.push(' props:');\n for (const variant of variants) {\n lines.push(` | (${variant})`);\n }\n lines.push(` ): import('react').JSX.Element`);\n lines.push(' }');\n\n return lines;\n}\n","/**\n * Route map codegen.\n *\n * Walks the scanned RouteTree and generates a TypeScript declaration file\n * mapping every route to its params and searchParams shapes.\n *\n * This runs at build time and in dev (regenerated on file changes).\n * No runtime overhead — purely static type generation.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.js';\nimport type { ParamEntry, RouteEntry } from './codegen-types.js';\nimport {\n buildCodecChainType,\n buildSchemaParamType,\n emitResolveSegmentFieldHelper,\n formatSearchParamsType,\n} from './codegen-shared.js';\nimport { formatLinkCatchAllOverloads, formatTypedLinkOverloads } from './link-codegen.js';\n\n/** Options for route map generation. */\nexport interface CodegenOptions {\n /** Absolute path to the app/ directory. Required for page searchParams detection. */\n appDir?: string;\n /**\n * Absolute path to the directory where the .d.ts file will be written.\n * Used to compute correct relative import paths for page files.\n * Defaults to appDir when not provided (preserves backward compat for tests).\n */\n outputDir?: string;\n /**\n * Whether a global schema (app/schema.ts) exists.\n * Auto-detected from appDir when not explicitly set.\n */\n hasSchema?: boolean;\n}\n\n/**\n * Generate a TypeScript declaration file string from a scanned route tree.\n *\n * The output is a `declare module '@timber-js/app'` block containing the Routes\n * interface that maps every route path to its params and searchParams shape.\n */\nexport function generateRouteMap(tree: RouteTree, options: CodegenOptions = {}): string {\n // Auto-detect schema from appDir when not explicitly set\n const hasSchema = options.hasSchema ?? detectSchema(options.appDir);\n\n const routes: RouteEntry[] = [];\n collectRoutes(tree.root, [], [], '', routes, hasSchema, false);\n\n // Sort routes alphabetically for deterministic output\n routes.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n\n // When outputDir differs from appDir, import paths must be relative to outputDir\n const importBase = options.outputDir ?? options.appDir;\n\n return formatDeclarationFile(routes, importBase, hasSchema, options.appDir);\n}\n\n/** Schema file extensions to check, in priority order. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Detect whether app/schema.{ts,tsx,js,jsx} exists.\n */\nfunction detectSchema(appDir: string | undefined): boolean {\n if (!appDir) return false;\n return SCHEMA_EXTENSIONS.some((ext) => existsSync(join(appDir, `schema${ext}`)));\n}\n\n/**\n * Recursively walk the segment tree and collect route entries.\n *\n * A route entry is created for any segment that has a `page` or `route` file.\n * Params accumulate from ancestor dynamic segments.\n */\nfunction collectRoutes(\n node: SegmentNode,\n ancestorParams: ParamEntry[],\n ancestorParamsFiles: string[],\n parentTreePath: string,\n routes: RouteEntry[],\n hasSchema: boolean,\n insideSlot: boolean\n): void {\n // Build the tree path (includes groups, slots — uniquely identifies this segment).\n // Root node has empty segmentName, producing treePath = ''.\n const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;\n // TIM-834: Identify this segment's own params.ts (if it has a\n // segmentParams export). The full chain of params.ts files in the\n // route ancestry is threaded down via `ancestorParamsFiles`; codec\n // resolution for each ParamEntry is deferred until leaf time so that\n // descendant params.ts files can override ancestor codecs (closest-\n // to-leaf wins, matching the runtime semantics of\n // coerceSegmentParams which walks segments top-down and overwrites\n // earlier coercions).\n const ownParamsFile =\n node.params && fileHasExport(node.params.filePath, 'segmentParams')\n ? node.params.filePath\n : undefined;\n\n // Accumulate params from this segment. We attach `codecFilePaths`\n // later (at leaf time) using the FULL chain so descendant overrides\n // are visible. The legacy layout/page fallback is recorded now\n // because it is per-segment (and does not participate in inheritance).\n const params = [...ancestorParams];\n if (node.paramName) {\n const legacyFallback = ownParamsFile ? undefined : findLegacyParamsExport(node);\n params.push({\n name: node.paramName,\n bracketName: node.segmentName,\n type: paramTypeForSegment(node.segmentType),\n // Codec chain populated at leaf time. We carry the per-segment\n // legacy fallback (if any) so leaf-time resolution can fall back\n // to it when no params.ts in the chain declares this key.\n legacyCodecFilePath: legacyFallback,\n });\n }\n\n // Extend the chain for descendants of this segment.\n const nextAncestorFiles = ownParamsFile\n ? [...ancestorParamsFiles, ownParamsFile]\n : ancestorParamsFiles;\n\n // Check if this segment is a leaf route (has page or route file)\n const isPage = !!node.page;\n const isApiRoute = !!node.route;\n\n if (isPage || isApiRoute) {\n // TIM-834 P1 fix: at LEAF time, the full chain of params.ts files\n // (root-to-leaf) is known. Resolve every ParamEntry's\n // `codecFilePaths` to the chain in LEAF-FIRST order so the\n // closest-to-leaf entry is checked first — matching runtime\n // closest-wins semantics. The chain is shared by all params in the\n // route, so we compute it once.\n const leafFirstChain = nextAncestorFiles.length > 0 ? [...nextAncestorFiles].reverse() : [];\n const resolvedParams: ParamEntry[] = params.map((p) => {\n const codecFilePaths =\n leafFirstChain.length > 0\n ? leafFirstChain\n : p.legacyCodecFilePath\n ? [p.legacyCodecFilePath]\n : undefined;\n return {\n name: p.name,\n bracketName: p.bracketName,\n type: p.type,\n codecFilePaths,\n };\n });\n\n const entry: RouteEntry = {\n urlPath: node.urlPath,\n segmentPath: treePath || '/',\n params: resolvedParams,\n hasSearchParams: false,\n isApiRoute,\n isSlotRoute: insideSlot,\n hasSchema,\n };\n\n // Detect searchParams export from params.ts (primary) or page.tsx (fallback)\n if (isPage) {\n if (node.params && fileHasExport(node.params.filePath, 'searchParams')) {\n entry.hasSearchParams = true;\n entry.searchParamsPagePath = node.params.filePath;\n } else if (node.page && fileHasExport(node.page.filePath, 'searchParams')) {\n entry.hasSearchParams = true;\n entry.searchParamsPagePath = node.page.filePath;\n }\n }\n\n routes.push(entry);\n }\n\n // Recurse into children\n for (const child of node.children) {\n collectRoutes(child, params, nextAncestorFiles, treePath, routes, hasSchema, insideSlot);\n }\n\n // Recurse into slots (they share the parent's URL path, but may have their own pages)\n for (const slot of Object.values(node.slots)) {\n collectRoutes(slot, params, nextAncestorFiles, treePath, routes, hasSchema, true);\n }\n}\n\n/**\n * Dedupe route entries by urlPath for urlPath-keyed emissions (the Routes\n * interface, useQueryStates overloads, and typed Link variants).\n *\n * Parallel-slot pages share their parent's urlPath; emitting one entry per\n * slot page produced duplicate interface keys (TS2300/TS2717 under\n * skipLibCheck:false) and duplicate overloads. The non-slot entry is the\n * canonical one; when only slot entries exist (parent has no page), the\n * lexicographically smallest segmentPath wins so output is independent of\n * slot scan order. A slot's searchParams definition is carried onto the\n * merged entry when the canonical entry has none — never silently dropped.\n *\n * segmentPath-keyed emissions (getSegmentParams, useSegmentParams,\n * TimberSegmentParams) must NOT use this — segmentPaths are already unique\n * and slot entries feed those APIs directly.\n */\nfunction dedupeRoutesByUrlPath(routes: RouteEntry[]): RouteEntry[] {\n const byPath = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = byPath.get(route.urlPath);\n if (!existing) {\n byPath.set(route.urlPath, route);\n continue;\n }\n\n let winner = existing;\n let loser = route;\n const routeWins =\n (existing.isSlotRoute && !route.isSlotRoute) ||\n (!!existing.isSlotRoute === !!route.isSlotRoute &&\n route.segmentPath.localeCompare(existing.segmentPath) < 0);\n if (routeWins) {\n winner = route;\n loser = existing;\n }\n\n if (!winner.hasSearchParams && loser.hasSearchParams) {\n winner = {\n ...winner,\n hasSearchParams: true,\n searchParamsPagePath: loser.searchParamsPagePath,\n };\n }\n byPath.set(route.urlPath, winner);\n }\n return [...byPath.values()];\n}\n\n/**\n * Determine the TypeScript type for a segment's param.\n */\nfunction paramTypeForSegment(segmentType: string): ParamEntry['type'] {\n switch (segmentType) {\n case 'catch-all':\n return 'string[]';\n case 'optional-catch-all':\n return 'string[] | undefined';\n default:\n return 'string';\n }\n}\n\n/**\n * Check if a file exports a specific named export.\n *\n * Uses a lightweight regex check — not full AST parsing. The actual type\n * extraction happens via the TypeScript compiler in the generated .d.ts.\n */\nfunction fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const content = readFileSync(filePath, 'utf-8');\n const e = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return (\n new RegExp(`export\\\\s+(const|let|var)\\\\s+${e}\\\\b`).test(content) ||\n new RegExp(`export\\\\s*\\\\{[^}]*\\\\b${e}\\\\b[^}]*\\\\}`).test(content)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Find a legacy `segmentParams` export on layout.tsx or page.tsx.\n *\n * Backward-compat shim: TIM-508 made params.ts the canonical location\n * for `segmentParams`. Layout/page exports are still accepted for the\n * OWN segment only (not inherited by descendants — see TIM-834).\n */\nfunction findLegacyParamsExport(node: SegmentNode): string | undefined {\n if (node.layout && fileHasExport(node.layout.filePath, 'segmentParams')) {\n return node.layout.filePath;\n }\n if (node.page && fileHasExport(node.page.filePath, 'segmentParams')) {\n return node.page.filePath;\n }\n return undefined;\n}\n\n/**\n * Emit the schema-based type exports: TimberSegmentParams, TimberRoute,\n * AllSegmentParams, RoutesWithParams.\n *\n * These types use InferCodecType references so they stay in sync with\n * the schema without hardcoding resolved types.\n *\n * Design doc: design/41-global-params.md §Codegen Output\n */\nfunction formatSchemaTypes(routes: RouteEntry[]): string[] {\n const lines: string[] = [];\n\n lines.push('/** Union of all valid route patterns. */');\n lines.push('export type TimberRoute = keyof TimberSegmentParams;');\n lines.push('');\n lines.push('/** Maps each segment path to its accumulated segment params. */');\n lines.push('export interface TimberSegmentParams {');\n\n for (const route of routes) {\n if (route.params.length === 0) {\n lines.push(` '${route.segmentPath}': {};`);\n } else {\n lines.push(` '${route.segmentPath}': {`);\n for (const p of route.params) {\n lines.push(` ${p.name}: ${buildSchemaParamType(p)};`);\n }\n lines.push(' };');\n }\n }\n\n lines.push('}');\n lines.push('');\n\n // AllSegmentParams — flat union of all param types across all routes\n lines.push('/** All segment params (union of all route params). */');\n lines.push('export type AllSegmentParams = {');\n lines.push(\n ' [K in keyof TimberSegmentParams as TimberSegmentParams[K] extends Record<string, never>'\n );\n lines.push(' ? never');\n lines.push(' : K]: TimberSegmentParams[K];');\n lines.push('} extends infer U');\n lines.push(' ? { [K in keyof U[keyof U]]: U[keyof U][K] }');\n lines.push(' : never;');\n lines.push('');\n\n // RoutesWithParams — filter routes by required param keys\n lines.push(\n '/** Filters TimberRoute to routes whose accumulated params include all listed keys. */'\n );\n lines.push('export type RoutesWithParams<K extends keyof AllSegmentParams> = {');\n lines.push(' [R in TimberRoute]: K extends keyof TimberSegmentParams[R] ? R : never;');\n lines.push('}[TimberRoute];');\n\n return lines;\n}\n\n/**\n * Format the collected routes into a TypeScript declaration file.\n */\nfunction formatDeclarationFile(\n routes: RouteEntry[],\n importBase?: string,\n hasSchema?: boolean,\n appDir?: string\n): string {\n const lines: string[] = [];\n\n lines.push('// This file is auto-generated by timber.js route map codegen.');\n lines.push('// Do not edit manually. Regenerated on build and in dev mode.');\n lines.push('');\n // export {} makes this file a module, so all declare module blocks are\n // augmentations rather than ambient replacements. Without this, the\n // declare module blocks would replace the original module types entirely\n // (removing exports like bindUseQueryStates that aren't listed here).\n lines.push('export {};');\n lines.push('');\n\n if (hasSchema) {\n // Schema-based codegen: import schema and InferCodecType\n // Compute the schema import path relative to the output directory\n const schemaImport =\n appDir && importBase\n ? './' + relative(importBase, join(appDir, 'schema')).replace(/\\\\/g, '/')\n : '../app/schema';\n lines.push(`import type schema from '${schemaImport}';`);\n lines.push(\"import type { InferCodecType, SegmentParamCodec } from '@timber-js/app/params';\");\n lines.push('');\n // Collect all unique bracket keys from routes for key validation\n const allBracketKeys = new Set<string>();\n for (const route of routes) {\n for (const p of route.params) {\n allBracketKeys.add(p.bracketName);\n }\n }\n\n // Augment the ValidDynamicSegmentKeysRegistry so defineSchema constrains keys\n // to known filesystem segments. Unknown keys produce inline TS errors.\n if (allBracketKeys.size > 0) {\n lines.push(\"declare module '@timber-js/app/params' {\");\n lines.push(' interface ValidDynamicSegmentKeysRegistry {');\n for (const key of [...allBracketKeys].sort()) {\n lines.push(` ${JSON.stringify(key)}: true;`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n }\n // Type-level validation: each schema value must be a Codec or Standard Schema.\n // Running `pnpm run typecheck` will surface errors for invalid values.\n lines.push('type _AssertSchemaValues = {');\n lines.push(\n \" [K in keyof typeof schema['segmentParams']]: typeof schema['segmentParams'][K] extends SegmentParamCodec ? true : ['Error: value for', K, 'is not a valid Codec or Standard Schema'];\"\n );\n lines.push('};');\n // Generic constraint enforces that all values are `true` — if any value is\n // an error tuple, TS reports a real diagnostic instead of silently computing it.\n lines.push(\n 'type _EnforceSchemaValues<_T extends Record<string, true> = _AssertSchemaValues> = true;'\n );\n lines.push('');\n }\n\n if (!hasSchema) {\n // TIM-834 P2: emit the shared codec-resolution helper type ONCE so the\n // per-param chain conditionals reference it instead of inlining the\n // fallback in both branches (which grows O(2^N) in chain depth).\n lines.push(emitResolveSegmentFieldHelper());\n lines.push('');\n }\n\n // urlPath-keyed emissions use the deduped list (slot pages share their\n // parent's urlPath); segmentPath-keyed emissions below keep all entries.\n const uniqueByUrlPath = dedupeRoutesByUrlPath(routes);\n\n lines.push(\"declare module '@timber-js/app' {\");\n lines.push(' interface Routes {');\n\n for (const route of uniqueByUrlPath) {\n const paramsType = formatParamsType(route.params, importBase, hasSchema);\n const searchParamsType = formatSearchParamsType(route, importBase);\n\n lines.push(` '${route.urlPath}': {`);\n lines.push(` segmentParams: ${paramsType}`);\n lines.push(` searchParams: ${searchParamsType}`);\n lines.push(` }`);\n }\n\n lines.push(' }');\n\n // When a global schema exists, emit segment param types inside the\n // @timber-js/app module augmentation so that declare module blocks\n // for @timber-js/app/server and @timber-js/app/client can reference\n // AllSegmentParams via `import type { AllSegmentParams } from '@timber-js/app'`.\n if (hasSchema) {\n lines.push('');\n lines.push(...formatSchemaTypes(routes).map((l) => ` ${l}`));\n }\n\n lines.push('}');\n lines.push('');\n\n // useQueryStates + typed Link are urlPath-keyed → deduped list.\n const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);\n // getSegmentParams / useSegmentParams are segmentPath-keyed → full list,\n // so slot segments keep their own typed overloads.\n const dynamicRoutes = routes.filter((r) => r.params.length > 0);\n\n // Generate @timber-js/app/server augmentation — typed getSegmentParams\n if (dynamicRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/server' {\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, importBase, hasSchema);\n lines.push(\n ` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function getSegmentParams(): Partial<AllSegmentParams>'\n : ' export function getSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('}');\n lines.push('');\n }\n\n // Generate overloads for @timber-js/app/client\n\n if (dynamicRoutes.length > 0 || pageRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\n \" import type { SearchParamsDefinition, SetParams, QueryStatesOptions, SearchParamCodec } from '@timber-js/app/search-params'\"\n );\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n lines.push('');\n\n // useSegmentParams overloads\n if (dynamicRoutes.length > 0) {\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, importBase, hasSchema);\n lines.push(\n ` export function useSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function useSegmentParams(): Partial<AllSegmentParams>'\n : ' export function useSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('');\n }\n\n // useQueryStates overloads\n if (pageRoutes.length > 0) {\n lines.push(...formatUseQueryStatesOverloads(pageRoutes, importBase));\n lines.push('');\n }\n\n // Typed Link overloads — per-route with DIRECT types (no conditionals).\n // Direct types preserve TypeScript's excess property checking.\n //\n // TIM-832: per-route and catch-all are emitted as TWO separate\n // augmentation blocks. Per TS's merging rule \"later overload sets\n // ordered first\", the catch-all block (declared SECOND in this file)\n // ends up FIRST in the merged call-signature list at resolution time,\n // which puts the per-route block LAST — so its error message is the\n // one TypeScript reports when no overload matches. This gives users a\n // clear prop-mismatch error (e.g. \"'string | undefined' is not\n // assignable to 'string | number' on id\") instead of the old\n // confusing \"Type 'string' is not assignable to type 'never'\" cascade.\n if (pageRoutes.length > 0) {\n lines.push(' // Typed Link overloads — per-route (block 1 / emitted first)');\n lines.push(...formatTypedLinkOverloads(pageRoutes, importBase, hasSchema));\n lines.push('');\n }\n\n lines.push('}');\n lines.push('');\n }\n\n // TIM-832: catch-all block — emitted as a SEPARATE `declare module`\n // augmentation so TS's \"later overload set first\" rule orders it ahead\n // of the per-route block above at resolution time, leaving per-route as\n // the \"last overload\" whose error TypeScript reports.\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n lines.push('');\n lines.push(...formatLinkCatchAllOverloads());\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format the params type for a route entry.\n */\nfunction formatParamsType(params: ParamEntry[], importBase?: string, hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const fields = params.map((p) => {\n const codecType = hasSchema\n ? buildSchemaParamType(p)\n : buildCodecChainType(p, importBase, p.type);\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * Generate useQueryStates overloads.\n *\n * For each page route:\n * - Routes with search-params.ts get a typed overload returning the inferred T\n * - Routes without search-params.ts get an overload returning [{}, SetParams<{}>]\n *\n * A fallback overload for standalone codecs (existing API) is emitted last.\n */\nfunction formatUseQueryStatesOverloads(routes: RouteEntry[], importBase?: string): string[] {\n const lines: string[] = [];\n\n for (const route of routes) {\n const searchParamsType = route.hasSearchParams\n ? formatSearchParamsType(route, importBase)\n : '{}';\n lines.push(\n ` export function useQueryStates<R extends '${route.urlPath}'>(route: R, options?: QueryStatesOptions): [${searchParamsType}, SetParams<${searchParamsType}>]`\n );\n }\n\n // Fallback: standalone codecs (existing API)\n lines.push(\n ' export function useQueryStates<T extends Record<string, unknown>>(codecs: { [K in keyof T]: SearchParamCodec<T[K]> }, options?: QueryStatesOptions): [T, SetParams<T>]'\n );\n\n return lines;\n}\n\n// Link overload formatters and helpers (`formatTypedLinkOverloads`,\n// `formatLinkCatchAllOverloads`, `formatLinkParamsType`,\n// `buildResolvedPattern`, `LINK_BASE_PROPS_TYPE`) were extracted to\n// `./link-codegen.ts` (TIM-835) to keep this file under the 500-line\n// cap. They are imported at the top of this file.\n","/**\n * Intercepting route utilities.\n *\n * Computes rewrite rules from the route tree that enable intercepting routes\n * to conditionally render when navigating via client-side (soft) navigation.\n *\n * The mechanism: at build time, each intercepting route directory generates a\n * conditional rewrite. On soft navigation, the client sends an `X-Timber-URL`\n * header with the current pathname. The server checks if any rewrite's source\n * (the intercepted URL) matches the target pathname AND the header matches\n * the intercepting route's parent URL. If both match, the intercepting route\n * renders instead of the normal route.\n *\n * On hard navigation (no header), no rewrite matches, and the normal route\n * renders.\n *\n * See design/07-routing.md §\"Intercepting Routes\"\n */\n\nimport type { SegmentNode, InterceptionMarker } from './types.js';\n\n/** A conditional rewrite rule generated from an intercepting route. */\nexport interface InterceptionRewrite {\n /**\n * The URL pattern that this rewrite intercepts (the target of navigation).\n * E.g., \"/photo/[id]\" for a (.)photo/[id] interception.\n */\n interceptedPattern: string;\n /**\n * The URL prefix that the client must be navigating FROM for this rewrite\n * to apply. Matched against the X-Timber-URL header.\n * E.g., \"/feed\" for a (.)photo/[id] inside /feed/@modal/.\n */\n interceptingPrefix: string;\n /**\n * Segments chain from root → intercepting leaf. Used to build the element\n * tree when the interception is active.\n */\n segmentPath: SegmentNode[];\n}\n\n/**\n * Collect all interception rewrite rules from the route tree.\n *\n * Walks the tree recursively. For each intercepting segment, computes the\n * intercepted URL based on the marker and the segment's position.\n */\nexport function collectInterceptionRewrites(root: SegmentNode): InterceptionRewrite[] {\n const rewrites: InterceptionRewrite[] = [];\n walkForInterceptions(root, [root], rewrites);\n return rewrites;\n}\n\n/**\n * Recursively walk the segment tree to find intercepting routes.\n */\nfunction walkForInterceptions(\n node: SegmentNode,\n ancestors: SegmentNode[],\n rewrites: InterceptionRewrite[]\n): void {\n // Check children\n for (const child of node.children) {\n if (child.segmentType === 'intercepting' && child.interceptionMarker) {\n // Found an intercepting route — collect rewrites from its sub-tree\n collectFromInterceptingNode(child, ancestors, rewrites);\n } else {\n walkForInterceptions(child, [...ancestors, child], rewrites);\n }\n }\n\n // Check slots (intercepting routes are typically inside slots like @modal)\n for (const slot of Object.values(node.slots)) {\n walkForInterceptions(slot, ancestors, rewrites);\n }\n}\n\n/**\n * For an intercepting segment, find all leaf pages in its sub-tree and\n * generate rewrite rules for each.\n */\nfunction collectFromInterceptingNode(\n interceptingNode: SegmentNode,\n ancestors: SegmentNode[],\n rewrites: InterceptionRewrite[]\n): void {\n const marker = interceptingNode.interceptionMarker!;\n const segmentName = interceptingNode.interceptedSegmentName!;\n\n // Compute the intercepted URL base based on the marker\n const parentUrlPath = ancestors[ancestors.length - 1].urlPath;\n const interceptedBase = computeInterceptedBase(parentUrlPath, marker);\n const interceptedUrlBase =\n interceptedBase === '/' ? `/${segmentName}` : `${interceptedBase}/${segmentName}`;\n\n // Find all leaf pages in the intercepting sub-tree\n collectLeavesWithRewrites(\n interceptingNode,\n interceptedUrlBase,\n parentUrlPath,\n [...ancestors, interceptingNode],\n rewrites\n );\n}\n\n/**\n * Recursively find leaf pages in an intercepting sub-tree and generate\n * rewrite rules for each.\n */\nfunction collectLeavesWithRewrites(\n node: SegmentNode,\n interceptedUrlPath: string,\n interceptingPrefix: string,\n segmentPath: SegmentNode[],\n rewrites: InterceptionRewrite[]\n): void {\n if (node.page) {\n rewrites.push({\n interceptedPattern: interceptedUrlPath,\n interceptingPrefix,\n segmentPath: [...segmentPath],\n });\n }\n\n for (const child of node.children) {\n const childUrl =\n child.segmentType === 'group'\n ? interceptedUrlPath\n : `${interceptedUrlPath}/${child.segmentName}`;\n collectLeavesWithRewrites(\n child,\n childUrl,\n interceptingPrefix,\n [...segmentPath, child],\n rewrites\n );\n }\n}\n\n/**\n * Compute the base URL that an intercepting route intercepts, given the\n * parent's URL path and the interception marker.\n *\n * - (.) — same level: parent's URL path\n * - (..) — one level up: parent's parent URL path\n * - (...) — root level: /\n * - (..)(..) — two levels up: parent's grandparent URL path\n *\n * Level counting operates on URL path segments, NOT filesystem directories.\n * Route groups and parallel slots are already excluded from urlPath (they\n * don't add URL depth), so (..) correctly climbs visible segments. This\n * avoids the Vinext bug where path.dirname() on filesystem paths would\n * waste climbs on invisible route groups.\n */\nfunction computeInterceptedBase(parentUrlPath: string, marker: InterceptionMarker): string {\n switch (marker) {\n case '(.)':\n return parentUrlPath;\n case '(..)': {\n const parts = parentUrlPath.split('/').filter(Boolean);\n parts.pop();\n return parts.length === 0 ? '/' : `/${parts.join('/')}`;\n }\n case '(...)':\n return '/';\n case '(..)(..)': {\n const parts = parentUrlPath.split('/').filter(Boolean);\n parts.pop();\n parts.pop();\n return parts.length === 0 ? '/' : `/${parts.join('/')}`;\n }\n }\n}\n","/**\n * Schema key/value validation against the filesystem route tree.\n *\n * Runs at codegen time (build + dev) to catch mismatches between\n * app/schema.ts keys and the actual dynamic segments on disk.\n *\n * Design doc: design/41-global-params.md\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { RouteTree, SegmentNode } from './types.js';\nimport { findSchemaFile, parseExistingSchemaKeys } from '../cli-schema-sync.js';\nimport { classifyUrlSegment } from './segment-classify.js';\n\nexport interface SchemaWarning {\n type: 'stale-key' | 'missing-key' | 'bracket-mismatch';\n key: string;\n message: string;\n filesystemKey?: string;\n}\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from a route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegmentsFromTree(tree: RouteTree): Set<string> {\n const segments = new Set<string>();\n walkTree(tree.root, segments);\n return segments;\n}\n\nfunction walkTree(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName && node.segmentName) {\n const classified = classifyUrlSegment(node.segmentName);\n if (classified.kind !== 'static') {\n segments.add(node.segmentName);\n }\n }\n for (const child of node.children) {\n walkTree(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkTree(slot, segments);\n }\n}\n\n/**\n * Extract the param name from a bracket key.\n * '[id]' → 'id', '[...slug]' → 'slug', '[[...topic]]' → 'topic'\n */\nfunction extractParamName(bracketKey: string): string | null {\n const seg = classifyUrlSegment(bracketKey);\n if (seg.kind === 'static') return null;\n return seg.name;\n}\n\n/**\n * Validate schema keys against the filesystem route tree.\n *\n * Returns warnings for:\n * - Stale keys: schema keys that don't match any filesystem segment\n * - Bracket form mismatches: same param name, different bracket form\n * - Missing keys: filesystem segments not registered in schema (informational)\n */\nexport function validateSchemaAgainstRoutes(tree: RouteTree, appDir: string): SchemaWarning[] {\n const schemaPath = findSchemaFile(appDir);\n if (!schemaPath) return [];\n\n const content = readFileSync(schemaPath, 'utf-8');\n const schemaKeys = parseExistingSchemaKeys(content);\n\n if (schemaKeys.length === 0) return [];\n\n const filesystemSegments = collectDynamicSegmentsFromTree(tree);\n\n return validateKeys(schemaKeys, filesystemSegments);\n}\n\n/**\n * Core validation: compare schema keys against filesystem segments.\n * Exported separately for testing without filesystem dependencies.\n */\nexport function validateKeys(\n schemaKeys: string[],\n filesystemSegments: Set<string>\n): SchemaWarning[] {\n const warnings: SchemaWarning[] = [];\n\n // Build a map of param name → bracket form for filesystem segments\n const fsParamToKey = new Map<string, string>();\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name) {\n fsParamToKey.set(name, fsKey);\n }\n }\n\n // Build a set of schema param names for the missing-key check\n const schemaParamNames = new Set<string>();\n\n for (const schemaKey of schemaKeys) {\n const schemaParamName = extractParamName(schemaKey);\n if (!schemaParamName) continue;\n\n schemaParamNames.add(schemaParamName);\n\n if (filesystemSegments.has(schemaKey)) {\n // Exact match — no issue\n continue;\n }\n\n // Check if the param name exists but with a different bracket form\n const fsKey = fsParamToKey.get(schemaParamName);\n if (fsKey) {\n warnings.push({\n type: 'bracket-mismatch',\n key: schemaKey,\n filesystemKey: fsKey,\n message:\n `Schema key '${schemaKey}' does not match filesystem bracket form '${fsKey}'. ` +\n `Update the schema key to '${fsKey}'.`,\n });\n } else {\n warnings.push({\n type: 'stale-key',\n key: schemaKey,\n message:\n `Schema key '${schemaKey}' does not match any dynamic segment in the filesystem. ` +\n `Remove it from app/schema.ts or create the corresponding route segment.`,\n });\n }\n }\n\n // Check for filesystem segments not in schema (informational)\n for (const fsKey of filesystemSegments) {\n const name = extractParamName(fsKey);\n if (name && !schemaParamNames.has(name)) {\n warnings.push({\n type: 'missing-key',\n key: fsKey,\n message:\n `Dynamic segment '${fsKey}' has no codec in app/schema.ts (defaults to string). ` +\n `Run: timber schema sync`,\n });\n }\n }\n\n return warnings;\n}\n","/**\n * Shared route-tree walkers (TIM-848).\n *\n * Tiny helpers that walk a `SegmentNode<TFile>` tree generically. Both the\n * build-time tree (`SegmentNode<RouteFile>`) and the runtime manifest\n * tree (`SegmentNode<ManifestFile>`) flow through these helpers because\n * the walker only reads the structural fields shared by both shapes\n * (`children`, `slots`, `page`, `route`, `urlPath`).\n *\n * Before this module, three near-identical `collectRoutes` functions\n * lived in `plugins/dev-404-page.ts`, `plugins/build-report.ts`, and\n * `routing/codegen.ts`. The codegen one is special-purpose (it\n * accumulates `ParamEntry[]` and resolves codec chains) and stays\n * local; the other two now share `collectLeafRoutes` from this file.\n */\n\nimport type { SegmentNode } from './types.js';\n\n/** A leaf route discovered while walking the segment tree. */\nexport interface LeafRoute<TFile> {\n /** URL path of the leaf (root is \"/\"). */\n urlPath: string;\n /** Segment chain from root to this leaf, inclusive. */\n segments: SegmentNode<TFile>[];\n /** The page file at this leaf, if any. */\n page?: TFile;\n /** The route handler file at this leaf, if any. */\n route?: TFile;\n}\n\n/** Options for `collectLeafRoutes`. */\nexport interface CollectLeafRoutesOptions {\n /**\n * If true, recurse into parallel slots and emit slot leaves alongside\n * the main route tree. Defaults to `false` because slots render\n * alongside their parent at the same URL and are not separately\n * URL-addressable. The build report excludes slots; route-listing\n * UIs that want to show \"all leaves with a page handler\" can opt in.\n */\n includeSlots?: boolean;\n}\n\n/**\n * Walk a segment tree and collect every leaf with a `page` or `route`\n * handler. Generic over `TFile` so it works on both the build-time\n * scanner output and the runtime manifest tree.\n *\n * - Pages and route handlers at the same URL produce two distinct\n * entries (the build report deduplicates by URL afterward).\n * - Parallel slots are skipped unless `includeSlots: true` (slots\n * share their parent's URL and are not addressable on their own).\n * - Result is sorted by `urlPath` for deterministic output.\n */\nexport function collectLeafRoutes<TFile>(\n root: SegmentNode<TFile>,\n options: CollectLeafRoutesOptions = {}\n): LeafRoute<TFile>[] {\n const { includeSlots = false } = options;\n const result: LeafRoute<TFile>[] = [];\n walk(root, [], result, includeSlots);\n result.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n return result;\n}\n\nfunction walk<TFile>(\n node: SegmentNode<TFile>,\n chain: SegmentNode<TFile>[],\n result: LeafRoute<TFile>[],\n includeSlots: boolean\n): void {\n const currentChain = [...chain, node];\n const path = node.urlPath || '/';\n\n if (node.page) {\n result.push({ urlPath: path, segments: currentChain, page: node.page });\n }\n if (node.route) {\n result.push({ urlPath: path, segments: currentChain, route: node.route });\n }\n\n for (const child of node.children) {\n walk(child, currentChain, result, includeSlots);\n }\n\n if (includeSlots) {\n for (const slotNode of Object.values(node.slots)) {\n walk(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}
@@ -23,7 +23,7 @@ import type { TimberPlatformAdapter, TimberConfig } from './types';
23
23
  export declare function getCloudflareBindings<T = Record<string, unknown>>(): T;
24
24
  /**
25
25
  * Run a function with Cloudflare bindings available via getCloudflareBindings().
26
- * @internal Used by wrapWithExecutionContext.
26
+ * @internal Used by cloudflareDevBindings() to wrap dev-server requests.
27
27
  */
28
28
  export declare function runWithBindings<T>(env: Record<string, unknown>, fn: () => T): T;
29
29
  /** KV namespace binding. `id` defaults to `''` (filled in by wrangler or dashboard). */
@@ -154,16 +154,6 @@ export interface CloudflareAdapterOptions {
154
154
  * ```
155
155
  */
156
156
  export declare function cloudflare(options?: CloudflareAdapterOptions): TimberPlatformAdapter;
157
- /**
158
- * Wrap a timber request handler to bind the Cloudflare execution context
159
- * for `waitUntil()` support and env bindings passthrough.
160
- * Called from the generated worker entry.
161
- *
162
- * This function:
163
- * 1. Binds `adapter.waitUntil()` to `ctx.waitUntil()` per-request
164
- * 2. Makes `env` accessible via `getCloudflareBindings()` per-request via ALS
165
- */
166
- export declare function wrapWithExecutionContext(adapter: TimberPlatformAdapter, handler: (req: Request) => Promise<Response>): CfExportedHandler<Record<string, unknown>>;
167
157
  /** @internal Exported for testing. */
168
158
  export declare function generateWorkerEntry(buildDir: string, outDir: string, hasManifestInit?: boolean, hasWorkerHandlers?: boolean): string;
169
159
  /** Wrangler binding sections generated from `CloudflareBindings`. */
@@ -221,8 +211,4 @@ export interface CfExecutionContext {
221
211
  waitUntil(promise: Promise<unknown>): void;
222
212
  passThroughOnException(): void;
223
213
  }
224
- /** @internal Minimal stub — use @cloudflare/workers-types for full types. */
225
- export interface CfExportedHandler<Env = Record<string, unknown>> {
226
- fetch?(request: Request, env: Env, ctx: CfExecutionContext): Promise<Response> | Response;
227
- }
228
214
  //# sourceMappingURL=cloudflare.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../../src/adapters/cloudflare.ts"],"names":[],"mappings":"AASA,OAA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AAsB,IAAI,IAAI,CAAC;CAChC"}
@@ -41,7 +41,7 @@ function getCloudflareBindings() {
41
41
  }
42
42
  /**
43
43
  * Run a function with Cloudflare bindings available via getCloudflareBindings().
44
- * @internal Used by wrapWithExecutionContext.
44
+ * @internal Used by cloudflareDevBindings() to wrap dev-server requests.
45
45
  */
46
46
  function runWithBindings(env, fn) {
47
47
  return getBindingsAls().run(env, fn);
@@ -99,31 +99,8 @@ function cloudflare(options = {}) {
99
99
  async preview(_config, buildDir) {
100
100
  const cmd = generatePreviewCommand(buildDir);
101
101
  await spawnPreviewProcess(cmd.command, cmd.args, cmd.cwd);
102
- },
103
- waitUntil(_promise) {}
104
- };
105
- }
106
- /**
107
- * Wrap a timber request handler to bind the Cloudflare execution context
108
- * for `waitUntil()` support and env bindings passthrough.
109
- * Called from the generated worker entry.
110
- *
111
- * This function:
112
- * 1. Binds `adapter.waitUntil()` to `ctx.waitUntil()` per-request
113
- * 2. Makes `env` accessible via `getCloudflareBindings()` per-request via ALS
114
- */
115
- function wrapWithExecutionContext(adapter, handler) {
116
- return { async fetch(request, env, ctx) {
117
- const originalWaitUntil = adapter.waitUntil;
118
- adapter.waitUntil = (promise) => {
119
- ctx.waitUntil(promise);
120
- };
121
- try {
122
- return await runWithBindings(env, () => handler(request));
123
- } finally {
124
- adapter.waitUntil = originalWaitUntil;
125
102
  }
126
- } };
103
+ };
127
104
  }
128
105
  /** @internal Exported for testing. */
129
106
  function generateWorkerEntry(buildDir, outDir, hasManifestInit = false, hasWorkerHandlers = false) {
@@ -133,7 +110,7 @@ function generateWorkerEntry(buildDir, outDir, hasManifestInit = false, hasWorke
133
110
  // Do not edit — this file is regenerated on each build.
134
111
 
135
112
  import { AsyncLocalStorage } from 'node:async_hooks'
136
- ${hasManifestInit ? "import './_timber-manifest-init.js'\n" : ""}import handler from '${rscEntryRelative}'
113
+ ${hasManifestInit ? "import './_timber-manifest-init.js'\n" : ""}import handler, { runWithWaitUntil } from '${rscEntryRelative}'
137
114
  ${hasWorkerHandlers ? "import * as workerHandlers from './_worker-handlers.js'\n" : ""}
138
115
  // Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.
139
116
  // See design/25-production-deployments.md §"TIMBER_RUNTIME".
@@ -151,7 +128,12 @@ if (!bindingsAls) {
151
128
 
152
129
  export default {
153
130
  ${hasWorkerHandlers ? " ...workerHandlers,\n" : ""} async fetch(request, env, ctx) {
154
- return bindingsAls.run(env, () => handler(request))
131
+ // Bridge ctx.waitUntil into the per-request ALS so waitUntil() calls in
132
+ // user code keep the isolate alive after the response is sent.
133
+ // See design/11-platform.md §"waitUntil()".
134
+ return bindingsAls.run(env, () =>
135
+ runWithWaitUntil((promise) => ctx.waitUntil(promise), () => handler(request))
136
+ )
155
137
  }
156
138
  }
157
139
  `;
@@ -287,6 +269,6 @@ function spawnPreviewProcess(command, args, cwd) {
287
269
  });
288
270
  }
289
271
  //#endregion
290
- export { cloudflare, generateBindingsConfig, generatePreviewCommand, generateWorkerEntry, generateWranglerConfig, getCloudflareBindings, runWithBindings, wrapWithExecutionContext };
272
+ export { cloudflare, generateBindingsConfig, generatePreviewCommand, generateWorkerEntry, generateWranglerConfig, getCloudflareBindings, runWithBindings };
291
273
 
292
274
  //# sourceMappingURL=cloudflare.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare.js","names":[],"sources":["../../src/adapters/cloudflare.ts"],"sourcesContent":["// Cloudflare Workers adapter\n//\n// Primary deployment target. Generates a Workers-compatible entry point\n// and wrangler.jsonc configuration. See design/11-platform.md §\"Cloudflare Workers\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Bindings passthrough ─────────────────────────────────────────────────\n// ALS stores the env object per-request so server components and middleware\n// can access KV, D1, DO, R2, Queues, etc. via getCloudflareBindings().\n// No global fallback — if called outside a request, it throws.\n// See design/11-platform.md §\"Platform Target\" and design/25-production-deployments.md.\n//\n// The ALS is stored on globalThis via Symbol.for so it survives Vite's\n// module instance split in dev mode. The Vite host process (where\n// cloudflareDevBindings → runWithBindings runs) and the RSC module runner\n// (where getCloudflareBindings runs) load separate instances of this file,\n// each with their own module-level variables. globalThis + Symbol.for\n// ensures both share the same ALS — same pattern React uses for\n// Symbol.for('react.element').\n\nconst BINDINGS_ALS_KEY = Symbol.for('timber:cf-bindings-als');\n\nfunction getBindingsAls(): AsyncLocalStorage<Record<string, unknown>> {\n let als = (globalThis as any)[BINDINGS_ALS_KEY] as\n | AsyncLocalStorage<Record<string, unknown>>\n | undefined;\n if (!als) {\n als = new AsyncLocalStorage<Record<string, unknown>>();\n (globalThis as any)[BINDINGS_ALS_KEY] = als;\n }\n return als;\n}\n\n/**\n * Get Cloudflare Worker bindings for the current request.\n *\n * Returns the `env` object passed to the Worker's `fetch` handler,\n * giving direct access to KV, D1, Durable Objects, R2, Queues, and\n * any other bindings configured in `wrangler.jsonc`.\n *\n * Must be called within a request context (server component, middleware,\n * server action). Throws outside a request.\n *\n * @example\n * ```ts\n * import { getCloudflareBindings } from '@timber-js/app/adapters/cloudflare'\n *\n * export default async function Page() {\n * const { MY_KV, MY_DB } = getCloudflareBindings()\n * const data = await MY_KV.get('key')\n * return <div>{data}</div>\n * }\n * ```\n */\nexport function getCloudflareBindings<T = Record<string, unknown>>(): T {\n const env = getBindingsAls().getStore();\n if (!env) {\n throw new Error(\n 'getCloudflareBindings() called outside a Cloudflare Workers request context. ' +\n 'It can only be called from server components, middleware, or server actions ' +\n 'when running on the Cloudflare adapter.'\n );\n }\n return env as T;\n}\n\n/**\n * Run a function with Cloudflare bindings available via getCloudflareBindings().\n * @internal Used by wrapWithExecutionContext.\n */\nexport function runWithBindings<T>(env: Record<string, unknown>, fn: () => T): T {\n return getBindingsAls().run(env, fn);\n}\n\n// ─── Binding configuration types ──────────────────────────────────────────────\n// Declarative binding config that maps to wrangler.jsonc binding sections.\n// See design/35-cloudflare-primitives.md §\"Binding Declarations in Adapter Config\".\n\n/** KV namespace binding. `id` defaults to `''` (filled in by wrangler or dashboard). */\nexport interface CloudflareKVBinding {\n name: string;\n id?: string;\n}\n\n/** D1 database binding. `database_id` is required (from Cloudflare dashboard). */\nexport interface CloudflareD1Binding {\n name: string;\n database_id: string;\n}\n\n/** R2 bucket binding. `bucket_name` must match the bucket created in Cloudflare. */\nexport interface CloudflareR2Binding {\n name: string;\n bucket_name: string;\n}\n\n/** Queue producer binding. `queue` is the queue name in Cloudflare. */\nexport interface CloudflareQueueProducer {\n name: string;\n queue: string;\n}\n\n/** Queue consumer declaration. Attached to the worker, not a binding name. */\nexport interface CloudflareQueueConsumer {\n queue: string;\n max_batch_size?: number;\n max_retries?: number;\n dead_letter_queue?: string;\n}\n\n/** Durable Object binding. `script_name` is for external DO references. */\nexport interface CloudflareDurableObjectBinding {\n name: string;\n class_name: string;\n script_name?: string;\n}\n\n/**\n * Declarative Cloudflare bindings configuration.\n *\n * These are converted to the appropriate wrangler.jsonc sections\n * (`kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, `durable_objects`).\n * The `wrangler` escape hatch overrides any generated binding sections\n * if there's a conflict.\n *\n * @example\n * ```ts\n * cloudflare({\n * bindings: {\n * kv: [{ name: 'TIMBER_CACHE' }],\n * d1: [{ name: 'MY_DB', database_id: 'xxxx' }],\n * r2: [{ name: 'MY_BUCKET', bucket_name: 'my-bucket' }],\n * queues: {\n * producers: [{ name: 'EMAIL_QUEUE', queue: 'email-queue' }],\n * consumers: [{ queue: 'email-queue', max_batch_size: 10 }],\n * },\n * durableObjects: [{ name: 'MY_DO', class_name: 'MyDurableObject' }],\n * },\n * })\n * ```\n */\nexport interface CloudflareBindings {\n kv?: CloudflareKVBinding[];\n d1?: CloudflareD1Binding[];\n r2?: CloudflareR2Binding[];\n queues?: {\n producers?: CloudflareQueueProducer[];\n consumers?: CloudflareQueueConsumer[];\n };\n durableObjects?: CloudflareDurableObjectBinding[];\n}\n\n/** Options for the Cloudflare Workers adapter. */\nexport interface CloudflareAdapterOptions {\n /**\n * Cloudflare compatibility date.\n * @default Current date in YYYY-MM-DD format at build time.\n */\n compatibilityDate?: string;\n\n /**\n * Additional compatibility flags.\n * @default ['nodejs_compat']\n */\n compatibilityFlags?: string[];\n\n /**\n * Declarative Cloudflare bindings. Generates the appropriate\n * `kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, and\n * `durable_objects` sections in wrangler.jsonc.\n *\n * If both `bindings` and `wrangler` specify the same section,\n * `wrangler` wins (it's the escape hatch).\n */\n bindings?: CloudflareBindings;\n\n /**\n * Custom wrangler.jsonc fields to merge.\n * Overrides generated values (including bindings-generated sections).\n */\n wrangler?: Record<string, unknown>;\n\n /**\n * Path to a module that exports additional Worker handlers (queue, scheduled, email, etc.).\n * The module is imported in the generated `_worker.js` and its named exports are\n * spread into the default export alongside `fetch`.\n *\n * The module receives `(batch/event, env, ctx)` — standard Cloudflare handler signatures.\n * It does NOT have access to timber's request pipeline (no ALS, no getCloudflareBindings).\n * Use `env` directly for bindings.\n *\n * @example\n * ```ts\n * // timber.config.ts\n * adapter: cloudflare({ workerHandlers: './src/worker-handlers.ts' })\n *\n * // src/worker-handlers.ts\n * export async function queue(batch, env) { ... }\n * export async function scheduled(controller, env, ctx) { ... }\n * ```\n */\n workerHandlers?: string;\n}\n\n/**\n * Create a Cloudflare Workers adapter.\n *\n * @example\n * ```ts\n * import { cloudflare } from '@timber-js/app/adapters/cloudflare'\n *\n * export default {\n * output: 'server',\n * adapter: cloudflare(),\n * }\n * ```\n */\nexport function cloudflare(options: CloudflareAdapterOptions = {}): TimberPlatformAdapter {\n return {\n name: 'cloudflare',\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'cloudflare');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'static',\n });\n\n // Compile optional worker handlers (queue, scheduled, etc.)\n // Uses Vite's build API to bundle the TypeScript source into ESM.\n let hasWorkerHandlers = false;\n if (options.workerHandlers) {\n const handlersEntry = join(process.cwd(), options.workerHandlers);\n const { build: viteBuild } = await import('vite');\n await viteBuild({\n configFile: false,\n logLevel: 'info',\n build: {\n lib: {\n entry: handlersEntry,\n formats: ['es'],\n fileName: () => '_worker-handlers.js',\n },\n outDir,\n emptyOutDir: false,\n minify: false,\n rollupOptions: {\n external: [/^node:/],\n },\n },\n });\n hasWorkerHandlers = true;\n }\n\n // Generate the Workers entry point\n const hasManifestInit = !!config.manifestInit;\n const workerEntry = generateWorkerEntry(outDir, outDir, hasManifestInit, hasWorkerHandlers);\n await writeFile(join(outDir, '_worker.js'), workerEntry);\n\n // Generate wrangler.jsonc\n const wranglerConfig = generateWranglerConfig(config, options);\n await writeFile(join(outDir, 'wrangler.jsonc'), JSON.stringify(wranglerConfig, null, 2));\n },\n\n async preview(_config: TimberConfig, buildDir: string) {\n const cmd = generatePreviewCommand(buildDir);\n await spawnPreviewProcess(cmd.command, cmd.args, cmd.cwd);\n },\n\n // Default no-op. wrapWithExecutionContext() replaces this per-request\n // with a function that routes to ctx.waitUntil().\n waitUntil(_promise: Promise<unknown>) {},\n };\n}\n\n/**\n * Wrap a timber request handler to bind the Cloudflare execution context\n * for `waitUntil()` support and env bindings passthrough.\n * Called from the generated worker entry.\n *\n * This function:\n * 1. Binds `adapter.waitUntil()` to `ctx.waitUntil()` per-request\n * 2. Makes `env` accessible via `getCloudflareBindings()` per-request via ALS\n */\nexport function wrapWithExecutionContext(\n adapter: TimberPlatformAdapter,\n handler: (req: Request) => Promise<Response>\n): CfExportedHandler<Record<string, unknown>> {\n return {\n async fetch(\n request: Request,\n env: Record<string, unknown>,\n ctx: CfExecutionContext\n ): Promise<Response> {\n // Bind the adapter's waitUntil to the Workers execution context\n const originalWaitUntil = adapter.waitUntil;\n adapter.waitUntil = (promise: Promise<unknown>) => {\n ctx.waitUntil(promise);\n };\n\n try {\n // Run the handler within ALS so getCloudflareBindings() works\n return await runWithBindings(env, () => handler(request));\n } finally {\n // Restore (in case adapter is reused across isolate resets)\n adapter.waitUntil = originalWaitUntil;\n }\n },\n };\n}\n\n// ─── Exported helpers (used by tests and build) ─────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateWorkerEntry(\n buildDir: string,\n outDir: string,\n hasManifestInit = false,\n hasWorkerHandlers = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let rscEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!rscEntryRelative.startsWith('.')) {\n rscEntryRelative = './' + rscEntryRelative;\n }\n\n // Build manifest init must be imported before the RSC handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Optional additional Worker handlers (queue, scheduled, email, etc.)\n // Compiled by buildOutput via Vite's build API into _worker-handlers.js.\n // The module's named exports are spread into the default export alongside fetch.\n const handlersImport = hasWorkerHandlers\n ? \"import * as workerHandlers from './_worker-handlers.js'\\n\"\n : '';\n const handlersSpread = hasWorkerHandlers ? ' ...workerHandlers,\\n' : '';\n\n return `// Generated by @timber-js/app/adapters/cloudflare\n// Do not edit — this file is regenerated on each build.\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${manifestImport}import handler from '${rscEntryRelative}'\n${handlersImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nglobalThis.process ??= { env: {} }\nprocess.env.TIMBER_RUNTIME = 'cloudflare'\n\n// Bind Cloudflare env to ALS so getCloudflareBindings() works at runtime.\n// Uses the same Symbol.for key as getCloudflareBindings() reads from.\nconst ALS_KEY = Symbol.for('timber:cf-bindings-als')\nlet bindingsAls = globalThis[ALS_KEY]\nif (!bindingsAls) {\n bindingsAls = new AsyncLocalStorage()\n globalThis[ALS_KEY] = bindingsAls\n}\n\nexport default {\n${handlersSpread} async fetch(request, env, ctx) {\n return bindingsAls.run(env, () => handler(request))\n }\n}\n`;\n}\n\n/** Wrangler binding sections generated from `CloudflareBindings`. */\nexport interface WranglerBindingsConfig {\n kv_namespaces?: Array<{ binding: string; id: string }>;\n d1_databases?: Array<{ binding: string; database_id: string }>;\n r2_buckets?: Array<{ binding: string; bucket_name: string }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<Record<string, unknown>>;\n };\n durable_objects?: {\n bindings: Array<Record<string, string>>;\n };\n}\n\n/**\n * Convert declarative `CloudflareBindings` into wrangler.jsonc binding sections.\n *\n * Maps:\n * - `kv` → `kv_namespaces`\n * - `d1` → `d1_databases`\n * - `r2` → `r2_buckets`\n * - `queues` → `queues` (producers + consumers)\n * - `durableObjects` → `durable_objects`\n *\n * Empty arrays are omitted from the output.\n *\n * @internal Exported for testing.\n */\nexport function generateBindingsConfig(\n bindings: CloudflareBindings | undefined\n): WranglerBindingsConfig {\n if (!bindings) return {};\n\n const result: WranglerBindingsConfig = {};\n\n // KV namespaces\n if (bindings.kv && bindings.kv.length > 0) {\n result.kv_namespaces = bindings.kv.map((kv) => ({\n binding: kv.name,\n id: kv.id ?? '',\n }));\n }\n\n // D1 databases\n if (bindings.d1 && bindings.d1.length > 0) {\n result.d1_databases = bindings.d1.map((d1) => ({\n binding: d1.name,\n database_id: d1.database_id,\n }));\n }\n\n // R2 buckets\n if (bindings.r2 && bindings.r2.length > 0) {\n result.r2_buckets = bindings.r2.map((r2) => ({\n binding: r2.name,\n bucket_name: r2.bucket_name,\n }));\n }\n\n // Queues (producers and/or consumers)\n if (bindings.queues) {\n const queues: Record<string, unknown> = {};\n if (bindings.queues.producers && bindings.queues.producers.length > 0) {\n queues.producers = bindings.queues.producers.map((p) => ({\n binding: p.name,\n queue: p.queue,\n }));\n }\n if (bindings.queues.consumers && bindings.queues.consumers.length > 0) {\n queues.consumers = bindings.queues.consumers.map((c) => {\n const consumer: Record<string, unknown> = { queue: c.queue };\n if (c.max_batch_size !== undefined) consumer.max_batch_size = c.max_batch_size;\n if (c.max_retries !== undefined) consumer.max_retries = c.max_retries;\n if (c.dead_letter_queue !== undefined) consumer.dead_letter_queue = c.dead_letter_queue;\n return consumer;\n });\n }\n if (Object.keys(queues).length > 0) {\n result.queues = queues;\n }\n }\n\n // Durable Objects\n if (bindings.durableObjects && bindings.durableObjects.length > 0) {\n result.durable_objects = {\n bindings: bindings.durableObjects.map((dobj) => {\n const entry: Record<string, string> = {\n name: dobj.name,\n class_name: dobj.class_name,\n };\n if (dobj.script_name) entry.script_name = dobj.script_name;\n return entry;\n }),\n };\n }\n\n return result;\n}\n\n/**\n * One-level deep merge: for each key in `override`, if both the base and\n * override values are plain objects (not arrays, not null), merge their\n * keys with override winning on conflicts. Everything else (primitives,\n * arrays, null) is replaced outright — matching the intuitive behavior\n * where `kv_namespaces: [...]` replaces fully but\n * `durable_objects: { migrations }` merges with generated `bindings`.\n */\nfunction shallowDeepMerge(\n base: Record<string, unknown>,\n override: Record<string, unknown>\n): Record<string, unknown> {\n const result = { ...base };\n for (const key of Object.keys(override)) {\n const baseVal = result[key];\n const overVal = override[key];\n if (isPlainObject(baseVal) && isPlainObject(overVal)) {\n result[key] = { ...baseVal, ...overVal };\n } else {\n result[key] = overVal;\n }\n }\n return result;\n}\n\n/** True for `{}` literals — false for arrays, null, Date, etc. */\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return val !== null && typeof val === 'object' && !Array.isArray(val);\n}\n\n/** @internal Exported for testing. */\nexport function generateWranglerConfig(\n config: TimberConfig,\n options: CloudflareAdapterOptions\n): Record<string, unknown> {\n const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);\n\n const flags = options.compatibilityFlags ?? ['nodejs_compat'];\n\n const base: Record<string, unknown> = {\n name: 'timber-app',\n main: '_worker.js',\n compatibility_date: compatDate,\n compatibility_flags: flags,\n // The build output is already fully bundled by Vite — skip wrangler's\n // esbuild pass to avoid issues with top-level await and module format.\n no_bundle: true,\n find_additional_modules: true,\n rules: [{ type: 'ESModule', globs: ['**/*.js'] }],\n assets: {\n directory: './static',\n },\n };\n\n // Layer 1: merge bindings-generated sections into base\n const bindingsConfig = generateBindingsConfig(options.bindings);\n const merged = { ...base, ...bindingsConfig };\n\n // Layer 2: wrangler escape hatch with deep merge for nested plain objects.\n // A shallow spread would replace entire sections like durable_objects and\n // queues — e.g. adding migrations via wrangler would drop the generated\n // durable_objects.bindings. Deep merge preserves generated keys while\n // letting wrangler override on actual key-level conflicts.\n if (options.wrangler) {\n return shallowDeepMerge(merged, options.wrangler);\n }\n\n return merged;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Command descriptor for preview — testable without spawning a process. */\nexport interface PreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generatePreviewCommand(buildDir: string): PreviewCommand {\n const cfDir = join(buildDir, 'cloudflare');\n return {\n command: 'wrangler',\n args: ['dev', '--local', '--config', join(cfDir, 'wrangler.jsonc')],\n cwd: cfDir,\n };\n}\n\n/**\n * Spawn a long-running preview process and pipe stdio to the parent.\n * Resolves when the process exits.\n */\nfunction spawnPreviewProcess(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Cloudflare Workers type stubs ───────────────────────────────────────────\n// Local type declarations so this file compiles without @cloudflare/workers-types.\n// These are NOT declared globally — that would clash with @cloudflare/workers-types\n// when users install it. Instead, they're module-scoped and used only within\n// this file's function signatures.\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExportedHandler<Env = Record<string, unknown>> {\n fetch?(request: Request, env: Env, ctx: CfExecutionContext): Promise<Response> | Response;\n}\n"],"mappings":";;;;;;AA0BA,IAAM,mBAAmB,OAAO,IAAI,wBAAwB;AAE5D,SAAS,iBAA6D;CACpE,IAAI,MAAO,WAAmB;CAG9B,IAAI,CAAC,KAAK;EACR,MAAM,IAAI,kBAA2C;EACrD,WAAoB,oBAAoB;CAC1C;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,wBAAwD;CACtE,MAAM,MAAM,eAAe,EAAE,SAAS;CACtC,IAAI,CAAC,KACH,MAAM,IAAI,MACR,kMAGF;CAEF,OAAO;AACT;;;;;AAMA,SAAgB,gBAAmB,KAA8B,IAAgB;CAC/E,OAAO,eAAe,EAAE,IAAI,KAAK,EAAE;AACrC;;;;;;;;;;;;;;AAiJA,SAAgB,WAAW,UAAoC,CAAC,GAA0B;CACxF,OAAO;EACL,MAAM;EAEN,MAAM,YAAY,QAAsB,UAAkB;GACxD,MAAM,SAAS,KAAK,UAAU,YAAY;GAI1C,MAAM,oBAAoB;IACxB;IACA;IACA;IACA,eAAe;GACjB,CAAC;GAID,IAAI,oBAAoB;GACxB,IAAI,QAAQ,gBAAgB;IAC1B,MAAM,gBAAgB,KAAK,QAAQ,IAAI,GAAG,QAAQ,cAAc;IAChE,MAAM,EAAE,OAAO,cAAc,MAAM,OAAO;IAC1C,MAAM,UAAU;KACd,YAAY;KACZ,UAAU;KACV,OAAO;MACL,KAAK;OACH,OAAO;OACP,SAAS,CAAC,IAAI;OACd,gBAAgB;MAClB;MACA;MACA,aAAa;MACb,QAAQ;MACR,eAAe,EACb,UAAU,CAAC,QAAQ,EACrB;KACF;IACF,CAAC;IACD,oBAAoB;GACtB;GAIA,M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f,CAAC;EACD,MAAM,QAAQ,KAAK,QAAQ,MAAM;EACjC,MAAM,QAAQ,KAAK,QAAQ,MAAM;CACnC,CAAC;AACH"}
1
+ {"version":3,"file":"cloudflare.js","names":[],"sources":["../../src/adapters/cloudflare.ts"],"sourcesContent":["// Cloudflare Workers adapter\n//\n// Primary deployment target. Generates a Workers-compatible entry point\n// and wrangler.jsonc configuration. See design/11-platform.md §\"Cloudflare Workers\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Bindings passthrough ─────────────────────────────────────────────────\n// ALS stores the env object per-request so server components and middleware\n// can access KV, D1, DO, R2, Queues, etc. via getCloudflareBindings().\n// No global fallback — if called outside a request, it throws.\n// See design/11-platform.md §\"Platform Target\" and design/25-production-deployments.md.\n//\n// The ALS is stored on globalThis via Symbol.for so it survives Vite's\n// module instance split in dev mode. The Vite host process (where\n// cloudflareDevBindings → runWithBindings runs) and the RSC module runner\n// (where getCloudflareBindings runs) load separate instances of this file,\n// each with their own module-level variables. globalThis + Symbol.for\n// ensures both share the same ALS — same pattern React uses for\n// Symbol.for('react.element').\n\nconst BINDINGS_ALS_KEY = Symbol.for('timber:cf-bindings-als');\n\nfunction getBindingsAls(): AsyncLocalStorage<Record<string, unknown>> {\n let als = (globalThis as any)[BINDINGS_ALS_KEY] as\n | AsyncLocalStorage<Record<string, unknown>>\n | undefined;\n if (!als) {\n als = new AsyncLocalStorage<Record<string, unknown>>();\n (globalThis as any)[BINDINGS_ALS_KEY] = als;\n }\n return als;\n}\n\n/**\n * Get Cloudflare Worker bindings for the current request.\n *\n * Returns the `env` object passed to the Worker's `fetch` handler,\n * giving direct access to KV, D1, Durable Objects, R2, Queues, and\n * any other bindings configured in `wrangler.jsonc`.\n *\n * Must be called within a request context (server component, middleware,\n * server action). Throws outside a request.\n *\n * @example\n * ```ts\n * import { getCloudflareBindings } from '@timber-js/app/adapters/cloudflare'\n *\n * export default async function Page() {\n * const { MY_KV, MY_DB } = getCloudflareBindings()\n * const data = await MY_KV.get('key')\n * return <div>{data}</div>\n * }\n * ```\n */\nexport function getCloudflareBindings<T = Record<string, unknown>>(): T {\n const env = getBindingsAls().getStore();\n if (!env) {\n throw new Error(\n 'getCloudflareBindings() called outside a Cloudflare Workers request context. ' +\n 'It can only be called from server components, middleware, or server actions ' +\n 'when running on the Cloudflare adapter.'\n );\n }\n return env as T;\n}\n\n/**\n * Run a function with Cloudflare bindings available via getCloudflareBindings().\n * @internal Used by cloudflareDevBindings() to wrap dev-server requests.\n */\nexport function runWithBindings<T>(env: Record<string, unknown>, fn: () => T): T {\n return getBindingsAls().run(env, fn);\n}\n\n// ─── Binding configuration types ──────────────────────────────────────────────\n// Declarative binding config that maps to wrangler.jsonc binding sections.\n// See design/35-cloudflare-primitives.md §\"Binding Declarations in Adapter Config\".\n\n/** KV namespace binding. `id` defaults to `''` (filled in by wrangler or dashboard). */\nexport interface CloudflareKVBinding {\n name: string;\n id?: string;\n}\n\n/** D1 database binding. `database_id` is required (from Cloudflare dashboard). */\nexport interface CloudflareD1Binding {\n name: string;\n database_id: string;\n}\n\n/** R2 bucket binding. `bucket_name` must match the bucket created in Cloudflare. */\nexport interface CloudflareR2Binding {\n name: string;\n bucket_name: string;\n}\n\n/** Queue producer binding. `queue` is the queue name in Cloudflare. */\nexport interface CloudflareQueueProducer {\n name: string;\n queue: string;\n}\n\n/** Queue consumer declaration. Attached to the worker, not a binding name. */\nexport interface CloudflareQueueConsumer {\n queue: string;\n max_batch_size?: number;\n max_retries?: number;\n dead_letter_queue?: string;\n}\n\n/** Durable Object binding. `script_name` is for external DO references. */\nexport interface CloudflareDurableObjectBinding {\n name: string;\n class_name: string;\n script_name?: string;\n}\n\n/**\n * Declarative Cloudflare bindings configuration.\n *\n * These are converted to the appropriate wrangler.jsonc sections\n * (`kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, `durable_objects`).\n * The `wrangler` escape hatch overrides any generated binding sections\n * if there's a conflict.\n *\n * @example\n * ```ts\n * cloudflare({\n * bindings: {\n * kv: [{ name: 'TIMBER_CACHE' }],\n * d1: [{ name: 'MY_DB', database_id: 'xxxx' }],\n * r2: [{ name: 'MY_BUCKET', bucket_name: 'my-bucket' }],\n * queues: {\n * producers: [{ name: 'EMAIL_QUEUE', queue: 'email-queue' }],\n * consumers: [{ queue: 'email-queue', max_batch_size: 10 }],\n * },\n * durableObjects: [{ name: 'MY_DO', class_name: 'MyDurableObject' }],\n * },\n * })\n * ```\n */\nexport interface CloudflareBindings {\n kv?: CloudflareKVBinding[];\n d1?: CloudflareD1Binding[];\n r2?: CloudflareR2Binding[];\n queues?: {\n producers?: CloudflareQueueProducer[];\n consumers?: CloudflareQueueConsumer[];\n };\n durableObjects?: CloudflareDurableObjectBinding[];\n}\n\n/** Options for the Cloudflare Workers adapter. */\nexport interface CloudflareAdapterOptions {\n /**\n * Cloudflare compatibility date.\n * @default Current date in YYYY-MM-DD format at build time.\n */\n compatibilityDate?: string;\n\n /**\n * Additional compatibility flags.\n * @default ['nodejs_compat']\n */\n compatibilityFlags?: string[];\n\n /**\n * Declarative Cloudflare bindings. Generates the appropriate\n * `kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, and\n * `durable_objects` sections in wrangler.jsonc.\n *\n * If both `bindings` and `wrangler` specify the same section,\n * `wrangler` wins (it's the escape hatch).\n */\n bindings?: CloudflareBindings;\n\n /**\n * Custom wrangler.jsonc fields to merge.\n * Overrides generated values (including bindings-generated sections).\n */\n wrangler?: Record<string, unknown>;\n\n /**\n * Path to a module that exports additional Worker handlers (queue, scheduled, email, etc.).\n * The module is imported in the generated `_worker.js` and its named exports are\n * spread into the default export alongside `fetch`.\n *\n * The module receives `(batch/event, env, ctx)` — standard Cloudflare handler signatures.\n * It does NOT have access to timber's request pipeline (no ALS, no getCloudflareBindings).\n * Use `env` directly for bindings.\n *\n * @example\n * ```ts\n * // timber.config.ts\n * adapter: cloudflare({ workerHandlers: './src/worker-handlers.ts' })\n *\n * // src/worker-handlers.ts\n * export async function queue(batch, env) { ... }\n * export async function scheduled(controller, env, ctx) { ... }\n * ```\n */\n workerHandlers?: string;\n}\n\n/**\n * Create a Cloudflare Workers adapter.\n *\n * @example\n * ```ts\n * import { cloudflare } from '@timber-js/app/adapters/cloudflare'\n *\n * export default {\n * output: 'server',\n * adapter: cloudflare(),\n * }\n * ```\n */\nexport function cloudflare(options: CloudflareAdapterOptions = {}): TimberPlatformAdapter {\n return {\n name: 'cloudflare',\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'cloudflare');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'static',\n });\n\n // Compile optional worker handlers (queue, scheduled, etc.)\n // Uses Vite's build API to bundle the TypeScript source into ESM.\n let hasWorkerHandlers = false;\n if (options.workerHandlers) {\n const handlersEntry = join(process.cwd(), options.workerHandlers);\n const { build: viteBuild } = await import('vite');\n await viteBuild({\n configFile: false,\n logLevel: 'info',\n build: {\n lib: {\n entry: handlersEntry,\n formats: ['es'],\n fileName: () => '_worker-handlers.js',\n },\n outDir,\n emptyOutDir: false,\n minify: false,\n rollupOptions: {\n external: [/^node:/],\n },\n },\n });\n hasWorkerHandlers = true;\n }\n\n // Generate the Workers entry point\n const hasManifestInit = !!config.manifestInit;\n const workerEntry = generateWorkerEntry(outDir, outDir, hasManifestInit, hasWorkerHandlers);\n await writeFile(join(outDir, '_worker.js'), workerEntry);\n\n // Generate wrangler.jsonc\n const wranglerConfig = generateWranglerConfig(config, options);\n await writeFile(join(outDir, 'wrangler.jsonc'), JSON.stringify(wranglerConfig, null, 2));\n },\n\n async preview(_config: TimberConfig, buildDir: string) {\n const cmd = generatePreviewCommand(buildDir);\n await spawnPreviewProcess(cmd.command, cmd.args, cmd.cwd);\n },\n\n // No adapter-level waitUntil: on Workers there is no ambient\n // ExecutionContext outside a request, so support is provided\n // per-request by the generated _worker.js, which bridges\n // ctx.waitUntil() into the ALS via runWithWaitUntil().\n // See design/11-platform.md §\"waitUntil()\".\n };\n}\n\n// ─── Exported helpers (used by tests and build) ─────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateWorkerEntry(\n buildDir: string,\n outDir: string,\n hasManifestInit = false,\n hasWorkerHandlers = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let rscEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!rscEntryRelative.startsWith('.')) {\n rscEntryRelative = './' + rscEntryRelative;\n }\n\n // Build manifest init must be imported before the RSC handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Optional additional Worker handlers (queue, scheduled, email, etc.)\n // Compiled by buildOutput via Vite's build API into _worker-handlers.js.\n // The module's named exports are spread into the default export alongside fetch.\n const handlersImport = hasWorkerHandlers\n ? \"import * as workerHandlers from './_worker-handlers.js'\\n\"\n : '';\n const handlersSpread = hasWorkerHandlers ? ' ...workerHandlers,\\n' : '';\n\n return `// Generated by @timber-js/app/adapters/cloudflare\n// Do not edit — this file is regenerated on each build.\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${manifestImport}import handler, { runWithWaitUntil } from '${rscEntryRelative}'\n${handlersImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nglobalThis.process ??= { env: {} }\nprocess.env.TIMBER_RUNTIME = 'cloudflare'\n\n// Bind Cloudflare env to ALS so getCloudflareBindings() works at runtime.\n// Uses the same Symbol.for key as getCloudflareBindings() reads from.\nconst ALS_KEY = Symbol.for('timber:cf-bindings-als')\nlet bindingsAls = globalThis[ALS_KEY]\nif (!bindingsAls) {\n bindingsAls = new AsyncLocalStorage()\n globalThis[ALS_KEY] = bindingsAls\n}\n\nexport default {\n${handlersSpread} async fetch(request, env, ctx) {\n // Bridge ctx.waitUntil into the per-request ALS so waitUntil() calls in\n // user code keep the isolate alive after the response is sent.\n // See design/11-platform.md §\"waitUntil()\".\n return bindingsAls.run(env, () =>\n runWithWaitUntil((promise) => ctx.waitUntil(promise), () => handler(request))\n )\n }\n}\n`;\n}\n\n/** Wrangler binding sections generated from `CloudflareBindings`. */\nexport interface WranglerBindingsConfig {\n kv_namespaces?: Array<{ binding: string; id: string }>;\n d1_databases?: Array<{ binding: string; database_id: string }>;\n r2_buckets?: Array<{ binding: string; bucket_name: string }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<Record<string, unknown>>;\n };\n durable_objects?: {\n bindings: Array<Record<string, string>>;\n };\n}\n\n/**\n * Convert declarative `CloudflareBindings` into wrangler.jsonc binding sections.\n *\n * Maps:\n * - `kv` → `kv_namespaces`\n * - `d1` → `d1_databases`\n * - `r2` → `r2_buckets`\n * - `queues` → `queues` (producers + consumers)\n * - `durableObjects` → `durable_objects`\n *\n * Empty arrays are omitted from the output.\n *\n * @internal Exported for testing.\n */\nexport function generateBindingsConfig(\n bindings: CloudflareBindings | undefined\n): WranglerBindingsConfig {\n if (!bindings) return {};\n\n const result: WranglerBindingsConfig = {};\n\n // KV namespaces\n if (bindings.kv && bindings.kv.length > 0) {\n result.kv_namespaces = bindings.kv.map((kv) => ({\n binding: kv.name,\n id: kv.id ?? '',\n }));\n }\n\n // D1 databases\n if (bindings.d1 && bindings.d1.length > 0) {\n result.d1_databases = bindings.d1.map((d1) => ({\n binding: d1.name,\n database_id: d1.database_id,\n }));\n }\n\n // R2 buckets\n if (bindings.r2 && bindings.r2.length > 0) {\n result.r2_buckets = bindings.r2.map((r2) => ({\n binding: r2.name,\n bucket_name: r2.bucket_name,\n }));\n }\n\n // Queues (producers and/or consumers)\n if (bindings.queues) {\n const queues: Record<string, unknown> = {};\n if (bindings.queues.producers && bindings.queues.producers.length > 0) {\n queues.producers = bindings.queues.producers.map((p) => ({\n binding: p.name,\n queue: p.queue,\n }));\n }\n if (bindings.queues.consumers && bindings.queues.consumers.length > 0) {\n queues.consumers = bindings.queues.consumers.map((c) => {\n const consumer: Record<string, unknown> = { queue: c.queue };\n if (c.max_batch_size !== undefined) consumer.max_batch_size = c.max_batch_size;\n if (c.max_retries !== undefined) consumer.max_retries = c.max_retries;\n if (c.dead_letter_queue !== undefined) consumer.dead_letter_queue = c.dead_letter_queue;\n return consumer;\n });\n }\n if (Object.keys(queues).length > 0) {\n result.queues = queues;\n }\n }\n\n // Durable Objects\n if (bindings.durableObjects && bindings.durableObjects.length > 0) {\n result.durable_objects = {\n bindings: bindings.durableObjects.map((dobj) => {\n const entry: Record<string, string> = {\n name: dobj.name,\n class_name: dobj.class_name,\n };\n if (dobj.script_name) entry.script_name = dobj.script_name;\n return entry;\n }),\n };\n }\n\n return result;\n}\n\n/**\n * One-level deep merge: for each key in `override`, if both the base and\n * override values are plain objects (not arrays, not null), merge their\n * keys with override winning on conflicts. Everything else (primitives,\n * arrays, null) is replaced outright — matching the intuitive behavior\n * where `kv_namespaces: [...]` replaces fully but\n * `durable_objects: { migrations }` merges with generated `bindings`.\n */\nfunction shallowDeepMerge(\n base: Record<string, unknown>,\n override: Record<string, unknown>\n): Record<string, unknown> {\n const result = { ...base };\n for (const key of Object.keys(override)) {\n const baseVal = result[key];\n const overVal = override[key];\n if (isPlainObject(baseVal) && isPlainObject(overVal)) {\n result[key] = { ...baseVal, ...overVal };\n } else {\n result[key] = overVal;\n }\n }\n return result;\n}\n\n/** True for `{}` literals — false for arrays, null, Date, etc. */\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return val !== null && typeof val === 'object' && !Array.isArray(val);\n}\n\n/** @internal Exported for testing. */\nexport function generateWranglerConfig(\n config: TimberConfig,\n options: CloudflareAdapterOptions\n): Record<string, unknown> {\n const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);\n\n const flags = options.compatibilityFlags ?? ['nodejs_compat'];\n\n const base: Record<string, unknown> = {\n name: 'timber-app',\n main: '_worker.js',\n compatibility_date: compatDate,\n compatibility_flags: flags,\n // The build output is already fully bundled by Vite — skip wrangler's\n // esbuild pass to avoid issues with top-level await and module format.\n no_bundle: true,\n find_additional_modules: true,\n rules: [{ type: 'ESModule', globs: ['**/*.js'] }],\n assets: {\n directory: './static',\n },\n };\n\n // Layer 1: merge bindings-generated sections into base\n const bindingsConfig = generateBindingsConfig(options.bindings);\n const merged = { ...base, ...bindingsConfig };\n\n // Layer 2: wrangler escape hatch with deep merge for nested plain objects.\n // A shallow spread would replace entire sections like durable_objects and\n // queues — e.g. adding migrations via wrangler would drop the generated\n // durable_objects.bindings. Deep merge preserves generated keys while\n // letting wrangler override on actual key-level conflicts.\n if (options.wrangler) {\n return shallowDeepMerge(merged, options.wrangler);\n }\n\n return merged;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Command descriptor for preview — testable without spawning a process. */\nexport interface PreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generatePreviewCommand(buildDir: string): PreviewCommand {\n const cfDir = join(buildDir, 'cloudflare');\n return {\n command: 'wrangler',\n args: ['dev', '--local', '--config', join(cfDir, 'wrangler.jsonc')],\n cwd: cfDir,\n };\n}\n\n/**\n * Spawn a long-running preview process and pipe stdio to the parent.\n * Resolves when the process exits.\n */\nfunction spawnPreviewProcess(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Cloudflare Workers type stubs ───────────────────────────────────────────\n// Local type declarations so this file compiles without @cloudflare/workers-types.\n// These are NOT declared globally — that would clash with @cloudflare/workers-types\n// when users install it. Instead, they're module-scoped and used only within\n// this file's function signatures.\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n"],"mappings":";;;;;;AA0BA,IAAM,mBAAmB,OAAO,IAAI,wBAAwB;AAE5D,SAAS,iBAA6D;CACpE,IAAI,MAAO,WAAmB;CAG9B,IAAI,CAAC,KAAK;EACR,MAAM,IAAI,kBAA2C;EACrD,WAAoB,oBAAoB;CAC1C;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,wBAAwD;CACtE,MAAM,MAAM,eAAe,EAAE,SAAS;CACtC,IAAI,CAAC,KACH,MAAM,IAAI,MACR,kMAGF;CAEF,OAAO;AACT;;;;;AAMA,SAAgB,gBAAmB,KAA8B,IAAgB;CAC/E,OAAO,eAAe,EAAE,IAAI,KAAK,EAAE;AACrC;;;;;;;;;;;;;;AAiJA,SAAgB,WAAW,UAAoC,CAAC,GAA0B;CACxF,OAAO;EACL,MAAM;EAEN,MAAM,YAAY,QAAsB,UAAkB;GACxD,MAAM,SAAS,KAAK,UAAU,YAAY;GAI1C,MAAM,oBAAoB;IACxB;IACA;IACA;IACA,eAAe;GACjB,CAAC;GAID,IAAI,oBAAoB;GACxB,IAAI,QAAQ,gBAAgB;IAC1B,MAAM,gBAAgB,KAAK,QAAQ,IAAI,GAAG,QAAQ,cAAc;IAChE,MAAM,EAAE,OAAO,cAAc,MAAM,OAAO;IAC1C,MAAM,UAAU;KACd,YAAY;KACZ,UAAU;KACV,OAAO;MACL,KAAK;OACH,OAAO;OACP,SAAS,CAAC,IAAI;OACd,gBAAgB;MAClB;MACA;MACA,aAAa;MACb,QAAQ;MACR,eAAe,EACb,UAAU,CAAC,QAAQ,EACrB;KACF;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"file":"compress-module.d.ts","sourceRoot":"","sources":["../../src/adapters/compress-module.ts"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAyG/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,qBAAqB,EAAgB,MAAM,SAAS,CAAC;AAOnE;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,aAAa,GACb,SAAS,GACT,cAAc,GACd,YAAY,GACZ,aAAa,GACb,iBAAiB,GACjB,aAAa,GACb,KAAK,CAAC;AAEV,2CAA2C;AAC3C,UAAU,YAAY;IACpB,mDAAmD;IACnD,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sEAAsE;IACtE,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iFAAiF;IACjF,WAAW,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAgFD,qCAAqC;AACrC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,OAAO,GAAE,mBAAwB,GAAG,qBAAqB,CAwE9E;AAID,sCAAsC;AACtC,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,WAAW,EACnB,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M,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAgFD,qCAAqC;AACrC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,OAAO,GAAE,mBAAwB,GAAG,qBAAqB,CAwE9E;AAID,sCAAsC;AACtC,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,WAAW,EACnB,QAAQ,UAAO,EACf,eAAe,UAAQ,GACtB,MAAM,CAwFR;AAED,sCAAsC;AACtC,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACnC,MAAM,CA0BR;AAOD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CA+QnF;AAED,wEAAwE;AACxE,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,sCAAsC;AACtC,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,GAClB,mBAAmB,GAAG,IAAI,CAY5B;AA+DD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,YAAY,CAEjE"}
@@ -17,7 +17,7 @@ function generateCompressModule() {
17
17
  // Uses node:zlib createGzip() (C++ native) on Node.js, falls back to
18
18
  // CompressionStream (Web API) on other runtimes. Brotli is left to CDNs/reverse
19
19
  // proxies — at streaming quality levels its ratio advantage is marginal.
20
- import { Readable } from 'node:stream';
20
+ import { Readable, pipeline } from 'node:stream';
21
21
  import { createGzip, constants } from 'node:zlib';
22
22
 
23
23
  const COMPRESSIBLE_TYPES = new Set([
@@ -78,8 +78,14 @@ function compressWithGzip(body) {
78
78
  // receives the HTML shell before Suspense boundaries resolve. Without it,
79
79
  // gzip buffers internally and breaks streaming.
80
80
  const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
81
- const compressed = nodeReadable.pipe(gzip);
82
- return Readable.toWeb(compressed);
81
+ // pipeline() instead of bare pipe(): pipe() does not forward source
82
+ // errors, so an erroring body would emit an unhandled 'error' event and
83
+ // crash the process. pipeline() destroys gzip on source error — the web
84
+ // stream rejects — and propagates consumer cancel back to the source
85
+ // body. Errors reach the consumer via the web stream; the callback only
86
+ // marks them handled at the Node layer.
87
+ pipeline(nodeReadable, gzip, () => {});
88
+ return Readable.toWeb(gzip);
83
89
  } catch {
84
90
  // Fallback: CompressionStream (CF Workers, or if node:stream unavailable)
85
91
  return body.pipeThrough(new CompressionStream('gzip'));
@@ -402,7 +408,14 @@ const host = process.env.HOST || process.env.HOSTNAME || 'localhost';
402
408
  let boundPort = startPort;
403
409
 
404
410
  const server = createServer(async (req, res) => {
405
- const url = new URL(req.url || '/', \`http://\${host}:\${boundPort}\`);
411
+ // Scheme from the socket's TLS state — a hardcoded http:// breaks CSRF
412
+ // origin comparison and absolute-URL construction when TLS is terminated
413
+ // at this server (TIM-1073; mirrors the dev-server fix in TIM-1067).
414
+ // X-Forwarded-Proto is intentionally not consulted here: on a direct
415
+ // connection it would be attacker-controlled. The CSRF layer honors it
416
+ // separately for reverse-proxy deployments.
417
+ const scheme = req.socket?.encrypted ? 'https' : 'http';
418
+ const url = new URL(req.url || '/', \`\${scheme}://\${host}:\${boundPort}\`);
406
419
 
407
420
  // Try serving static files from the public directory first.
408
421
  const filePath = join(publicDir, url.pathname);
@@ -488,7 +501,7 @@ const server = createServer(async (req, res) => {
488
501
  // is silently dropped: defineCookie().setCookie() in actions, middleware
489
502
  // cookie writes, the framework's own session cookies, all of it. See
490
503
  // LOCAL-741.
491
- const responseHeaders: Record<string, string | string[]> = {};
504
+ const responseHeaders = {};
492
505
  webResponse.headers.forEach((value, key) => {
493
506
  if (key.toLowerCase() !== 'set-cookie') {
494
507
  responseHeaders[key] = value;