@rangojs/router 0.0.0-experimental.dfdb0387 → 0.0.0-experimental.e16b7c00

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 (237) hide show
  1. package/README.md +120 -25
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/vite/index.js +2106 -842
  4. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  5. package/package.json +13 -8
  6. package/skills/breadcrumbs/SKILL.md +3 -1
  7. package/skills/bundle-analysis/SKILL.md +159 -0
  8. package/skills/cache-guide/SKILL.md +222 -30
  9. package/skills/caching/SKILL.md +188 -8
  10. package/skills/composability/SKILL.md +27 -2
  11. package/skills/document-cache/SKILL.md +78 -55
  12. package/skills/handler-use/SKILL.md +364 -0
  13. package/skills/hooks/SKILL.md +229 -20
  14. package/skills/host-router/SKILL.md +45 -20
  15. package/skills/i18n/SKILL.md +276 -0
  16. package/skills/intercept/SKILL.md +46 -4
  17. package/skills/layout/SKILL.md +28 -7
  18. package/skills/links/SKILL.md +247 -17
  19. package/skills/loader/SKILL.md +219 -9
  20. package/skills/middleware/SKILL.md +47 -12
  21. package/skills/migrate-nextjs/SKILL.md +582 -0
  22. package/skills/migrate-react-router/SKILL.md +769 -0
  23. package/skills/mime-routes/SKILL.md +27 -0
  24. package/skills/observability/SKILL.md +137 -0
  25. package/skills/parallel/SKILL.md +71 -6
  26. package/skills/prerender/SKILL.md +14 -33
  27. package/skills/rango/SKILL.md +236 -22
  28. package/skills/react-compiler/SKILL.md +168 -0
  29. package/skills/response-routes/SKILL.md +66 -9
  30. package/skills/route/SKILL.md +57 -4
  31. package/skills/router-setup/SKILL.md +3 -3
  32. package/skills/server-actions/SKILL.md +751 -0
  33. package/skills/streams-and-websockets/SKILL.md +283 -0
  34. package/skills/typesafety/SKILL.md +319 -27
  35. package/skills/use-cache/SKILL.md +36 -5
  36. package/skills/view-transitions/SKILL.md +294 -0
  37. package/src/__augment-tests__/augment.ts +81 -0
  38. package/src/__augment-tests__/augmented.check.ts +117 -0
  39. package/src/browser/action-coordinator.ts +53 -36
  40. package/src/browser/app-shell.ts +52 -0
  41. package/src/browser/event-controller.ts +86 -70
  42. package/src/browser/history-state.ts +21 -0
  43. package/src/browser/index.ts +3 -3
  44. package/src/browser/navigation-bridge.ts +86 -11
  45. package/src/browser/navigation-client.ts +45 -25
  46. package/src/browser/navigation-store.ts +32 -9
  47. package/src/browser/navigation-transaction.ts +10 -28
  48. package/src/browser/partial-update.ts +61 -28
  49. package/src/browser/prefetch/cache.ts +124 -26
  50. package/src/browser/prefetch/fetch.ts +129 -37
  51. package/src/browser/prefetch/queue.ts +36 -5
  52. package/src/browser/rango-state.ts +53 -13
  53. package/src/browser/react/Link.tsx +18 -13
  54. package/src/browser/react/NavigationProvider.tsx +72 -31
  55. package/src/browser/react/filter-segment-order.ts +51 -7
  56. package/src/browser/react/index.ts +3 -0
  57. package/src/browser/react/location-state-shared.ts +175 -4
  58. package/src/browser/react/location-state.ts +39 -13
  59. package/src/browser/react/use-handle.ts +17 -9
  60. package/src/browser/react/use-navigation.ts +22 -2
  61. package/src/browser/react/use-params.ts +20 -8
  62. package/src/browser/react/use-reverse.ts +106 -0
  63. package/src/browser/react/use-router.ts +22 -2
  64. package/src/browser/react/use-segments.ts +11 -8
  65. package/src/browser/response-adapter.ts +25 -0
  66. package/src/browser/rsc-router.tsx +64 -22
  67. package/src/browser/scroll-restoration.ts +22 -14
  68. package/src/browser/segment-reconciler.ts +10 -14
  69. package/src/browser/segment-structure-assert.ts +2 -2
  70. package/src/browser/server-action-bridge.ts +23 -30
  71. package/src/browser/types.ts +21 -0
  72. package/src/build/collect-fallback-refs.ts +107 -0
  73. package/src/build/generate-manifest.ts +60 -35
  74. package/src/build/generate-route-types.ts +2 -0
  75. package/src/build/index.ts +2 -0
  76. package/src/build/route-trie.ts +52 -25
  77. package/src/build/route-types/codegen.ts +4 -4
  78. package/src/build/route-types/include-resolution.ts +1 -1
  79. package/src/build/route-types/per-module-writer.ts +7 -4
  80. package/src/build/route-types/router-processing.ts +55 -14
  81. package/src/build/route-types/scan-filter.ts +1 -1
  82. package/src/build/route-types/source-scan.ts +118 -0
  83. package/src/build/runtime-discovery.ts +9 -20
  84. package/src/cache/cache-error.ts +104 -0
  85. package/src/cache/cache-policy.ts +95 -1
  86. package/src/cache/cache-runtime.ts +79 -13
  87. package/src/cache/cache-scope.ts +77 -46
  88. package/src/cache/cache-tag.ts +135 -0
  89. package/src/cache/cf/cf-cache-store.ts +1067 -176
  90. package/src/cache/cf/index.ts +4 -1
  91. package/src/cache/document-cache.ts +59 -7
  92. package/src/cache/index.ts +6 -0
  93. package/src/cache/memory-segment-store.ts +158 -14
  94. package/src/cache/tag-invalidation.ts +206 -0
  95. package/src/cache/types.ts +27 -0
  96. package/src/client.rsc.tsx +3 -0
  97. package/src/client.tsx +92 -182
  98. package/src/context-var.ts +5 -5
  99. package/src/decode-loader-results.ts +36 -0
  100. package/src/errors.ts +30 -1
  101. package/src/handle.ts +4 -6
  102. package/src/host/index.ts +2 -2
  103. package/src/host/router.ts +129 -57
  104. package/src/host/types.ts +31 -2
  105. package/src/host/utils.ts +1 -1
  106. package/src/href-client.ts +140 -20
  107. package/src/index.rsc.ts +16 -4
  108. package/src/index.ts +65 -15
  109. package/src/loader-store.ts +500 -0
  110. package/src/loader.rsc.ts +2 -5
  111. package/src/loader.ts +3 -10
  112. package/src/missing-id-error.ts +68 -0
  113. package/src/outlet-context.ts +1 -1
  114. package/src/prerender.ts +4 -4
  115. package/src/response-utils.ts +37 -0
  116. package/src/reverse.ts +65 -36
  117. package/src/route-content-wrapper.tsx +6 -28
  118. package/src/route-definition/dsl-helpers.ts +384 -257
  119. package/src/route-definition/helper-factories.ts +29 -139
  120. package/src/route-definition/helpers-types.ts +100 -28
  121. package/src/route-definition/resolve-handler-use.ts +6 -0
  122. package/src/route-definition/use-item-types.ts +32 -0
  123. package/src/route-types.ts +26 -41
  124. package/src/router/content-negotiation.ts +15 -2
  125. package/src/router/error-handling.ts +1 -1
  126. package/src/router/handler-context.ts +21 -38
  127. package/src/router/intercept-resolution.ts +4 -18
  128. package/src/router/lazy-includes.ts +8 -8
  129. package/src/router/loader-resolution.ts +19 -2
  130. package/src/router/manifest.ts +22 -13
  131. package/src/router/match-api.ts +4 -3
  132. package/src/router/match-handlers.ts +1 -0
  133. package/src/router/match-middleware/cache-lookup.ts +46 -92
  134. package/src/router/match-middleware/cache-store.ts +3 -2
  135. package/src/router/match-result.ts +53 -32
  136. package/src/router/metrics.ts +1 -1
  137. package/src/router/middleware-types.ts +15 -26
  138. package/src/router/middleware.ts +99 -84
  139. package/src/router/pattern-matching.ts +101 -17
  140. package/src/router/prerender-match.ts +3 -1
  141. package/src/router/preview-match.ts +3 -1
  142. package/src/router/request-classification.ts +4 -28
  143. package/src/router/revalidation.ts +58 -2
  144. package/src/router/router-interfaces.ts +45 -28
  145. package/src/router/router-options.ts +25 -1
  146. package/src/router/router-registry.ts +2 -5
  147. package/src/router/segment-resolution/fresh.ts +27 -6
  148. package/src/router/segment-resolution/loader-cache.ts +8 -17
  149. package/src/router/segment-resolution/revalidation.ts +147 -106
  150. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  151. package/src/router/substitute-pattern-params.ts +56 -0
  152. package/src/router/trie-matching.ts +18 -13
  153. package/src/router/types.ts +8 -0
  154. package/src/router/url-params.ts +49 -0
  155. package/src/router.ts +23 -18
  156. package/src/rsc/handler-context.ts +2 -2
  157. package/src/rsc/handler.ts +38 -70
  158. package/src/rsc/helpers.ts +72 -43
  159. package/src/rsc/index.ts +1 -1
  160. package/src/rsc/origin-guard.ts +28 -10
  161. package/src/rsc/progressive-enhancement.ts +4 -0
  162. package/src/rsc/response-route-handler.ts +54 -54
  163. package/src/rsc/rsc-rendering.ts +35 -51
  164. package/src/rsc/runtime-warnings.ts +9 -10
  165. package/src/rsc/server-action.ts +17 -37
  166. package/src/rsc/ssr-setup.ts +16 -0
  167. package/src/rsc/types.ts +8 -2
  168. package/src/search-params.ts +4 -4
  169. package/src/segment-content-promise.ts +67 -0
  170. package/src/segment-loader-promise.ts +122 -0
  171. package/src/segment-system.tsx +132 -116
  172. package/src/serialize.ts +243 -0
  173. package/src/server/context.ts +143 -53
  174. package/src/server/cookie-store.ts +28 -4
  175. package/src/server/request-context.ts +46 -44
  176. package/src/ssr/index.tsx +5 -1
  177. package/src/static-handler.ts +1 -1
  178. package/src/types/cache-types.ts +13 -4
  179. package/src/types/error-types.ts +5 -1
  180. package/src/types/global-namespace.ts +39 -26
  181. package/src/types/handler-context.ts +68 -50
  182. package/src/types/index.ts +1 -0
  183. package/src/types/loader-types.ts +5 -6
  184. package/src/types/request-scope.ts +126 -0
  185. package/src/types/route-entry.ts +11 -0
  186. package/src/types/segments.ts +35 -2
  187. package/src/urls/include-helper.ts +34 -67
  188. package/src/urls/index.ts +0 -3
  189. package/src/urls/path-helper-types.ts +41 -7
  190. package/src/urls/path-helper.ts +17 -52
  191. package/src/urls/pattern-types.ts +36 -19
  192. package/src/urls/response-types.ts +22 -29
  193. package/src/urls/type-extraction.ts +26 -116
  194. package/src/urls/urls-function.ts +1 -5
  195. package/src/use-loader.tsx +413 -42
  196. package/src/vite/debug.ts +185 -0
  197. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  198. package/src/vite/discovery/discover-routers.ts +101 -51
  199. package/src/vite/discovery/discovery-errors.ts +194 -0
  200. package/src/vite/discovery/gate-state.ts +171 -0
  201. package/src/vite/discovery/prerender-collection.ts +67 -26
  202. package/src/vite/discovery/route-types-writer.ts +40 -84
  203. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  204. package/src/vite/discovery/state.ts +33 -0
  205. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  206. package/src/vite/index.ts +2 -0
  207. package/src/vite/plugin-types.ts +67 -0
  208. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  209. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  210. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  211. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  212. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  213. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  214. package/src/vite/plugins/expose-action-id.ts +54 -30
  215. package/src/vite/plugins/expose-id-utils.ts +12 -8
  216. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  217. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  218. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  219. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  220. package/src/vite/plugins/expose-internal-ids.ts +496 -486
  221. package/src/vite/plugins/performance-tracks.ts +29 -25
  222. package/src/vite/plugins/use-cache-transform.ts +65 -50
  223. package/src/vite/plugins/version-injector.ts +39 -23
  224. package/src/vite/plugins/version-plugin.ts +59 -2
  225. package/src/vite/plugins/virtual-entries.ts +2 -2
  226. package/src/vite/rango.ts +116 -29
  227. package/src/vite/router-discovery.ts +750 -100
  228. package/src/vite/utils/ast-handler-extract.ts +15 -15
  229. package/src/vite/utils/banner.ts +1 -1
  230. package/src/vite/utils/bundle-analysis.ts +4 -2
  231. package/src/vite/utils/client-chunks.ts +190 -0
  232. package/src/vite/utils/forward-user-plugins.ts +193 -0
  233. package/src/vite/utils/manifest-utils.ts +21 -5
  234. package/src/vite/utils/package-resolution.ts +41 -1
  235. package/src/vite/utils/prerender-utils.ts +21 -6
  236. package/src/vite/utils/shared-utils.ts +107 -26
  237. package/src/browser/action-response-classifier.ts +0 -99
@@ -15,6 +15,7 @@ import {
15
15
  import ts from "typescript";
16
16
  import { generateRouteTypesSource } from "./codegen.js";
17
17
  import type { ScanFilter } from "./scan-filter.js";
18
+ import { firstCodeMatchIndex } from "./source-scan.js";
18
19
  import {
19
20
  resolveImportedVariable,
20
21
  resolveImportPath,
@@ -38,6 +39,8 @@ function countPublicRouteEntries(source: string): number {
38
39
  }
39
40
 
40
41
  const ROUTER_CALL_PATTERN = /\bcreateRouter\s*[<(]/;
42
+ // Global variant for the code-region scan (firstCodeMatchIndex sets lastIndex).
43
+ const ROUTER_CALL_PATTERN_G = /\bcreateRouter\s*[<(]/g;
41
44
 
42
45
  function isRoutableSourceFile(name: string): boolean {
43
46
  return (
@@ -61,7 +64,7 @@ function findRouterFilesRecursive(
61
64
  entries = readdirSync(dir, { withFileTypes: true });
62
65
  } catch (err) {
63
66
  console.warn(
64
- `[rsc-router] Failed to scan directory ${dir}: ${(err as Error).message}`,
67
+ `[rango] Failed to scan directory ${dir}: ${(err as Error).message}`,
65
68
  );
66
69
  return;
67
70
  }
@@ -90,7 +93,17 @@ function findRouterFilesRecursive(
90
93
 
91
94
  try {
92
95
  const source = readFileSync(fullPath, "utf-8");
93
- if (ROUTER_CALL_PATTERN.test(source)) {
96
+ // Fast path: most files contain no `createRouter(` at all, so the cheap
97
+ // raw regex short-circuits before the code-region scan. Only a file that
98
+ // mentions the token (real call OR a comment/string mention) is rescanned
99
+ // over code regions — allocation-free, never building a stripped copy —
100
+ // so a mention inside a comment or string is not mistaken for a real
101
+ // router file (which previously triggered a spurious "Multiple routers
102
+ // found" error).
103
+ if (
104
+ ROUTER_CALL_PATTERN.test(source) &&
105
+ firstCodeMatchIndex(source, ROUTER_CALL_PATTERN_G) >= 0
106
+ ) {
94
107
  routerFilesInDir.push(fullPath);
95
108
  }
96
109
  } catch {
@@ -142,7 +155,7 @@ export function findNestedRouterConflict(
142
155
 
143
156
  export function formatNestedRouterConflictError(
144
157
  conflict: { ancestor: string; nested: string },
145
- prefix = "[rsc-router]",
158
+ prefix = "[rango]",
146
159
  ): string {
147
160
  return (
148
161
  `${prefix} Nested router roots are not supported.\n` +
@@ -339,6 +352,36 @@ function applyBasenameToRoutes(
339
352
  return { routes: prefixed, searchSchemas: result.searchSchemas };
340
353
  }
341
354
 
355
+ // Filesystem path of the generated route-types file for a router source file.
356
+ // Native separators — matches the self-gen-tracking Map key the watcher compares.
357
+ export function genFileTsPath(sourceFile: string): string {
358
+ const base = pathBasename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
359
+ return join(dirname(sourceFile), `${base}.named-routes.gen.ts`);
360
+ }
361
+
362
+ // Search schemas for the gen file: prefer the runtime manifest's; when it omits
363
+ // them (some module-runner flows) fall back to static parsing filtered to the
364
+ // public route-name set. Returns the runtime value unchanged otherwise.
365
+ export function resolveSearchSchemas(
366
+ publicRouteNames: string[],
367
+ runtimeSchemas: Record<string, Record<string, string>> | undefined,
368
+ sourceFile: string,
369
+ ): Record<string, Record<string, string>> | undefined {
370
+ if (runtimeSchemas && Object.keys(runtimeSchemas).length > 0) {
371
+ return runtimeSchemas;
372
+ }
373
+ const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
374
+ if (Object.keys(staticParsed.searchSchemas).length === 0) {
375
+ return runtimeSchemas;
376
+ }
377
+ const filtered: Record<string, Record<string, string>> = {};
378
+ for (const name of publicRouteNames) {
379
+ const schema = staticParsed.searchSchemas[name];
380
+ if (schema) filtered[name] = schema;
381
+ }
382
+ return Object.keys(filtered).length > 0 ? filtered : runtimeSchemas;
383
+ }
384
+
342
385
  /**
343
386
  * Resolve routes and search schemas from a router source file by following the
344
387
  * variable passed to `.routes(...)` or `urls: ...` in createRouter options,
@@ -528,7 +571,10 @@ export function findRouterFiles(root: string, filter?: ScanFilter): string[] {
528
571
  export function writeCombinedRouteTypes(
529
572
  root: string,
530
573
  knownRouterFiles?: string[],
531
- opts?: { preserveIfLarger?: boolean },
574
+ opts?: {
575
+ preserveIfLarger?: boolean;
576
+ onWrite?: (outPath: string, content: string) => void;
577
+ },
532
578
  ): void {
533
579
  // Delete old combined named-routes.gen.ts if it exists (stale from older versions)
534
580
  try {
@@ -536,7 +582,7 @@ export function writeCombinedRouteTypes(
536
582
  if (existsSync(oldCombinedPath)) {
537
583
  unlinkSync(oldCombinedPath);
538
584
  console.log(
539
- `[rsc-router] Removed stale combined route types: ${oldCombinedPath}`,
585
+ `[rango] Removed stale combined route types: ${oldCombinedPath}`,
540
586
  );
541
587
  }
542
588
  } catch {}
@@ -566,14 +612,7 @@ export function writeCombinedRouteTypes(
566
612
  if (!extractUrlsFromRouter(routerSource)) continue;
567
613
  }
568
614
 
569
- const routerBasename = pathBasename(routerFilePath).replace(
570
- /\.(tsx?|jsx?)$/,
571
- "",
572
- );
573
- const outPath = join(
574
- dirname(routerFilePath),
575
- `${routerBasename}.named-routes.gen.ts`,
576
- );
615
+ const outPath = genFileTsPath(routerFilePath);
577
616
  const existing = existsSync(outPath)
578
617
  ? readFileSync(outPath, "utf-8")
579
618
  : null;
@@ -584,6 +623,7 @@ export function writeCombinedRouteTypes(
584
623
  if (Object.keys(result.routes).length === 0) {
585
624
  if (!existing) {
586
625
  const emptySource = generateRouteTypesSource({});
626
+ opts?.onWrite?.(outPath, emptySource);
587
627
  writeFileSync(outPath, emptySource);
588
628
  }
589
629
  continue;
@@ -609,9 +649,10 @@ export function writeCombinedRouteTypes(
609
649
  continue;
610
650
  }
611
651
  }
652
+ opts?.onWrite?.(outPath, source);
612
653
  writeFileSync(outPath, source);
613
654
  console.log(
614
- `[rsc-router] Generated route types (${Object.keys(result.routes).length} routes) -> ${outPath}`,
655
+ `[rango] Generated route types (${Object.keys(result.routes).length} routes) -> ${outPath}`,
615
656
  );
616
657
  }
617
658
  }
@@ -54,7 +54,7 @@ export function findTsFiles(dir: string, filter?: ScanFilter): string[] {
54
54
  entries = readdirSync(dir, { withFileTypes: true });
55
55
  } catch (err) {
56
56
  console.warn(
57
- `[rsc-router] Failed to scan directory ${dir}: ${(err as Error).message}`,
57
+ `[rango] Failed to scan directory ${dir}: ${(err as Error).message}`,
58
58
  );
59
59
  return results;
60
60
  }
@@ -0,0 +1,118 @@
1
+ // Allocation-light, linear-time source scanning for the build-time scanners.
2
+ //
3
+ // The router-file scanner, the HMR relevance check, and the unsupported-shape
4
+ // warning all need to know whether a token like `createRouter(` / `createLoader(`
5
+ // appears in REAL code versus inside a comment or string literal. Rather than
6
+ // build a full comment/string-stripped copy of the source (which on a large
7
+ // file allocates an O(n) string plus, naively, a per-char array), these helpers
8
+ // run the regex over the whole source ONCE (the engine sweeps left-to-right,
9
+ // O(n)) and classify each match's offset with a forward, O(1)-memory cursor that
10
+ // advances monotonically across the source.
11
+ //
12
+ // Time: O(n) — one native regex sweep plus one forward classification pass.
13
+ // Memory: O(1) for the boolean check; O(#matches) for the index list. No
14
+ // stripped copy and no per-char array are ever materialized.
15
+ //
16
+ // Pragmatic scanner, not a full tokenizer: regex literals are not special-cased
17
+ // (a target token inside one is implausible) and template interpolations are
18
+ // treated as opaque string content. One intentional consequence: a token whose
19
+ // match would only complete by treating an interleaved comment as whitespace
20
+ // (e.g. `createRouter /* x */ (`) is not detected — real calls never interleave
21
+ // a comment between the callee and its arguments.
22
+
23
+ // JS line terminators end a `//` comment: LF, CR, LS (U+2028), PS (U+2029).
24
+ function isLineTerminator(ch: string): boolean {
25
+ const c = ch.charCodeAt(0);
26
+ // LF, CR, LS (U+2028), PS (U+2029)
27
+ return c === 10 || c === 13 || c === 0x2028 || c === 0x2029;
28
+ }
29
+
30
+ /**
31
+ * Build a classifier that answers "is offset `q` in code (not a comment or
32
+ * string)?" for STRICTLY INCREASING `q`. The internal cursor only moves forward,
33
+ * so a full left-to-right sequence of queries costs O(n) total with O(1) memory.
34
+ */
35
+ function makeCodeClassifier(code: string): (q: number) => boolean {
36
+ const n = code.length;
37
+ let i = 0; // forward cursor: everything before `i` is already classified
38
+ let skipStart = -1; // last detected comment/string region (cache)
39
+ let skipEnd = -1;
40
+
41
+ return (q: number): boolean => {
42
+ if (q >= skipStart && q < skipEnd) return false; // q in the cached region
43
+ while (i < n && i <= q) {
44
+ const c = code[i];
45
+ const d = i + 1 < n ? code[i + 1] : "";
46
+ let end = -1;
47
+ if (c === "/" && d === "/") {
48
+ let j = i + 2;
49
+ while (j < n && !isLineTerminator(code[j])) j++;
50
+ end = j;
51
+ } else if (c === "/" && d === "*") {
52
+ let j = i + 2;
53
+ while (j < n && !(code[j] === "*" && code[j + 1] === "/")) j++;
54
+ end = Math.min(n, j + 2);
55
+ } else if (c === '"' || c === "'" || c === "`") {
56
+ let j = i + 1;
57
+ while (j < n) {
58
+ if (code[j] === "\\") {
59
+ j += 2;
60
+ continue;
61
+ }
62
+ if (code[j] === c) {
63
+ j++;
64
+ break;
65
+ }
66
+ j++;
67
+ }
68
+ end = j;
69
+ }
70
+ if (end >= 0) {
71
+ // Comment/string region [i, end). `q >= i` here (loop condition).
72
+ if (q < end) {
73
+ skipStart = i;
74
+ skipEnd = end;
75
+ return false;
76
+ }
77
+ i = end;
78
+ } else {
79
+ i++;
80
+ }
81
+ }
82
+ return true; // reached q in code mode
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Index of the first match of `pattern` that occurs in code (not in a comment
88
+ * or string), or -1. `pattern` MUST be a global (`/g`) regex. Single native
89
+ * regex sweep with early-exit; O(1) extra memory.
90
+ */
91
+ export function firstCodeMatchIndex(code: string, pattern: RegExp): number {
92
+ const inCode = makeCodeClassifier(code);
93
+ pattern.lastIndex = 0;
94
+ let m: RegExpExecArray | null;
95
+ while ((m = pattern.exec(code)) !== null) {
96
+ if (inCode(m.index)) return m.index;
97
+ if (pattern.lastIndex <= m.index) pattern.lastIndex = m.index + 1;
98
+ }
99
+ return -1;
100
+ }
101
+
102
+ /**
103
+ * Byte offsets of every match of `pattern` that occurs in code (not in a
104
+ * comment or string). `pattern` MUST be a global (`/g`) regex. Each offset is
105
+ * the match start — the same byte offset a raw `pattern.exec` reports. O(n)
106
+ * time, O(#matches) memory.
107
+ */
108
+ export function codeMatchIndices(code: string, pattern: RegExp): number[] {
109
+ const inCode = makeCodeClassifier(code);
110
+ const indices: number[] = [];
111
+ pattern.lastIndex = 0;
112
+ let m: RegExpExecArray | null;
113
+ while ((m = pattern.exec(code)) !== null) {
114
+ if (inCode(m.index)) indices.push(m.index);
115
+ if (pattern.lastIndex <= m.index) pattern.lastIndex = m.index + 1;
116
+ }
117
+ return indices;
118
+ }
@@ -1,8 +1,9 @@
1
- import { dirname, join, basename, resolve } from "node:path";
1
+ import { resolve } from "node:path";
2
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import {
4
4
  generateRouteTypesSource,
5
- buildCombinedRouteMapForRouterFile,
5
+ genFileTsPath,
6
+ resolveSearchSchemas,
6
7
  } from "./generate-route-types.ts";
7
8
  import { isAutoGeneratedRouteName } from "../route-name.js";
8
9
 
@@ -175,25 +176,13 @@ export async function discoverAndWriteRouteTypes(
175
176
  );
176
177
  }
177
178
 
178
- // Search schema fallback: runtime manifest may omit search schema metadata
179
- // in some module-runner flows. Fall back to static source parsing.
180
- if (!routeSearchSchemas || Object.keys(routeSearchSchemas).length === 0) {
181
- const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
182
- if (Object.keys(staticParsed.searchSchemas).length > 0) {
183
- const filtered: Record<string, Record<string, string>> = {};
184
- for (const name of Object.keys(routeManifest)) {
185
- const schema = staticParsed.searchSchemas[name];
186
- if (schema) filtered[name] = schema;
187
- }
188
- if (Object.keys(filtered).length > 0) {
189
- routeSearchSchemas = filtered;
190
- }
191
- }
192
- }
179
+ routeSearchSchemas = resolveSearchSchemas(
180
+ Object.keys(routeManifest),
181
+ routeSearchSchemas,
182
+ sourceFile,
183
+ );
193
184
 
194
- const routerDir = dirname(sourceFile);
195
- const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
196
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
185
+ const outPath = genFileTsPath(sourceFile);
197
186
 
198
187
  const source = generateRouteTypesSource(
199
188
  routeManifest,
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Cache error reporting.
3
+ *
4
+ * Caches are best-effort: a read failure degrades to a miss (render fresh) and a
5
+ * write failure degrades to a no-op - they MUST NOT throw up and fail the
6
+ * request. But the failure must still be LOUD: it is logged to the console (so
7
+ * it is visible even in a background waitUntil task or when no hook is wired)
8
+ * AND routed through the router's onError callback (via the request context's
9
+ * deduped _reportBackgroundError) so consumers can observe cache degradation in
10
+ * their own telemetry.
11
+ *
12
+ * The one deliberate exception is the invalidation WRITE verb (updateTag ->
13
+ * store.invalidateTags): a failed durable marker write is rejected so an awaited
14
+ * updateTag() surfaces it (read-your-own-writes honesty). That is not a data
15
+ * read/write and does not go through this helper's swallow-and-degrade path.
16
+ */
17
+
18
+ import { _getRequestContext } from "../server/request-context.js";
19
+
20
+ /**
21
+ * Minimal shape of a request context for error reporting. Passed explicitly by
22
+ * background tasks (waitUntil) where the ALS context is already gone, so the
23
+ * error can still reach the router's onError. Structural to avoid importing the
24
+ * full RequestContext type (request-context.ts imports CacheErrorCategory from
25
+ * here - a mutual type-only reference).
26
+ */
27
+ export interface CacheErrorReporter {
28
+ _reportBackgroundError?: (
29
+ error: unknown,
30
+ category: CacheErrorCategory,
31
+ ) => void;
32
+ }
33
+
34
+ export type CacheErrorCategory =
35
+ /** A read failed (transient infra: KV/Cache API error). Degrade to a miss. */
36
+ | "cache-read"
37
+ /** A write failed. Degrade to a no-op (entry simply not cached). */
38
+ | "cache-write"
39
+ /** A delete/eviction failed. Best-effort. */
40
+ | "cache-delete"
41
+ /**
42
+ * A STORED entry could not be parsed/deserialized (partial KV read, truncated
43
+ * Cache API body, malformed envelope/RSC payload). The entry is faulty and is
44
+ * evicted so subsequent reads do not keep failing on it. Distinct from
45
+ * cache-read so consumers can tell corruption from a transient outage.
46
+ */
47
+ | "cache-corrupt"
48
+ /** A tag-invalidation side effect failed (e.g. the eager CDN purge hook). */
49
+ | "cache-invalidate"
50
+ /**
51
+ * A background stale-while-revalidate refresh failed (the `"use cache"`
52
+ * read-through path). The stale value was already served; the refresh that
53
+ * would have replaced it errored.
54
+ */
55
+ | "stale-revalidation";
56
+
57
+ /**
58
+ * Report a non-fatal cache error loudly without failing the request: always logs
59
+ * (label + error) and, when a request context is available, routes the error
60
+ * through the router's onError callback. Never throws.
61
+ *
62
+ * `ctx` is for callers running in a detached background task (waitUntil), where
63
+ * the ALS request context is already gone (so `_getRequestContext()` is null):
64
+ * they capture the context up front and pass it here so onError still fires.
65
+ * Foreground callers omit it and fall back to the ALS context.
66
+ */
67
+ export function reportCacheError(
68
+ error: unknown,
69
+ category: CacheErrorCategory,
70
+ label: string,
71
+ ctx?: CacheErrorReporter,
72
+ ): void {
73
+ console.error(`${label}:`, error);
74
+ try {
75
+ const target = ctx ?? _getRequestContext();
76
+ target?._reportBackgroundError?.(error, category);
77
+ } catch {
78
+ // Reporting must never itself break the cache path.
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Run a best-effort async cache task (typically scheduled via waitUntil), catching
84
+ * any rejection and routing it through reportCacheError so background cache work
85
+ * (non-blocking L1 writes, KV persistence, L1 promotion) reports failures via
86
+ * onError instead of throwing or silently swallowing. Never rejects.
87
+ *
88
+ * Pass `ctx` when the task runs detached (the ALS context is gone) and the
89
+ * failure should still reach onError; omit it to fall back to the ALS context.
90
+ *
91
+ * @example this.waitUntil(() => reportingAsync(() => cache.put(req, res), "cache-write", "[CFCacheStore] L1 write"))
92
+ */
93
+ export async function reportingAsync(
94
+ task: () => Promise<unknown>,
95
+ category: CacheErrorCategory,
96
+ label: string,
97
+ ctx?: CacheErrorReporter,
98
+ ): Promise<void> {
99
+ try {
100
+ await task();
101
+ } catch (error) {
102
+ reportCacheError(error, category, label, ctx);
103
+ }
104
+ }
@@ -9,6 +9,7 @@
9
9
  import type { CacheDefaults, SegmentCacheStore } from "./types.js";
10
10
  import { _getRequestContext } from "../server/request-context.js";
11
11
  import type { RequestContext } from "../server/request-context.js";
12
+ import { normalizeTags } from "./cache-tag.js";
12
13
 
13
14
  /**
14
15
  * Default TTL for route-level cache() DSL and loader cache.
@@ -108,6 +109,64 @@ export async function resolveCacheKey(
108
109
  return defaultKey;
109
110
  }
110
111
 
112
+ // ============================================================================
113
+ // Cache Tag Resolution
114
+ // ============================================================================
115
+
116
+ /**
117
+ * Resolve cache tags from a tags option (static array or function of ctx).
118
+ *
119
+ * Fails open: a thrown tag callback falls back to no tags rather than
120
+ * aborting the request. Tags are additive metadata (not identity), so a
121
+ * missing tag does not cause cache collisions, only a missed invalidation.
122
+ *
123
+ * Shared by the cache() DSL (cache-scope) and loader caching (loader-cache)
124
+ * so tag resolution behaves identically across every cache axis.
125
+ */
126
+ export function resolveTagsOption<TEnv>(
127
+ tags: string[] | ((ctx: RequestContext<TEnv>) => string[]) | undefined,
128
+ ctx: RequestContext<TEnv> | undefined,
129
+ label: string,
130
+ ): string[] | undefined {
131
+ if (!tags) return undefined;
132
+ if (typeof tags === "function") {
133
+ if (!ctx) {
134
+ // A dynamic tags function needs the request context to run. Without it
135
+ // (e.g. resolved outside a request, at build/prerender time) the entry is
136
+ // cached UNTAGGED and can never be invalidated - surface that rather than
137
+ // silently dropping the tags, matching the thrown-callback branch below.
138
+ console.warn(
139
+ `[${label}] Dynamic tags function present but no request context; ` +
140
+ `caching without tags (this entry will not be tag-invalidatable).`,
141
+ );
142
+ return undefined;
143
+ }
144
+ try {
145
+ return normalizeTagList(tags(ctx));
146
+ } catch (error) {
147
+ console.error(
148
+ `[${label}] Tags function failed, caching without tags:`,
149
+ error,
150
+ );
151
+ return undefined;
152
+ }
153
+ }
154
+ return normalizeTagList(tags);
155
+ }
156
+
157
+ /**
158
+ * Normalize a resolved tags array so the WRITE path matches the invalidate path:
159
+ * updateTag()/revalidateTag()/cacheTag() all drop empty/whitespace-only tags via
160
+ * normalizeTag(). Without this, an empty tag attached at write time would enter
161
+ * the store index but could never be invalidated (the verbs normalize it away),
162
+ * and on CFCacheStore would also cost a wasted KV marker read per request.
163
+ * Returns undefined when nothing usable remains, keeping the entry header-free.
164
+ */
165
+ function normalizeTagList(tags: string[]): string[] | undefined {
166
+ const out = normalizeTags(tags);
167
+ return out.length > 0 ? out : undefined;
168
+ }
169
+
111
170
  // ============================================================================
112
171
  // Cache Store Resolution
113
172
  // ============================================================================
@@ -120,6 +179,41 @@ export async function resolveCacheKey(
120
179
  export function resolveCacheStore(
121
180
  explicitStore: SegmentCacheStore | undefined,
122
181
  ): SegmentCacheStore | null {
123
- if (explicitStore) return explicitStore;
182
+ if (explicitStore) {
183
+ // Register explicit per-scope stores so updateTag()/revalidateTag() can
184
+ // reach them. This is the single chokepoint every cache axis (segment,
185
+ // response, loader) resolves through, so registering here covers them all
186
+ // eagerly - no dependence on whether a tagged write has happened yet. The
187
+ // app-level store is intentionally not registered (always reachable via
188
+ // ctx._cacheStore).
189
+ registerExplicitTaggedStore(explicitStore);
190
+ return explicitStore;
191
+ }
124
192
  return _getRequestContext()?._cacheStore ?? null;
125
193
  }
194
+
195
+ /**
196
+ * Upper bound on the per-handler explicit-store registry. A module-singleton
197
+ * store (the recommended pattern) dedupes to a single entry and never approaches
198
+ * this. The cap bounds the niche case of an explicit store constructed PER
199
+ * request/boundary (e.g. a ctx-bound CFCacheStore, which must take a per-request
200
+ * ctx): without it the registry - which intentionally persists across requests so
201
+ * a server action's updateTag() can reach stores a prior render registered -
202
+ * would accumulate one dead instance per request and fan invalidation out to
203
+ * finished execution contexts. LRU-touch on re-resolution keeps a live, re-used
204
+ * store from being evicted by that churn.
205
+ */
206
+ const EXPLICIT_STORE_REGISTRY_CAP = 64;
207
+
208
+ function registerExplicitTaggedStore(store: SegmentCacheStore): void {
209
+ const set = _getRequestContext()?._explicitTaggedStores;
210
+ if (!set) return;
211
+ // LRU touch: move an already-present store to the most-recent position (Set
212
+ // preserves insertion order) so a store re-resolved every request stays live.
213
+ set.delete(store);
214
+ set.add(store);
215
+ if (set.size > EXPLICIT_STORE_REGISTRY_CAP) {
216
+ const oldest = set.values().next().value;
217
+ if (oldest !== undefined) set.delete(oldest);
218
+ }
219
+ }