@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
@@ -4,9 +4,11 @@
4
4
  * cache.component (TIM-1140).
5
5
  *
6
6
  * `cache.component(fn, opts)` call sites are rewritten at build time to
7
- * `__prebuilt(stableId, fn, opts)` (production) or `__prebuiltDev(name, fn)`
8
- * (dev). Both are exported via #server-internal — they are framework
9
- * plumbing, never called by user code directly.
7
+ * `__prebuilt(stableId, fn, opts)`, in dev and production alike. It is
8
+ * exported via #server-internal — framework plumbing, never called by user
9
+ * code directly. In dev the build artifact is replaced by the in-memory dev
10
+ * store (prebuilt/dev-store.ts): a prerender entry is captured on its first
11
+ * request and served until a watched file changes (TIM-1588).
10
12
  *
11
13
  * Cache hits are served by FLIGHT REVIVAL: the cached `.flight` payload is
12
14
  * decoded back into React elements inside the RSC environment with
@@ -37,8 +39,7 @@ import { createElement } from 'react';
37
39
 
38
40
  import { requestContextAls, type RequestContextStore } from './als-registry.ts';
39
41
  import type { CoercedParams } from '../shared/param-value.ts';
40
- import type { SlotParamsRecord } from '../shared/slot-params.ts';
41
- import { computeComponentCacheKey, tryCanonicalize } from './prebuilt/cache-key.ts';
42
+ import { computeComponentCacheKey, resolveKeyParams } from './prebuilt/cache-key.ts';
42
43
  import {
43
44
  resolveSlotNames,
44
45
  prepareSlotRender,
@@ -59,11 +60,22 @@ import {
59
60
  import { hasRuntimeLifetime, resolveTags, warnNestingClamps } from './prebuilt/lifetime.ts';
60
61
  import {
61
62
  hasPrebuiltPayloadSource,
62
- lookupPrebuiltPayload,
63
- getManifestEntry,
64
63
  isParamIndependent,
64
+ lookupArtifactSeed,
65
+ type Seed,
65
66
  } from './prebuilt/payload-source.ts';
66
67
  import { lookupOverlay, storeOverlayEntry, overlayKey } from './prebuilt/overlay.ts';
68
+ import {
69
+ clearDevPrebuiltStore,
70
+ discardDevEntry,
71
+ getDevSeed,
72
+ isDevPrebuiltCacheBypassed,
73
+ isDevPrebuiltStoreActive,
74
+ isHardReload,
75
+ setDevSeed,
76
+ } from './prebuilt/dev-store.ts';
77
+ import { renderEntry } from './prebuilt/capture-render.ts';
78
+ import { BuildTimeContextError } from './prebuilt/synthetic-store.ts';
67
79
  import { getWaitUntil } from './waituntil-bridge.ts';
68
80
  import { runBackgroundFlight } from './pipeline-helpers.ts';
69
81
  import { runOutsideReactCacheScope } from './react-cache-scope.ts';
@@ -162,66 +174,13 @@ export interface PrebuiltRegistration {
162
174
  /**
163
175
  * Server-side component registry, keyed by stable component ID. Populated at
164
176
  * module load time by `__prebuilt` calls; consumed by the post-build capture
165
- * pass (TIM-1119). Never serialized — component functions are not
177
+ * pass (TIM-1119). Not written in dev, where nothing walks it. Never serialized — component functions are not
166
178
  * Flight-serializable.
167
179
  */
168
180
  const registry = new Map<string, PrebuiltRegistration>();
169
181
 
170
- /**
171
- * Resolve the params the cache key may faithfully hash, or null if this
172
- * render is unkeyable.
173
- *
174
- * A wrapper rendered inside a parallel slot reads params merged with that
175
- * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
176
- * — but the cache key hashes only the route-level params, and the wrapper
177
- * cannot know which slot it renders under. The route params are usable
178
- * only when every slot's merged view canonicalizes identically to them;
179
- * otherwise two renders with the same key could see different effective
180
- * inputs and a hit could serve the WRONG cached subtree — so the render
181
- * goes live: slower, never wrong. (Build-time capture doesn't model slot
182
- * params either, so a divergent request could never have a faithful
183
- * entry. Codex review on PR #835; revisit with segment-path-scoped keys
184
- * if slot-scoped prebuilt is ever needed.)
185
- *
186
- * Comparison happens through `tryCanonicalize` — the same single
187
- * definition of value equality the cache key uses — so anything it
188
- * cannot represent faithfully (bigint-coerced codec params, accessors,
189
- * aliases, …) is unkeyable here too, and this guard can never throw.
190
- */
191
- function resolveKeyParams(store: {
192
- segmentParams?: CoercedParams;
193
- slotParams?: SlotParamsRecord;
194
- }): CoercedParams | null {
195
- const main = store.segmentParams ?? {};
196
- const slots = store.slotParams;
197
- if (!slots || Object.keys(slots).length === 0) return main;
198
- // Spread before canonicalizing: param records are framework-produced
199
- // Object.create(null) objects (prototype-pollution defense) — normalize
200
- // the records themselves, let nested values face the full allowlist.
201
- const mainCanonical = tryCanonicalize({ ...main });
202
- if (mainCanonical === null) return null;
203
- for (const slotParams of Object.values(slots)) {
204
- const merged = tryCanonicalize({ ...main, ...slotParams });
205
- if (merged === null || merged !== mainCanonical) return null;
206
- }
207
- return main;
208
- }
209
-
210
- /**
211
- * Mirror the production cache-key decision for a slot render, with no
212
- * cache IO — used by the dev wrapper so slot substitution happens in dev
213
- * exactly when production would serve the cache path rather than the
214
- * live fallback (dev/prod parity, codex P2 on PR #890): requires an ALS
215
- * store, keyable params (slot-param divergence unkeys), and keyable data
216
- * props (after the children slot outlet strip).
217
- */
218
- function isSlotRenderKeyable(dataProps: Record<string, unknown>): boolean {
219
- const store = requestContextAls.getStore();
220
- if (!store) return false;
221
- const keyParams = resolveKeyParams(store);
222
- if (keyParams === null) return false;
223
- return computeComponentCacheKey(withoutChildrenOutlet(dataProps), keyParams) !== null;
224
- }
182
+ /** Dev: IDs registered so far, to detect a module re-evaluating (no functions held). */
183
+ const devRegisteredIds = new Set<string>();
225
184
 
226
185
  /** Wrap payload bytes as a single-chunk ReadableStream for the decoder. */
227
186
  function bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
@@ -244,15 +203,14 @@ function bytesToStream(bytes: Uint8Array): ReadableStream<Uint8Array> {
244
203
  * Null on any miss — the caller renders live with the original props.
245
204
  */
246
205
  async function tryReviveSlotShell(
247
- id: string,
248
- options: PrebuiltComponentOptions,
206
+ registration: PrebuiltRegistration,
249
207
  slots: readonly string[],
250
208
  props: Record<string, unknown>
251
209
  ): Promise<{ element: unknown } | null> {
252
210
  const render = prepareSlotRender(props, slots);
253
211
  if (render === null) return null; // top-level props unkeyable → live render
254
212
  const { shellProps, dataProps, slotValues } = render;
255
- const revived = await tryRevivePayload(id, options, shellProps, dataProps);
213
+ const revived = await tryRevivePayload(registration, shellProps, dataProps);
256
214
  if (revived === null) return null;
257
215
  return { element: wrapInSlotsProvider(revived.element, slotValues) };
258
216
  }
@@ -521,21 +479,94 @@ function backgroundRerender(
521
479
  }
522
480
  }
523
481
 
482
+ /** Components already announced by the one-time dev log. */
483
+ const devLoggedIds = new Set<string>();
484
+
485
+ /**
486
+ * Dev: the seed for a prerender entry — the stored capture, or a new one
487
+ * rendered exactly as the build would render it (synthetic store, isolated
488
+ * render, nested wrappers baked flat) and stored until the next source
489
+ * change (prebuilt/dev-store.ts).
490
+ *
491
+ * Throws the BuildTimeContextError when the component read request
492
+ * context: `pnpm build` would fail on it, so dev fails too. Null on any
493
+ * other capture failure — the live render that follows reproduces the
494
+ * error, deny(), or redirect() with its normal semantics.
495
+ */
496
+ async function resolveDevSeed(
497
+ registration: PrebuiltRegistration,
498
+ props: Record<string, unknown>,
499
+ keyParams: CoercedParams,
500
+ cacheKey: string
501
+ ): Promise<Seed | null> {
502
+ const { id, options } = registration;
503
+ const stored = getDevSeed(id, cacheKey);
504
+ if (stored) return { payload: stored.bytes, capturedAt: stored.capturedAt };
505
+
506
+ const tags = resolveTags(options, props);
507
+ const oKey = overlayKey(id, cacheKey);
508
+ // The epoch scopes the flight: a request after a source change (which
509
+ // invalidates everything) never joins a capture of the old code.
510
+ const sfKey = `prebuilt-dev:${id}:${cacheKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
511
+ try {
512
+ return await componentSingleflight.do(sfKey, async (signal) => {
513
+ const startEpoch = currentInvalidationEpoch();
514
+ const capturedAt = Date.now();
515
+ const { renderFlight } = requireRscFunctions();
516
+ // Outside the request's React.cache scope, like every stored capture
517
+ // (TIM-1529).
518
+ const outcome = await runOutsideReactCacheScope(() =>
519
+ renderEntry(registration, props, keyParams, getCaptureTimeoutMs(), false, renderFlight)
520
+ );
521
+ if (outcome.failure instanceof BuildTimeContextError) throw outcome.failure;
522
+ if (outcome.bytes === null) return null;
523
+ // Smoke-revive before storing, as the build does: bytes that cannot
524
+ // be decoded would fail every later request until the next save.
525
+ if ((await revivePayload(id, outcome.bytes, 'not storing the dev capture')) === null) {
526
+ return null;
527
+ }
528
+ // A save (or revalidateTag) while this rendered: the bytes may come
529
+ // from the old code, so this request gets them but the store does not.
530
+ if (!signal.aborted && !wasInvalidatedSince(startEpoch, oKey, tags)) {
531
+ setDevSeed(id, cacheKey, { bytes: outcome.bytes, tags, capturedAt });
532
+ warnNestingClamps({ id, options, tags }, outcome.nested, warnedNestingPairs, (m) =>
533
+ console.warn(m)
534
+ );
535
+ if (!devLoggedIds.has(id)) {
536
+ devLoggedIds.add(id);
537
+ console.log(
538
+ `[timber] cache.component "${id}": prerendered in dev — served from memory until ` +
539
+ `a file changes. A hard reload (Cache-Control: no-cache) renders it again.`
540
+ );
541
+ }
542
+ }
543
+ return { payload: outcome.bytes, capturedAt };
544
+ });
545
+ } catch (error) {
546
+ if (error instanceof BuildTimeContextError) throw error;
547
+ console.error(`[timber] cache.component dev capture failed for "${id}":`, error);
548
+ return null;
549
+ }
550
+ }
551
+
524
552
  /**
525
- * Try to serve this render from the prebuilt cache: overlay → artifact →
553
+ * Try to serve this render from the prebuilt cache: overlay → seed →
526
554
  * live render. Handles ISR (SWR, tombstones, re-renders) per design/45.
527
555
  *
528
556
  * Null on any miss — the caller renders live.
529
557
  */
530
558
  async function tryRevivePayload(
531
- id: string,
532
- options: PrebuiltComponentOptions,
559
+ registration: PrebuiltRegistration,
533
560
  props: Record<string, unknown>,
534
561
  keyPropsOverride?: Record<string, unknown>
535
562
  ): Promise<{ element: unknown } | null> {
563
+ // The wrapper's own registration: re-renders run the component through
564
+ // the wrapper's closure, never a registry lookup.
565
+ const { id, options, component } = registration;
536
566
  const hasSource = hasPrebuiltPayloadSource();
567
+ const devStore = isDevPrebuiltStoreActive();
537
568
  const hasRuntime = hasRuntimeLifetime(options);
538
- if (!hasSource && !hasRuntime) return null;
569
+ if (!hasSource && !devStore && !hasRuntime) return null;
539
570
 
540
571
  const store = requestContextAls.getStore();
541
572
  if (!store) return null;
@@ -570,8 +601,13 @@ async function tryRevivePayload(
570
601
  ? 'failing the render (fallbackOnMissingSegmentParams: false)'
571
602
  : 'rendering dynamically';
572
603
 
573
- const registration = registry.get(id);
574
- const component = registration?.component;
604
+ // Dev only: a hard reload discards this entry first, so the lookups
605
+ // below miss and it renders again — a prerender entry under the
606
+ // synthetic store, exactly as on its first request (prebuilt/dev-store.ts
607
+ // `isHardReload`).
608
+ if (devStore && isHardReload(store.originalHeaders)) {
609
+ await discardDevEntry(id, cacheKey, overlayKey(id, cacheKey));
610
+ }
575
611
 
576
612
  // ─── Step 1: Check overlay (CacheHandler) ─────────────────────────
577
613
  if (hasRuntime) {
@@ -579,16 +615,13 @@ async function tryRevivePayload(
579
615
  if (overlayResult) {
580
616
  const overlayHasSeed = overlayResult.record?.s ?? false;
581
617
  if (overlayResult.kind === 'tombstone') {
582
- if (component) {
583
- return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
584
- }
585
- return null;
618
+ return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
586
619
  }
587
620
  if (overlayResult.kind === 'fresh' && overlayResult.payload) {
588
621
  return await revivePayload(id, overlayResult.payload, outcome);
589
622
  }
590
623
  if (overlayResult.kind === 'stale' && overlayResult.payload) {
591
- if (options.staleWhileRevalidate && component) {
624
+ if (options.staleWhileRevalidate) {
592
625
  backgroundRerender(
593
626
  id,
594
627
  component,
@@ -600,72 +633,66 @@ async function tryRevivePayload(
600
633
  );
601
634
  return await revivePayload(id, overlayResult.payload, outcome);
602
635
  }
603
- if (component) {
604
- return await inlineRerender(
636
+ return await inlineRerender(
637
+ id,
638
+ component,
639
+ props,
640
+ cacheKey,
641
+ options,
642
+ overlayHasSeed,
643
+ outcome
644
+ );
645
+ }
646
+ }
647
+ }
648
+
649
+ // ─── Step 2: Check the seed (build artifact, or the dev store) ────
650
+ const seed = devStore
651
+ ? options.prerender
652
+ ? await resolveDevSeed(registration, props, keyParams, cacheKey)
653
+ : null
654
+ : hasSource
655
+ ? await lookupArtifactSeed(id, cacheKey, options.ttl !== undefined)
656
+ : null;
657
+ if (seed !== null) {
658
+ // Check seed freshness when the component has a TTL.
659
+ if (options.ttl !== undefined) {
660
+ const seedAge = (Date.now() - seed.capturedAt) / 1000;
661
+ if (seedAge > options.ttl) {
662
+ // Stale seed
663
+ if (options.staleWhileRevalidate) {
664
+ backgroundRerender(
605
665
  id,
606
666
  component,
607
667
  props,
608
668
  cacheKey,
609
669
  options,
610
- overlayHasSeed,
611
- outcome
670
+ true,
671
+ snapshotRequestContext(store)
612
672
  );
673
+ return await revivePayload(id, seed.payload, outcome);
613
674
  }
614
- return null;
675
+ return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
615
676
  }
616
677
  }
678
+ // Fresh seed (or no TTL — immutable until redeploy)
679
+ return await revivePayload(id, seed.payload, outcome);
617
680
  }
618
681
 
619
- // ─── Step 2: Check build artifact ─────────────────────────────────
620
- if (hasSource) {
621
- const artifactPayload = await lookupPrebuiltPayload(id, cacheKey);
622
- if (artifactPayload !== null) {
623
- // Check seed freshness when the component has a TTL.
624
- if (options.ttl !== undefined) {
625
- const entry = await getManifestEntry(id, cacheKey);
626
- const buildTs = entry?.buildTimestamp ?? 0;
627
- const seedAge = (Date.now() - buildTs) / 1000;
628
- if (seedAge > options.ttl) {
629
- // Stale seed
630
- if (options.staleWhileRevalidate && component) {
631
- backgroundRerender(
632
- id,
633
- component,
634
- props,
635
- cacheKey,
636
- options,
637
- true,
638
- snapshotRequestContext(store)
639
- );
640
- return await revivePayload(id, artifactPayload, outcome);
641
- }
642
- if (component) {
643
- return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
644
- }
645
- // No component in registry — can't re-render; fall through to
646
- // live render via the wrapper (design/45 step 3).
647
- return null;
648
- }
649
- }
650
- // Fresh seed (or no TTL — immutable until redeploy)
651
- return await revivePayload(id, artifactPayload, outcome);
652
- }
653
-
654
- // Manifest miss
655
- if (options.prerender) {
656
- console.warn(
657
- `[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(
658
- store.segmentParams ?? {}
659
- )} — ${outcome}`
660
- );
661
- }
682
+ // Manifest miss
683
+ if (hasSource && options.prerender) {
684
+ console.warn(
685
+ `[timber] cache.component cache miss: "${id}" with params ${JSON.stringify(
686
+ store.segmentParams ?? {}
687
+ )} — ${outcome}`
688
+ );
662
689
  }
663
690
 
664
691
  // ─── Step 3: Full miss with runtime lifetime — inline re-render ───
665
692
  // Skip when fallbackOnMissingSegmentParams is false — that option means
666
693
  // "only prebuilt content", so an unenumerated miss must throw (the
667
694
  // wrapper handles the throw after we return null).
668
- if (hasRuntime && component && options.fallbackOnMissingSegmentParams !== false) {
695
+ if (hasRuntime && options.fallbackOnMissingSegmentParams !== false) {
669
696
  return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
670
697
  }
671
698
 
@@ -707,7 +734,19 @@ export function __prebuilt<C extends ServerComponent>(
707
734
  if (resolution.kind === 'disabled') {
708
735
  options = { ...options, slots: undefined };
709
736
  }
710
- registry.set(id, { id, component, options });
737
+ const registration: PrebuiltRegistration = { id, component, options };
738
+ if (isDevPrebuiltStoreActive()) {
739
+ // Dev: a second registration of an ID means its module re-evaluated,
740
+ // so some code in this subtree changed. Clear rather than trust that
741
+ // the watcher event already did (it may land after this request
742
+ // rendered). Dev keeps only the ID: nothing walks the registry there,
743
+ // and an edited call site gets a new ID, so holding registrations
744
+ // would pin every superseded component and its module for the session.
745
+ if (devRegisteredIds.has(id)) clearDevPrebuiltStore();
746
+ devRegisteredIds.add(id);
747
+ } else {
748
+ registry.set(id, registration);
749
+ }
711
750
 
712
751
  const wrapper = async (props: Parameters<C>[0]) => {
713
752
  // Report this render to the enclosing capture, if any — cycle
@@ -723,10 +762,16 @@ export function __prebuilt<C extends ServerComponent>(
723
762
  // spuriously fail the outer entry (codex P2 on PR #836).
724
763
  return createElement(component as RenderableComponent, props as Record<string, unknown>);
725
764
  }
765
+ // Dev without HMR: nothing could invalidate a cached entry, so render
766
+ // live, as dev did before it cached (no fallbackOnMissingSegmentParams
767
+ // throw either: there is no build to have missed).
768
+ if (isDevPrebuiltCacheBypassed()) {
769
+ return createElement(component as RenderableComponent, props as Record<string, unknown>);
770
+ }
726
771
 
727
772
  const revived = slots
728
- ? await tryReviveSlotShell(id, options, slots, props as Record<string, unknown>)
729
- : await tryRevivePayload(id, options, props as Record<string, unknown>);
773
+ ? await tryReviveSlotShell(registration, slots, props as Record<string, unknown>)
774
+ : await tryRevivePayload(registration, props as Record<string, unknown>);
730
775
  if (revived !== null) {
731
776
  return revived.element;
732
777
  }
@@ -761,50 +806,3 @@ export function getPrebuiltRegistration(id: string): PrebuiltRegistration | unde
761
806
  export function getPrebuiltRegistry(): ReadonlyMap<string, PrebuiltRegistration> {
762
807
  return registry;
763
808
  }
764
-
765
- /**
766
- * Dev-mode wrapper injected by the timber-prebuilt transform: a no-op that
767
- * renders the component dynamically on every request, logging once per
768
- * component on first render so the production behavior difference is visible.
769
- * See design/44 §Dev Mode.
770
- */
771
- export function __prebuiltDev<C extends ServerComponent>(
772
- name: string,
773
- component: C,
774
- options: PrebuiltComponentOptions = {}
775
- ): C {
776
- // Dev/prod parity for slot components: in production a slot component
777
- // ALWAYS receives a SlotOutlet element for each declared slot (never the
778
- // live children), so a component that introspects a slot prop would
779
- // behave differently between dev and prod if dev passed children
780
- // through. Dev renders the same tree shape — outlets in the props,
781
- // live values via SlotsProvider — just without any caching. The same
782
- // validation applies (including the lifetime requirement): slots are
783
- // active in dev exactly when they would be active in production.
784
- const resolution = resolveSlotNames(name, options);
785
- const slots = resolution.kind === 'active' ? resolution.slots : null;
786
- let logged = false;
787
- const wrapper = (props: Parameters<C>[0]) => {
788
- if (!logged) {
789
- logged = true;
790
- console.log(`[timber] cache.component: "${name}" — rendering dynamically (dev mode)`);
791
- }
792
- if (slots) {
793
- const render = prepareSlotRender(props as Record<string, unknown>, slots);
794
- // Substitute outlets only when PRODUCTION would: top-level props
795
- // splittable AND the data props keyable. Unkeyable inputs render
796
- // live with the original props there, so dev must too (parity —
797
- // codex P2 on PR #890).
798
- if (render !== null && isSlotRenderKeyable(render.dataProps)) {
799
- return wrapInSlotsProvider(
800
- createElement(component as RenderableComponent, render.shellProps),
801
- render.slotValues
802
- );
803
- }
804
- }
805
- // Element, not a direct call — same dispatcher reasoning as the
806
- // production wrapper's live fallback.
807
- return createElement(component as RenderableComponent, props as Record<string, unknown>);
808
- };
809
- return wrapper as C;
810
- }
@@ -8,6 +8,8 @@
8
8
  * Design doc: 02-rendering-pipeline.md §"Streaming Constraints"
9
9
  */
10
10
 
11
+ import { onAbortUntil } from './abort-scope.ts';
12
+
11
13
  /** `renderTimeoutMs` when timber.config.ts leaves it unset. */
12
14
  export const DEFAULT_RENDER_TIMEOUT_MS = 30_000;
13
15
 
@@ -76,30 +78,23 @@ export function createRenderTimeout(timeoutMs: number, parentSignal?: AbortSigna
76
78
  const reason = new RenderTimeoutError(timeoutMs, 'RSC stream read timed out');
77
79
 
78
80
  const timer = setTimeout(() => controller.abort(reason), timeoutMs);
81
+ const scope = new AbortController();
79
82
 
80
- let onParentAbort: (() => void) | null = null;
81
-
82
- if (parentSignal) {
83
- if (parentSignal.aborted) {
83
+ // The parent listener lasts until cancel() (server/abort-scope.ts).
84
+ onAbortUntil(
85
+ parentSignal,
86
+ () => {
84
87
  clearTimeout(timer);
85
- controller.abort(parentSignal.reason);
86
- } else {
87
- onParentAbort = () => {
88
- clearTimeout(timer);
89
- controller.abort(parentSignal.reason);
90
- };
91
- parentSignal.addEventListener('abort', onParentAbort, { once: true });
92
- }
93
- }
88
+ controller.abort(parentSignal?.reason);
89
+ },
90
+ scope.signal
91
+ );
94
92
 
95
93
  return {
96
94
  signal: controller.signal,
97
95
  cancel: () => {
98
96
  clearTimeout(timer);
99
- if (onParentAbort && parentSignal) {
100
- parentSignal.removeEventListener('abort', onParentAbort);
101
- onParentAbort = null;
102
- }
97
+ scope.abort();
103
98
  },
104
99
  };
105
100
  }
@@ -112,7 +112,9 @@ export function buildActionDispatcher(
112
112
  // as a GET — the rerender with the action's form state, the throw with
113
113
  // its error, which the route renders in place of its page so the
114
114
  // nearest error page answers (SSR has no error boundaries, so that page
115
- // comes from the shell-failure path):
115
+ // comes from the shell-failure path). `reenter` enters after proxy.ts,
116
+ // which already ran for this POST: the GET is the POST's answer, not a
117
+ // second request (TIM-1445). Middleware and access.ts run on it.
116
118
  // - Same URL (so route matching lands on the same page)
117
119
  // - Cookie header DROPPED entirely. The post-action RYW state is
118
120
  // handed over as a parsed `Map<string, string>` and becomes the
@@ -58,6 +58,11 @@ import { renderFallbackError as renderFallback } from '../fallback-error.ts';
58
58
  import { loadInstrumentation } from '../instrumentation.ts';
59
59
  import { createDenyFallbackRenderer } from './deny-fallback.ts';
60
60
  import { DenySignal } from '../primitives.ts';
61
+ import {
62
+ PREBUILT_DEV_CLEAR_EVENT,
63
+ clearDevPrebuiltStore,
64
+ setDevPrebuiltStoreMode,
65
+ } from '../prebuilt/dev-store.ts';
61
66
  import { renderRoute } from './render-route.ts';
62
67
  import { isDebug, isDevMode, setDebugFromConfig } from '../debug.ts';
63
68
  import { capturePrebuiltPayloads } from '../prebuilt-builder.ts';
@@ -114,16 +119,21 @@ async function createRequestHandler(manifest: typeof routeManifest, runtimeConfi
114
119
  }
115
120
 
116
121
  // Wire the CDN purge handler so revalidateTag triggers CDN purge (TIM-1166).
117
- const userCdnPurge = await loadCdnPurgeHandler();
122
+ // Applied on every entry run, absent included: in dev the store outlives
123
+ // an edit that removes the handler.
124
+ const { applyConfiguredCdnPurgeHandler } = await import('../../cdn/purge-store.ts');
125
+ const userCdnPurge = (await loadCdnPurgeHandler()) as
126
+ | Parameters<typeof applyConfiguredCdnPurgeHandler>[0]
127
+ | null;
118
128
  if (userCdnPurge) {
119
- const { setCdnPurgeHandler } = await import('../../cdn/purge-store.ts');
120
- setCdnPurgeHandler(userCdnPurge as Parameters<typeof setCdnPurgeHandler>[0]);
129
+ applyConfiguredCdnPurgeHandler(userCdnPurge);
121
130
  } else if (typeof process !== 'undefined' && process.env?.TIMBER_RUNTIME === 'cloudflare') {
122
131
  // Auto-wire Workers Cache purge on Cloudflare — no API token needed,
123
132
  // available on all plans via ctx.cache.purge({ tags }) (TIM-1170).
124
133
  const { WorkersCachePurge } = await import('../../cdn/workers-cache-purge.ts');
125
- const { setCdnPurgeHandler } = await import('../../cdn/purge-store.ts');
126
- setCdnPurgeHandler(new WorkersCachePurge());
134
+ applyConfiguredCdnPurgeHandler(new WorkersCachePurge());
135
+ } else {
136
+ applyConfiguredCdnPurgeHandler(undefined);
127
137
  }
128
138
 
129
139
  // Wire the prebuilt payload source so cache.component wrappers can look
@@ -131,9 +141,20 @@ async function createRequestHandler(manifest: typeof routeManifest, runtimeConfi
131
141
  // platform-aware: Node/Nitro reads from disk; Cloudflare reads from
132
142
  // static assets via globalThis.__TIMBER_PREBUILT_SOURCE__ (set by the
133
143
  // generated _worker.js before this module loads).
134
- // In dev mode there are no prebuilt artifacts — source stays null and
135
- // all cache.component wrappers render dynamically.
136
- if (!isDevMode()) {
144
+ // In dev mode there are no prebuilt artifacts — source stays null and the
145
+ // in-memory dev store stands in for them: prerender entries are captured
146
+ // on first request and cleared on every dev-server watcher event, which
147
+ // the timber-dev-server plugin forwards here (TIM-1588). Without HMR
148
+ // (`server.hmr: false`) no event would ever clear it, so dev bypasses
149
+ // cache.component caching entirely and every wrapper renders live.
150
+ if (isDevMode()) {
151
+ if (import.meta.hot) {
152
+ setDevPrebuiltStoreMode('active');
153
+ import.meta.hot.on(PREBUILT_DEV_CLEAR_EVENT, clearDevPrebuiltStore);
154
+ } else {
155
+ setDevPrebuiltStoreMode('bypass');
156
+ }
157
+ } else {
137
158
  const platformSource = (globalThis as Record<string, unknown>).__TIMBER_PREBUILT_SOURCE__ as
138
159
  | import('../prebuilt/payload-source.ts').PrebuiltPayloadSource
139
160
  | undefined;
@@ -511,11 +532,12 @@ await loadInstrumentation(loadUserInstrumentation);
511
532
 
512
533
  // Wire the cache handler — prebuilt components may call timber.cache
513
534
  // during capture and must see the configured store, not the fallback.
514
- const userCacheHandler = await loadCacheHandler();
515
- if (userCacheHandler) {
516
- const { setCacheHandler } = await import('../../cache/handler-store.ts');
517
- setCacheHandler(userCacheHandler as Parameters<typeof setCacheHandler>[0]);
518
- }
535
+ // Applied on every entry run, absent included: in dev the store outlives an
536
+ // edit that removes the handler from timber.cache.ts.
537
+ const { applyConfiguredCacheHandler } = await import('../../cache/handler-store.ts');
538
+ applyConfiguredCacheHandler(
539
+ ((await loadCacheHandler()) ?? null) as Parameters<typeof applyConfiguredCacheHandler>[0]
540
+ );
519
541
 
520
542
  // In capture mode the plugin only calls __timber_capturePrebuilt — skip
521
543
  // the remaining production startup (CDN purge, OTEL, route matchers)
@@ -529,3 +551,15 @@ if (!isCaptureMode) {
529
551
  }
530
552
 
531
553
  export default _handler!;
554
+
555
+ // A server-module edit propagates to this boundary, so the module runner
556
+ // re-executes only the edited module and its importers up to here (the dev
557
+ // middleware re-imports this entry per request). Without a boundary every
558
+ // edit is a full program reload: the runner re-evaluates everything,
559
+ // node_modules included, and React's dev Flight server leaks each discarded
560
+ // copy through the async hook and console patches it installs at module
561
+ // load — the dev server grew ~110 MB per edit until it ran out of heap.
562
+ // This is the boundary @vitejs/plugin-rsc documents for the RSC entry.
563
+ if (import.meta.hot) {
564
+ import.meta.hot.accept();
565
+ }