@timber-js/app 0.2.0-alpha.227 → 0.2.0-alpha.229

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 (164) hide show
  1. package/agent-skill.md +9 -0
  2. package/dist/_chunks/{actions-B1xSIv32.js → actions-DHum77eH.js} +3 -3
  3. package/dist/_chunks/{actions-B1xSIv32.js.map → actions-DHum77eH.js.map} +1 -1
  4. package/dist/_chunks/{cache-api-DsSXA4Sp.js → cache-api-BZJNt01a.js} +4 -4
  5. package/dist/_chunks/{cache-api-DsSXA4Sp.js.map → cache-api-BZJNt01a.js.map} +1 -1
  6. package/dist/_chunks/{chains-Dgm3PrMe.js → chains-D-RRc7CM.js} +2 -2
  7. package/dist/_chunks/{chains-Dgm3PrMe.js.map → chains-D-RRc7CM.js.map} +1 -1
  8. package/dist/_chunks/chains-KblEfYzm.js +1 -0
  9. package/dist/_chunks/{classify--_kINHQV.js → classify-_W0RWa5w.js} +2 -2
  10. package/dist/_chunks/{classify--_kINHQV.js.map → classify-_W0RWa5w.js.map} +1 -1
  11. package/dist/_chunks/{cli-check-B33yhAPa.js → cli-check-B-JZkpBD.js} +3 -3
  12. package/dist/_chunks/{cli-check-B33yhAPa.js.map → cli-check-B-JZkpBD.js.map} +1 -1
  13. package/dist/_chunks/{cli-schema-sync-DIPurq7X.js → cli-schema-sync-CAllbqRB.js} +2 -2
  14. package/dist/_chunks/{cli-schema-sync-DIPurq7X.js.map → cli-schema-sync-CAllbqRB.js.map} +1 -1
  15. package/dist/_chunks/{cli-schema-sync-uq72EZmD.js → cli-schema-sync-y_8ijmzO.js} +1 -1
  16. package/dist/_chunks/{client-dep-entries-CP7AkMCM.js → client-dep-entries-C9hv-3k9.js} +2 -2
  17. package/dist/_chunks/{client-dep-entries-CP7AkMCM.js.map → client-dep-entries-C9hv-3k9.js.map} +1 -1
  18. package/dist/_chunks/{convention-lint-hZwz5wd4.js → convention-lint-CrDKERHg.js} +4 -13
  19. package/dist/_chunks/convention-lint-CrDKERHg.js.map +1 -0
  20. package/dist/_chunks/dev-server-L8biS7Az.js +1 -0
  21. package/dist/_chunks/{dev-server-B7o4As0l.js → dev-server-Rq659RR1.js} +8 -2
  22. package/dist/_chunks/dev-server-Rq659RR1.js.map +1 -0
  23. package/dist/_chunks/{build-manifest-Y4jl7nwU.js → dev-span-_NzMX-au.js} +25 -2
  24. package/dist/_chunks/dev-span-_NzMX-au.js.map +1 -0
  25. package/dist/_chunks/{error-boundary-D3YyVVuP.js → error-boundary-OHK1mI99.js} +3 -3
  26. package/dist/_chunks/{error-boundary-D3YyVVuP.js.map → error-boundary-OHK1mI99.js.map} +1 -1
  27. package/dist/_chunks/{flight-source-node-0Tp6evlz.js → flight-source-node-BGanuoSS.js} +2 -2
  28. package/dist/_chunks/{flight-source-node-0Tp6evlz.js.map → flight-source-node-BGanuoSS.js.map} +1 -1
  29. package/dist/_chunks/{global-context-DbxNWeBP.js → global-context-CFSSysdJ.js} +32 -2
  30. package/dist/_chunks/global-context-CFSSysdJ.js.map +1 -0
  31. package/dist/_chunks/{json-lossy-check-DVkLUlfC.js → json-lossy-check-BXM45k8p.js} +2 -2
  32. package/dist/_chunks/{json-lossy-check-DVkLUlfC.js.map → json-lossy-check-BXM45k8p.js.map} +1 -1
  33. package/dist/_chunks/{live-graph-BcVjQ1Te.js → live-graph-C7-yA8W9.js} +4 -4
  34. package/dist/_chunks/{live-graph-BcVjQ1Te.js.map → live-graph-C7-yA8W9.js.map} +1 -1
  35. package/dist/_chunks/{logger-CWk44DLp.js → logger-YtMSKfft.js} +103 -60
  36. package/dist/_chunks/logger-YtMSKfft.js.map +1 -0
  37. package/dist/_chunks/navigation-root-CoGHIMiE.js +239 -0
  38. package/dist/_chunks/navigation-root-CoGHIMiE.js.map +1 -0
  39. package/dist/_chunks/{node-response-B9aviPDa.js → node-response-D3hXWb8y.js} +2 -2
  40. package/dist/_chunks/{node-response-B9aviPDa.js.map → node-response-D3hXWb8y.js.map} +1 -1
  41. package/dist/_chunks/{poison-scan-DJYxZc_7.js → poison-scan-CRSP06Es.js} +2 -2
  42. package/dist/_chunks/{poison-scan-DJYxZc_7.js.map → poison-scan-CRSP06Es.js.map} +1 -1
  43. package/dist/_chunks/route-methods-Dk2kZc0n.js +36 -0
  44. package/dist/_chunks/route-methods-Dk2kZc0n.js.map +1 -0
  45. package/dist/_chunks/{scanner-CJC-ScJU.js → scanner-BNQ4qnLX.js} +2 -2
  46. package/dist/_chunks/{scanner-CJC-ScJU.js.map → scanner-BNQ4qnLX.js.map} +1 -1
  47. package/dist/_chunks/segment-context-GAyTjjtS.js +33 -0
  48. package/dist/_chunks/segment-context-GAyTjjtS.js.map +1 -0
  49. package/dist/_chunks/{sizeof-DG4W40lv.js → sizeof-Cmx6Fs-Y.js} +2 -2
  50. package/dist/_chunks/{sizeof-DG4W40lv.js.map → sizeof-Cmx6Fs-Y.js.map} +1 -1
  51. package/dist/_chunks/{status-page-marker-C8POawuF.js → status-page-marker-U6B1aFMb.js} +3 -32
  52. package/dist/_chunks/status-page-marker-U6B1aFMb.js.map +1 -0
  53. package/dist/_chunks/{walkers-DIE203ir.js → walkers-D_QHR_nf.js} +3 -3
  54. package/dist/_chunks/{walkers-DIE203ir.js.map → walkers-D_QHR_nf.js.map} +1 -1
  55. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  56. package/dist/analyze/crawl-entry.js +3 -3
  57. package/dist/analyze/graph-command.js +2 -2
  58. package/dist/cache/index.js +2 -2
  59. package/dist/cache/stores/memory.js +1 -1
  60. package/dist/cli.js +3 -3
  61. package/dist/client/browser-entry/hmr.d.ts +7 -1
  62. package/dist/client/browser-entry/hmr.d.ts.map +1 -1
  63. package/dist/client/dev-pill/index.d.ts +32 -0
  64. package/dist/client/dev-pill/index.d.ts.map +1 -0
  65. package/dist/client/dev-pill/store.d.ts +96 -0
  66. package/dist/client/dev-pill/store.d.ts.map +1 -0
  67. package/dist/client/dev-pill/view.d.ts +9 -0
  68. package/dist/client/dev-pill/view.d.ts.map +1 -0
  69. package/dist/client/error-boundary.js +1 -1
  70. package/dist/client/index.d.ts +1 -0
  71. package/dist/client/index.d.ts.map +1 -1
  72. package/dist/client/index.js +3 -3
  73. package/dist/client/internal.js +16 -7
  74. package/dist/client/internal.js.map +1 -1
  75. package/dist/client/navigation-context.d.ts +20 -0
  76. package/dist/client/navigation-context.d.ts.map +1 -1
  77. package/dist/client/router-lifecycle.d.ts +4 -1
  78. package/dist/client/router-lifecycle.d.ts.map +1 -1
  79. package/dist/client/use-pending-navigation.d.ts +33 -9
  80. package/dist/client/use-pending-navigation.d.ts.map +1 -1
  81. package/dist/config-types.d.ts +10 -0
  82. package/dist/config-types.d.ts.map +1 -1
  83. package/dist/config-validation.d.ts.map +1 -1
  84. package/dist/dev-tools/await-span.d.ts +17 -0
  85. package/dist/dev-tools/await-span.d.ts.map +1 -0
  86. package/dist/dev-tools/instrumentation.d.ts.map +1 -1
  87. package/dist/dev-tools/logger.d.ts.map +1 -1
  88. package/dist/dev-tools/logs.d.ts.map +1 -1
  89. package/dist/dev-tools/span-sink.d.ts +42 -0
  90. package/dist/dev-tools/span-sink.d.ts.map +1 -0
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +282 -9
  93. package/dist/index.js.map +1 -1
  94. package/dist/plugins/dev-await.d.ts +40 -0
  95. package/dist/plugins/dev-await.d.ts.map +1 -0
  96. package/dist/plugins/entries.d.ts.map +1 -1
  97. package/dist/routing/convention-lint.d.ts.map +1 -1
  98. package/dist/routing/index.js +2 -2
  99. package/dist/server/action-handler.d.ts.map +1 -1
  100. package/dist/server/csrf.d.ts +1 -1
  101. package/dist/server/csrf.d.ts.map +1 -1
  102. package/dist/server/index.js +2 -2
  103. package/dist/server/internal.d.ts +2 -1
  104. package/dist/server/internal.d.ts.map +1 -1
  105. package/dist/server/internal.js +26 -27
  106. package/dist/server/internal.js.map +1 -1
  107. package/dist/server/pipeline.d.ts +8 -0
  108. package/dist/server/pipeline.d.ts.map +1 -1
  109. package/dist/server/route-handler.d.ts +1 -2
  110. package/dist/server/route-handler.d.ts.map +1 -1
  111. package/dist/server/route-methods.d.ts +23 -0
  112. package/dist/server/route-methods.d.ts.map +1 -0
  113. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  114. package/dist/server/slot-resolver.d.ts.map +1 -1
  115. package/dist/server/tracing.d.ts +18 -8
  116. package/dist/server/tracing.d.ts.map +1 -1
  117. package/dist/shared/dev-span.d.ts +97 -0
  118. package/dist/shared/dev-span.d.ts.map +1 -0
  119. package/docs/api/31-api-client.mdx +27 -1
  120. package/docs/api/34-api-config.mdx +21 -1
  121. package/docs/learn/09-streaming.mdx +7 -1
  122. package/package.json +3 -3
  123. package/src/client/browser-entry/hmr.ts +13 -1
  124. package/src/client/browser-entry/index.ts +4 -1
  125. package/src/client/dev-pill/index.ts +128 -0
  126. package/src/client/dev-pill/store.ts +231 -0
  127. package/src/client/dev-pill/view.ts +278 -0
  128. package/src/client/index.ts +1 -0
  129. package/src/client/navigation-context.ts +5 -2
  130. package/src/client/router-lifecycle.ts +23 -3
  131. package/src/client/use-pending-navigation.ts +93 -14
  132. package/src/config-types.ts +10 -0
  133. package/src/config-validation.ts +10 -0
  134. package/src/dev-tools/await-span.ts +40 -0
  135. package/src/dev-tools/instrumentation.ts +20 -0
  136. package/src/dev-tools/logger.ts +3 -37
  137. package/src/dev-tools/logs.ts +10 -1
  138. package/src/dev-tools/span-sink.ts +132 -0
  139. package/src/index.ts +2 -0
  140. package/src/plugins/dev-await.ts +268 -0
  141. package/src/plugins/entries.ts +2 -0
  142. package/src/routing/convention-lint.ts +1 -3
  143. package/src/server/action-handler.ts +5 -0
  144. package/src/server/csrf.ts +11 -3
  145. package/src/server/internal.ts +2 -1
  146. package/src/server/pipeline.ts +14 -0
  147. package/src/server/route-handler.ts +8 -19
  148. package/src/server/route-methods.ts +37 -0
  149. package/src/server/rsc-entry/index.ts +7 -1
  150. package/src/server/slot-resolver.ts +45 -5
  151. package/src/server/tracing.ts +124 -90
  152. package/src/shared/dev-span.ts +182 -0
  153. package/dist/_chunks/build-manifest-Y4jl7nwU.js.map +0 -1
  154. package/dist/_chunks/chains-CwOr3Myj.js +0 -1
  155. package/dist/_chunks/convention-lint-hZwz5wd4.js.map +0 -1
  156. package/dist/_chunks/dev-server-B7o4As0l.js.map +0 -1
  157. package/dist/_chunks/dev-server-hZzmbMvK.js +0 -1
  158. package/dist/_chunks/global-context-DbxNWeBP.js.map +0 -1
  159. package/dist/_chunks/logger-CWk44DLp.js.map +0 -1
  160. package/dist/_chunks/navigation-root-M3B2ZrdO.js +0 -122
  161. package/dist/_chunks/navigation-root-M3B2ZrdO.js.map +0 -1
  162. package/dist/_chunks/segment-context-CYiGTi3K.js +0 -131
  163. package/dist/_chunks/segment-context-CYiGTi3K.js.map +0 -1
  164. package/dist/_chunks/status-page-marker-C8POawuF.js.map +0 -1
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { randomUUID } from 'node:crypto';
12
+ import { trace, SpanStatusCode, type Span, type Tracer } from '@opentelemetry/api';
12
13
  import { traceAls, type TraceStore } from './als-registry.ts';
13
14
  import { controlFlowStatus, isSsrStreamError } from './signal-identity.ts';
14
15
 
@@ -127,9 +128,6 @@ export async function initDevTracing(
127
128
  const globals = globalThis as Record<symbol, unknown>;
128
129
  if (globals[DEV_TRACING_INIT_KEY]) return;
129
130
 
130
- const api = await getOtelApi();
131
- if (!api) return;
132
-
133
131
  // Tracing is a diagnostic: any failure to load or construct the SDK
134
132
  // disables it with a warning and never fails the server's boot (TIM-1554).
135
133
  try {
@@ -141,9 +139,6 @@ export async function initDevTracing(
141
139
  return;
142
140
  }
143
141
 
144
- // Reset cached tracer so next getTracer() picks up the new provider
145
- _tracer = undefined;
146
-
147
142
  globals[DEV_TRACING_INIT_KEY] = true;
148
143
  }
149
144
 
@@ -194,42 +189,19 @@ export function getPlatformTracer(): PlatformTracer | undefined {
194
189
  // ─── OTEL Span Helpers ───────────────────────────────────────────────────
195
190
 
196
191
  /**
197
- * Attempt to get the @opentelemetry/api tracer. Returns undefined if the
198
- * package is not installed or no SDK is registered.
192
+ * The timber.js OTEL tracer.
199
193
  *
200
- * timber.js depends on @opentelemetry/api as the vendor-neutral interface.
201
- * The API is a no-op by default — spans are only emitted when the developer
202
- * initializes an SDK in register().
203
- */
204
- let _otelApi: typeof import('@opentelemetry/api') | null | undefined;
205
-
206
- async function getOtelApi(): Promise<typeof import('@opentelemetry/api') | null> {
207
- if (_otelApi === undefined) {
208
- try {
209
- _otelApi = await import('@opentelemetry/api');
210
- } catch {
211
- _otelApi = null;
212
- }
213
- }
214
- return _otelApi;
215
- }
216
-
217
- /** OTEL tracer instance, lazily created. */
218
- let _tracer: import('@opentelemetry/api').Tracer | null | undefined;
219
-
220
- /**
221
- * Get the timber.js OTEL tracer. Returns null if @opentelemetry/api is not available.
194
+ * `@opentelemetry/api` is a direct dependency and a no-op until an SDK
195
+ * registers a provider (the user's `register()`, or dev tracing). Imported
196
+ * statically, not lazily, so `withSpan()` can invoke its callback in the
197
+ * same synchronous frame it was called in: a server component wrapped in a
198
+ * span (`timber.page`, `timber.layout`) must run while React's render
199
+ * dispatcher is still set, or a synchronous component that calls `use()`
200
+ * fails with an invalid hook call. Looked up per span — the API's proxy
201
+ * tracer follows a provider registered after boot.
222
202
  */
223
- export async function getTracer(): Promise<import('@opentelemetry/api').Tracer | null> {
224
- if (_tracer === undefined) {
225
- const api = await getOtelApi();
226
- if (api) {
227
- _tracer = api.trace.getTracer('timber.js');
228
- } else {
229
- _tracer = null;
230
- }
231
- }
232
- return _tracer;
203
+ function getTracer(): Tracer {
204
+ return trace.getTracer('timber.js');
233
205
  }
234
206
 
235
207
  /**
@@ -239,9 +211,12 @@ export async function getTracer(): Promise<import('@opentelemetry/api').Tracer |
239
211
  * (Cloudflare Workers), the fn is wrapped in platformTracer.enterSpan()
240
212
  * so it appears in the platform's native trace view.
241
213
  * - **OTEL span** — when an OTEL SDK is active, the fn also runs inside an
242
- * OTEL span (dual emission). No SDK and no platform tracer = zero overhead.
214
+ * OTEL span (dual emission). With no SDK the OTEL span is the API's
215
+ * non-recording no-op.
243
216
  *
244
217
  * Automatically:
218
+ * - Invokes fn synchronously, in the caller's frame — a wrapped server
219
+ * component still sees React's render dispatcher (see getTracer())
245
220
  * - Creates the span as a child of the current context
246
221
  * - Runs fn in its own trace scope carrying the span's IDs, for log–trace
247
222
  * correlation and setSpanAttribute()
@@ -251,8 +226,27 @@ export async function getTracer(): Promise<import('@opentelemetry/api').Tracer |
251
226
  export async function withSpan<T>(
252
227
  name: string,
253
228
  attributes: Record<string, string | number | boolean>,
254
- fn: () => T | Promise<T>
229
+ fn: () => T | PromiseLike<T>
255
230
  ): Promise<T> {
231
+ return traceCall(name, attributes, fn);
232
+ }
233
+
234
+ /**
235
+ * The span core of {@link withSpan}, keeping the shape of the call: `fn` runs
236
+ * synchronously, a value it returns comes back as that value, a promise as a
237
+ * promise, and a synchronous throw is rethrown synchronously.
238
+ *
239
+ * For a framework wrapper that invokes a server component inside a span.
240
+ * React drives a synchronous component through throws: `use()` on a pending
241
+ * promise throws, and Flight retries the component once it settles. That only
242
+ * works if the throw leaves the wrapper synchronously — `withSpan()` would
243
+ * turn it into a rejection, which Flight reports as a render error.
244
+ */
245
+ export function traceCall<T>(
246
+ name: string,
247
+ attributes: Record<string, string | number | boolean>,
248
+ fn: () => T | PromiseLike<T>
249
+ ): T | Promise<T> {
256
250
  const platformTracer = getPlatformTracer();
257
251
  if (!platformTracer) {
258
252
  return runOtelSpan(name, attributes, fn);
@@ -269,20 +263,17 @@ export async function withSpan<T>(
269
263
  });
270
264
  }
271
265
 
272
- /** The OTEL half of withSpan() — no-op passthrough when no SDK is active. */
273
- async function runOtelSpan<T>(
266
+ /**
267
+ * The OTEL half of withSpan() — a non-recording span when no SDK is active.
268
+ * Calls `fn` synchronously; see {@link getTracer}.
269
+ */
270
+ function runOtelSpan<T>(
274
271
  name: string,
275
272
  attributes: Record<string, string | number | boolean>,
276
- fn: () => T | Promise<T>
277
- ): Promise<T> {
278
- const tracer = await getTracer();
279
- if (!tracer) {
280
- return fn();
281
- }
282
-
283
- const api = (await getOtelApi())!;
284
- return tracer.startActiveSpan(name, { attributes }, (span) =>
285
- runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(api, span, fn))
273
+ fn: () => T | PromiseLike<T>
274
+ ): T | Promise<T> {
275
+ return getTracer().startActiveSpan(name, { attributes }, (span) =>
276
+ runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(span, fn))
286
277
  );
287
278
  }
288
279
 
@@ -301,26 +292,83 @@ function isOutcomeSignal(error: unknown): boolean {
301
292
  return status !== undefined && status < 500;
302
293
  }
303
294
 
304
- /** Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}). */
305
- async function settleOtelSpan<T>(
306
- api: typeof import('@opentelemetry/api'),
307
- span: import('@opentelemetry/api').Span,
308
- fn: () => T | Promise<T>
309
- ): Promise<T> {
295
+ /**
296
+ * Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}),
297
+ * keeping the call's shape (see {@link traceCall}).
298
+ */
299
+ function settleOtelSpan<T>(span: Span, fn: () => T | PromiseLike<T>): T | Promise<T> {
300
+ let result: T | PromiseLike<T>;
310
301
  try {
311
- const result = await fn();
312
- span.setStatus({ code: api.SpanStatusCode.OK });
313
- return result;
302
+ result = fn();
314
303
  } catch (error) {
315
- if (isOutcomeSignal(error)) throw error;
316
- span.setStatus({ code: api.SpanStatusCode.ERROR });
304
+ endSpanWithError(span, error);
305
+ throw error;
306
+ }
307
+ if (isPromiseLike(result)) {
308
+ // Any thenable, not only a native Promise — a custom or cross-realm one
309
+ // must hold the span open too, as `await` would. Its `then` is called
310
+ // here, synchronously, so a lazy thenable starts its work in this span.
311
+ const thenable = result;
312
+ return new Promise<T>((resolve, reject) => {
313
+ const fail = (error: unknown) => {
314
+ endSpanWithError(span, error);
315
+ reject(error);
316
+ };
317
+ try {
318
+ thenable.then((value) => {
319
+ endSpanOk(span);
320
+ resolve(value);
321
+ }, fail);
322
+ } catch (error) {
323
+ // A `then` that throws is a rejection, as for `await`; end the span.
324
+ fail(error);
325
+ }
326
+ });
327
+ }
328
+ endSpanOk(span);
329
+ return result;
330
+ }
331
+
332
+ function isPromiseLike<T>(value: T | PromiseLike<T>): value is PromiseLike<T> {
333
+ return (
334
+ (typeof value === 'object' || typeof value === 'function') &&
335
+ value !== null &&
336
+ 'then' in value &&
337
+ typeof value.then === 'function'
338
+ );
339
+ }
340
+
341
+ function endSpanOk(span: Span): void {
342
+ span.setStatus({ code: SpanStatusCode.OK });
343
+ span.end();
344
+ }
345
+
346
+ /**
347
+ * True when `error` is React suspending the component, not failing it: a
348
+ * thrown thenable, or the `SuspenseException` that `use()` throws on a
349
+ * pending promise. Flight retries the component once the promise settles, so
350
+ * a span around a synchronous component (see {@link traceCall}) that suspends
351
+ * is not an error span — the retry's span carries the real outcome.
352
+ *
353
+ * React does not export `SuspenseException`; Flight recognises it by
354
+ * identity, and its message — which React keeps stable because it is the
355
+ * user-facing explanation when one is caught by mistake — is the only handle
356
+ * outside React.
357
+ */
358
+ function isReactSuspension(error: unknown): boolean {
359
+ if (typeof error !== 'object' || error === null) return false;
360
+ if ('then' in error && typeof error.then === 'function') return true;
361
+ return error instanceof Error && error.message.startsWith('Suspense Exception:');
362
+ }
363
+
364
+ function endSpanWithError(span: Span, error: unknown): void {
365
+ if (!isOutcomeSignal(error) && !isReactSuspension(error)) {
366
+ span.setStatus({ code: SpanStatusCode.ERROR });
317
367
  if (error instanceof Error) {
318
368
  span.recordException(error);
319
369
  }
320
- throw error;
321
- } finally {
322
- span.end();
323
370
  }
371
+ span.end();
324
372
  }
325
373
 
326
374
  /**
@@ -337,11 +385,8 @@ export async function setSpanAttribute(
337
385
  platformSpan.setAttribute(key, value);
338
386
  }
339
387
 
340
- const api = await getOtelApi();
341
- if (!api) return;
342
-
343
- const activeSpan = api.trace.getActiveSpan();
344
- if (activeSpan) {
388
+ const activeSpan = trace.getActiveSpan();
389
+ if (activeSpan?.isRecording()) {
345
390
  activeSpan.setAttribute(key, value);
346
391
  }
347
392
  }
@@ -354,11 +399,8 @@ export async function addSpanEvent(
354
399
  name: string,
355
400
  attributes?: Record<string, string | number | boolean>
356
401
  ): Promise<void> {
357
- const api = await getOtelApi();
358
- if (!api) return;
359
-
360
- const activeSpan = api.trace.getActiveSpan();
361
- if (activeSpan) {
402
+ const activeSpan = trace.getActiveSpan();
403
+ if (activeSpan?.isRecording()) {
362
404
  activeSpan.addEvent(name, attributes);
363
405
  }
364
406
  }
@@ -367,8 +409,7 @@ export async function addSpanEvent(
367
409
  * Fire-and-forget span event — no await, no microtask overhead.
368
410
  *
369
411
  * Used on the cache hot path where awaiting addSpanEvent creates an
370
- * unnecessary microtask per cache operation. If OTEL is not loaded yet,
371
- * the event is silently dropped (acceptable for diagnostics).
412
+ * unnecessary microtask per cache operation.
372
413
  *
373
414
  * See TIM-370 for perf motivation.
374
415
  */
@@ -376,12 +417,8 @@ export function addSpanEventSync(
376
417
  name: string,
377
418
  attributes?: Record<string, string | number | boolean>
378
419
  ): void {
379
- // Fast path: if OTEL API hasn't been loaded yet, skip entirely.
380
- // _otelApi is undefined (not yet loaded), null (failed to load), or the module.
381
- if (!_otelApi) return;
382
-
383
- const activeSpan = _otelApi.trace.getActiveSpan();
384
- if (activeSpan) {
420
+ const activeSpan = trace.getActiveSpan();
421
+ if (activeSpan?.isRecording()) {
385
422
  activeSpan.addEvent(name, attributes);
386
423
  }
387
424
  }
@@ -392,10 +429,7 @@ export function addSpanEventSync(
392
429
  * reaches logs through the span's own trace scope, not from here.)
393
430
  */
394
431
  export async function getOtelTraceId(): Promise<string | undefined> {
395
- const api = await getOtelApi();
396
- if (!api) return undefined;
397
-
398
- const activeSpan = api.trace.getActiveSpan();
432
+ const activeSpan = trace.getActiveSpan();
399
433
  if (!activeSpan) return undefined;
400
434
 
401
435
  const ctx = activeSpan.spanContext();
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The wire contract between the dev server's span sink and the dev request
3
+ * pill in the browser. Dev-only; see design/50-dev-request-pill.md.
4
+ *
5
+ * Isomorphic: no server, client, or build-time imports.
6
+ */
7
+
8
+ /** HMR event that carries one finished span to the browser. */
9
+ export const DEV_SPAN_EVENT = 'timber:span';
10
+
11
+ /** HMR event a tab sends to ask for a trace's spans that ended before it connected. */
12
+ export const DEV_SPAN_REPLAY_EVENT = 'timber:span-replay';
13
+
14
+ /**
15
+ * `globalThis` key holding the span sink. The dev server plugin installs it
16
+ * and `DevSpanProcessor` (RSC module graph, same process, separate module
17
+ * instances) reads it, so the hand-off is a `Symbol.for` global.
18
+ */
19
+ export const DEV_SPAN_SINK_KEY = Symbol.for('timber.dev.span-sink');
20
+
21
+ /** The `Server-Timing` metric whose `desc` is the response's trace ID. */
22
+ export const TRACE_TIMING_NAME = 'timber-trace';
23
+
24
+ /**
25
+ * `globalThis` key holding the dev await wrapper. The dev await transform
26
+ * (`plugins/dev-await.ts`) rewrites `await x` in app server code to call
27
+ * it, looked up at call time; dev tracing installs it. With nothing
28
+ * installed the call is a plain await. See design/50-dev-request-pill.md
29
+ * §"Phase 2".
30
+ */
31
+ export const DEV_AWAIT_KEY = Symbol.for('timber.dev.await');
32
+
33
+ /** Span name for one awaited call in app server code. */
34
+ export const AWAIT_SPAN_NAME = 'timber.await';
35
+
36
+ /**
37
+ * Await spans shorter than this are dropped before they reach the terminal
38
+ * tree or the pill: `await params` and other awaits of settled values would
39
+ * otherwise drown the I/O the spans exist to show.
40
+ */
41
+ export const AWAIT_SPAN_MIN_MS = 1;
42
+
43
+ /** Root span of every pipeline request. */
44
+ export const ROOT_SPAN_NAME = 'http.server.request';
45
+
46
+ /**
47
+ * The span attributes that may reach the browser — the ones the pill reads,
48
+ * and nothing else. An allowlist of keys, not of prefixes: a prefix let
49
+ * through `timber.fetch_error` (an error message that can quote a full URL)
50
+ * and user attributes such as `url.full` or
51
+ * `http.request.header.authorization`. Typing the payload with this list
52
+ * means the pill cannot read an attribute that isn't on it.
53
+ */
54
+ export const DEV_SPAN_ATTRIBUTES = [
55
+ 'http.request.method',
56
+ 'http.response.status_code',
57
+ /** Query and fragment stripped. */
58
+ 'http.url',
59
+ /** Query and fragment stripped. */
60
+ 'url.path',
61
+ 'timber.route',
62
+ 'timber.segment',
63
+ 'timber.slot',
64
+ 'timber.action_name',
65
+ 'timber.cache_status',
66
+ /** The awaited expression's source text, whitespace collapsed, truncated. */
67
+ 'timber.await_label',
68
+ /** `path/relative/to/root.ts:line` of the await. */
69
+ 'timber.await_location',
70
+ ] as const;
71
+
72
+ export type DevSpanAttribute = (typeof DEV_SPAN_ATTRIBUTES)[number];
73
+
74
+ /** Attributes that hold a URL; sent without query or fragment. */
75
+ export const DEV_SPAN_URL_ATTRIBUTES: ReadonlySet<DevSpanAttribute> = new Set([
76
+ 'http.url',
77
+ 'url.path',
78
+ ]);
79
+
80
+ export type DevSpanSink = (span: DevSpanPayload) => void;
81
+
82
+ /** One finished span, projected for the browser. */
83
+ export interface DevSpanPayload {
84
+ traceId: string;
85
+ spanId: string;
86
+ /** Absent for the root span. */
87
+ parentSpanId?: string;
88
+ name: string;
89
+ /** Epoch milliseconds. */
90
+ startMs: number;
91
+ /** Epoch milliseconds. */
92
+ endMs: number;
93
+ error: boolean;
94
+ /** Only `DEV_SPAN_ATTRIBUTES`; URLs without query or fragment. */
95
+ attributes: Partial<Record<DevSpanAttribute, string | number | boolean>>;
96
+ /** Names of `timber.*` span events, e.g. `timber.cache.hit`. */
97
+ events: string[];
98
+ }
99
+
100
+ /**
101
+ * Read the trace ID from `Server-Timing` metrics, either a raw header value
102
+ * or the `serverTiming` entries of a `PerformanceResourceTiming`.
103
+ */
104
+ export function traceIdFromServerTiming(
105
+ timing: string | null | readonly { name: string; description: string }[]
106
+ ): string | null {
107
+ if (timing == null) return null;
108
+ if (typeof timing !== 'string') {
109
+ return timing.find((t) => t.name === TRACE_TIMING_NAME)?.description || null;
110
+ }
111
+ // `timber-trace;desc="<32 hex>"` — the ID is hex, so no escaping to undo.
112
+ const match = new RegExp(`(?:^|,)\\s*${TRACE_TIMING_NAME}\\s*;\\s*desc="?([0-9a-f]+)"?`).exec(
113
+ timing
114
+ );
115
+ return match?.[1] ?? null;
116
+ }
117
+
118
+ /** The `Server-Timing` entry that carries a trace ID. */
119
+ export function traceTimingEntry(traceId: string): string {
120
+ return `${TRACE_TIMING_NAME};desc="${traceId}"`;
121
+ }
122
+
123
+ // ─── Labels ─────────────────────────────────────────────────────────────────
124
+
125
+ /** Span attributes as either side holds them (OTEL also allows arrays). */
126
+ type SpanAttributes = Readonly<Record<string, unknown>>;
127
+
128
+ /** `@slot ` for a span from a parallel slot, so it reads apart from the main route. */
129
+ function slotPrefix(attrs: SpanAttributes): string {
130
+ const slot = attrs['timber.slot'];
131
+ return slot ? `${String(slot)} ` : '';
132
+ }
133
+
134
+ /**
135
+ * Map a span to its display label and environment tag. One mapping for the
136
+ * terminal tree and the dev request pill, so the two never name a span
137
+ * differently.
138
+ */
139
+ export function devSpanLabel(name: string, attrs: SpanAttributes): { label: string; env: string } {
140
+ switch (name) {
141
+ case ROOT_SPAN_NAME: {
142
+ const method = attrs['http.request.method'] ?? 'GET';
143
+ const path = attrs['url.path'] ?? '/';
144
+ return { label: `${String(method)} ${String(path)}`, env: 'rsc' };
145
+ }
146
+ case 'timber.proxy':
147
+ return { label: 'proxy.ts', env: 'proxy' };
148
+ case 'timber.middleware':
149
+ return { label: 'middleware.ts', env: 'rsc' };
150
+ case 'timber.render':
151
+ return { label: 'render', env: 'rsc' };
152
+ case 'timber.access': {
153
+ const seg = attrs['timber.segment'] ?? 'segment';
154
+ return { label: `AccessGate (${String(seg)})`, env: 'rsc' };
155
+ }
156
+ case 'timber.ssr':
157
+ return { label: 'hydration render', env: 'ssr' };
158
+ case 'timber.action': {
159
+ const actionName = attrs['timber.action_name'] ?? 'action';
160
+ return { label: String(actionName), env: 'rsc' };
161
+ }
162
+ case 'timber.metadata':
163
+ return { label: 'metadata()', env: 'rsc' };
164
+ case 'timber.layout': {
165
+ const seg = attrs['timber.segment'] ?? '/';
166
+ return { label: `layout ${slotPrefix(attrs)}${String(seg)}`, env: 'rsc' };
167
+ }
168
+ case 'timber.page': {
169
+ const route = attrs['timber.route'] ?? '/';
170
+ return { label: `page ${slotPrefix(attrs)}${String(route)}`, env: 'rsc' };
171
+ }
172
+ case AWAIT_SPAN_NAME:
173
+ return { label: `await ${String(attrs['timber.await_label'] ?? '')}`, env: 'await' };
174
+ case 'timber.fetch': {
175
+ const fetchMethod = attrs['http.request.method'] ?? 'GET';
176
+ const fetchUrl = attrs['http.url'] ?? '';
177
+ return { label: `fetch ${String(fetchMethod)} ${String(fetchUrl)}`, env: 'fetch' };
178
+ }
179
+ default:
180
+ return { label: name, env: 'rsc' };
181
+ }
182
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-manifest-Y4jl7nwU.js","names":[],"sources":["../../src/server/build-manifest.ts"],"sourcesContent":["/**\n * Build manifest types and utilities for CSS and JS asset tracking.\n *\n * The build manifest maps route segment file paths to their output\n * chunks from Vite's client build. This enables:\n * - <link rel=\"stylesheet\"> injection in HTML <head>\n * - <script type=\"module\"> with hashed URLs in production\n * - <link rel=\"modulepreload\"> for client chunk dependencies\n * - Link preload headers for Early Hints (103)\n *\n * In dev mode, Vite's HMR client handles CSS/JS injection, so the build\n * manifest is empty. In production, it's populated from Vite's\n * .vite/manifest.json after the client build.\n *\n * Design docs: 18-build-system.md §\"Build Manifest\", 02-rendering-pipeline.md §\"Early Hints\"\n */\n\n/** A font asset entry in the build manifest. */\nexport interface ManifestFontEntry {\n /** URL path to the font file (e.g. `/_timber/fonts/inter-latin-400-abc123.woff2`). */\n href: string;\n /** Font format (e.g. `woff2`). */\n format: string;\n /** Crossorigin attribute — always `anonymous` for fonts. */\n crossOrigin: string;\n}\n\n/** Build manifest mapping input file paths to output asset URLs. */\nexport interface BuildManifest {\n /** Map from input file path (relative to project root) to output CSS URLs. */\n css: Record<string, string[]>;\n /** Map from input file path to output JS chunk URL (hashed filename). */\n js: Record<string, string>;\n /** Map from input file path to transitive JS dependency URLs for modulepreload. */\n modulepreload: Record<string, string[]>;\n /** Map from input file path to font assets used by that module. */\n fonts: Record<string, ManifestFontEntry[]>;\n /**\n * Cache-busting hashes for metadata route files (opengraph-image, etc.).\n * Map from file path (relative to project root) to short content hash.\n * In dev mode this is empty — a startup nonce is used instead.\n */\n metadataRouteHashes?: Record<string, string>;\n /**\n * Static request-dependency map from the Vite plugin's module-graph analysis.\n * Map from segment entry file path to whether it's request-dependent.\n * Used by buildSegmentInfo() for X-Timber-Segments in production.\n */\n requestDep?: Record<string, boolean>;\n}\n\n/**\n * Empty build manifest used in dev mode, and the single source of truth for\n * what an empty manifest contains.\n *\n * `virtual:timber-build-manifest` serializes this constant into its generated\n * source rather than restating it — one literal for the dev module, one for the\n * production module's `globalThis.__TIMBER_BUILD_MANIFEST__ ?? …` fallback.\n * They were three hand-written objects that had already drifted: this one and\n * the dev literal were missing `requestDep` while the production fallback had\n * it, so a reader who grepped the built bundle for `requestDep` found the one\n * copy that mentioned it and read the fallback as the shipped map (TIM-1300).\n * A field added here now reaches every copy.\n */\nexport const EMPTY_BUILD_MANIFEST: BuildManifest = {\n css: {},\n js: {},\n modulepreload: {},\n fonts: {},\n metadataRouteHashes: {},\n requestDep: {},\n};\n\n/** Segment shape expected by collectRouteCss (matches ManifestSegmentNode). */\ninterface SegmentWithFiles {\n layout?: { filePath: string };\n page?: { filePath: string };\n}\n\n/**\n * Collect all CSS files needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting CSS for each layout and page.\n * Deduplicates while preserving order (root layout CSS first).\n */\nexport function collectRouteCss(segments: SegmentWithFiles[], manifest: BuildManifest): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const cssFiles = manifest.css[file.filePath];\n if (!cssFiles) continue;\n for (const url of cssFiles) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"stylesheet\"> tags for CSS URLs.\n *\n * Returns an HTML string to prepend to headHtml for injection\n * via injectHead() before </head>.\n */\nexport function buildCssLinkTags(cssUrls: string[]): string {\n // Emit only <link rel=\"stylesheet\"> — no preload tags. CSS preloading\n // is handled by 103 Early Hints (Link header) which fires before the\n // HTML stream. Float also emits `<link rel=\"stylesheet\" data-precedence>`\n // at the top of <head> during Fizz rendering — the browser discovers\n // CSS from that tag. A <link rel=\"preload\"> here would arrive *after*\n // Float's stylesheet tag and trigger \"Preload was ignored\" warnings.\n return cssUrls.map((url) => `<link rel=\"stylesheet\" href=\"${url}\">`).join('');\n}\n\n// ─── Font utilities ──────────────────────────────────────────────────────\n\n/**\n * Collect all font entries needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting fonts for each layout and page.\n * Deduplicates by href while preserving order.\n */\nexport function collectRouteFonts(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): ManifestFontEntry[] {\n const seen = new Set<string>();\n const result: ManifestFontEntry[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const fonts = manifest.fonts[file.filePath];\n if (!fonts) continue;\n for (const entry of fonts) {\n if (!seen.has(entry.href)) {\n seen.add(entry.href);\n result.push(entry);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"preload\"> tags for font assets.\n *\n * Font preloads use `as=font` and always include `crossorigin` (required\n * for font preloads even for same-origin resources per the spec).\n */\nexport function buildFontPreloadTags(fonts: ManifestFontEntry[]): string {\n return fonts\n .map(\n (f) =>\n `<link rel=\"preload\" href=\"${f.href}\" as=\"font\" type=\"font/${f.format}\" crossorigin=\"${f.crossOrigin}\">`\n )\n .join('');\n}\n\n// ─── JS chunk utilities ──────────────────────────────────────────────────\n\n/**\n * Collect modulepreload URLs for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting transitive JS dependencies\n * for each layout and page. Deduplicates across segments.\n */\nexport function collectRouteModulepreloads(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const preloads = manifest.modulepreload[file.filePath];\n if (!preloads) continue;\n for (const url of preloads) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"modulepreload\"> tags for JS dependency URLs.\n *\n * Modulepreload hints tell the browser to fetch and parse JS modules\n * before they're needed, reducing waterfall latency for dynamic imports.\n */\nexport function buildModulepreloadTags(urls: string[]): string {\n return urls.map((url) => `<link rel=\"modulepreload\" href=\"${url}\">`).join('');\n}\n"],"mappings":";;;;;;;;;;;;;;AAgEA,IAAa,uBAAsC;CACjD,KAAK,CAAC;CACN,IAAI,CAAC;CACL,eAAe,CAAC;CAChB,OAAO,CAAC;CACR,qBAAqB,CAAC;CACtB,YAAY,CAAC;AACf;;;;;;;AAcA,SAAgB,gBAAgB,UAA8B,UAAmC;CAC/F,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,IAAI,KAAK;EACnC,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT;;;;;;;AA0BA,SAAgB,kBACd,UACA,UACqB;CACrB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA8B,CAAC;CAErC,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,QAAQ,SAAS,MAAM,KAAK;EAClC,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,SAAS,OAClB,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,GAAG;GACzB,KAAK,IAAI,MAAM,IAAI;GACnB,OAAO,KAAK,KAAK;EACnB;CAEJ;CAGF,OAAO;AACT;;;;;;;AAyBA,SAAgB,2BACd,UACA,UACU;CACV,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,cAAc,KAAK;EAC7C,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT"}
@@ -1 +0,0 @@
1
- export { t as formatChains } from "./chains-Dgm3PrMe.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"convention-lint-hZwz5wd4.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFileAtomic(segmentFile, content))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '/// <reference types=\"react/canary\" />',\n '/// <reference types=\"react-dom/canary\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\n/**\n * Write `timber-env.d.ts` only when its content differs.\n *\n * Its content is constant per timber version, so almost every call is a no-op\n * — and a file that is not rewritten cannot be read half-written. It is not\n * replaced atomically because it lives in the user's project root, often\n * committed: a rename would turn a symlink into a regular file, reset its\n * permissions, and a process killed mid-write would leave a temp file next to\n * their source. The in-place write happens only on first run or a timber\n * upgrade.\n */\nasync function writeEnvDts(envPath: string): Promise<void> {\n const existing = await readFile(envPath, 'utf-8').catch(() => null);\n if (existing !== TIMBER_ENV_DTS) await writeFile(envPath, TIMBER_ENV_DTS, 'utf-8');\n}\n\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n // The type checker can read these while they are being rewritten — an\n // editor's TS server during `timber dev`, a `tsgo` run during `vite\n // build`. A truncating write shows it an empty route map for the length\n // of the write, and every typed route degrades to `any` (TIM-1562).\n // The generated files under `.timber/` are replaced atomically.\n Promise.all([\n writeFileAtomic(routesPath, content),\n writeEnvDts(envPath),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and fatal\n * to rendering. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n getCsrfExport,\n} from './export-detect.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(tree: RouteTree, appDir: string): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n // Check 8: middleware.ts inside a parallel slot subtree (silently dead)\n checkSlotMiddleware(tree.root, warnings);\n\n // Check 9: `export const csrf` anywhere but route.ts, or in a form the\n // scanner cannot read (TIM-1543)\n checkCsrfExports(tree.root, warnings);\n if (tree.proxy) checkCsrfExport(tree.proxy, 'proxy.ts', warnings);\n if (tree.globalError) checkCsrfExport(tree.globalError, 'global-error', warnings);\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: CSRF Exemption Export ──────────────────────────────────────────\n\n/** Single-file segment conventions other than route.ts. */\nconst NON_ROUTE_FILE_KEYS = [\n 'page',\n 'layout',\n 'middleware',\n 'access',\n 'error',\n 'default',\n 'denied',\n] as const satisfies readonly (keyof SegmentNode)[];\n\n/**\n * Fail the build on a `csrf` export the CSRF gate would not honor.\n *\n * Both findings are proven from source, and both are fatal in the sense\n * the error level requires: the developer wrote an exemption that silently\n * does nothing, so a legitimate cross-site POST they meant to accept gets\n * a 403 in production, or they believe a page or action is exempt when\n * the gate still protects it. The exemption exists only on route.ts —\n * server actions always get the check (design/08 §\"Per-route exemption\").\n * A `'use server'` module cannot export it at all: plugin-rsc rejects every\n * non-async-function export there.\n */\nfunction checkCsrfExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) checkCsrfExport(node.route, 'route.ts', warnings);\n for (const key of NON_ROUTE_FILE_KEYS) {\n const file = node[key];\n if (file) checkCsrfExport(file, key, warnings);\n }\n // Status files and metadata routes (sitemap.ts, opengraph-image.tsx, …).\n // JSON status files are skipped by the script-extension check.\n for (const [name, file] of Object.entries(node.statusFiles ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const [name, file] of Object.entries(node.metadataRoutes ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const child of node.children) checkCsrfExports(child, warnings);\n for (const slot of Object.values(node.slots)) checkCsrfExports(slot, warnings);\n}\n\nfunction checkCsrfExport(file: RouteFile, convention: string, warnings: ConventionWarning[]): void {\n if (!isScriptExtension(file.extension)) return;\n const found = getCsrfExport(file.filePath);\n if (found === 'absent') return;\n const isRoute = convention === 'route.ts';\n if (isRoute && found === 'exempt') return;\n warnings.push({\n id: `CSRF_EXPORT_INVALID:${file.filePath}`,\n summary: isRoute\n ? `route.ts csrf export must be exactly \\`export const csrf = false\\`: ${file.filePath}`\n : `\\`csrf\\` can only be exported from route.ts, not ${convention}: ${file.filePath}`,\n details:\n ` File: ${file.filePath}\\n\\n` +\n (isRoute\n ? ' The CSRF gate reads this export from source before any module loads, so only\\n' +\n ' the literal form counts. Other values, `let`, and re-exports are not read.\\n\\n' +\n ' To fix: write `export const csrf = false;` in this file, or remove the export.\\n'\n : ' The per-route CSRF exemption applies only to route.ts handlers. Pages, layouts\\n' +\n ' and server actions always get the CSRF check.\\n\\n' +\n ' To fix: remove the export. To accept a cross-site POST, handle it in a route.ts\\n' +\n ' that exports `const csrf = false`.\\n'),\n level: 'error',\n });\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/** HTTP methods that route.ts can export. */\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // Only script extensions need the 'use client' check — .json status files\n // never reach React at all, and are not in `statusFiles`.\n if (!isScriptExtension(file.extension)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: Slot Middleware ─────────────────────────────────────────────────\n\n/**\n * Error when middleware.ts appears inside a parallel slot subtree.\n *\n * Middleware is collected from the main matched segment chain only\n * (route-matcher.ts `collectMiddlewareChain`). The slot resolver never\n * walks `middleware` on its matched chain, so a middleware.ts under any\n * `@slot/` directory silently never executes. `access.ts` in slot chains\n * DOES run (via SlotAccessGate), making the asymmetry invisible unless\n * you know to look.\n *\n * This is a build error rather than a warning: the file provably cannot\n * run and its presence misleads the author into thinking the slot is\n * middleware-protected.\n *\n * See design/07-routing.md §\"Parallel Routes\"\n */\nfunction checkSlotMiddleware(node: SegmentNode, warnings: ConventionWarning[]): void {\n for (const [slotName, slotRoot] of Object.entries(node.slots)) {\n collectSlotMiddleware(slotRoot, slotName, warnings);\n }\n for (const child of node.children) {\n checkSlotMiddleware(child, warnings);\n }\n}\n\n/**\n * Walk a slot subtree and report every middleware.ts found.\n */\nfunction collectSlotMiddleware(\n node: SegmentNode,\n slotName: string,\n warnings: ConventionWarning[]\n): void {\n if (node.middleware) {\n warnings.push({\n id: `SLOT_MIDDLEWARE:${node.middleware.filePath}`,\n summary: `middleware.ts inside slot @${slotName} never executes: ${node.middleware.filePath}`,\n details:\n ` File: ${node.middleware.filePath}\\n\\n` +\n ` Middleware is collected from the main route chain only.\\n` +\n ` The slot resolver does not run middleware — this file is silently dead.\\n` +\n ` (access.ts in slots does run via SlotAccessGate; middleware.ts does not.)\\n\\n` +\n ` To fix: Move the middleware logic into access.ts for slot-scoped auth,\\n` +\n ` or into a middleware.ts on the main route chain outside the slot.\\n`,\n level: 'error',\n });\n }\n for (const child of node.children) {\n collectSlotMiddleware(child, slotName, warnings);\n }\n for (const [nestedSlotName, nestedSlot] of Object.entries(node.slots)) {\n collectSlotMiddleware(nestedSlot, nestedSlotName, warnings);\n }\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push(style('dim', w.details));\n }\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,mBAAmB,MAAiB,QAA0C;CAC5F,MAAM,sBAAM,IAAI,IAAyB;CAEzC,SAAS,KAAK,MAAmB,QAAgB,UAAwB;EACvE,IAAI,IAAI,QAAQ;GACd,OAAO,KAAK,WAAW;GACvB,aAAa,YAAY;EAC3B,CAAC;EAED,KAAK,MAAM,SAAS,KAAK,UAGvB,KAAK,OAFY,KAAK,QAAQ,MAAM,WAExB,GAAU,GADG,SAAS,GAAG,MAAM,aACR;EAErC,KAAK,MAAM,CAAC,UAAU,aAAa,OAAO,QAAQ,KAAK,KAAK,GAG1D,KAAK,UAFW,KAAK,QAAQ,IAAI,UAElB,GAAS,GADA,SAAS,IAAI,UACD;CAExC;CAEA,KAAK,KAAK,MAAM,QAAQ,EAAE;CAC1B,OAAO;AACT;;;;AAKA,SAAgB,mBAAmB,MAA2B;CAC5D,OAAO;EACL,wBAAwB,KAAK,MAAM;EACnC,+BAA+B,KAAK,YAAY;EAChD;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;AAOA,eAAsB,kBACpB,WACA,QACA,MACe;CAGf,MAAM,WAAW,OAAO,MAAM,KAAK,SAAS,CAAC;CAC7C,MAAM,YAAY,KAAK,MAAM,WAAW,SAAS,QAAQ;CACzD,MAAM,MAAM,mBAAmB,WAAW,MAAM;CAEhD,MAAM,SAA0B,CAAC;CACjC,KAAK,MAAM,CAAC,OAAO,SAAS,KAAK;EAE/B,MAAM,SAAS,MAAM,MAAM,OAAO,MAAM;EACxC,MAAM,aAAa,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