@timber-js/app 0.2.0-alpha.220 → 0.2.0-alpha.221

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 (152) hide show
  1. package/dist/_chunks/{actions-BwkmAYXq.js → actions-BDqn4Oxj.js} +2 -2
  2. package/dist/_chunks/{actions-BwkmAYXq.js.map → actions-BDqn4Oxj.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-LA3sBpUS.js → cache-api-GE4AOe2H.js} +30 -151
  4. package/dist/_chunks/cache-api-GE4AOe2H.js.map +1 -0
  5. package/dist/_chunks/dev-server-BiWNMBVU.js +1 -0
  6. package/dist/_chunks/{dev-server-DnODXuNM.js → dev-server-DIy-SY-J.js} +11 -6
  7. package/dist/_chunks/{dev-server-DnODXuNM.js.map → dev-server-DIy-SY-J.js.map} +1 -1
  8. package/dist/_chunks/dev-store-BOa304m_.js +283 -0
  9. package/dist/_chunks/dev-store-BOa304m_.js.map +1 -0
  10. package/dist/_chunks/{error-boundary-xxxLtXt6.js → error-boundary-Bc8QPZuq.js} +71 -21
  11. package/dist/_chunks/error-boundary-Bc8QPZuq.js.map +1 -0
  12. package/dist/_chunks/{flight-source-node-0dE-t3kq.js → flight-source-node-HptmGMT8.js} +6 -7
  13. package/dist/_chunks/flight-source-node-HptmGMT8.js.map +1 -0
  14. package/dist/_chunks/{node-response-Dibufw_b.js → node-response-rkQqcFGq.js} +48 -2
  15. package/dist/_chunks/node-response-rkQqcFGq.js.map +1 -0
  16. package/dist/_chunks/{purge-store-Byr8XOjU.js → purge-store-WZaxu-3m.js} +2 -2
  17. package/dist/_chunks/purge-store-WZaxu-3m.js.map +1 -0
  18. package/dist/_chunks/{render-timeout-DOf_BBcO.js → render-timeout-joFhz4KH.js} +1 -10
  19. package/dist/_chunks/render-timeout-joFhz4KH.js.map +1 -0
  20. package/dist/cache/cache-api.d.ts.map +1 -1
  21. package/dist/cache/handler-store.d.ts +13 -1
  22. package/dist/cache/handler-store.d.ts.map +1 -1
  23. package/dist/cache/index.js +2 -1
  24. package/dist/cache/invalidation-epoch.d.ts +7 -0
  25. package/dist/cache/invalidation-epoch.d.ts.map +1 -1
  26. package/dist/cache/timber-cache.d.ts.map +1 -1
  27. package/dist/cdn/index.js +1 -1
  28. package/dist/cdn/purge-store.d.ts +10 -1
  29. package/dist/cdn/purge-store.d.ts.map +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  32. package/dist/client/error-boundary.js +1 -1
  33. package/dist/client/index.js +6 -15
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/internal.js +37 -64
  36. package/dist/client/internal.js.map +1 -1
  37. package/dist/client/link.d.ts.map +1 -1
  38. package/dist/client/navigation-transition.d.ts +68 -14
  39. package/dist/client/navigation-transition.d.ts.map +1 -1
  40. package/dist/client/router-effects.d.ts +35 -31
  41. package/dist/client/router-effects.d.ts.map +1 -1
  42. package/dist/client/router-pipeline.d.ts +2 -6
  43. package/dist/client/router-pipeline.d.ts.map +1 -1
  44. package/dist/client/router-types.d.ts +10 -30
  45. package/dist/client/router-types.d.ts.map +1 -1
  46. package/dist/client/router.d.ts.map +1 -1
  47. package/dist/dev-tools/logs.d.ts +2 -2
  48. package/dist/dev-tools/logs.d.ts.map +1 -1
  49. package/dist/index.js +144 -51
  50. package/dist/index.js.map +1 -1
  51. package/dist/plugins/dev-server.d.ts.map +1 -1
  52. package/dist/plugins/entries.d.ts +5 -0
  53. package/dist/plugins/entries.d.ts.map +1 -1
  54. package/dist/plugins/orphaned-modules.d.ts +57 -0
  55. package/dist/plugins/orphaned-modules.d.ts.map +1 -0
  56. package/dist/plugins/prebuilt.d.ts +6 -6
  57. package/dist/plugins/prerender-sugar.d.ts.map +1 -1
  58. package/dist/plugins/routing.d.ts +1 -1
  59. package/dist/plugins/routing.d.ts.map +1 -1
  60. package/dist/rsc-runtime/dev-reference-cache.d.ts +47 -0
  61. package/dist/rsc-runtime/dev-reference-cache.d.ts.map +1 -0
  62. package/dist/rsc-runtime/rsc.d.ts +0 -15
  63. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  64. package/dist/rsc-runtime/ssr.d.ts +0 -11
  65. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  66. package/dist/server/abort-scope.d.ts +27 -0
  67. package/dist/server/abort-scope.d.ts.map +1 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -1
  69. package/dist/server/index.js +1 -1
  70. package/dist/server/instrumentation.d.ts +2 -1
  71. package/dist/server/instrumentation.d.ts.map +1 -1
  72. package/dist/server/internal.d.ts +1 -1
  73. package/dist/server/internal.d.ts.map +1 -1
  74. package/dist/server/internal.js +328 -132
  75. package/dist/server/internal.js.map +1 -1
  76. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  77. package/dist/server/pipeline.d.ts +10 -7
  78. package/dist/server/pipeline.d.ts.map +1 -1
  79. package/dist/server/prebuilt/cache-key.d.ts +26 -0
  80. package/dist/server/prebuilt/cache-key.d.ts.map +1 -1
  81. package/dist/server/prebuilt/capture-render.d.ts +9 -4
  82. package/dist/server/prebuilt/capture-render.d.ts.map +1 -1
  83. package/dist/server/prebuilt/capture-routes.d.ts +1 -1
  84. package/dist/server/prebuilt/dev-store.d.ts +103 -0
  85. package/dist/server/prebuilt/dev-store.d.ts.map +1 -0
  86. package/dist/server/prebuilt/overlay.d.ts +5 -0
  87. package/dist/server/prebuilt/overlay.d.ts.map +1 -1
  88. package/dist/server/prebuilt/payload-source.d.ts +8 -0
  89. package/dist/server/prebuilt/payload-source.d.ts.map +1 -1
  90. package/dist/server/prebuilt/slots.d.ts +5 -6
  91. package/dist/server/prebuilt/slots.d.ts.map +1 -1
  92. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  93. package/dist/server/prebuilt-runtime.d.ts +5 -10
  94. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  95. package/dist/server/render-timeout.d.ts.map +1 -1
  96. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  98. package/dist/server/ssr-render.d.ts.map +1 -1
  99. package/docs/api/32-api-cache.mdx +2 -0
  100. package/docs/learn/10-caching.mdx +12 -0
  101. package/docs/learn/11-middleware.mdx +2 -0
  102. package/package.json +1 -1
  103. package/src/cache/cache-api.ts +7 -1
  104. package/src/cache/handler-store.ts +38 -1
  105. package/src/cache/invalidation-epoch.ts +18 -6
  106. package/src/cache/timber-cache.ts +6 -2
  107. package/src/cdn/purge-store.ts +29 -1
  108. package/src/client/browser-entry/action-dispatch.ts +5 -5
  109. package/src/client/browser-entry/router-init.ts +2 -4
  110. package/src/client/link.tsx +14 -18
  111. package/src/client/navigation-transition.ts +86 -33
  112. package/src/client/router-effects.ts +70 -45
  113. package/src/client/router-lifecycle.ts +1 -1
  114. package/src/client/router-pipeline.ts +52 -65
  115. package/src/client/router-types.ts +11 -31
  116. package/src/client/router.ts +98 -104
  117. package/src/dev-tools/logs.ts +76 -50
  118. package/src/plugins/dev-server.ts +23 -8
  119. package/src/plugins/entries.ts +6 -0
  120. package/src/plugins/orphaned-modules.ts +78 -0
  121. package/src/plugins/prebuilt.ts +17 -17
  122. package/src/plugins/prerender-sugar.ts +38 -6
  123. package/src/plugins/routing.ts +23 -1
  124. package/src/rsc-runtime/dev-reference-cache.ts +115 -0
  125. package/src/rsc-runtime/rsc.ts +10 -0
  126. package/src/rsc-runtime/ssr.ts +10 -0
  127. package/src/server/abort-scope.ts +49 -0
  128. package/src/server/flight-source-node.ts +5 -4
  129. package/src/server/instrumentation.ts +32 -8
  130. package/src/server/internal.ts +1 -6
  131. package/src/server/pipeline-helpers.ts +5 -3
  132. package/src/server/pipeline.ts +31 -20
  133. package/src/server/prebuilt/cache-key.ts +41 -0
  134. package/src/server/prebuilt/capture-render.ts +10 -6
  135. package/src/server/prebuilt/capture-routes.ts +1 -1
  136. package/src/server/prebuilt/dev-store.ts +173 -0
  137. package/src/server/prebuilt/overlay.ts +7 -1
  138. package/src/server/prebuilt/payload-source.ts +19 -0
  139. package/src/server/prebuilt/slots.ts +5 -6
  140. package/src/server/prebuilt-builder.ts +3 -2
  141. package/src/server/prebuilt-runtime.ts +174 -176
  142. package/src/server/render-timeout.ts +12 -17
  143. package/src/server/rsc-entry/action-dispatcher.ts +3 -1
  144. package/src/server/rsc-entry/index.ts +47 -13
  145. package/src/server/ssr-render.ts +9 -11
  146. package/dist/_chunks/cache-api-LA3sBpUS.js.map +0 -1
  147. package/dist/_chunks/dev-server-DkytOEG2.js +0 -1
  148. package/dist/_chunks/error-boundary-xxxLtXt6.js.map +0 -1
  149. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +0 -1
  150. package/dist/_chunks/node-response-Dibufw_b.js.map +0 -1
  151. package/dist/_chunks/purge-store-Byr8XOjU.js.map +0 -1
  152. package/dist/_chunks/render-timeout-DOf_BBcO.js.map +0 -1
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Abort listeners scoped to the work they guard.
3
+ *
4
+ * A request's signal outlives the render, stream, or timer that listens to
5
+ * it, and a listener left on it keeps everything its closure holds reachable
6
+ * from the request. In production that only delays collection until the
7
+ * request is garbage. In dev it pins the request forever: React's dev Flight
8
+ * server tracks every live promise in an async-hook Map whose debug chains
9
+ * reach the request, so any promise reachable from the request is never
10
+ * collected and never leaves that Map (TIM-1589).
11
+ *
12
+ * So server code never calls `signal.addEventListener('abort', …)` itself
13
+ * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}
14
+ * takes the end of the listener's scope as a required argument, which makes
15
+ * a listener without a removal unwritable.
16
+ */
17
+
18
+ /**
19
+ * Call `onAbort` if `signal` aborts before the scope `until` ends. If
20
+ * `signal` has already aborted, `onAbort` runs now.
21
+ *
22
+ * `until` is the scope: a promise (the listener is removed when it fulfills
23
+ * or rejects, a microtask later) or an `AbortSignal` (removed synchronously
24
+ * when it aborts; use one when an abort later in the same tick must not
25
+ * fire, as after a timeout's `cancel()`).
26
+ */
27
+ export function onAbortUntil(
28
+ signal: AbortSignal | undefined,
29
+ onAbort: () => void,
30
+ until: PromiseLike<unknown> | AbortSignal
31
+ ): void {
32
+ if (!signal) return;
33
+ if (signal.aborted) {
34
+ onAbort();
35
+ return;
36
+ }
37
+ let scope: AbortSignal;
38
+ if (until instanceof AbortSignal) {
39
+ scope = until;
40
+ } else {
41
+ const ended = new AbortController();
42
+ const end = (): void => ended.abort();
43
+ until.then(end, end);
44
+ scope = ended.signal;
45
+ }
46
+ // addEventListener's own `signal` option removes the listener when the
47
+ // scope aborts: the platform's one-step removal, no handle to keep.
48
+ signal.addEventListener('abort', onAbort, { once: true, signal: scope });
49
+ }
@@ -19,6 +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
23
  import { RenderTimeoutError } from './render-timeout.ts';
23
24
 
24
25
  // `String.prototype.toWellFormed` ships in every Node timber supports
@@ -93,7 +94,7 @@ export function pipeFlightToNode(
93
94
  flight: PipeableFlight,
94
95
  { signal, timeoutMs }: NodeFlightAbort
95
96
  ): Readable {
96
- const onAbort = (): void => flight.abort(signal?.reason);
97
+ const scope = new AbortController();
97
98
  const timer =
98
99
  timeoutMs === undefined
99
100
  ? undefined
@@ -107,7 +108,7 @@ export function pipeFlightToNode(
107
108
  callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);
108
109
  },
109
110
  destroy(error, callback) {
110
- signal?.removeEventListener('abort', onAbort);
111
+ scope.abort();
111
112
  clearTimeout(timer);
112
113
  // A no-op once Flight has finished (it ignores abort after close).
113
114
  flight.abort(error ?? undefined);
@@ -115,8 +116,8 @@ export function pipeFlightToNode(
115
116
  },
116
117
  });
117
118
  stream.on('error', ignoreError);
118
- if (signal?.aborted) flight.abort(signal.reason);
119
- else signal?.addEventListener('abort', onAbort, { once: true });
119
+ // The listener lasts until the stream is destroyed (server/abort-scope.ts).
120
+ onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);
120
121
  flight.pipe(stream);
121
122
  return stream;
122
123
  }
@@ -9,7 +9,7 @@
9
9
  * See design/17-logging.md §"instrumentation.ts — The Entry Point"
10
10
  */
11
11
 
12
- import { setLogger, type TimberLogger } from './logger.ts';
12
+ import { getLogger, setLogger, type TimberLogger } from './logger.ts';
13
13
 
14
14
  // ─── Instrumentation Types ────────────────────────────────────────────────
15
15
 
@@ -60,7 +60,19 @@ interface InstrumentationModule {
60
60
  // once at server startup and persists for the lifetime of the process/isolate.
61
61
  // These must NOT be migrated to ALS — they are correctly scoped to the app.
62
62
 
63
- let _initialized = false;
63
+ type InstrumentationLoader = () => Promise<InstrumentationModule | null>;
64
+
65
+ /**
66
+ * The loader the current hooks came from. One app passes one loader
67
+ * (`virtual:timber-instrumentation`), so a second call with it is a no-op.
68
+ * In dev a new loader means instrumentation.ts changed: the RSC entry is an
69
+ * HMR boundary (design/21 §HMR Wiring), so editing instrumentation.ts
70
+ * re-executes the virtual loader module and the entry, while this module
71
+ * keeps its state. The new module then replaces the old one's hooks.
72
+ */
73
+ let _loadedFrom: InstrumentationLoader | null = null;
74
+ /** The framework logger before any instrumentation module replaced it. */
75
+ let _loggerBeforeLoad: TimberLogger | null = null;
64
76
  let _onRequestError: InstrumentationOnRequestError | null = null;
65
77
 
66
78
  /**
@@ -73,11 +85,16 @@ let _onRequestError: InstrumentationOnRequestError | null = null;
73
85
  * @param loader - Function that dynamically imports the user's instrumentation module.
74
86
  * Returns null if no instrumentation.ts exists.
75
87
  */
76
- export async function loadInstrumentation(
77
- loader: () => Promise<InstrumentationModule | null>
78
- ): Promise<void> {
79
- if (_initialized) return;
80
- _initialized = true;
88
+ export async function loadInstrumentation(loader: InstrumentationLoader): Promise<void> {
89
+ if (_loadedFrom === loader) return;
90
+ if (_loadedFrom === null) {
91
+ _loggerBeforeLoad = getLogger();
92
+ } else {
93
+ // A changed instrumentation.ts (dev): drop what the previous one installed.
94
+ _onRequestError = null;
95
+ setLogger(_loggerBeforeLoad!);
96
+ }
97
+ _loadedFrom = loader;
81
98
 
82
99
  let mod: InstrumentationModule | null;
83
100
  try {
@@ -105,6 +122,12 @@ export async function loadInstrumentation(
105
122
  await mod.register();
106
123
  } catch (error) {
107
124
  console.error('[timber] instrumentation.ts register() threw:', error);
125
+ // Not loaded: the entry fails, and its next run (the next request or
126
+ // edit in dev) must call register() again instead of returning early
127
+ // on this loader and serving without it (TIM-1589).
128
+ _onRequestError = null;
129
+ if (_loggerBeforeLoad) setLogger(_loggerBeforeLoad);
130
+ _loadedFrom = null;
108
131
  throw error;
109
132
  }
110
133
  }
@@ -138,6 +161,7 @@ export function hasOnRequestError(): boolean {
138
161
  * Reset instrumentation state. Test-only.
139
162
  */
140
163
  export function resetInstrumentation(): void {
141
- _initialized = false;
164
+ _loadedFrom = null;
165
+ _loggerBeforeLoad = null;
142
166
  _onRequestError = null;
143
167
  }
@@ -152,12 +152,7 @@ export { RenderTimeoutError } from './render-timeout.ts';
152
152
  export type { RenderTimeout } from './render-timeout.ts';
153
153
 
154
154
  // ── Prebuilt Components (cache.component transform targets) ─────────────
155
- export {
156
- __prebuilt,
157
- __prebuiltDev,
158
- getPrebuiltRegistration,
159
- getPrebuiltRegistry,
160
- } from './prebuilt-runtime.ts';
155
+ export { __prebuilt, getPrebuiltRegistration, getPrebuiltRegistry } from './prebuilt-runtime.ts';
161
156
  export type { PrebuiltComponentOptions, PrebuiltRegistration } from './prebuilt-runtime.ts';
162
157
  export { setPrebuiltPayloadSource, hasPrebuiltPayloadSource } from './prebuilt/payload-source.ts';
163
158
  export type {
@@ -18,6 +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
22
  import { RedirectSignal } from './primitives.ts';
22
23
  import { isControlFlowSignal } from './signal-identity.ts';
23
24
  import { logRenderError, logSkippedModule, swallow } from './logger.ts';
@@ -522,14 +523,15 @@ export async function runBackgroundFlight(
522
523
  const request = requestContextAls.getStore()?.request;
523
524
  if (request && isReportableError(error)) fireInBackground(callHook(error, request, 'render'));
524
525
  };
525
- const onTimeout = (): void => failed(signal.reason);
526
- signal.addEventListener('abort', onTimeout, { once: true });
526
+ // The listener lasts until the work settles (server/abort-scope.ts).
527
+ const settled = new AbortController();
528
+ onAbortUntil(signal, () => failed(signal.reason), settled.signal);
527
529
  try {
528
530
  await work();
529
531
  } catch (error) {
530
532
  if (!signal.aborted) failed(error);
531
533
  } finally {
532
- signal.removeEventListener('abort', onTimeout);
534
+ settled.abort();
533
535
  }
534
536
  }
535
537
 
@@ -251,16 +251,19 @@ export interface PipelineConfig {
251
251
  * value that `handleRequest` and `matchRoute` use. Do NOT re-derive it
252
252
  * from `req.url` (which re-encodes).
253
253
  *
254
- * The `reenter` parameter is the full pipeline function (including proxy,
255
- * ALS, tracing) for the no-JS action rerender path — the synthetic GET
256
- * flows through the complete pipeline. Its `cookies` become that request's
257
- * parsed cookies and its `formState` the action's form state for SSR
258
- * (`runWithRequestContext`'s options), so the rerender reads both without
259
- * the pipeline needing the same `Request` object to reach them.
254
+ * The `reenter` parameter renders the page for a no-JS action that did
255
+ * not redirect. It enters the pipeline after proxy.ts: the synthetic GET
256
+ * is an internal render of the POST's answer, not a second wire request,
257
+ * so it keeps the POST's trace ID and is neither proxied nor logged again
258
+ * (TIM-1445). Route matching, middleware.ts and access.ts run as for any
259
+ * page render. It runs in its own request context: the GET, with the
260
+ * reentry's `cookies` as its parsed cookies and its `formState` or
261
+ * `actionError` for the render (`runWithRequestContext`'s options).
260
262
  *
261
263
  * Moved into the pipeline (TIM-1213) so proxy.ts runs on action POSTs,
262
264
  * matching the design doc contract: "proxy.ts runs on every request,
263
- * no exclusions."
265
+ * no exclusions." It runs once per wire request; the outer pass wraps
266
+ * the rerendered response.
264
267
  */
265
268
  dispatchAction?: (
266
269
  req: Request,
@@ -307,11 +310,7 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
307
310
  // Logged with each request for diagnosing resource contention.
308
311
  let activeRequests = 0;
309
312
 
310
- // Self-reference for re-entry — the no-JS validation rerender path
311
- // passes a synthetic GET back through the full pipeline (including
312
- // proxy, ALS, tracing). The inner closure captures `pipelineFn` by
313
- // name; by the time it's invoked, the const binding is initialized.
314
- const pipelineFn = async (req: Request, reentry?: PipelineReentry): Promise<Response> => {
313
+ return async (req: Request): Promise<Response> => {
315
314
  const url = new URL(req.url);
316
315
  const method = req.method;
317
316
  const path = url.pathname;
@@ -416,10 +415,28 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
416
415
  );
417
416
  if (redirect) return redirect;
418
417
  if (config.dispatchAction) {
418
+ // A no-JS action's answer re-enters here, inside this
419
+ // request's proxy.ts, trace and log scope, which ran once
420
+ // for the wire POST (TIM-1445). Only the request context
421
+ // is new. It renders the POST's canonical path: the
422
+ // answer is always the page the form posted to.
423
+ const reenter = (rerenderReq: Request, reentry: PipelineReentry) =>
424
+ runWithRequestContext(
425
+ rerenderReq,
426
+ () =>
427
+ handleRequest(
428
+ config,
429
+ rerenderReq,
430
+ rerenderReq.method,
431
+ canonicalPath,
432
+ true
433
+ ),
434
+ reentry
435
+ );
419
436
  const actionResult = await config.dispatchAction(
420
437
  canonicalReq,
421
438
  canonicalPath,
422
- pipelineFn
439
+ reenter
423
440
  );
424
441
  if (actionResult) return actionResult;
425
442
  }
@@ -571,13 +588,7 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
571
588
 
572
589
  return serverTiming === 'detailed' ? runWithTimingCollector(runRequest) : runRequest();
573
590
  };
574
- return runWithRequestContext(req, inRequestContext, {
575
- cookies: reentry?.cookies,
576
- formState: reentry?.formState,
577
- actionError: reentry?.actionError,
578
- });
591
+ return runWithRequestContext(req, inRequestContext);
579
592
  });
580
593
  };
581
-
582
- return pipelineFn;
583
594
  }
@@ -42,6 +42,7 @@
42
42
 
43
43
  import { createHash } from 'node:crypto';
44
44
  import type { CoercedParams } from '../../shared/param-value.ts';
45
+ import type { SlotParamsRecord } from '../../shared/slot-params.ts';
45
46
 
46
47
  class UnkeyableValueError extends Error {}
47
48
 
@@ -297,3 +298,43 @@ export function computeComponentCacheKey(
297
298
  // aggressively.
298
299
  return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
299
300
  }
301
+
302
+ /**
303
+ * Resolve the params the cache key may faithfully hash, or null if this
304
+ * render is unkeyable.
305
+ *
306
+ * A wrapper rendered inside a parallel slot reads params merged with that
307
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
308
+ * — but the cache key hashes only the route-level params, and the wrapper
309
+ * cannot know which slot it renders under. The route params are usable
310
+ * only when every slot's merged view canonicalizes identically to them;
311
+ * otherwise two renders with the same key could see different effective
312
+ * inputs and a hit could serve the WRONG cached subtree — so the render
313
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
314
+ * params either, so a divergent request could never have a faithful
315
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
316
+ * if slot-scoped prebuilt is ever needed.)
317
+ *
318
+ * Comparison happens through `tryCanonicalize` — the same single
319
+ * definition of value equality the cache key uses — so anything it
320
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
321
+ * aliases, …) is unkeyable here too, and this guard can never throw.
322
+ */
323
+ export function resolveKeyParams(store: {
324
+ segmentParams?: CoercedParams;
325
+ slotParams?: SlotParamsRecord;
326
+ }): CoercedParams | null {
327
+ const main = store.segmentParams ?? {};
328
+ const slots = store.slotParams;
329
+ if (!slots || Object.keys(slots).length === 0) return main;
330
+ // Spread before canonicalizing: param records are framework-produced
331
+ // Object.create(null) objects (prototype-pollution defense) — normalize
332
+ // the records themselves, let nested values face the full allowlist.
333
+ const mainCanonical = tryCanonicalize({ ...main });
334
+ if (mainCanonical === null) return null;
335
+ for (const slotParams of Object.values(slots)) {
336
+ const merged = tryCanonicalize({ ...main, ...slotParams });
337
+ if (merged === null || merged !== mainCanonical) return null;
338
+ }
339
+ return main;
340
+ }
@@ -1,16 +1,19 @@
1
1
  /**
2
- * One build-time capture entry (server/prebuilt-builder.ts): render a
3
- * registered component in isolation under the synthetic build store and
4
- * drain its flight payload under a deadline.
2
+ * One build-time capture entry: render a registered component in isolation
3
+ * under the synthetic build store and drain its flight payload under a
4
+ * deadline. Run by the post-build capture pass (server/prebuilt-builder.ts)
5
+ * and, in dev, by the first request for a prerender entry
6
+ * (server/prebuilt-runtime.ts, TIM-1588) — which is why the flight renderer
7
+ * is a parameter: the request-time runtime renders through the functions
8
+ * the RSC entry injected.
5
9
  */
6
10
 
7
11
  import { createElement } from 'react';
8
12
 
9
13
  import { SlotOutlet } from '../../client/slot-outlet.tsx';
10
14
  import type { CoercedParams } from '../../shared/param-value.ts';
11
- import { renderFlight } from '../../rsc-runtime/rsc.ts';
12
15
  import { requestContextAls } from '../als-registry.ts';
13
- import { collectFlightBytes } from '../flight-source.ts';
16
+ import { collectFlightBytes, type RenderFlight } from '../flight-source.ts';
14
17
  import type { PrebuiltRegistration } from '../prebuilt-runtime.ts';
15
18
  import { createCaptureScope, type NestedWrapperRender } from './capture-state.ts';
16
19
  import { resolveTags } from './lifetime.ts';
@@ -53,7 +56,8 @@ export async function renderEntry(
53
56
  props: Record<string, unknown>,
54
57
  coercedParams: CoercedParams,
55
58
  timeoutMs: number,
56
- isLayout: boolean
59
+ isLayout: boolean,
60
+ renderFlight: RenderFlight
57
61
  ): Promise<EntryOutcome> {
58
62
  const storeHandle = createBuildTimeStore(registration.id, coercedParams);
59
63
  const { store, violations } = storeHandle;
@@ -27,7 +27,7 @@ export interface CandidateRoute {
27
27
  * layouts above it) has prebuilt components attributed to it. Slots and
28
28
  * intercepting/private segments are not walked — slot-scoped prebuilt is
29
29
  * already unkeyable at request time when slot params diverge (see
30
- * resolveKeyParams in prebuilt-runtime.ts), so the build doesn't model
30
+ * resolveKeyParams in prebuilt/cache-key.ts), so the build doesn't model
31
31
  * slots either.
32
32
  */
33
33
  export function collectCandidateRoutes(
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Dev-mode store for cache.component output (TIM-1588, design/44 §Dev Mode).
3
+ *
4
+ * In production a `prerender` entry is captured at build time and frozen
5
+ * until the next deploy. Dev has no build step, so this in-memory store
6
+ * stands in for the build artifact: a prerender-tier render is captured on
7
+ * its first request (under the synthetic build store, so request-context
8
+ * reads fail exactly as `pnpm build` would) and served from here after
9
+ * that. Runtime-tier entries (`ttl`/`tags`) keep using the cache-handler
10
+ * overlay; in dev their keys carry this store's namespace (`overlayKey`).
11
+ *
12
+ * Invalidation is deliberately coarse: ANY dev-server watcher event clears
13
+ * everything. The dev-server plugin sends `PREBUILT_DEV_CLEAR_EVENT` to the
14
+ * RSC environment and the RSC entry calls `clearDevPrebuiltStore()`. There
15
+ * is no per-component dependency tracking — the module graph misses files
16
+ * read with `fs`, and one re-render per save is what dev used to pay on
17
+ * every request. A clear does three things:
18
+ *
19
+ * 1. drops every seed;
20
+ * 2. bumps the generation, which namespaces dev overlay keys, so
21
+ * runtime-tier entries stored before the save become unreachable;
22
+ * 3. records an invalidation of everything (`recordInvalidationOfAll`),
23
+ * so a capture already in flight — which may have loaded the
24
+ * pre-save code — is not stored, and a request arriving after the
25
+ * save does not join that flight (the TIM-1028 guard every capture
26
+ * path already runs).
27
+ *
28
+ * Inactive outside dev: production never enables it. Dev enables it only
29
+ * when HMR is on — with `server.hmr: false` Vite delivers no watcher events
30
+ * to plugins and nothing would clear the store, so dev bypasses caching
31
+ * entirely instead (`DevPrebuiltStoreMode`).
32
+ */
33
+
34
+ import { getCacheHandler } from '../../cache/handler-store.ts';
35
+ import { recordInvalidation, recordInvalidationOfAll } from '../../cache/invalidation-epoch.ts';
36
+
37
+ /** Custom HMR event the dev-server plugin sends to the RSC environment. */
38
+ export const PREBUILT_DEV_CLEAR_EVENT = 'timber:prebuilt-dev-clear';
39
+
40
+ /** One captured prerender-tier entry — the dev counterpart of a `.flight` seed. */
41
+ export interface DevSeed {
42
+ bytes: Uint8Array;
43
+ /** Resolved tags, so `revalidateTag` can drop an ISR seed. */
44
+ tags: string[];
45
+ /** Capture time; stands in for the manifest's buildTimestamp. */
46
+ capturedAt: number;
47
+ }
48
+
49
+ /**
50
+ * - `off`: production (and the default). Wrappers use the build artifact and
51
+ * the overlay.
52
+ * - `active`: dev with HMR. The dev store stands in for the build artifact.
53
+ * - `bypass`: dev without HMR (`server.hmr: false`). No watcher event would
54
+ * ever reach the store, so nothing is cached at all: every wrapper renders
55
+ * live, runtime-tier ones included (the overlay would otherwise hold
56
+ * entries a save never clears).
57
+ */
58
+ export type DevPrebuiltStoreMode = 'off' | 'active' | 'bypass';
59
+
60
+ let mode: DevPrebuiltStoreMode = 'off';
61
+ let generation = 0;
62
+ const seeds = new Map<string, DevSeed>();
63
+
64
+ /**
65
+ * Distinguishes this process's overlay keys from a previous dev session's,
66
+ * in case the configured cache handler outlives the process (Redis in dev).
67
+ * Created on first use, never at module load: production imports this
68
+ * module too, and Workers reject random-value generation in global scope.
69
+ * Global `crypto`, not node:crypto, because dev may run the RSC environment
70
+ * in workerd.
71
+ */
72
+ let processToken: string | null = null;
73
+
74
+ function seedKey(componentId: string, cacheKey: string): string {
75
+ return `${componentId}:${cacheKey}`;
76
+ }
77
+
78
+ /** Set by the RSC entry in dev (and by tests). The store starts empty either way. */
79
+ export function setDevPrebuiltStoreMode(next: DevPrebuiltStoreMode): void {
80
+ mode = next;
81
+ seeds.clear();
82
+ }
83
+
84
+ export function isDevPrebuiltStoreActive(): boolean {
85
+ return mode === 'active';
86
+ }
87
+
88
+ /** Dev without HMR: every cache.component wrapper renders live. */
89
+ export function isDevPrebuiltCacheBypassed(): boolean {
90
+ return mode === 'bypass';
91
+ }
92
+
93
+ /**
94
+ * Namespace for overlay keys while the dev store is active, in place of the
95
+ * deployment ID (which is null in dev). Changes on every clear. Null when
96
+ * inactive.
97
+ */
98
+ export function devOverlayNamespace(): string | null {
99
+ if (mode !== 'active') return null;
100
+ processToken ??= crypto.randomUUID().slice(0, 8);
101
+ return `dev-${processToken}-${generation}`;
102
+ }
103
+
104
+ /**
105
+ * The key a `cache.data` entry is stored under: the logical key, prefixed in
106
+ * dev with the namespace above. So a save makes every data entry stored
107
+ * before it unreachable, whatever the handler. A data function's ID comes
108
+ * from its call site, so editing a helper it calls, or a file it reads,
109
+ * would otherwise keep serving the old result to every component captured
110
+ * after the save. Invalidation epochs and singleflight stay on the logical
111
+ * key; only the handler sees the prefix.
112
+ */
113
+ export function devDataCacheKey(key: string): string {
114
+ const namespace = devOverlayNamespace();
115
+ return namespace === null ? key : `${namespace}\u0000${key}`;
116
+ }
117
+
118
+ export function getDevSeed(componentId: string, cacheKey: string): DevSeed | undefined {
119
+ return seeds.get(seedKey(componentId, cacheKey));
120
+ }
121
+
122
+ /**
123
+ * Store a captured seed. The caller has already checked that no clear (or
124
+ * tag invalidation) happened while it was capturing.
125
+ */
126
+ export function setDevSeed(componentId: string, cacheKey: string, seed: DevSeed): void {
127
+ seeds.set(seedKey(componentId, cacheKey), seed);
128
+ }
129
+
130
+ /** Drop everything — called on every dev-server watcher event. */
131
+ export function clearDevPrebuiltStore(): void {
132
+ seeds.clear();
133
+ generation++;
134
+ recordInvalidationOfAll();
135
+ }
136
+
137
+ /**
138
+ * A hard reload: discard one entry — its seed and its overlay record — so
139
+ * the request renders it again. Recorded as an invalidation of its key
140
+ * first, so a capture of it already in flight (which may have read the old
141
+ * external data) neither stores nor is joined by this request.
142
+ */
143
+ export async function discardDevEntry(
144
+ componentId: string,
145
+ cacheKey: string,
146
+ overlayKey: string
147
+ ): Promise<void> {
148
+ recordInvalidation({ key: overlayKey });
149
+ seeds.delete(seedKey(componentId, cacheKey));
150
+ await getCacheHandler().invalidate({ key: overlayKey });
151
+ }
152
+
153
+ /**
154
+ * `revalidateTag` in dev: drop the seeds carrying the tag. This is the dev
155
+ * counterpart of writing a tombstone over a build seed (design/45 §ISR
156
+ * mechanics) — the next request misses and captures again.
157
+ */
158
+ export function invalidateDevSeedsByTag(tag: string): void {
159
+ for (const [key, seed] of seeds) {
160
+ if (seed.tags.includes(tag)) seeds.delete(key);
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Whether the request asks to skip caches — a browser hard reload, or any
166
+ * request while DevTools "Disable cache" is on, sends `Cache-Control:
167
+ * no-cache`. Dev only: the escape hatch for components that read external
168
+ * data (a CMS, a database) while it is being edited. Production never
169
+ * honors it — a client must not be able to force cache.component re-renders.
170
+ */
171
+ export function isHardReload(headers: Headers): boolean {
172
+ return /(?:^|,)\s*no-cache\s*(?:,|$)/i.test(headers.get('cache-control') ?? '');
173
+ }
@@ -16,6 +16,7 @@
16
16
  import { getCacheHandler, isCacheHandlerConfigured } from '../../cache/handler-store.ts';
17
17
  import { MemoryCacheHandler } from '../../cache/index.ts';
18
18
  import { getDeploymentId } from '../version-skew.ts';
19
+ import { devOverlayNamespace } from './dev-store.ts';
19
20
  import { buildTagIndex, type SeedKeyInfo } from './manifest-tag-index.ts';
20
21
  import type { PrebuiltManifest } from './payload-source.ts';
21
22
  import { ensureManifestLoaded } from './payload-source.ts';
@@ -62,8 +63,13 @@ export function isTombstone(v: unknown): v is ComponentTombstoneRecord {
62
63
 
63
64
  // ─── Overlay key generation ──────────────────────────────────────────────
64
65
 
66
+ /**
67
+ * In dev the deployment ID is null; the dev store namespace stands in for
68
+ * it and changes on every source change, so entries stored before a save
69
+ * become unreachable (server/prebuilt/dev-store.ts).
70
+ */
65
71
  export function overlayKey(componentId: string, cacheKey: string): string {
66
- const deploymentId = getDeploymentId() ?? 'dev';
72
+ const deploymentId = getDeploymentId() ?? devOverlayNamespace() ?? 'dev';
67
73
  return `timber:c:${deploymentId}:${componentId}:${cacheKey}`;
68
74
  }
69
75
 
@@ -200,3 +200,22 @@ export async function lookupPrebuiltPayload(
200
200
  return null;
201
201
  }
202
202
  }
203
+
204
+ /** A seed entry: build artifact bytes, or their dev-store counterpart. */
205
+ export interface Seed {
206
+ payload: Uint8Array;
207
+ /** When the seed was rendered — the logical start of its `ttl`. */
208
+ capturedAt: number;
209
+ }
210
+
211
+ /** The build-artifact seed for an entry, or null if the build has none. */
212
+ export async function lookupArtifactSeed(
213
+ id: string,
214
+ cacheKey: string,
215
+ needsTimestamp: boolean
216
+ ): Promise<Seed | null> {
217
+ const payload = await lookupPrebuiltPayload(id, cacheKey);
218
+ if (payload === null) return null;
219
+ const entry = needsTimestamp ? await getManifestEntry(id, cacheKey) : null;
220
+ return { payload, capturedAt: entry?.buildTimestamp ?? 0 };
221
+ }
@@ -8,9 +8,9 @@
8
8
  * TIM-1181 layout mechanism to explicitly declared, named slots on any
9
9
  * cached component. Layouts use the same mechanism with a `children` slot.
10
10
  *
11
- * Both the production wrapper (cache path) and the dev wrapper (no cache,
12
- * same tree shape for dev/prod parity) build their render from these
13
- * helpers. See design/45-cache-lifetimes.md §Slot Components.
11
+ * The `__prebuilt` wrapper builds its slot render from these helpers, in
12
+ * dev and production alike. See design/45-cache-lifetimes.md §Slot
13
+ * Components.
14
14
  */
15
15
 
16
16
  import { createElement } from 'react';
@@ -113,9 +113,8 @@ function isDenseStringArray(value: unknown): value is string[] {
113
113
  }
114
114
 
115
115
  /**
116
- * Validate the `slots` option. Both the production and dev wrappers gate
117
- * on this — slot substitution is active in dev exactly when it would be
118
- * active in production, so the tree shape a component sees never
116
+ * Validate the `slots` option. The `__prebuilt` wrapper gates on this in
117
+ * dev and production alike, so the tree shape a component sees never
119
118
  * diverges between the two.
120
119
  */
121
120
  export function resolveSlotNames(id: string, options: PrebuiltComponentOptions): SlotResolution {
@@ -58,7 +58,7 @@ import { BuildTimeContextError } from './prebuilt/synthetic-store.ts';
58
58
  import { getPrebuiltRegistration } from './prebuilt-runtime.ts';
59
59
  import { createRouteMatcher } from './route-matcher.ts';
60
60
  import type { ManifestRoot } from './route-matcher.ts';
61
- import { createFromReadableStream } from '../rsc-runtime/rsc.ts';
61
+ import { createFromReadableStream, renderFlight } from '../rsc-runtime/rsc.ts';
62
62
  import { loadModule } from './safe-load.ts';
63
63
  import { resolvePathWithParams } from './sitemap-generator.ts';
64
64
  import { resolveRenderTimeoutMs } from './render-timeout.ts';
@@ -390,7 +390,8 @@ export async function capturePrebuiltPayloads(
390
390
  callSiteProps,
391
391
  coercedParams,
392
392
  timeoutMs,
393
- isLayout
393
+ isLayout,
394
+ renderFlight
394
395
  );
395
396
  // Track param reads immediately — before any failure continue —
396
397
  // so a combo that reads params then fails still prevents