@timber-js/app 0.2.0-alpha.224 → 0.2.0-alpha.225

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 (77) hide show
  1. package/dist/_chunks/{actions-7dTXYJfu.js → actions-B1xSIv32.js} +2 -2
  2. package/dist/_chunks/{actions-7dTXYJfu.js.map → actions-B1xSIv32.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-TDZ4hlDc.js → cache-api-DsSXA4Sp.js} +68 -47
  4. package/dist/_chunks/cache-api-DsSXA4Sp.js.map +1 -0
  5. package/dist/_chunks/{cli-check-Dv3f8d2j.js → cli-check-B33yhAPa.js} +2 -2
  6. package/dist/_chunks/{cli-check-Dv3f8d2j.js.map → cli-check-B33yhAPa.js.map} +1 -1
  7. package/dist/_chunks/cli-context-BPdyA7Fp.js +1 -0
  8. package/dist/_chunks/{cli-context-CbZp32SK.js → cli-context-CwTKMjVe.js} +10 -2
  9. package/dist/_chunks/cli-context-CwTKMjVe.js.map +1 -0
  10. package/dist/_chunks/{error-boundary-DRQXGWCp.js → error-boundary-D3YyVVuP.js} +2 -2
  11. package/dist/_chunks/{error-boundary-DRQXGWCp.js.map → error-boundary-D3YyVVuP.js.map} +1 -1
  12. package/dist/_chunks/{singleflight-BChPMjwH.js → singleflight-CzoOVB9Y.js} +2 -3
  13. package/dist/_chunks/singleflight-CzoOVB9Y.js.map +1 -0
  14. package/dist/_chunks/{status-page-marker-XIQXlTOb.js → status-page-marker-C8POawuF.js} +2 -2
  15. package/dist/_chunks/{status-page-marker-XIQXlTOb.js.map → status-page-marker-C8POawuF.js.map} +1 -1
  16. package/dist/adapters/cloudflare-kv-cache.d.ts +0 -1
  17. package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -1
  18. package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
  19. package/dist/cache/index.d.ts +5 -5
  20. package/dist/cache/index.d.ts.map +1 -1
  21. package/dist/cache/index.js +1 -1
  22. package/dist/cache/redis-handler.d.ts +0 -1
  23. package/dist/cache/redis-handler.d.ts.map +1 -1
  24. package/dist/cache/singleflight.d.ts +12 -2
  25. package/dist/cache/singleflight.d.ts.map +1 -1
  26. package/dist/cache/stable-stringify.d.ts +6 -0
  27. package/dist/cache/stable-stringify.d.ts.map +1 -1
  28. package/dist/cache/tag-aware-handler.d.ts +0 -1
  29. package/dist/cache/tag-aware-handler.d.ts.map +1 -1
  30. package/dist/cache/timber-cache.d.ts +1 -1
  31. package/dist/cache/timber-cache.d.ts.map +1 -1
  32. package/dist/cli-context.d.ts +8 -0
  33. package/dist/cli-context.d.ts.map +1 -1
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +8 -2
  36. package/dist/cli.js.map +1 -1
  37. package/dist/client/error-boundary.js +1 -1
  38. package/dist/client/internal.js +3 -3
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +112 -0
  41. package/dist/index.js.map +1 -1
  42. package/dist/plugins/client-in-server-package-deps.d.ts +63 -0
  43. package/dist/plugins/client-in-server-package-deps.d.ts.map +1 -0
  44. package/dist/plugins/optimize-package-imports.d.ts +11 -0
  45. package/dist/plugins/optimize-package-imports.d.ts.map +1 -1
  46. package/dist/server/flight-injector-core.d.ts.map +1 -1
  47. package/dist/server/index.js +1 -1
  48. package/dist/server/internal.js +162 -33
  49. package/dist/server/internal.js.map +1 -1
  50. package/dist/server/pipeline-helpers.d.ts +5 -2
  51. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  52. package/dist/server/pipeline.d.ts.map +1 -1
  53. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  54. package/dist/server/response-framing.d.ts +43 -0
  55. package/dist/server/response-framing.d.ts.map +1 -0
  56. package/package.json +2 -2
  57. package/src/adapters/cloudflare-kv-cache.ts +1 -5
  58. package/src/cache/index.ts +7 -27
  59. package/src/cache/redis-handler.ts +1 -5
  60. package/src/cache/singleflight.ts +17 -5
  61. package/src/cache/stable-stringify.ts +53 -0
  62. package/src/cache/tag-aware-handler.ts +1 -5
  63. package/src/cache/timber-cache.ts +55 -52
  64. package/src/cli-context.ts +9 -0
  65. package/src/cli.ts +16 -0
  66. package/src/index.ts +2 -0
  67. package/src/plugins/client-in-server-package-deps.ts +139 -0
  68. package/src/plugins/optimize-package-imports.ts +1 -1
  69. package/src/server/flight-injector-core.ts +13 -9
  70. package/src/server/pipeline-helpers.ts +9 -5
  71. package/src/server/pipeline.ts +7 -0
  72. package/src/server/prebuilt-runtime.ts +125 -121
  73. package/src/server/response-framing.ts +59 -0
  74. package/dist/_chunks/cache-api-TDZ4hlDc.js.map +0 -1
  75. package/dist/_chunks/cli-context-CbZp32SK.js.map +0 -1
  76. package/dist/_chunks/cli-context-n5hmkdla.js +0 -1
  77. package/dist/_chunks/singleflight-BChPMjwH.js.map +0 -1
@@ -0,0 +1,139 @@
1
+ /**
2
+ * timber-client-in-server-package-deps — in dev, the RSC environment resolves
3
+ * a package's inner 'use client' file through its bare package path, so the
4
+ * browser loads it from the client pre-bundle.
5
+ *
6
+ * plugin-rsc records a package source only for a file the RSC environment
7
+ * reaches through a bare import. A server component that reaches a 'use
8
+ * client' file through the package's own relative imports (lucide-react's
9
+ * `icons/play.mjs` → `createLucideIcon.mjs` → `./Icon.mjs`, or
10
+ * `@mui/material/Button` → `./Button.mjs`) gets a client reference whose
11
+ * browser module re-exports the file's absolute path
12
+ * (`client-in-server-package-proxy`). Vite serves that file, and everything it
13
+ * imports, raw:
14
+ *
15
+ * - If an app client component also imports the package, the browser holds
16
+ * two instances of those modules, the pre-bundled one and the raw one, so a
17
+ * context the package provides (`LucideProvider`) does not reach icons
18
+ * rendered by server components. plugin-rsc detects this and warns "client
19
+ * component dependency is inconsistently optimized" on every dev start.
20
+ * - If the file imports a CommonJS package (`prop-types`), the browser
21
+ * cannot link it and the page fails (vitejs/vite-plugin-react#1538).
22
+ *
23
+ * This plugin resolves such an import as the bare specifier the file has from
24
+ * the app root (`lucide-react/dist/esm/Icon.mjs`). plugin-rsc then records that
25
+ * specifier as the file's package source and gives the browser
26
+ * `client-package-proxy`, which imports the bare specifier. The client deps
27
+ * optimizer pre-bundles it like any package import, splitting the modules it
28
+ * shares with the package's own entry into one chunk, so the browser loads one
29
+ * instance. No inconsistency remains, so plugin-rsc does not warn.
30
+ *
31
+ * Every rule leans toward leaving the import alone, which keeps plugin-rsc's
32
+ * raw-file behavior:
33
+ * - only in the RSC environment, in dev (a build has no proxy modules);
34
+ * - only for a non-bare source (a bare one already gets a package source);
35
+ * - only from a package file, or for an absolute path into `node_modules`
36
+ * (what the barrel rewrite emits), so an app module's own relative imports
37
+ * are not resolved twice;
38
+ * - only when the resolved id is a plain file (no query but Vite's `?v=`; a
39
+ * `?raw` or `?url` import asks for something other than the module), under
40
+ * `node_modules`, whose directive prologue holds 'use client';
41
+ * - only when the bare specifier resolves to the same file, from the importer
42
+ * here and from the app root in plugin-rsc. A package whose `exports` hides
43
+ * the file, or a transitive dependency the app cannot import by name, stays
44
+ * as it is.
45
+ *
46
+ * A file found after startup is a new client dep, so the client optimizer
47
+ * re-runs once, as for any import discovered late; Vite keeps it in the dep
48
+ * cache for later starts. See design/21-dev-server.md §"Inner 'use client'
49
+ * Files of Packages".
50
+ *
51
+ * Remove once plugin-rsc imports these files through the client pre-bundle
52
+ * itself.
53
+ */
54
+
55
+ import { readFile } from 'node:fs/promises';
56
+ import type { Plugin } from 'vite';
57
+ import { detectDirective } from '../analyze/classify.ts';
58
+ import { asFilePath } from './optimize-package-imports.ts';
59
+
60
+ const NODE_MODULES = '/node_modules/';
61
+
62
+ // Vite's own test for a bare import (packages/vite/src/node/utils.ts).
63
+ const BARE_IMPORT_RE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
64
+
65
+ /**
66
+ * The bare specifier `file` has as a package path, or null when the file is not
67
+ * inside a package. The last `node_modules` segment is the package, so a pnpm
68
+ * store path (`.pnpm/lucide-react@1.66.0/node_modules/lucide-react/…`) names
69
+ * the package, not the store.
70
+ */
71
+ export function packagePathOf(file: string): string | null {
72
+ const index = file.lastIndexOf(NODE_MODULES);
73
+ if (index === -1) return null;
74
+ const id = file.slice(index + NODE_MODULES.length);
75
+ return id === '' || id.startsWith('.') ? null : id;
76
+ }
77
+
78
+ export function timberClientInServerPackageDeps(rscEnvironmentName = 'rsc'): Plugin {
79
+ // File path → whether its directive prologue holds 'use client'. Installed
80
+ // packages are assumed not to change while the process runs, as the barrel
81
+ // rewrite assumes. The read is cached as a promise so concurrent resolves
82
+ // share it; a failed read caches false (the import is left alone).
83
+ const isClientFile = new Map<string, Promise<boolean>>();
84
+
85
+ function hasUseClient(file: string): Promise<boolean> {
86
+ let cached = isClientFile.get(file);
87
+ if (!cached) {
88
+ cached = readFile(file, 'utf8').then(
89
+ // A text check skips parsing the files that cannot carry it.
90
+ (code) => code.includes('use client') && detectDirective(code, file) === 'use client',
91
+ () => false
92
+ );
93
+ isClientFile.set(file, cached);
94
+ }
95
+ return cached;
96
+ }
97
+
98
+ return {
99
+ name: 'timber-client-in-server-package-deps',
100
+ apply: 'serve',
101
+ resolveId: {
102
+ order: 'pre',
103
+ async handler(source, importer, options) {
104
+ if (this.environment.name !== rscEnvironmentName || !importer) return;
105
+ if (BARE_IMPORT_RE.test(source) || source.startsWith('\0')) return;
106
+ // A package's own relative imports, or an absolute path into a
107
+ // package (what the barrel rewrite emits). An app module's relative
108
+ // imports stay in the app and are not resolved twice.
109
+ if (!importer.includes(NODE_MODULES) && !source.includes(NODE_MODULES)) return;
110
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
111
+ if (!resolved || resolved.external) return resolved;
112
+ // Vite's `?v=<hash>` is dropped; any other query (`?raw`, `?url`)
113
+ // asks for something other than the module, so it is left alone.
114
+ const file = asFilePath(resolved.id);
115
+ const bare = file && packagePathOf(file);
116
+ if (!file || !bare || !(await hasUseClient(file))) return resolved;
117
+ // Resolving the bare specifier runs plugin-rsc's resolver for bare
118
+ // imports, which records it as the file's package source when it
119
+ // resolves from the app root to this same file. Otherwise it records
120
+ // nothing and the file keeps its raw proxy.
121
+ //
122
+ // The bare specifier is one this plugin made up, not one the package
123
+ // wrote, so it may not resolve at all: a package whose `exports` map
124
+ // hides the file still imports it by a relative path, and Vite throws
125
+ // ("is not exported under the conditions") instead of returning
126
+ // null. That only means the file has no package path; the relative
127
+ // import that already resolved stays.
128
+ let viaPackage: Awaited<ReturnType<typeof this.resolve>>;
129
+ try {
130
+ viaPackage = await this.resolve(bare, importer, { ...options, skipSelf: true });
131
+ } catch {
132
+ return resolved;
133
+ }
134
+ if (!viaPackage || asFilePath(viaPackage.id) !== file) return resolved;
135
+ return viaPackage;
136
+ },
137
+ },
138
+ };
139
+ }
@@ -338,7 +338,7 @@ function langForFile(file: string): Lang {
338
338
  * the emitted path resolves to the same id the barrel's own import would, which
339
339
  * keeps one module instance per file.
340
340
  */
341
- function asFilePath(id: string): string | null {
341
+ export function asFilePath(id: string): string | null {
342
342
  const path = id.replace(/\?v=[\w.-]+$/, '');
343
343
  return isAbsolute(path) && !path.includes('?') && !path.includes('\0') ? path : null;
344
344
  }
@@ -305,18 +305,22 @@ export class FlightInjectorCore {
305
305
  // scripts (Node only — a Web source never has chunks to take).
306
306
  this.enqueue(this.encoder.push([result.value, ...this.reader.takeBuffered()]));
307
307
 
308
- // Yield between reads so HTML chunks get priority — but only while
309
- // HTML is still streaming. Once flush() fires (HTML_DONE), drain
310
- // without yielding so remaining RSC data doesn't stall.
308
+ // While HTML is still streaming, yield first so HTML chunks get
309
+ // priority. Once flush() fires (HTML_DONE) there is no HTML left to
310
+ // wait for.
311
311
  if (!isHtmlDone(this.machine.state)) {
312
312
  await new Promise<void>((r) => setImmediate(r));
313
- // After yielding, drain. Without this, hydration blocks waiting
314
- // for flight data stuck in pending[]. Safe because we're between
315
- // event-loop ticks (no transform() call mid-execution → no
316
- // mid-tag risk; the buffered transform upstream coalesced HTML
317
- // chunks to coherent fragments).
318
- if (this.pending.length > 0) onYieldDrain();
319
313
  }
314
+ // Drain after every read, in both phases. Safe while streaming
315
+ // because we're between event-loop ticks (no transform() call
316
+ // mid-execution → no mid-tag risk; the buffered transform upstream
317
+ // coalesced HTML chunks to coherent fragments), and trivially safe
318
+ // after HTML_DONE. Draining only while streaming held every script
319
+ // read after Fizz finished until the whole Flight stream ended: a
320
+ // promise prop that settles late kept the shell's own rows — what
321
+ // hydration needs — off the wire until it resolved (design/05
322
+ // §"Promise Props").
323
+ if (this.pending.length > 0) onYieldDrain();
320
324
  }
321
325
  } catch (err) {
322
326
  // Release the source on any failure (a timed-out read leaves it live);
@@ -504,7 +504,10 @@ const skippedFiles = new Map<string, string>();
504
504
  * per request that joined it, so the report happens inside the body. A
505
505
  * body still running when the singleflight times out is reported then,
506
506
  * with the timeout error (the signal's reason), and its later rejection
507
- * is dropped.
507
+ * is not reported again.
508
+ * - **Settles with the work's outcome.** The value or the error passes
509
+ * through, so an inline re-render that joined this flight receives the
510
+ * captured bytes, or the failure, instead of `undefined`.
508
511
  * - **Against the request whose stale read started it**, read from the
509
512
  * request context the work runs in. With no request (the build-time
510
513
  * capture store) it is only logged.
@@ -513,11 +516,11 @@ const skippedFiles = new Map<string, string>();
513
516
  * revalidated page tree included). The request's own abort does not
514
517
  * suppress the report: the work runs after the response either way.
515
518
  */
516
- export async function runBackgroundFlight(
519
+ export async function runBackgroundFlight<T>(
517
520
  signal: AbortSignal,
518
- work: () => Promise<unknown>,
521
+ work: () => Promise<T>,
519
522
  log: (error: unknown) => void
520
- ): Promise<void> {
523
+ ): Promise<T> {
521
524
  const failed = (error: unknown): void => {
522
525
  log(error);
523
526
  const request = requestContextAls.getStore()?.request;
@@ -527,9 +530,10 @@ export async function runBackgroundFlight(
527
530
  const settled = new AbortController();
528
531
  onAbortUntil(signal, () => failed(signal.reason), settled.signal);
529
532
  try {
530
- await work();
533
+ return await work();
531
534
  } catch (error) {
532
535
  if (!signal.aborted) failed(error);
536
+ throw error;
533
537
  } finally {
534
538
  settled.abort();
535
539
  }
@@ -39,6 +39,7 @@ import { outcomeToResponse } from './pipeline-outcome.ts';
39
39
  import { canonicalize } from './canonicalize.ts';
40
40
  import { enforceRscCacheKey, hardenRscPayloadResponse } from './rsc-cache-key-guard.ts';
41
41
  import { stripHeadBody } from './head-response.ts';
42
+ import { dropUpstreamFraming } from './response-framing.ts';
42
43
  import { RSC_KEY_HEADERS } from '../shared/rsc-cache-key.ts';
43
44
  import { isDebug } from './debug.ts';
44
45
  import type { ReactFormState } from 'react-dom/client';
@@ -536,6 +537,12 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
536
537
  // covered, not just the success path (TIM-1268).
537
538
  hardenRscPayloadResponse(result);
538
539
 
540
+ // A forwarded fetch() Response carries the upstream's framing
541
+ // (the encoded body's length, its connection headers) around
542
+ // a decoded body — applied at this single exit so every
543
+ // producer is covered (design/13-security.md #42).
544
+ dropUpstreamFraming(result);
545
+
539
546
  // A HEAD response carries the headers its GET would produce and
540
547
  // no content (RFC 9110 §9.3.2). Applied at this single exit so
541
548
  // every response shape is covered — page render, API route,
@@ -95,10 +95,13 @@ import {
95
95
  /** Default timeout for component re-renders (overridden by renderTimeoutMs). */
96
96
  const DEFAULT_COMPONENT_TIMEOUT_MS = DEFAULT_RENDER_TIMEOUT_MS;
97
97
 
98
- /** Singleflight for component re-renders (inline and background). */
99
- let componentSingleflight = createSingleflight({
100
- timeoutMs: DEFAULT_COMPONENT_TIMEOUT_MS,
101
- });
98
+ /**
99
+ * Singleflight for component re-renders (inline and background) and dev
100
+ * captures. One instance for the process: replacing it at boot would drop
101
+ * every flight in progress and let a caller after the swap run a second
102
+ * execution beside one still writing. The timeout is passed per call.
103
+ */
104
+ const componentSingleflight = createSingleflight();
102
105
  let componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
103
106
 
104
107
  /**
@@ -107,7 +110,6 @@ let componentTimeoutMs = DEFAULT_COMPONENT_TIMEOUT_MS;
107
110
  */
108
111
  export function setComponentRefreshTimeout(timeoutMs: number): void {
109
112
  componentTimeoutMs = timeoutMs;
110
- componentSingleflight = createSingleflight({ timeoutMs });
111
113
  }
112
114
 
113
115
  let warnedNoWaitUntil = false;
@@ -365,43 +367,68 @@ async function storeCapturedEntry(
365
367
  );
366
368
  }
367
369
 
370
+ /** A re-render of one component entry: what both re-render paths capture. */
371
+ interface Rerender {
372
+ id: string;
373
+ component: ServerComponent;
374
+ props: Record<string, unknown>;
375
+ cacheKey: string;
376
+ options: PrebuiltComponentOptions;
377
+ hasSeed: boolean;
378
+ }
379
+
368
380
  /**
369
- * Inline re-render: capture flight bytes, store in overlay, revive for
370
- * the current request. Singleflight-coalesced by overlay key.
381
+ * Capture flight bytes and store them in the overlay, coalesced into one
382
+ * flight per overlay key. The inline and the background (SWR) re-render
383
+ * share the flight key: two executions for one key could otherwise both
384
+ * store, the older, slower one landing last (TIM-1447). A caller joining
385
+ * a flight started by the other path gets its bytes, or its error.
386
+ *
387
+ * Keyed by the overlay key, which carries the dev namespace: a request
388
+ * after a save never joins a re-render of the pre-save code. `wrap` runs
389
+ * the work inside the flight body — the background path reports its
390
+ * failure there, once per flight.
371
391
  */
372
- async function inlineRerender(
373
- id: string,
374
- component: ServerComponent,
375
- props: Record<string, unknown>,
376
- cacheKey: string,
377
- options: PrebuiltComponentOptions,
378
- hasSeed: boolean,
379
- outcome: string
380
- ): Promise<{ element: unknown } | null> {
392
+ function rerenderFlight(
393
+ r: Rerender,
394
+ wrap?: (signal: AbortSignal, work: () => Promise<Uint8Array>) => Promise<Uint8Array>
395
+ ): Promise<Uint8Array> {
396
+ const { id, component, props, cacheKey, options, hasSeed } = r;
381
397
  const tags = resolveTags(options, props);
382
398
  const oKey = overlayKey(id, cacheKey);
383
- // Keyed by the overlay key, which carries the dev namespace: a request
384
- // after a save never joins a re-render of the pre-save code.
385
399
  const sfKey = `prebuilt:${oKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
400
+ return componentSingleflight.do(
401
+ sfKey,
402
+ (signal) => {
403
+ const startEpoch = currentInvalidationEpoch();
404
+ const work = async (): Promise<Uint8Array> => {
405
+ const captured = await captureComponentPayload(id, component, props, options);
406
+ // Skip the store if aborted (singleflight timeout) or if the
407
+ // key/tags were invalidated, or a dev save landed, while rendering.
408
+ if (
409
+ !signal.aborted &&
410
+ hasRuntimeLifetime(options) &&
411
+ mayStoreRerender(startEpoch, id, cacheKey, oKey, tags)
412
+ ) {
413
+ await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
414
+ }
415
+ return captured.bytes;
416
+ };
417
+ return wrap ? wrap(signal, work) : work();
418
+ },
419
+ componentTimeoutMs
420
+ );
421
+ }
386
422
 
423
+ /**
424
+ * Inline re-render: capture (or join the flight capturing) the entry, and
425
+ * revive it for the current request.
426
+ */
427
+ async function inlineRerender(r: Rerender, outcome: string): Promise<{ element: unknown } | null> {
387
428
  try {
388
- const payload = await componentSingleflight.do(sfKey, async (signal) => {
389
- const startEpoch = currentInvalidationEpoch();
390
- const captured = await captureComponentPayload(id, component, props, options);
391
- // Skip the store if aborted (singleflight timeout) or if the
392
- // key/tags were invalidated, or a dev save landed, while rendering.
393
- if (
394
- !signal.aborted &&
395
- hasRuntimeLifetime(options) &&
396
- mayStoreRerender(startEpoch, id, cacheKey, oKey, tags)
397
- ) {
398
- await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
399
- }
400
- return captured.bytes;
401
- });
402
- return await revivePayload(id, payload, outcome);
429
+ return await revivePayload(r.id, await rerenderFlight(r), outcome);
403
430
  } catch (error) {
404
- console.error(`[timber] cache.component re-render failed for "${id}" — ${outcome}:`, error);
431
+ console.error(`[timber] cache.component re-render failed for "${r.id}" — ${outcome}:`, error);
405
432
  return null;
406
433
  }
407
434
  }
@@ -432,44 +459,20 @@ function snapshotRequestContext(store: RequestContextStore): RequestContextStore
432
459
  * Kick off a background re-render via waitUntil. The re-render runs inside
433
460
  * a fresh ALS scope with snapshotted request context.
434
461
  */
435
- function backgroundRerender(
436
- id: string,
437
- component: ServerComponent,
438
- props: Record<string, unknown>,
439
- cacheKey: string,
440
- options: PrebuiltComponentOptions,
441
- hasSeed: boolean,
442
- snapshot: RequestContextStore
443
- ): void {
462
+ function backgroundRerender(r: Rerender, snapshot: RequestContextStore): void {
444
463
  const waitUntil = getWaitUntil();
445
- const tags = resolveTags(options, props);
446
- const oKey = overlayKey(id, cacheKey);
447
- const startEpoch = currentInvalidationEpoch();
448
- const sfKey = `prebuilt-bg:${oKey}\0${lastInvalidationEpochFor(oKey, tags)}`;
449
464
 
450
465
  const work = requestContextAls.run(snapshot, () =>
451
- componentSingleflight
452
- // The stale payload already answered the request, so nothing else sees
453
- // a failure here: logged and reported once per flight. Inline re-render
454
- // and revive failures are only logged: a live render answers instead.
455
- .do(sfKey, (signal) =>
456
- runBackgroundFlight(
457
- signal,
458
- async () => {
459
- const captured = await captureComponentPayload(id, component, props, options);
460
- if (!signal.aborted && mayStoreRerender(startEpoch, id, cacheKey, oKey, tags)) {
461
- await storeCapturedEntry(id, cacheKey, captured, options, tags, hasSeed);
462
- }
463
- },
464
- (error) =>
465
- console.error(
466
- `[timber] cache.component background re-render failed for "${id}":`,
467
- error
468
- )
469
- )
466
+ // The stale payload already answered the request, so nothing else sees
467
+ // a failure here: logged and reported once per flight, inside the body.
468
+ // Inline re-render and revive failures are only logged: a live render
469
+ // answers instead.
470
+ rerenderFlight(r, (signal, capture) =>
471
+ runBackgroundFlight(signal, capture, (error) =>
472
+ console.error(`[timber] cache.component background re-render failed for "${r.id}":`, error)
470
473
  )
471
- // runBackgroundFlight never rejects; only the singleflight timeout,
472
- // which it already reported, can reject the flight.
474
+ )
475
+ // Reported inside the flight; this handle only keeps it unhandled-free.
473
476
  .catch(() => {})
474
477
  );
475
478
 
@@ -518,38 +521,42 @@ async function resolveDevSeed(
518
521
  const guardTags = [...tags, devComponentTag(id)];
519
522
  const sfKey = `prebuilt-dev:${guardKey}\0${lastInvalidationEpochFor(guardKey, guardTags)}`;
520
523
  try {
521
- return await componentSingleflight.do(sfKey, async (signal) => {
522
- const startEpoch = currentInvalidationEpoch();
523
- const capturedAt = Date.now();
524
- const { renderFlight } = requireRscFunctions();
525
- // Outside the request's React.cache scope, like every stored capture
526
- // (TIM-1529).
527
- const outcome = await runOutsideReactCacheScope(() =>
528
- renderEntry(registration, props, keyParams, getCaptureTimeoutMs(), false, renderFlight)
529
- );
530
- if (outcome.failure instanceof BuildTimeContextError) throw outcome.failure;
531
- if (outcome.bytes === null) return null;
532
- // Smoke-revive before storing, as the build does: bytes that cannot
533
- // be decoded would fail every later request until the next save.
534
- if ((await revivePayload(id, outcome.bytes, 'not storing the dev capture')) === null) {
535
- return null;
536
- }
537
- // A save (or revalidateTag) while this rendered: the bytes may come
538
- // from the old code, so this request gets them but the store does not.
539
- const moved = isr && overlayKey(id, cacheKey) !== guardKey;
540
- if (!signal.aborted && !moved && !wasInvalidatedSince(startEpoch, guardKey, guardTags)) {
541
- setDevSeed(id, cacheKey, {
542
- bytes: outcome.bytes,
543
- tags,
544
- capturedAt,
545
- isr,
546
- });
547
- warnNestingClamps({ id, options, tags }, outcome.nested, warnedNestingPairs, (m) =>
548
- console.warn(m)
524
+ return await componentSingleflight.do(
525
+ sfKey,
526
+ async (signal) => {
527
+ const startEpoch = currentInvalidationEpoch();
528
+ const capturedAt = Date.now();
529
+ const { renderFlight } = requireRscFunctions();
530
+ // Outside the request's React.cache scope, like every stored capture
531
+ // (TIM-1529).
532
+ const outcome = await runOutsideReactCacheScope(() =>
533
+ renderEntry(registration, props, keyParams, getCaptureTimeoutMs(), false, renderFlight)
549
534
  );
550
- }
551
- return { payload: outcome.bytes, capturedAt };
552
- });
535
+ if (outcome.failure instanceof BuildTimeContextError) throw outcome.failure;
536
+ if (outcome.bytes === null) return null;
537
+ // Smoke-revive before storing, as the build does: bytes that cannot
538
+ // be decoded would fail every later request until the next save.
539
+ if ((await revivePayload(id, outcome.bytes, 'not storing the dev capture')) === null) {
540
+ return null;
541
+ }
542
+ // A save (or revalidateTag) while this rendered: the bytes may come
543
+ // from the old code, so this request gets them but the store does not.
544
+ const moved = isr && overlayKey(id, cacheKey) !== guardKey;
545
+ if (!signal.aborted && !moved && !wasInvalidatedSince(startEpoch, guardKey, guardTags)) {
546
+ setDevSeed(id, cacheKey, {
547
+ bytes: outcome.bytes,
548
+ tags,
549
+ capturedAt,
550
+ isr,
551
+ });
552
+ warnNestingClamps({ id, options, tags }, outcome.nested, warnedNestingPairs, (m) =>
553
+ console.warn(m)
554
+ );
555
+ }
556
+ return { payload: outcome.bytes, capturedAt };
557
+ },
558
+ componentTimeoutMs
559
+ );
553
560
  } catch (error) {
554
561
  if (error instanceof BuildTimeContextError) throw error;
555
562
  console.error(`[timber] cache.component dev capture failed for "${id}":`, error);
@@ -624,7 +631,10 @@ async function tryRevivePayload(
624
631
  if (overlayResult) {
625
632
  const overlayHasSeed = overlayResult.record?.s ?? false;
626
633
  if (overlayResult.kind === 'tombstone') {
627
- return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
634
+ return await inlineRerender(
635
+ { id, component, props, cacheKey, options, hasSeed: true },
636
+ outcome
637
+ );
628
638
  }
629
639
  // Unreadable is decided after the seed lookup: the seed says whether
630
640
  // this key was ever enumerated (a strict miss must still throw), but
@@ -636,23 +646,13 @@ async function tryRevivePayload(
636
646
  if (overlayResult.kind === 'stale' && overlayResult.payload) {
637
647
  if (options.staleWhileRevalidate) {
638
648
  backgroundRerender(
639
- id,
640
- component,
641
- props,
642
- cacheKey,
643
- options,
644
- overlayHasSeed,
649
+ { id, component, props, cacheKey, options, hasSeed: overlayHasSeed },
645
650
  snapshotRequestContext(store)
646
651
  );
647
652
  return await revivePayload(id, overlayResult.payload, outcome);
648
653
  }
649
654
  return await inlineRerender(
650
- id,
651
- component,
652
- props,
653
- cacheKey,
654
- options,
655
- overlayHasSeed,
655
+ { id, component, props, cacheKey, options, hasSeed: overlayHasSeed },
656
656
  outcome
657
657
  );
658
658
  }
@@ -669,7 +669,10 @@ async function tryRevivePayload(
669
669
  : null;
670
670
  if (seed !== null && overlayUnreadable) {
671
671
  // Render, as for a tombstone (design/06 §Store failures).
672
- return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
672
+ return await inlineRerender(
673
+ { id, component, props, cacheKey, options, hasSeed: true },
674
+ outcome
675
+ );
673
676
  }
674
677
  if (seed !== null) {
675
678
  // Check seed freshness when the component has a TTL.
@@ -679,17 +682,15 @@ async function tryRevivePayload(
679
682
  // Stale seed
680
683
  if (options.staleWhileRevalidate) {
681
684
  backgroundRerender(
682
- id,
683
- component,
684
- props,
685
- cacheKey,
686
- options,
687
- true,
685
+ { id, component, props, cacheKey, options, hasSeed: true },
688
686
  snapshotRequestContext(store)
689
687
  );
690
688
  return await revivePayload(id, seed.payload, outcome);
691
689
  }
692
- return await inlineRerender(id, component, props, cacheKey, options, true, outcome);
690
+ return await inlineRerender(
691
+ { id, component, props, cacheKey, options, hasSeed: true },
692
+ outcome
693
+ );
693
694
  }
694
695
  }
695
696
  // Fresh seed (or no TTL — immutable until redeploy)
@@ -710,7 +711,10 @@ async function tryRevivePayload(
710
711
  // "only prebuilt content", so an unenumerated miss must throw (the
711
712
  // wrapper handles the throw after we return null).
712
713
  if (hasRuntime && options.fallbackOnMissingSegmentParams !== false) {
713
- return await inlineRerender(id, component, props, cacheKey, options, false, outcome);
714
+ return await inlineRerender(
715
+ { id, component, props, cacheKey, options, hasSeed: false },
716
+ outcome
717
+ );
714
718
  }
715
719
 
716
720
  return null;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Upstream framing on forwarded responses (GHSA-pc58-hwjq-p385 class,
3
+ * design/13-security.md #42).
4
+ *
5
+ * `fetch()` transparently decodes a gzip/br/deflate/zstd body but keeps the
6
+ * upstream's `Content-Encoding` and `Content-Length`, along with its
7
+ * connection-level headers. A route handler, proxy.ts or middleware that
8
+ * returns that `Response` — directly or through
9
+ * `new Response(res.body, { headers: res.headers })` — would otherwise send
10
+ * the decoded bytes framed by the encoded length. On a keep-alive HTTP/1.1
11
+ * connection the surplus bytes are read as the *next* response: a reverse
12
+ * proxy that queues several clients on one backend connection hands an
13
+ * upstream-controlled response to another client, or one client's response
14
+ * to the wrong one.
15
+ *
16
+ * Whether a body was decoded is not observable from the `Response` (the
17
+ * header-copying proxy pattern produces an ordinary constructed `Response`),
18
+ * so the rule is stated on the headers alone:
19
+ *
20
+ * - A response that declares `Content-Encoding` loses it and its
21
+ * `Content-Length`. The length described the encoded bytes; the server
22
+ * frames what it actually writes, and the adapter's compression step may
23
+ * re-encode it. Matches Next.js (vercel/next.js#101108). The cost: a
24
+ * handler cannot hand back a pre-compressed body under its own
25
+ * `Content-Encoding`.
26
+ * - Hop-by-hop headers (RFC 9110 §7.6.1) describe the upstream's
27
+ * connection, not this one, and are owned by the server writing the
28
+ * socket. They are always dropped. A forwarded `Connection: keep-alive` otherwise
29
+ * overrides the client's `Connection: close`, and a forwarded
30
+ * `Transfer-Encoding` claims a framing the server did not choose.
31
+ * The extra headers a `Connection` value names are deliberately not
32
+ * honored: the response's headers here are the upstream's merged with
33
+ * the app's own (cookies, middleware headers), and an upstream sending
34
+ * `Connection: set-cookie` must not be able to delete the app's session.
35
+ * - A `Content-Length` on an unencoded response is the route's own claim
36
+ * and is kept — a HEAD response relies on it (head-requests.test.ts).
37
+ *
38
+ * Applied at the pipeline's single exit, before compression, so every
39
+ * producer is covered — including ones added later. Timber's own renderers
40
+ * set none of these headers inside the pipeline.
41
+ */
42
+
43
+ const HOP_BY_HOP = [
44
+ 'connection',
45
+ 'keep-alive',
46
+ 'proxy-connection',
47
+ 'te',
48
+ 'trailer',
49
+ 'transfer-encoding',
50
+ 'upgrade',
51
+ ];
52
+
53
+ export function dropUpstreamFraming(response: Response): void {
54
+ const { headers } = response;
55
+ for (const name of HOP_BY_HOP) headers.delete(name);
56
+ if (!headers.has('content-encoding')) return;
57
+ headers.delete('content-encoding');
58
+ headers.delete('content-length');
59
+ }