@rangojs/router 0.9.0 → 0.10.1

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 (68) hide show
  1. package/AGENTS.md +1 -1
  2. package/LICENSE +21 -0
  3. package/README.md +17 -15
  4. package/dist/types/cache/cf/cf-cache-constants.d.ts +1 -1
  5. package/dist/types/cache/cf/cf-cache-store.d.ts +1 -1
  6. package/dist/types/outlet-context.d.ts +9 -0
  7. package/dist/types/outlet-provider.d.ts +2 -1
  8. package/dist/types/route-content-wrapper.d.ts +4 -1
  9. package/dist/types/rsc/nonce.d.ts +10 -0
  10. package/dist/types/rsc/shell-capture-constants.d.ts +1 -1
  11. package/dist/types/rsc/types.d.ts +6 -2
  12. package/dist/types/ssr/index.d.ts +18 -0
  13. package/dist/types/ssr/ssr-root.d.ts +16 -0
  14. package/dist/types/ssr-suspension-warning.d.ts +20 -0
  15. package/dist/types/types/loader-types.d.ts +5 -1
  16. package/dist/types/types/segments.d.ts +17 -0
  17. package/dist/types/vite/discovery/state.d.ts +6 -0
  18. package/dist/types/vite/plugin-types.d.ts +27 -0
  19. package/dist/types/vite/plugins/virtual-entries.d.ts +1 -1
  20. package/dist/types/vite/utils/shared-utils.d.ts +1 -0
  21. package/dist/vite/index.js +56 -26
  22. package/package.json +26 -26
  23. package/skills/bundle-analysis/SKILL.md +1 -1
  24. package/skills/loader/SKILL.md +17 -2
  25. package/skills/testing/SKILL.md +1 -1
  26. package/skills/testing/bindings.md +1 -1
  27. package/skills/testing/cache-prerender.md +1 -1
  28. package/skills/testing/client-components.md +1 -1
  29. package/skills/testing/e2e-parity.md +1 -1
  30. package/skills/testing/flight.md +1 -1
  31. package/skills/testing/handles.md +1 -1
  32. package/skills/testing/loader.md +1 -1
  33. package/skills/testing/middleware.md +1 -1
  34. package/skills/testing/render-handler.md +1 -1
  35. package/skills/testing/response-routes.md +1 -1
  36. package/skills/testing/reverse-and-types.md +1 -1
  37. package/skills/testing/server-actions.md +1 -1
  38. package/skills/testing/server-tree.md +1 -1
  39. package/skills/testing/setup.md +1 -1
  40. package/src/browser/merge-segment-loaders.ts +4 -0
  41. package/src/cache/cache-runtime.ts +2 -2
  42. package/src/cache/cf/cf-cache-constants.ts +1 -1
  43. package/src/cache/cf/cf-cache-store.ts +1 -1
  44. package/src/client.tsx +2 -0
  45. package/src/outlet-context.ts +9 -0
  46. package/src/outlet-provider.tsx +4 -0
  47. package/src/route-content-wrapper.tsx +7 -0
  48. package/src/router/segment-resolution/fresh.ts +48 -17
  49. package/src/router.ts +7 -2
  50. package/src/rsc/handler.ts +4 -4
  51. package/src/rsc/nonce.ts +16 -0
  52. package/src/rsc/shell-capture-constants.ts +1 -1
  53. package/src/rsc/shell-capture.ts +41 -8
  54. package/src/rsc/types.ts +6 -2
  55. package/src/segment-system.tsx +57 -12
  56. package/src/ssr/index.tsx +53 -1
  57. package/src/ssr/ssr-root.tsx +50 -22
  58. package/src/ssr-suspension-warning.ts +68 -0
  59. package/src/types/loader-types.ts +5 -1
  60. package/src/types/segments.ts +17 -0
  61. package/src/use-loader.tsx +24 -1
  62. package/src/vite/discovery/shell-prerender-phase.ts +5 -0
  63. package/src/vite/discovery/state.ts +6 -0
  64. package/src/vite/plugin-types.ts +28 -0
  65. package/src/vite/plugins/virtual-entries.ts +26 -3
  66. package/src/vite/rango.ts +3 -0
  67. package/src/vite/router-discovery.ts +31 -19
  68. package/src/vite/utils/shared-utils.ts +8 -2
@@ -45,6 +45,12 @@ export interface PluginOptions {
45
45
  * capture endpoint with the app's configured head-script strategy.
46
46
  */
47
47
  headScripts?: import("../plugin-types.js").HeadScriptsOption;
48
+ /**
49
+ * rango({ progressiveChunkSize }) — threaded alongside headScripts so the
50
+ * temp server's virtual SSR entry bakes the app's configured Fizz outlining
51
+ * budget into its capture/render handlers.
52
+ */
53
+ progressiveChunkSize?: number;
48
54
  }
49
55
 
50
56
  export interface PrecomputedEntry {
@@ -159,6 +159,34 @@ interface RangoBaseOptions {
159
159
  */
160
160
  headScripts?: HeadScriptsOption;
161
161
 
162
+ /**
163
+ * React Fizz `progressiveChunkSize`, forwarded to the document renders the
164
+ * generated SSR entry performs: renderToReadableStream (live SSR) and
165
+ * prerender (PPR shell capture); resume() inherits the capture value from
166
+ * the stored postponed state.
167
+ *
168
+ * Controls COMPLETED-boundary outlining. Once the shell exceeds this budget
169
+ * (React's default is 12800 bytes — any real document), Fizz moves every
170
+ * completed Suspense boundary over ~500 bytes out of its document position
171
+ * to an end-of-stream `<div hidden>` + `$RC()` script reveal. Raise it (e.g.
172
+ * `Number.MAX_SAFE_INTEGER`) to keep completed content inline: in-place for
173
+ * non-executing HTML consumers, no reveal step. Boundaries with suspensey
174
+ * content (hoisted stylesheets) still outline — their reveal must wait for
175
+ * the CSS. Trade-off: inline content delays later shell bytes behind it,
176
+ * which is why React outlines by default.
177
+ *
178
+ * When UNSET, document renders whose matched chain has a
179
+ * `loader(Def, { ssr: false })` entry auto-raise to MAX_SAFE_INTEGER — the
180
+ * loader was awaited before first flush precisely so its content ships
181
+ * in-place, and outlining the boundary it feeds would defeat that. Setting
182
+ * an explicit value disables the auto-raise. The auto-raise is live-SSR
183
+ * only; captured shells use the explicit value or React's default.
184
+ *
185
+ * Apps with a custom SSR entry set this per-handler via
186
+ * `SSRDependencies.progressiveChunkSize`.
187
+ */
188
+ progressiveChunkSize?: number;
189
+
162
190
  /**
163
191
  * Filter which files route discovery scans, by glob. Paths are matched
164
192
  * root-relative (e.g. `src/routes/**`). `include` restricts discovery to
@@ -48,6 +48,18 @@ async function initializeApp() {
48
48
  initializeApp().catch(console.error);
49
49
  `.trim();
50
50
 
51
+ function emitProgressiveChunkSize(value: number): string {
52
+ if (value === Number.POSITIVE_INFINITY) {
53
+ return "Number.POSITIVE_INFINITY";
54
+ }
55
+ if (!Number.isFinite(value)) {
56
+ throw new Error(
57
+ `rango({ progressiveChunkSize }) must be a finite number or Infinity, received ${String(value)}`,
58
+ );
59
+ }
60
+ return JSON.stringify(value);
61
+ }
62
+
51
63
  /**
52
64
  * Generate the virtual SSR entry. `headScripts` mirrors the rango() plugin
53
65
  * option: "preinit" (default) installs the client-reference preinit hook and
@@ -56,6 +68,7 @@ initializeApp().catch(console.error);
56
68
  */
57
69
  export function getVirtualEntrySSR(
58
70
  headScripts: HeadScriptsOption = "preinit",
71
+ progressiveChunkSize?: number,
59
72
  ): string {
60
73
  const preinit = headScripts !== "preload";
61
74
  // The preload variant drops exactly three preinit-only lines, all built
@@ -73,6 +86,16 @@ installClientReferencePreinit(setOnClientReference);
73
86
  `
74
87
  : "";
75
88
  const hs = JSON.stringify(headScripts);
89
+ // Emitted into all three handlers: live SSR and shell capture consume it
90
+ // directly; the resume handler receives it for dep-shape uniformity (resume()
91
+ // itself inherits the capture value from the postponed state). Finite numbers
92
+ // stringify exactly (incl. MAX_SAFE_INTEGER). Infinity is emitted as
93
+ // Number.POSITIVE_INFINITY — JSON.stringify(Infinity) is null, which React
94
+ // would treat as "no budget" rather than "never outline".
95
+ const pcs =
96
+ progressiveChunkSize !== undefined
97
+ ? `\n progressiveChunkSize: ${emitProgressiveChunkSize(progressiveChunkSize)},`
98
+ : "";
76
99
  return `
77
100
  import {
78
101
  ${depsImportNames}
@@ -90,7 +113,7 @@ export const renderHTML = createSSRHandler({
90
113
  createFromReadableStream,
91
114
  renderToReadableStream,
92
115
  injectRSCPayload,
93
- headScripts: ${hs},
116
+ headScripts: ${hs},${pcs}
94
117
  loadBootstrapScriptContent: () =>
95
118
  import.meta.viteRsc.loadBootstrapScriptContent("index"),
96
119
  });
@@ -101,7 +124,7 @@ export const captureShellHTML = createShellCaptureHandler({
101
124
  injectRSCPayload,
102
125
  prerender,
103
126
  resume,
104
- headScripts: ${hs},
127
+ headScripts: ${hs},${pcs}
105
128
  loadBootstrapScriptContent: () =>
106
129
  import.meta.viteRsc.loadBootstrapScriptContent("index"),
107
130
  });
@@ -112,7 +135,7 @@ export const resumeShellHTML = createShellResumeHandler({
112
135
  injectRSCPayload,
113
136
  prerender,
114
137
  resume,
115
- headScripts: ${hs},
138
+ headScripts: ${hs},${pcs}
116
139
  loadBootstrapScriptContent: () =>
117
140
  import.meta.viteRsc.loadBootstrapScriptContent("index"),
118
141
  });
package/src/vite/rango.ts CHANGED
@@ -269,6 +269,7 @@ export async function rango(options?: RangoOptions): Promise<PluginOption[]> {
269
269
  plugins.push(
270
270
  createVirtualEntriesPlugin(finalEntries, undefined, {
271
271
  headScripts: resolvedOptions.headScripts,
272
+ progressiveChunkSize: resolvedOptions.progressiveChunkSize,
272
273
  }),
273
274
  );
274
275
  plugins.push(performanceTracksPlugin());
@@ -519,6 +520,7 @@ export async function rango(options?: RangoOptions): Promise<PluginOption[]> {
519
520
  plugins.push(
520
521
  createVirtualEntriesPlugin(finalEntries, routerRef, {
521
522
  headScripts: resolvedOptions.headScripts,
523
+ progressiveChunkSize: resolvedOptions.progressiveChunkSize,
522
524
  }),
523
525
  );
524
526
  plugins.push(performanceTracksPlugin());
@@ -585,6 +587,7 @@ export async function rango(options?: RangoOptions): Promise<PluginOption[]> {
585
587
  discovery: options?.discovery,
586
588
  clientChunkCtx,
587
589
  headScripts: resolvedOptions.headScripts,
590
+ progressiveChunkSize: resolvedOptions.progressiveChunkSize,
588
591
  }),
589
592
  );
590
593
 
@@ -265,7 +265,10 @@ async function createTempRscServer(
265
265
  },
266
266
  load(id: string) {
267
267
  return id === "\0rango-temp-real-ssr-entry"
268
- ? getVirtualEntrySSR(state.opts?.headScripts)
268
+ ? getVirtualEntrySSR(
269
+ state.opts?.headScripts,
270
+ state.opts?.progressiveChunkSize,
271
+ )
269
272
  : null;
270
273
  },
271
274
  } satisfies import("vite").Plugin,
@@ -1707,6 +1710,8 @@ export function createRouterDiscoveryPlugin(
1707
1710
  if (expectedEpoch === undefined) return;
1708
1711
  void (async () => {
1709
1712
  const deadline = Date.now() + 15_000;
1713
+ let reloadBackoffMs = 100;
1714
+ let nextReloadAt = Date.now() + reloadBackoffMs;
1710
1715
  do {
1711
1716
  if (devServerClosed || expectedEpoch !== s.devDiscoveryEpoch) {
1712
1717
  return;
@@ -1732,10 +1737,18 @@ export function createRouterDiscoveryPlugin(
1732
1737
  publishDevDiscoveryReady(expectedEpoch);
1733
1738
  return;
1734
1739
  }
1740
+ await response.body?.cancel().catch(() => {});
1735
1741
  // A response without the expected epoch proves an older worker
1736
1742
  // evaluation won the race after the initial invalidation. Clear
1737
- // that completed evaluation and retry the reload.
1738
- reloadWorkerd();
1743
+ // that completed evaluation and retry the reload. Back off the
1744
+ // retries: reloading faster than workerd can evaluate prevents
1745
+ // convergence and retains overlapping module generations.
1746
+ const now = Date.now();
1747
+ if (now >= nextReloadAt) {
1748
+ reloadWorkerd();
1749
+ reloadBackoffMs = Math.min(reloadBackoffMs * 2, 1_000);
1750
+ nextReloadAt = now + reloadBackoffMs;
1751
+ }
1739
1752
  } catch {}
1740
1753
  } while (Date.now() < deadline);
1741
1754
 
@@ -1949,26 +1962,25 @@ export function createRouterDiscoveryPlugin(
1949
1962
  // the entry + router sources so the import re-creates the routers
1950
1963
  // against the refreshed projection (installed by the pre-entry
1951
1964
  // refresh in discover-routers.ts).
1952
- if (isUseClient && hasClientUrls) {
1953
- const rscGraph = (server.environments as any)?.rsc?.moduleGraph;
1965
+ const mainRscEnv = (server.environments as any)?.rsc;
1966
+ if (isUseClient && hasClientUrls && mainRscEnv?.runner) {
1967
+ const rscGraph = mainRscEnv.moduleGraph;
1954
1968
  if (rscGraph?.getModulesByFile) {
1955
1969
  // Importers must be invalidated too: the virtual RSC entry
1956
1970
  // holds a live `import { router }` binding, and re-evaluating
1957
1971
  // router.tsx alone leaves that binding on the OLD instance —
1958
1972
  // the request pipeline would keep serving the stale mount.
1959
- // Same blast radius as a server urls edit (Vite's own
1960
- // file-change invalidation propagates upward identically).
1961
- const invalidateWithImporters = (
1962
- mod: any,
1963
- seen: Set<any>,
1964
- ): void => {
1965
- if (!mod || seen.has(mod)) return;
1966
- seen.add(mod);
1967
- rscGraph.invalidateModule(mod);
1968
- for (const importer of mod.importers ?? []) {
1969
- invalidateWithImporters(importer, seen);
1970
- }
1971
- };
1973
+ // Vite's invalidateModule already walks importers. Share its
1974
+ // seen set across roots instead of recursively starting a new
1975
+ // traversal at every importer (quadratic on a large graph).
1976
+ // Vite's walk skips HMR-accepting importers and soft-invalidates
1977
+ // static ones (vs the old unconditional hard walk) — safe here:
1978
+ // the entry and every router source are invalidated directly as
1979
+ // roots, and ancestors get the exact treatment Vite's own
1980
+ // file-change propagation applies on a server urls edit.
1981
+ // Cloudflare has no local runner and skips this block: its temp
1982
+ // discovery graph and workerd graph are invalidated wholesale
1983
+ // by refreshRuntimeDiscovery() after this watcher event.
1972
1984
  const routerSourceFiles = new Set<string>();
1973
1985
  if (s.resolvedEntryPath) {
1974
1986
  routerSourceFiles.add(resolve(s.resolvedEntryPath));
@@ -1991,7 +2003,7 @@ export function createRouterDiscoveryPlugin(
1991
2003
  continue;
1992
2004
  }
1993
2005
  for (const mod of mods) {
1994
- invalidateWithImporters(mod, seen);
2006
+ rscGraph.invalidateModule(mod, seen);
1995
2007
  }
1996
2008
  }
1997
2009
  debugDiscovery?.(
@@ -110,7 +110,10 @@ export function normalizeHostRouterEntry(
110
110
  export function createVirtualEntriesPlugin(
111
111
  entries: { client: string; ssr: string; rsc?: string },
112
112
  routerPathRef?: { path?: string; kind?: "router" | "host" },
113
- options?: { headScripts?: HeadScriptsOption },
113
+ options?: {
114
+ headScripts?: HeadScriptsOption;
115
+ progressiveChunkSize?: number;
116
+ },
114
117
  ): Plugin {
115
118
  // Build virtual modules map based on which entries use virtual IDs
116
119
  const virtualModules: Record<string, string> = {};
@@ -119,7 +122,10 @@ export function createVirtualEntriesPlugin(
119
122
  virtualModules[VIRTUAL_IDS.browser] = VIRTUAL_ENTRY_BROWSER;
120
123
  }
121
124
  if (entries.ssr === VIRTUAL_IDS.ssr) {
122
- virtualModules[VIRTUAL_IDS.ssr] = getVirtualEntrySSR(options?.headScripts);
125
+ virtualModules[VIRTUAL_IDS.ssr] = getVirtualEntrySSR(
126
+ options?.headScripts,
127
+ options?.progressiveChunkSize,
128
+ );
123
129
  }
124
130
 
125
131
  // RSC entry is resolved lazily in load() because routerPath may be