@timber-js/app 0.2.0-alpha.236 → 0.2.0-alpha.238

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 (105) hide show
  1. package/dist/_chunks/chains-CmzbpG-6.js +1 -0
  2. package/dist/_chunks/{chains-BsGKkMTK.js → chains-DMoHX4yH.js} +2 -2
  3. package/dist/_chunks/{chains-BsGKkMTK.js.map → chains-DMoHX4yH.js.map} +1 -1
  4. package/dist/_chunks/{classify-cmE0Gins.js → classify-BwyAd-dZ.js} +3 -3
  5. package/dist/_chunks/{classify-cmE0Gins.js.map → classify-BwyAd-dZ.js.map} +1 -1
  6. package/dist/_chunks/{cli-check-BwiahbTC.js → cli-check-DQAD9MLo.js} +3 -3
  7. package/dist/_chunks/{cli-check-BwiahbTC.js.map → cli-check-DQAD9MLo.js.map} +1 -1
  8. package/dist/_chunks/{cli-schema-sync-Brw7kTmm.js → cli-schema-sync-C_xNLqBj.js} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js → cli-schema-sync-CmGls3dc.js} +2 -2
  10. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js.map → cli-schema-sync-CmGls3dc.js.map} +1 -1
  11. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js → client-dep-entries-C5BTQtFS.js} +2 -2
  12. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js.map → client-dep-entries-C5BTQtFS.js.map} +1 -1
  13. package/dist/_chunks/{convention-lint-CLpuzY5h.js → convention-lint-GQA6WTRo.js} +2 -2
  14. package/dist/_chunks/{convention-lint-CLpuzY5h.js.map → convention-lint-GQA6WTRo.js.map} +1 -1
  15. package/dist/_chunks/dev-server--4_Ogy_6.js +1 -0
  16. package/dist/_chunks/{dev-server-lrdpD7Ws.js → dev-server-Cr3_Fu5A.js} +244 -26
  17. package/dist/_chunks/dev-server-Cr3_Fu5A.js.map +1 -0
  18. package/dist/_chunks/{flight-source-node-BO_xD9jC.js → flight-source-node-BsrlUjMO.js} +7 -3
  19. package/dist/_chunks/flight-source-node-BsrlUjMO.js.map +1 -0
  20. package/dist/_chunks/{scanner-CrB_h6FA.js → interception-CtNt9jPt.js} +169 -1043
  21. package/dist/_chunks/interception-CtNt9jPt.js.map +1 -0
  22. package/dist/_chunks/{live-graph-ChuFfmLi.js → live-graph-HcLScfiV.js} +4 -4
  23. package/dist/_chunks/{live-graph-ChuFfmLi.js.map → live-graph-HcLScfiV.js.map} +1 -1
  24. package/dist/_chunks/{metadata-routes-BL26HCDd.js → metadata-routes-MXNjWOt5.js} +60 -2
  25. package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -0
  26. package/dist/_chunks/{node-response-DNNnKnoS.js → node-response-omewa8e6.js} +20 -3
  27. package/dist/_chunks/node-response-omewa8e6.js.map +1 -0
  28. package/dist/_chunks/{poison-scan-CJ9QfJWb.js → poison-scan-DONdiCGX.js} +2 -2
  29. package/dist/_chunks/{poison-scan-CJ9QfJWb.js.map → poison-scan-DONdiCGX.js.map} +1 -1
  30. package/dist/_chunks/render-timeout-MrrqD1wd.js.map +1 -1
  31. package/dist/_chunks/scanner-DSAJjH0x.js +1043 -0
  32. package/dist/_chunks/scanner-DSAJjH0x.js.map +1 -0
  33. package/dist/_chunks/{walkers-BUvpsb2Q.js → walkers-96YopJds.js} +3 -3
  34. package/dist/_chunks/{walkers-BUvpsb2Q.js.map → walkers-96YopJds.js.map} +1 -1
  35. package/dist/analyze/crawl-entry.js +3 -3
  36. package/dist/analyze/graph-command.js +2 -2
  37. package/dist/cli.js +3 -3
  38. package/dist/config-types.d.ts +11 -0
  39. package/dist/config-types.d.ts.map +1 -1
  40. package/dist/config-validation.d.ts.map +1 -1
  41. package/dist/index.js +6 -155
  42. package/dist/index.js.map +1 -1
  43. package/dist/native/rsc/server/abort-scope.js +6 -2
  44. package/dist/native/rsc/server/abort-scope.js.map +1 -1
  45. package/dist/native/rsc/server/flight-source-node.js +6 -2
  46. package/dist/native/rsc/server/flight-source-node.js.map +1 -1
  47. package/dist/native/rsc/server/pipeline-helpers.js +2 -2
  48. package/dist/native/rsc/server/pipeline-helpers.js.map +1 -1
  49. package/dist/native/rsc/server/pipeline-metadata-route.js +2 -2
  50. package/dist/native/rsc/server/pipeline-metadata-route.js.map +1 -1
  51. package/dist/native/rsc/server/render-timeout.js.map +1 -1
  52. package/dist/native/rsc/server/safe-load.js +14 -2
  53. package/dist/native/rsc/server/safe-load.js.map +1 -1
  54. package/dist/native/ssr/server/abort-scope.js +6 -2
  55. package/dist/native/ssr/server/abort-scope.js.map +1 -1
  56. package/dist/native/ssr/server/flight-source-node.js +6 -2
  57. package/dist/native/ssr/server/flight-source-node.js.map +1 -1
  58. package/dist/native/ssr/server/pipeline-helpers.js +2 -2
  59. package/dist/native/ssr/server/pipeline-helpers.js.map +1 -1
  60. package/dist/native/ssr/server/pipeline-metadata-route.js +2 -2
  61. package/dist/native/ssr/server/pipeline-metadata-route.js.map +1 -1
  62. package/dist/native/ssr/server/render-timeout.js +3 -4
  63. package/dist/native/ssr/server/render-timeout.js.map +1 -1
  64. package/dist/native/ssr/server/safe-load.js +10 -1
  65. package/dist/native/ssr/server/safe-load.js.map +1 -1
  66. package/dist/plugins/dev-precompile.d.ts +42 -14
  67. package/dist/plugins/dev-precompile.d.ts.map +1 -1
  68. package/dist/plugins/dev-server.d.ts.map +1 -1
  69. package/dist/routing/index.js +3 -2
  70. package/dist/routing/manifest-codegen.d.ts +2 -0
  71. package/dist/routing/manifest-codegen.d.ts.map +1 -1
  72. package/dist/server/abort-scope.d.ts +7 -0
  73. package/dist/server/abort-scope.d.ts.map +1 -1
  74. package/dist/server/flight-source-node.d.ts.map +1 -1
  75. package/dist/server/internal.js +46 -7
  76. package/dist/server/internal.js.map +1 -1
  77. package/dist/server/render-timeout.d.ts.map +1 -1
  78. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  79. package/dist/server/safe-load.d.ts +22 -0
  80. package/dist/server/safe-load.d.ts.map +1 -1
  81. package/docs/api/34-api-config.mdx +18 -0
  82. package/package.json +1 -1
  83. package/src/config-types.ts +11 -0
  84. package/src/config-validation.ts +15 -8
  85. package/src/plugins/dev-precompile.ts +108 -20
  86. package/src/plugins/dev-server.ts +12 -11
  87. package/src/routing/manifest-codegen.ts +2 -2
  88. package/src/server/abort-scope.ts +20 -1
  89. package/src/server/flight-source-node.ts +11 -2
  90. package/src/server/pipeline-helpers.ts +2 -2
  91. package/src/server/pipeline-metadata-route.ts +2 -2
  92. package/src/server/render-timeout.ts +8 -5
  93. package/src/server/rsc-entry/index.ts +5 -0
  94. package/src/server/safe-load.ts +53 -1
  95. package/dist/_chunks/chains-DHmoKxkO.js +0 -1
  96. package/dist/_chunks/dev-server-BGGGhHXx.js +0 -1
  97. package/dist/_chunks/dev-server-lrdpD7Ws.js.map +0 -1
  98. package/dist/_chunks/flight-source-node-BO_xD9jC.js.map +0 -1
  99. package/dist/_chunks/metadata-routes-BL26HCDd.js.map +0 -1
  100. package/dist/_chunks/node-response-DNNnKnoS.js.map +0 -1
  101. package/dist/_chunks/scanner-CrB_h6FA.js.map +0 -1
  102. package/dist/_chunks/segment-keys-Y60KNc8C.js +0 -61
  103. package/dist/_chunks/segment-keys-Y60KNc8C.js.map +0 -1
  104. package/dist/_chunks/tree-match-Bqdr9szG.js +0 -168
  105. package/dist/_chunks/tree-match-Bqdr9szG.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"render-timeout.d.ts","sourceRoot":"","sources":["../../src/server/render-timeout.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,+DAA+D;AAC/D,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAEhD;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,SAAU,CAAC;AAEjD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAE7E;AAED;;;;;GAKG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B,YAAY,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAO9C;CACF;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,+CAA+C;IAC/C,MAAM,EAAE,WAAW,CAAC;IACpB,qEAAqE;IACrE,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,WAAW,GAAG,aAAa,CAwBhG;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAC3B,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,CAAC,CAAC,CAWZ"}
1
+ {"version":3,"file":"render-timeout.d.ts","sourceRoot":"","sources":["../../src/server/render-timeout.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,+DAA+D;AAC/D,eAAO,MAAM,yBAAyB,QAAS,CAAC;AAEhD;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,SAAU,CAAC;AAEjD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAE7E;AAED;;;;;GAKG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B,YAAY,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAO9C;CACF;AAED;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,+CAA+C;IAC/C,MAAM,EAAE,WAAW,CAAC;IACpB,qEAAqE;IACrE,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,WAAW,GAAG,aAAa,CA2BhG;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAC3B,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,CAAC,CAAC,CAWZ"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/index.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AA4FlE;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAEjD;AAkWD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAInE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAK1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAItE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,OAAO,wBAAwB,EAAE,cAAc,GACvD,OAAO,CAAC,OAAO,wBAAwB,EAAE,cAAc,CAAC,CAE1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,OAAO,wBAAwB,EAAE,uBAAuB,GAChE,OAAO,CAAC,OAAO,wBAAwB,EAAE,uBAAuB,CAAC,CAQnE;8BA4CoB,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/rsc-entry/index.ts"],"names":[],"mappings":"AA0CA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mCAAmC,CAAC;AA6FlE;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAEjD;AAkWD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AAInE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAK1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAItE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,OAAO,wBAAwB,EAAE,cAAc,GACvD,OAAO,CAAC,OAAO,wBAAwB,EAAE,cAAc,CAAC,CAE1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,OAAO,wBAAwB,EAAE,uBAAuB,GAChE,OAAO,CAAC,OAAO,wBAAwB,EAAE,uBAAuB,CAAC,CAQnE;8BA4CoB,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC"}
@@ -27,12 +27,34 @@ export declare class ModuleLoadError extends Error {
27
27
  readonly filePath: string;
28
28
  constructor(filePath: string, cause: unknown);
29
29
  }
30
+ /**
31
+ * Declare that route modules cannot change for the life of the process: no
32
+ * dev server's HMR can swap them. Called by the RSC entry when
33
+ * `import.meta.hot` is unset (a built server). Never call it under a dev
34
+ * server, whatever NODE_ENV says.
35
+ */
36
+ export declare function markRouteModulesImmutable(): void;
30
37
  /**
31
38
  * Load a route manifest module with enriched error context.
32
39
  *
33
40
  * On success: returns the module object (same as `loader.load()`).
34
41
  * On failure: throws `ModuleLoadError` with file path and original cause.
35
42
  *
43
+ * Production builds cache the module per loader. A dev server never does,
44
+ * whatever NODE_ENV says: HMR depends on each request re-importing, so an
45
+ * edited file is picked up, and the manifest (with its loader objects) is
46
+ * not re-evaluated when a route file changes. Both must hold:
47
+ *
48
+ * - `process.env.NODE_ENV === 'production'`, which the server build defines
49
+ * for every adapter, Workers included (plugins/server-bundle.ts). It also
50
+ * keeps vitest (`test`) from caching.
51
+ * - {@link markRouteModulesImmutable} was called. `import.meta.hot` is what
52
+ * says HMR can swap modules, and a dev server started with
53
+ * NODE_ENV=production still has it, but runtime modules cannot read it
54
+ * (they may load outside Vite's module runner, design/51 §"Boundary"), so
55
+ * the RSC entry reads it and calls this, as rsc-entry/ssr-bridge.ts gates
56
+ * the SSR entry.
57
+ *
36
58
  * Error rendering paths that need fallthrough use `loadFallbackModule()`.
37
59
  */
38
60
  export declare function loadModule<T = Record<string, unknown>>(loader: ManifestLoader): Promise<T>;
@@ -1 +1 @@
1
- {"version":3,"file":"safe-load.d.ts","sourceRoot":"","sources":["../../src/server/safe-load.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,yCAAyC;IACzC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAK3C;CACF;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAMhG"}
1
+ {"version":3,"file":"safe-load.d.ts","sourceRoot":"","sources":["../../src/server/safe-load.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,yCAAyC;IACzC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAK3C;CACF;AAsBD;;;;;GAKG;AACH,wBAAgB,yBAAyB,IAAI,IAAI,CAEhD;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAsB,UAAU,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAahG"}
@@ -37,6 +37,7 @@ interface TimberUserConfig {
37
37
  slowPhaseMs?: number;
38
38
  hostname?: string | false;
39
39
  requestPill?: boolean;
40
+ precompile?: boolean;
40
41
  };
41
42
  budget?: {
42
43
  firstLoadJs?: number;
@@ -242,6 +243,23 @@ export default {
242
243
 
243
244
  It never appears in a browser driven by automation (Playwright, Selenium, Puppeteer), so it can't intercept clicks in your e2e tests.
244
245
 
246
+ ### `dev.precompile`
247
+
248
+ - **Type:** `boolean`
249
+ - **Default:** `true`
250
+
251
+ Once the dev server is listening, compile your app's server code in the background: every route's layouts, pages and route handlers and the modules they statically import, for both server renders, starting with what `/` loads. A dynamic `import()` in your code still compiles at the request that reaches it. Nothing runs, so `instrumentation.ts` still runs at the first request. Without it, the first request to each page waits while Vite compiles its server code one module at a time.
252
+
253
+ Set `false` to leave compiling to each request, for example on a very large app where you only ever open a few routes. `TIMBER_DEV_PRECOMPILE=0` turns it off for a single run.
254
+
255
+ ```ts title="timber.config.ts"
256
+ export default {
257
+ dev: {
258
+ precompile: false,
259
+ },
260
+ };
261
+ ```
262
+
245
263
  ### `dev.hostname`
246
264
 
247
265
  - **Type:** `string | false`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.236",
3
+ "version": "0.2.0-alpha.238",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -168,6 +168,17 @@ export interface TimberUserConfig {
168
168
  * Default: `true`. Automated browsers (`navigator.webdriver`) never get it.
169
169
  */
170
170
  requestPill?: boolean;
171
+ /**
172
+ * Compile the app's server code in the background once the dev server
173
+ * listens: every route's layouts, pages and handlers and what they
174
+ * import, in the RSC and SSR environments, `/` first. Nothing executes;
175
+ * the first request still runs the modules. `false` leaves compiling to
176
+ * each request, as Vite does by default (`TIMBER_DEV_PRECOMPILE=0` does
177
+ * the same for one run).
178
+ *
179
+ * Default: `true`. See design/21-dev-server.md §"Server Pre-compile".
180
+ */
181
+ precompile?: boolean;
171
182
  };
172
183
  /**
173
184
  * Control Server-Timing header output.
@@ -206,14 +206,21 @@ export function validateConfig(config: TimberUserConfig): ConfigError[] {
206
206
  }
207
207
  }
208
208
 
209
- // dev.requestPill — not fatal: dev-only, like dev.hostname below.
210
- if (config.dev?.requestPill !== undefined && typeof config.dev.requestPill !== 'boolean') {
211
- errors.push({
212
- field: 'dev.requestPill',
213
- message: `dev.requestPill must be a boolean, got ${JSON.stringify(config.dev.requestPill)}.`,
214
- value: config.dev.requestPill,
215
- suggestion: 'Use dev: { requestPill: false } to turn the dev request pill off.',
216
- });
209
+ // Boolean dev switches — not fatal: dev-only, like dev.hostname below.
210
+ const devSwitches = [
211
+ ['requestPill', 'the dev request pill'],
212
+ ['precompile', 'the background server compile'],
213
+ ] as const;
214
+ for (const [key, what] of devSwitches) {
215
+ const value = config.dev?.[key];
216
+ if (value !== undefined && typeof value !== 'boolean') {
217
+ errors.push({
218
+ field: `dev.${key}`,
219
+ message: `dev.${key} must be a boolean, got ${JSON.stringify(value)}.`,
220
+ value,
221
+ suggestion: `Use dev: { ${key}: false } to turn ${what} off.`,
222
+ });
223
+ }
217
224
  }
218
225
 
219
226
  // dev.hostname — not fatal: it is dev-only, so a typo must not fail
@@ -13,9 +13,15 @@
13
13
  * - `env.transformRequest()` only: nothing executes, so the app's
14
14
  * instrumentation `register()` and cache handler setup still run at the
15
15
  * first request, as before.
16
- * - Static imports only (`result.deps`), from the entries and the root
17
- * layout. A route's own page and layouts are dynamic imports of the route
18
- * manifest; they compile at the request for them.
16
+ * - Static imports only (`result.deps`), from the entries and every module
17
+ * file in the route tree ({@link routeTreeSeeds}). Route files are dynamic
18
+ * imports of the route manifest, which the crawl does not follow, so they
19
+ * are seeded directly. Crawling only the root layout left most of an app
20
+ * whose UI sits in route groups and slots to the first request: on
21
+ * relisten-web it covered 53 of the 499 SSR modules `GET /` needed, and the
22
+ * whole route tree (~960 modules) takes ~1.6s (TIM-1630).
23
+ * - In waves: what `GET /` can load first, RSC then SSR, so the
24
+ * most common first request is ready soonest; then the rest.
19
25
  * - Errors are swallowed. The request that loads the module hits the same
20
26
  * error and reports it as it always has; Vite's `warmupRequest` was
21
27
  * rejected because it logs each error a second time.
@@ -28,30 +34,99 @@
28
34
  *
29
35
  * `analyze/crawl.ts` also walks `transformRequest`, for a different job:
30
36
  * classifying every module the app can reach, dynamic imports included, in
31
- * a throwaway middleware-mode server. Following its edges here would
32
- * compile every route of the app at each start.
37
+ * a throwaway middleware-mode server.
38
+ *
39
+ * `dev.precompile: false` in timber.config, or `TIMBER_DEV_PRECOMPILE=0`,
40
+ * turns it off.
33
41
  *
34
42
  * See design/21-dev-server.md §"Server Pre-compile".
35
43
  */
36
44
 
37
45
  import { normalizePath, type DevEnvironment, type ViteDevServer } from 'vite';
38
46
  import type { PluginApi } from '@vitejs/plugin-rsc';
47
+ import type { RouteFile, RouteTree, SegmentNode } from '../routing/types.ts';
48
+ import { RECORD_FILE_KEYS, SINGLE_FILE_KEYS } from '../routing/manifest-codegen.ts';
49
+ import { isStaticMetadataExtension } from '../server/metadata-routes.ts';
39
50
 
40
51
  /** `TIMBER_DEV_PRECOMPILE=0` turns the crawl off (A/B measurement, escape hatch). */
41
52
  export const PRECOMPILE_ENV = 'TIMBER_DEV_PRECOMPILE';
42
53
 
43
54
  /**
44
- * Past this, the crawl starts no new transform. Generous: ~1.2s covers the
45
- * kitchen-sink. It bounds a crawl stuck behind a slow transform plugin.
55
+ * Past this, the crawl starts no new transform. Generous: the whole route
56
+ * tree takes ~1.6s on relisten-web. It bounds a crawl stuck behind a slow
57
+ * transform plugin, or an app too large to finish.
46
58
  */
47
59
  export const PRECOMPILE_DEADLINE_MS = 60_000;
48
60
 
49
- /** The roots of each server environment's crawl. */
61
+ /**
62
+ * The roots of each server environment's crawl. `rsc` is crawled in waves,
63
+ * in order; after each wave the SSR environment crawls `ssr` and every
64
+ * client reference recorded so far.
65
+ */
50
66
  export interface PrecompileRoots {
51
- rsc: string[];
67
+ rsc: string[][];
52
68
  ssr: string[];
53
69
  }
54
70
 
71
+ /**
72
+ * Segment types whose subtree can match its parent's URL: they consume no
73
+ * URL segment (or none, for an empty optional catch-all).
74
+ */
75
+ const PATHLESS = new Set(['group', 'optional-catch-all']);
76
+
77
+ /** `node`, or a pathless segment under it, has a page or handler for its URL. */
78
+ function rendersOwnPath(node: SegmentNode): boolean {
79
+ if (node.page || node.route) return true;
80
+ return node.children.some((child) => PATHLESS.has(child.segmentType) && rendersOwnPath(child));
81
+ }
82
+
83
+ /**
84
+ * The files of a segment that the runtime loads as modules: every file the
85
+ * route manifest lists for it (routing/manifest-codegen.ts, so a convention
86
+ * the manifest learns is crawled too), except JSON status files and static
87
+ * metadata files (`sitemap.xml`, `icon.png`, …), which are read from disk
88
+ * and never imported.
89
+ */
90
+ function segmentFiles(node: SegmentNode): RouteFile[] {
91
+ const files: RouteFile[] = [];
92
+ for (const key of SINGLE_FILE_KEYS) {
93
+ const file = node[key];
94
+ if (file) files.push(file);
95
+ }
96
+ for (const key of RECORD_FILE_KEYS) {
97
+ if (key === 'jsonStatusFiles') continue;
98
+ for (const [name, file] of Object.entries(node[key] ?? {})) {
99
+ if (key === 'metadataRoutes' && isStaticMetadataExtension(name, file.extension)) continue;
100
+ files.push(file);
101
+ }
102
+ }
103
+ return files;
104
+ }
105
+
106
+ /**
107
+ * Every module file in the route tree, in two waves. `home` is what `GET /`
108
+ * can load: `proxy.ts`, `global-error`, the root segment, and under it the
109
+ * pathless segments (groups, optional catch-alls) with a page or handler at
110
+ * `/`, and the slots of those. A group that only organises other sections
111
+ * (`(admin)/admin/…`) is not in it. `rest` is every other segment's.
112
+ */
113
+ export function routeTreeSeeds(tree: RouteTree): { home: string[]; rest: string[] } {
114
+ const home: string[] = [];
115
+ const rest: string[] = [];
116
+ for (const file of [tree.proxy, tree.globalError]) if (file) home.push(file.filePath);
117
+ const walk = (node: SegmentNode, inHome: boolean): void => {
118
+ for (const file of segmentFiles(node)) (inHome ? home : rest).push(file.filePath);
119
+ for (const child of node.children) {
120
+ walk(child, inHome && PATHLESS.has(child.segmentType) && rendersOwnPath(child));
121
+ }
122
+ // A slot renders beside its parent's page, so it is in whichever wave
123
+ // its parent is.
124
+ for (const slot of Object.values(node.slots)) walk(slot, inHome);
125
+ };
126
+ walk(tree.root, true);
127
+ return { home, rest };
128
+ }
129
+
55
130
  /**
56
131
  * The id `transformRequest` takes for an entry of `result.deps`, or null for
57
132
  * one it must not follow: a bare specifier, which in a server environment is
@@ -85,14 +160,17 @@ export function fileUrl(file: string, root: string): string {
85
160
  /**
86
161
  * Transform `roots` and every module they statically import in `env`.
87
162
  * Starts no transform once `shouldStop()` is true. Resolves with the
88
- * number of modules visited once the graph is done; never rejects.
163
+ * number of ids in `seen` (every module visited in `env` so far, across
164
+ * crawls that share it) once the graph is done; never rejects. `seen`
165
+ * carries visited ids across crawls of one environment, so a later wave
166
+ * skips what an earlier one transformed.
89
167
  */
90
168
  export async function crawlServerGraph(
91
169
  env: DevEnvironment,
92
170
  roots: string[],
93
- shouldStop: () => boolean = () => false
171
+ shouldStop: () => boolean = () => false,
172
+ seen: Set<string> = new Set()
94
173
  ): Promise<number> {
95
- const seen = new Set<string>();
96
174
  const visit = async (id: string): Promise<void> => {
97
175
  if (seen.has(id) || shouldStop()) return;
98
176
  seen.add(id);
@@ -115,8 +193,8 @@ export async function crawlServerGraph(
115
193
 
116
194
  /**
117
195
  * The SSR environment loads each client component the RSC render
118
- * references, by the id plugin-rsc registered for it. Read once the RSC
119
- * crawl is done: plugin-rsc records a client reference when it transforms
196
+ * references, by the id plugin-rsc registered for it. Read after each RSC
197
+ * wave: plugin-rsc records a client reference when it transforms
120
198
  * the `'use client'` module in the RSC environment.
121
199
  */
122
200
  function clientReferenceIds(server: ViteDevServer): string[] {
@@ -134,9 +212,9 @@ function clientReferenceIds(server: ViteDevServer): string[] {
134
212
  }
135
213
 
136
214
  /**
137
- * Crawl the RSC graph, then the SSR graph with the client references the
138
- * RSC crawl found. A request that arrives mid-crawl shares the transforms
139
- * already in flight for the URLs it asks for.
215
+ * For each RSC wave, crawl the RSC graph, then the SSR graph with the client
216
+ * references found so far. A request that arrives mid-crawl shares the
217
+ * transforms already in flight for the URLs it asks for.
140
218
  */
141
219
  export async function precompileServerGraphs(
142
220
  server: ViteDevServer,
@@ -144,9 +222,19 @@ export async function precompileServerGraphs(
144
222
  shouldStop: () => boolean
145
223
  ): Promise<void> {
146
224
  const { rsc, ssr } = server.environments;
147
- if (rsc) await crawlServerGraph(rsc, roots.rsc, shouldStop);
148
- if (ssr && !shouldStop()) {
149
- await crawlServerGraph(ssr, [...roots.ssr, ...clientReferenceIds(server)], shouldStop);
225
+ const rscSeen = new Set<string>();
226
+ const ssrSeen = new Set<string>();
227
+ for (const wave of roots.rsc) {
228
+ if (shouldStop()) return;
229
+ if (rsc) await crawlServerGraph(rsc, wave, shouldStop, rscSeen);
230
+ if (ssr && !shouldStop()) {
231
+ await crawlServerGraph(
232
+ ssr,
233
+ [...roots.ssr, ...clientReferenceIds(server)],
234
+ shouldStop,
235
+ ssrSeen
236
+ );
237
+ }
150
238
  }
151
239
  }
152
240
 
@@ -39,7 +39,7 @@ import {
39
39
  } from '../dev-tools/dev-page-shell.ts';
40
40
  import { addVirtualModuleContext } from '../config-validation.ts';
41
41
  import { devRecordRoot, registerDevDiscovery } from './dev-discovery.ts';
42
- import { fileUrl, precompileOnListen } from './dev-precompile.ts';
42
+ import { fileUrl, precompileOnListen, routeTreeSeeds } from './dev-precompile.ts';
43
43
  import { VIRTUAL_IDS } from './virtual-ids.ts';
44
44
  import { advertisedUrls, applyDevHostname } from './dev-hostname.ts';
45
45
  import {
@@ -312,16 +312,17 @@ export function timberDevServer(ctx: PluginContext): Plugin {
312
312
 
313
313
  // Transform the server graphs in the background once listening, so
314
314
  // the first request does not compile them one module at a time. See
315
- // design/21 §Server Pre-compile.
316
- precompileOnListen(server, () => {
317
- const rootLayout = ctx.routeTree?.root.layout?.filePath;
318
- return {
319
- rsc: rootLayout
320
- ? [VIRTUAL_IDS.rscEntry, fileUrl(rootLayout, server.config.root)]
321
- : [VIRTUAL_IDS.rscEntry],
322
- ssr: [VIRTUAL_IDS.ssrEntry],
323
- };
324
- });
315
+ // design/21 §Server Pre-compile. `dev.precompile: false` opts out.
316
+ if (ctx.config.dev?.precompile !== false) {
317
+ precompileOnListen(server, () => {
318
+ const toUrl = (file: string) => fileUrl(file, server.config.root);
319
+ const seeds = ctx.routeTree ? routeTreeSeeds(ctx.routeTree) : { home: [], rest: [] };
320
+ return {
321
+ rsc: [[VIRTUAL_IDS.rscEntry, ...seeds.home.map(toUrl)], seeds.rest.map(toUrl)],
322
+ ssr: [VIRTUAL_IDS.ssrEntry],
323
+ };
324
+ });
325
+ }
325
326
 
326
327
  // Close the holding server and await the port release so Vite's
327
328
  // port probe and bind see a free port. configureServer is awaited
@@ -16,7 +16,7 @@ import type { RouteTree, SegmentNode, RouteFile } from './types.ts';
16
16
  // ── Single-file conventions ─────────────────────────────────────────────
17
17
  // Each entry maps to a node property that holds a single RouteFile.
18
18
  // Order matches the original serializeNode output for byte-identical diffs.
19
- const SINGLE_FILE_KEYS = [
19
+ export const SINGLE_FILE_KEYS = [
20
20
  'page',
21
21
  'layout',
22
22
  'middleware',
@@ -29,7 +29,7 @@ const SINGLE_FILE_KEYS = [
29
29
 
30
30
  // ── Record-shaped conventions ───────────────────────────────────────────
31
31
  // Each entry maps to a node property that holds Record<string, RouteFile>.
32
- const RECORD_FILE_KEYS = ['statusFiles', 'jsonStatusFiles', 'metadataRoutes'] as const;
32
+ export const RECORD_FILE_KEYS = ['statusFiles', 'jsonStatusFiles', 'metadataRoutes'] as const;
33
33
 
34
34
  const SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
35
35
 
@@ -39,7 +39,7 @@ export function onAbortUntil(
39
39
  scope = until;
40
40
  } else {
41
41
  const ended = new AbortController();
42
- const end = (): void => ended.abort();
42
+ const end = (): void => endScope(ended);
43
43
  until.then(end, end);
44
44
  scope = ended.signal;
45
45
  }
@@ -47,3 +47,22 @@ export function onAbortUntil(
47
47
  // scope aborts: the platform's one-step removal, no handle to keep.
48
48
  signal.addEventListener('abort', onAbort, { once: true, signal: scope });
49
49
  }
50
+
51
+ /**
52
+ * The reason every scope controller aborts with. Nothing reads a scope
53
+ * signal's reason (it only removes listeners, through addEventListener's
54
+ * `signal` option), and `abort()` with no reason builds a DOMException, stack
55
+ * trace included, on every call: several per request, ~1.8% of an HTML
56
+ * request's CPU (TIM-1626).
57
+ */
58
+ const SCOPE_ENDED: unique symbol = Symbol('timber.scope-ended');
59
+
60
+ /**
61
+ * End a scope: abort a server-private controller whose signal only bounds
62
+ * listeners (an `onAbortUntil` `until`). Never use it on a signal anything
63
+ * reads a reason from — a render, fetch or stream would see this symbol
64
+ * instead of an AbortError.
65
+ */
66
+ export function endScope(scope: AbortController): void {
67
+ scope.abort(SCOPE_ENDED);
68
+ }
@@ -19,7 +19,7 @@
19
19
  import { Readable, Transform } from 'node:stream';
20
20
  import { NodeBodyResponse } from './node-body-response.ts';
21
21
  import { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';
22
- import { onAbortUntil } from './abort-scope.ts';
22
+ import { endScope, onAbortUntil } from './abort-scope.ts';
23
23
  import { RenderTimeoutError } from './render-timeout.ts';
24
24
  import { releaseReason } from './render-utils.ts';
25
25
 
@@ -109,8 +109,17 @@ export function pipeFlightToNode(
109
109
  callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);
110
110
  },
111
111
  destroy(error, callback) {
112
- scope.abort();
112
+ endScope(scope);
113
113
  clearTimeout(timer);
114
+ // Flight ended the stream (React calls `end()` once the render is
115
+ // complete) and nothing failed: the render is over, so there is
116
+ // nothing to release. Every normally finished render takes this path,
117
+ // and `releaseReason()` would build a DOMException just for React to
118
+ // ignore it (TIM-1626).
119
+ if (error == null && stream.writableEnded) {
120
+ callback(error);
121
+ return;
122
+ }
114
123
  // A no-op once Flight has finished (it ignores abort after close). A
115
124
  // release without a reason aborts with an AbortError, so the render's
116
125
  // onError does not log the abort (releaseReason, TIM-1597).
@@ -18,7 +18,7 @@ import {
18
18
  } from './instrumentation.ts';
19
19
  import { getTraceId } from './tracing.ts';
20
20
  import { requestContextAls } from './als-registry.ts';
21
- import { onAbortUntil } from './abort-scope.ts';
21
+ import { endScope, onAbortUntil } from './abort-scope.ts';
22
22
  import { RedirectSignal } from './primitives.ts';
23
23
  import { isControlFlowSignal } from './signal-identity.ts';
24
24
  import { logRenderError, logSkippedModule, swallow } from './logger.ts';
@@ -535,7 +535,7 @@ export async function runBackgroundFlight<T>(
535
535
  if (!signal.aborted) failed(error);
536
536
  throw error;
537
537
  } finally {
538
- settled.abort();
538
+ endScope(settled);
539
539
  }
540
540
  }
541
541
 
@@ -52,7 +52,7 @@ import { logRenderError, logRouteSetupError } from './logger.ts';
52
52
  import { isDebug } from './debug.ts';
53
53
  import { resolveRenderTimeoutMs } from './render-timeout.ts';
54
54
  import { concatBytes, drainWithDeadline } from './stream-utils.ts';
55
- import { onAbortUntil } from './abort-scope.ts';
55
+ import { endScope, onAbortUntil } from './abort-scope.ts';
56
56
  import type { PipelineConfig, RouteMatch } from './pipeline.ts';
57
57
  import type { MetadataHandler, MetadataRoute } from './types.ts';
58
58
 
@@ -229,7 +229,7 @@ async function bufferResponse(
229
229
  'Metadata route body'
230
230
  );
231
231
  } finally {
232
- readDone.abort();
232
+ endScope(readDone);
233
233
  }
234
234
  const bytes = concatBytes(chunks);
235
235
  const headers = new Headers(response.headers);
@@ -8,7 +8,7 @@
8
8
  * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
9
9
  */
10
10
 
11
- import { onAbortUntil } from './abort-scope.ts';
11
+ import { endScope, onAbortUntil } from './abort-scope.ts';
12
12
 
13
13
  /** `renderTimeoutMs` when timber.config.ts leaves it unset. */
14
14
  export const DEFAULT_RENDER_TIMEOUT_MS = 30_000;
@@ -75,9 +75,12 @@ export interface RenderTimeout {
75
75
  */
76
76
  export function createRenderTimeout(timeoutMs: number, parentSignal?: AbortSignal): RenderTimeout {
77
77
  const controller = new AbortController();
78
- const reason = new RenderTimeoutError(timeoutMs, 'RSC stream read timed out');
79
-
80
- const timer = setTimeout(() => controller.abort(reason), timeoutMs);
78
+ // The error is built when the timer fires, not up front: almost every
79
+ // render finishes in time, and an Error captures a stack trace.
80
+ const timer = setTimeout(
81
+ () => controller.abort(new RenderTimeoutError(timeoutMs, 'RSC stream read timed out')),
82
+ timeoutMs
83
+ );
81
84
  const scope = new AbortController();
82
85
 
83
86
  // The parent listener lasts until cancel() (server/abort-scope.ts).
@@ -94,7 +97,7 @@ export function createRenderTimeout(timeoutMs: number, parentSignal?: AbortSigna
94
97
  signal: controller.signal,
95
98
  cancel: () => {
96
99
  clearTimeout(timer);
97
- scope.abort();
100
+ endScope(scope);
98
101
  },
99
102
  };
100
103
  }
@@ -88,6 +88,7 @@ import { SlotOutlet } from '../../client/slot-outlet.tsx';
88
88
  import { SlotsProvider } from '../../client/slot-provider.tsx';
89
89
  import { DenyLastResort } from '../../client/deny-last-resort.tsx';
90
90
  import { provideRscViteHandoff } from '../vite-handoff-rsc.ts';
91
+ import { markRouteModulesImmutable } from '../safe-load.ts';
91
92
 
92
93
  // Before anything can render: the runtime reads these at call and render
93
94
  // time through server/vite-handoff-rsc.ts (design/51-native-dev-runtime.md).
@@ -606,4 +607,8 @@ export default _handler!;
606
607
  // This is the boundary @vitejs/plugin-rsc documents for the RSC entry.
607
608
  if (import.meta.hot) {
608
609
  import.meta.hot.accept();
610
+ } else {
611
+ // No dev server can swap route modules: loadModule() may keep them
612
+ // (server/safe-load.ts, TIM-1626).
613
+ markRouteModulesImmutable();
609
614
  }
@@ -36,17 +36,69 @@ export class ModuleLoadError extends Error {
36
36
  }
37
37
  }
38
38
 
39
+ /**
40
+ * Modules already loaded in production, keyed by their manifest loader.
41
+ *
42
+ * Manifest loaders are static objects in the generated manifest module
43
+ * (routing/manifest-codegen.ts), so one loader is one file for the life of
44
+ * the process. A caller that wraps a loader in a fresh object (the sitemap
45
+ * generator does, once per generation) only misses the cache. Node hands back the same namespace on every `import()`, but
46
+ * the round-trip through the loader costs ~2.7µs, and a request loads every
47
+ * layout, page and slot on its path (16 loads on a parallel-routes page):
48
+ * caching measured −4.65% CPU on an HTML page and up to −12.5% on RSC
49
+ * navigation (TIM-1626). A WeakMap hit is ~0.09µs.
50
+ *
51
+ * Only successful loads are stored, so a failed load is retried on the next
52
+ * request and keeps reporting `ModuleLoadError`.
53
+ */
54
+ const loaded = new WeakMap<ManifestLoader, unknown>();
55
+
56
+ /** Set once no dev server can swap route modules; see {@link loadModule}. */
57
+ let routeModulesImmutable = false;
58
+
59
+ /**
60
+ * Declare that route modules cannot change for the life of the process: no
61
+ * dev server's HMR can swap them. Called by the RSC entry when
62
+ * `import.meta.hot` is unset (a built server). Never call it under a dev
63
+ * server, whatever NODE_ENV says.
64
+ */
65
+ export function markRouteModulesImmutable(): void {
66
+ routeModulesImmutable = true;
67
+ }
68
+
39
69
  /**
40
70
  * Load a route manifest module with enriched error context.
41
71
  *
42
72
  * On success: returns the module object (same as `loader.load()`).
43
73
  * On failure: throws `ModuleLoadError` with file path and original cause.
44
74
  *
75
+ * Production builds cache the module per loader. A dev server never does,
76
+ * whatever NODE_ENV says: HMR depends on each request re-importing, so an
77
+ * edited file is picked up, and the manifest (with its loader objects) is
78
+ * not re-evaluated when a route file changes. Both must hold:
79
+ *
80
+ * - `process.env.NODE_ENV === 'production'`, which the server build defines
81
+ * for every adapter, Workers included (plugins/server-bundle.ts). It also
82
+ * keeps vitest (`test`) from caching.
83
+ * - {@link markRouteModulesImmutable} was called. `import.meta.hot` is what
84
+ * says HMR can swap modules, and a dev server started with
85
+ * NODE_ENV=production still has it, but runtime modules cannot read it
86
+ * (they may load outside Vite's module runner, design/51 §"Boundary"), so
87
+ * the RSC entry reads it and calls this, as rsc-entry/ssr-bridge.ts gates
88
+ * the SSR entry.
89
+ *
45
90
  * Error rendering paths that need fallthrough use `loadFallbackModule()`.
46
91
  */
47
92
  export async function loadModule<T = Record<string, unknown>>(loader: ManifestLoader): Promise<T> {
93
+ const cache = process.env.NODE_ENV === 'production' && routeModulesImmutable;
94
+ if (cache) {
95
+ const hit = loaded.get(loader);
96
+ if (hit !== undefined) return hit as T;
97
+ }
48
98
  try {
49
- return (await loader.load()) as T;
99
+ const mod = await loader.load();
100
+ if (cache) loaded.set(loader, mod);
101
+ return mod as T;
50
102
  } catch (error) {
51
103
  throw new ModuleLoadError(loader.filePath, error);
52
104
  }
@@ -1 +0,0 @@
1
- export { t as formatChains } from "./chains-BsGKkMTK.js";
@@ -1 +0,0 @@
1
- export { t as RESTART_EXIT_CODE } from "./dev-server-lrdpD7Ws.js";