@timber-js/app 0.1.38 → 0.1.39

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.
@@ -0,0 +1,200 @@
1
+ // Response compression for self-hosted deployments (dev server, Nitro preview).
2
+ //
3
+ // Uses CompressionStream (Web Platform API) for gzip and node:zlib for
4
+ // brotli (CompressionStream doesn't support brotli). Cloudflare Workers
5
+ // auto-compress at the edge — this module is only used on Node.js/Bun.
6
+ //
7
+ // See design/25-production-deployments.md.
8
+
9
+ import { createBrotliCompress, constants as zlibConstants } from 'node:zlib';
10
+ import { Readable } from 'node:stream';
11
+
12
+ // ─── Constants ────────────────────────────────────────────────────────────
13
+
14
+ /**
15
+ * MIME types that benefit from compression.
16
+ * text/* is handled via prefix matching; these are the specific
17
+ * application/* and image/* types that are compressible.
18
+ */
19
+ export const COMPRESSIBLE_TYPES = new Set([
20
+ 'text/html',
21
+ 'text/css',
22
+ 'text/plain',
23
+ 'text/xml',
24
+ 'text/javascript',
25
+ 'text/x-component',
26
+ 'application/json',
27
+ 'application/javascript',
28
+ 'application/xml',
29
+ 'application/xhtml+xml',
30
+ 'application/rss+xml',
31
+ 'application/atom+xml',
32
+ 'image/svg+xml',
33
+ ]);
34
+
35
+ /**
36
+ * Status codes that should never be compressed (no body or special semantics).
37
+ */
38
+ const NO_COMPRESS_STATUSES = new Set([204, 304]);
39
+
40
+ // ─── Encoding Negotiation ─────────────────────────────────────────────────
41
+
42
+ /**
43
+ * Parse Accept-Encoding and return the best supported encoding.
44
+ * Prefers brotli (br) over gzip. Returns null if no supported encoding.
45
+ *
46
+ * We always prefer brotli regardless of quality values because:
47
+ * 1. Brotli achieves better compression ratios than gzip
48
+ * 2. All modern browsers that send br in Accept-Encoding support it well
49
+ * 3. Respecting q-values for br vs gzip adds complexity with no real benefit
50
+ */
51
+ export function negotiateEncoding(acceptEncoding: string): 'br' | 'gzip' | null {
52
+ if (!acceptEncoding) return null;
53
+
54
+ // Parse tokens from the Accept-Encoding header (ignore quality values).
55
+ // e.g. "gzip;q=1.0, br;q=0.8, deflate" → ['gzip', 'br', 'deflate']
56
+ const tokens = acceptEncoding.split(',').map((s) => s.split(';')[0].trim().toLowerCase());
57
+
58
+ if (tokens.includes('br')) return 'br';
59
+ if (tokens.includes('gzip')) return 'gzip';
60
+ return null;
61
+ }
62
+
63
+ // ─── Compressibility Check ────────────────────────────────────────────────
64
+
65
+ /**
66
+ * Determine if a response should be compressed.
67
+ *
68
+ * Returns false for:
69
+ * - Responses without a body (204, 304, null body)
70
+ * - Already-encoded responses (Content-Encoding set)
71
+ * - Non-compressible content types (images, binary)
72
+ * - SSE streams (text/event-stream — must not be buffered)
73
+ */
74
+ export function shouldCompress(response: Response): boolean {
75
+ // No body to compress
76
+ if (!response.body) return false;
77
+ if (NO_COMPRESS_STATUSES.has(response.status)) return false;
78
+
79
+ // Already compressed
80
+ if (response.headers.has('Content-Encoding')) return false;
81
+
82
+ // Check content type
83
+ const contentType = response.headers.get('Content-Type');
84
+ if (!contentType) return false;
85
+
86
+ // Extract the MIME type (strip charset and other parameters)
87
+ const mimeType = contentType.split(';')[0].trim().toLowerCase();
88
+
89
+ // SSE must not be compressed — it relies on chunk-by-chunk delivery
90
+ if (mimeType === 'text/event-stream') return false;
91
+
92
+ return COMPRESSIBLE_TYPES.has(mimeType);
93
+ }
94
+
95
+ // ─── Compression ──────────────────────────────────────────────────────────
96
+
97
+ /**
98
+ * Compress a Web Response if the client supports it and the content is compressible.
99
+ *
100
+ * Returns the original response unchanged if compression is not applicable.
101
+ * Returns a new Response with the compressed body, Content-Encoding, and Vary headers.
102
+ *
103
+ * The body is piped through a compression stream — no buffering of the full response.
104
+ * This preserves streaming behavior for HTML shell + deferred Suspense chunks.
105
+ */
106
+ export function compressResponse(request: Request, response: Response): Response {
107
+ // Check if response is compressible
108
+ if (!shouldCompress(response)) return response;
109
+
110
+ // Negotiate encoding with the client
111
+ const acceptEncoding = request.headers.get('Accept-Encoding') ?? '';
112
+ const encoding = negotiateEncoding(acceptEncoding);
113
+ if (!encoding) return response;
114
+
115
+ // Compress the body stream
116
+ const compressedBody = encoding === 'br'
117
+ ? compressWithBrotli(response.body!)
118
+ : compressWithGzip(response.body!);
119
+
120
+ // Build new headers: copy originals, add compression headers, remove Content-Length
121
+ // (compressed size is unknown until streaming completes).
122
+ const headers = new Headers(response.headers);
123
+ headers.set('Content-Encoding', encoding);
124
+ headers.delete('Content-Length');
125
+
126
+ // Append to Vary header (preserve existing Vary values)
127
+ const existingVary = headers.get('Vary');
128
+ if (existingVary) {
129
+ if (!existingVary.toLowerCase().includes('accept-encoding')) {
130
+ headers.set('Vary', `${existingVary}, Accept-Encoding`);
131
+ }
132
+ } else {
133
+ headers.set('Vary', 'Accept-Encoding');
134
+ }
135
+
136
+ return new Response(compressedBody, {
137
+ status: response.status,
138
+ statusText: response.statusText,
139
+ headers,
140
+ });
141
+ }
142
+
143
+ // ─── Gzip (CompressionStream API) ────────────────────────────────────────
144
+
145
+ /**
146
+ * Compress a ReadableStream with gzip using the Web Platform CompressionStream API.
147
+ * Available in Node 18+, Bun, and Deno — no npm dependency needed.
148
+ */
149
+ function compressWithGzip(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
150
+ const compressionStream = new CompressionStream('gzip');
151
+ // Cast needed: CompressionStream's WritableStream<BufferSource> type is wider
152
+ // than ReadableStream's Uint8Array, but Uint8Array is a valid BufferSource.
153
+ return body.pipeThrough(compressionStream as unknown as TransformStream<Uint8Array, Uint8Array>);
154
+ }
155
+
156
+ // ─── Brotli (node:zlib) ──────────────────────────────────────────────────
157
+
158
+ /**
159
+ * Compress a ReadableStream with brotli using node:zlib.
160
+ *
161
+ * CompressionStream doesn't support brotli — it only handles gzip and deflate.
162
+ * We use node:zlib's createBrotliCompress() and bridge between Web streams
163
+ * and Node streams.
164
+ */
165
+ function compressWithBrotli(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
166
+ const brotli = createBrotliCompress({
167
+ params: {
168
+ // Quality 4 balances compression ratio and CPU time for streaming.
169
+ // Default (11) is too slow for real-time responses.
170
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 4,
171
+ },
172
+ });
173
+
174
+ // Pipe the Web ReadableStream into the Node brotli transform.
175
+ const reader = body.getReader();
176
+
177
+ // Pump chunks from the Web ReadableStream into the Node transform.
178
+ const pump = async (): Promise<void> => {
179
+ try {
180
+ while (true) {
181
+ const { done, value } = await reader.read();
182
+ if (done) {
183
+ brotli.end();
184
+ return;
185
+ }
186
+ // Write to brotli, wait for drain if buffer is full
187
+ if (!brotli.write(value)) {
188
+ await new Promise<void>((resolve) => brotli.once('drain', resolve));
189
+ }
190
+ }
191
+ } catch (err) {
192
+ brotli.destroy(err instanceof Error ? err : new Error(String(err)));
193
+ }
194
+ };
195
+ // Start pumping (fire and forget — errors propagate via brotli stream)
196
+ pump();
197
+
198
+ // Convert the Node readable (brotli output) to a Web ReadableStream.
199
+ return Readable.toWeb(brotli) as ReadableStream<Uint8Array>;
200
+ }
@@ -32,6 +32,7 @@ import { setParsedSearchParams } from './request-context.js';
32
32
  import type { SearchParamsDefinition } from '#/search-params/create.js';
33
33
  import { wrapSegmentWithErrorBoundaries } from './error-boundary-wrapper.js';
34
34
  import type { InterceptionContext } from './pipeline.js';
35
+ import { shouldSkipSegment } from './state-tree-diff.js';
35
36
 
36
37
  // ─── Types ────────────────────────────────────────────────────────────────
37
38
 
@@ -91,7 +92,8 @@ export class RouteSignalWithContext extends Error {
91
92
  export async function buildRouteElement(
92
93
  req: Request,
93
94
  match: RouteMatch,
94
- interception?: InterceptionContext
95
+ interception?: InterceptionContext,
96
+ clientStateTree?: Set<string> | null
95
97
  ): Promise<RouteElementResult> {
96
98
  const segments = match.segments as unknown as ManifestSegmentNode[];
97
99
 
@@ -308,8 +310,32 @@ export async function buildRouteElement(
308
310
  // 1. Error boundaries (status files + error.tsx)
309
311
  // 2. Layout component — wraps children + parallel slots
310
312
  // 3. SegmentProvider — records position for useSelectedLayoutSegment
313
+ //
314
+ // When clientStateTree is provided (from X-Timber-State-Tree header on
315
+ // client navigation), sync layouts the client already has are skipped.
316
+ // Access.ts already ran for ALL segments in the pre-render loop above.
317
+ // See design/19-client-navigation.md §"X-Timber-State-Tree Header"
311
318
  for (let i = segments.length - 1; i >= 0; i--) {
312
319
  const segment = segments[i];
320
+ const isLeaf = i === segments.length - 1;
321
+ const layoutComponent = layoutBySegment.get(segment);
322
+
323
+ // Check if this segment's layout can be skipped for partial rendering.
324
+ // Skipped segments: no layout wrapping, no error boundaries, no slots,
325
+ // no AccessGate in element tree (access already ran pre-render).
326
+ const skip = shouldSkipSegment(
327
+ segment.urlPath,
328
+ layoutComponent,
329
+ isLeaf,
330
+ clientStateTree ?? null
331
+ );
332
+
333
+ if (skip) {
334
+ // Skip this segment entirely — the client uses its cached version.
335
+ // Access.ts already ran in the pre-render loop (security guarantee).
336
+ // Metadata was already resolved above (head elements are correct).
337
+ continue;
338
+ }
313
339
 
314
340
  // Wrap with error boundaries from this segment (inside layout).
315
341
  element = await wrapSegmentWithErrorBoundaries(segment, element, h);
@@ -335,7 +361,6 @@ export async function buildRouteElement(
335
361
  }
336
362
 
337
363
  // Wrap with layout if this segment has one — traced with OTEL span
338
- const layoutComponent = layoutBySegment.get(segment);
339
364
  if (layoutComponent) {
340
365
  // Resolve parallel slots for this layout
341
366
  const slotProps: Record<string, unknown> = {};
@@ -59,6 +59,7 @@ import {
59
59
  escapeHtml,
60
60
  isRscPayloadRequest,
61
61
  } from './helpers.js';
62
+ import { parseClientStateTree } from '#/server/state-tree-diff.js';
62
63
  import { buildRscPayloadResponse } from './rsc-payload.js';
63
64
  import { renderRscStream } from './rsc-stream.js';
64
65
  import { renderSsrResponse } from './ssr-renderer.js';
@@ -268,11 +269,18 @@ async function renderRoute(
268
269
  return handleApiRoute(_req, match, segments, responseHeaders);
269
270
  }
270
271
 
272
+ // Parse X-Timber-State-Tree for RSC payload requests (client navigation).
273
+ // The state tree lists sync segments the client has cached — the server
274
+ // skips re-rendering those layouts for a smaller, faster RSC payload.
275
+ // Only used for RSC requests — HTML requests always get a full render.
276
+ // See design/19-client-navigation.md §"X-Timber-State-Tree Header"
277
+ const clientStateTree = isRscPayloadRequest(_req) ? parseClientStateTree(_req) : null;
278
+
271
279
  // Build the React element tree — loads modules, runs access checks,
272
280
  // resolves metadata. DenySignal/RedirectSignal propagate for HTTP handling.
273
281
  let routeResult;
274
282
  try {
275
- routeResult = await buildRouteElement(_req, match, interception);
283
+ routeResult = await buildRouteElement(_req, match, interception, clientStateTree);
276
284
  } catch (error) {
277
285
  // RouteSignalWithContext wraps DenySignal/RedirectSignal with layout context
278
286
  if (error instanceof RouteSignalWithContext) {
@@ -0,0 +1,77 @@
1
+ /**
2
+ * State Tree Diffing — Server-side parsing and diffing of X-Timber-State-Tree.
3
+ *
4
+ * The client sends X-Timber-State-Tree on navigation requests, listing
5
+ * the sync segments it has cached. The server diffs this against the
6
+ * target route's segments to skip re-rendering unchanged sync layouts.
7
+ *
8
+ * This is a performance optimization only — NOT a security boundary.
9
+ * All access.ts files run regardless of the state tree content.
10
+ * A fabricated state tree can only cause extra rendering work or stale
11
+ * layouts — never auth bypass.
12
+ *
13
+ * See design/19-client-navigation.md §"X-Timber-State-Tree Header"
14
+ * See design/13-security.md §"State tree manipulation"
15
+ */
16
+
17
+ /**
18
+ * Parse the X-Timber-State-Tree header from a request.
19
+ *
20
+ * Returns a Set of segment paths the client has cached, or null if
21
+ * the header is missing, malformed, or empty. Parsing happens before
22
+ * renderToReadableStream — not inside the React render pass.
23
+ *
24
+ * @returns Set of sync segment paths, or null if no valid state tree
25
+ */
26
+ export function parseClientStateTree(req: Request): Set<string> | null {
27
+ const header = req.headers.get('X-Timber-State-Tree');
28
+ if (!header) return null;
29
+
30
+ try {
31
+ const parsed = JSON.parse(header) as { segments?: unknown };
32
+ if (!Array.isArray(parsed.segments) || parsed.segments.length === 0) {
33
+ return null;
34
+ }
35
+ return new Set(parsed.segments as string[]);
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Determine whether a segment's layout rendering can be skipped.
43
+ *
44
+ * A segment is skipped when ALL of the following are true:
45
+ * 1. The client has the segment in its state tree (clientSegments contains urlPath)
46
+ * 2. The layout is sync (not an async function — async layouts always re-render)
47
+ * 3. The segment is NOT the leaf (pages are never cached across navigations)
48
+ *
49
+ * Access.ts still runs for skipped segments — this is enforced by the caller
50
+ * (buildRouteElement) which runs all access checks before building the tree.
51
+ *
52
+ * @param urlPath - The segment's URL path (e.g., "/", "/dashboard")
53
+ * @param layoutComponent - The loaded layout component function
54
+ * @param isLeaf - Whether this is the leaf segment (page segment)
55
+ * @param clientSegments - Set of paths from X-Timber-State-Tree, or null
56
+ */
57
+ export function shouldSkipSegment(
58
+ urlPath: string,
59
+ layoutComponent: ((...args: unknown[]) => unknown) | undefined,
60
+ isLeaf: boolean,
61
+ clientSegments: Set<string> | null
62
+ ): boolean {
63
+ // No state tree → full render (initial load, refresh, etc.)
64
+ if (!clientSegments) return false;
65
+
66
+ // Leaf segments (pages) are never skipped
67
+ if (isLeaf) return false;
68
+
69
+ // No layout → nothing to skip
70
+ if (!layoutComponent) return false;
71
+
72
+ // Async layouts always re-render (they may depend on request context)
73
+ if (layoutComponent.constructor?.name === 'AsyncFunction') return false;
74
+
75
+ // Skip if the client already has this segment cached
76
+ return clientSegments.has(urlPath);
77
+ }