@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
@@ -1,5 +1,7 @@
1
- import { useSyncExternalStore } from 'react';
1
+ import { use, useMemo, useRef, useSyncExternalStore } from 'react';
2
+ import { getOrCreateContext } from './navigation-context.ts';
2
3
  import { getRouterOrNull } from './router-ref.ts';
4
+ import { parseRouterUrl } from './router-url.ts';
3
5
 
4
6
  function subscribe(onStoreChange: () => void): () => void {
5
7
  const router = getRouterOrNull();
@@ -7,19 +9,43 @@ function subscribe(onStoreChange: () => void): () => void {
7
9
  return router.onPendingChange(onStoreChange);
8
10
  }
9
11
 
10
- function getSnapshot(): boolean {
12
+ function isPending(): boolean {
11
13
  const router = getRouterOrNull();
12
14
  return router ? router.isPending() : false;
13
15
  }
14
16
 
15
- const getServerSnapshot = getSnapshot;
17
+ const HAS_SCHEME = /^[a-z][a-z\d+.-]*:/i;
16
18
 
17
19
  /**
18
- * Returns true while an RSC navigation is in flight.
20
+ * A router URL as a `URL`, read the way the router reads it (`parseRouterUrl`)
21
+ * so `to` names the page the router will commit. Anything without a scheme is
22
+ * a path on this document's origin; an absolute URL keeps its own.
23
+ */
24
+ function pageUrl(url: string): URL {
25
+ const parsed = parseRouterUrl(url);
26
+ if (HAS_SCHEME.test(url)) return parsed;
27
+ return new URL(window.location.origin + parsed.pathname + parsed.search + parsed.hash);
28
+ }
29
+
30
+ /**
31
+ * Decides what a component wants to know about the navigation in flight.
19
32
  *
20
- * Reads from the router's external pending store via useSyncExternalStore.
21
- * Only components that call this hook re-render when pending state
22
- * changes — no full-tree re-render.
33
+ * `to` is where the router is going, with the `#fragment` of a link or
34
+ * `router.push()` that has one (traversals and refreshes carry none). `from`
35
+ * is the page the navigation departs from, as the calling component rendered
36
+ * it — not the address bar, which on Back/Forward has already moved. Both are
37
+ * fresh `URL`s; don't mutate them.
38
+ */
39
+ export type PendingNavigationSelector<T> = (to: URL, from: URL) => T;
40
+
41
+ /**
42
+ * Whether an RSC navigation is in flight — until its payload has decoded and
43
+ * React has committed the destination, so it never turns false while the
44
+ * departing page is still on screen.
45
+ *
46
+ * Reads the router's external pending store via `useSyncExternalStore`, so
47
+ * only components that call this hook re-render when a navigation starts or
48
+ * ends.
23
49
  *
24
50
  * ```tsx
25
51
  * 'use client'
@@ -27,14 +53,67 @@ const getServerSnapshot = getSnapshot;
27
53
  *
28
54
  * export function NavBar() {
29
55
  * const isPending = usePendingNavigation()
30
- * return (
31
- * <nav className={isPending ? 'opacity-50' : ''}>
32
- * <Link href="/dashboard">Dashboard</Link>
33
- * </nav>
34
- * )
56
+ * return <nav className={isPending ? 'opacity-50' : ''}>…</nav>
35
57
  * }
36
58
  * ```
37
59
  */
38
- export function usePendingNavigation(): boolean {
39
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
60
+ export function usePendingNavigation(): boolean;
61
+ /**
62
+ * The selector form: `select(to, from)` while a navigation is in flight,
63
+ * `false` when none is. A navigation starting, being superseded or ending
64
+ * re-renders the component only when the result changes (`Object.is`), so
65
+ * return a primitive. The selector form also re-renders on commits, as
66
+ * `usePathname()` does. A superseded navigation reports the newest target; a
67
+ * followed redirect reports the redirect's destination.
68
+ *
69
+ * ```tsx
70
+ * // Dim a list only while its own sort/filter/page navigation is in flight.
71
+ * const replacing = usePendingNavigation((to, from) => to.pathname === from.pathname)
72
+ * ```
73
+ *
74
+ * See design/19-client-navigation.md §"Where the navigation is going".
75
+ */
76
+ export function usePendingNavigation<T>(select: PendingNavigationSelector<T>): T | false;
77
+ export function usePendingNavigation<T>(select?: PendingNavigationSelector<T>): T | boolean {
78
+ // Read only by the selector form, so the plain form — TopLoader, a global
79
+ // spinner — does not re-render on every commit.
80
+ const nav = select ? use(getOrCreateContext()) : null;
81
+ if (select && nav === null) {
82
+ throw new Error(
83
+ '[timber] usePendingNavigation(select) was called outside the timber app tree ' +
84
+ '(no NavigationProvider found). In tests, render the component ' +
85
+ 'inside the timber providers.'
86
+ );
87
+ }
88
+ const rendered = nav ? nav.pathname + nav.search : null;
89
+
90
+ // The page each navigation departs from: what this component was rendering
91
+ // when it first saw the target. Held for the navigation's lifetime because
92
+ // the location context moves to the destination at its commit, while the
93
+ // router is still pending — read live, a link away would report "same page"
94
+ // for that commit and for any streaming tail after it.
95
+ const departure = useRef<{ target: string; from: string } | null>(null);
96
+
97
+ const getSnapshot = useMemo((): (() => T | boolean) => {
98
+ if (!select || rendered === null) return isPending;
99
+ // `getSnapshot` must return the same value for the same store state, and
100
+ // a selector returning `to` would otherwise hand React a new URL per call.
101
+ let last: { target: string; from: string; value: T } | null = null;
102
+ return () => {
103
+ const target = getRouterOrNull()?.getPendingUrl() ?? null;
104
+ if (target === null) {
105
+ departure.current = null;
106
+ return false;
107
+ }
108
+ if (departure.current?.target !== target) departure.current = { target, from: rendered };
109
+ const from = departure.current.from;
110
+ if (last?.target !== target || last.from !== from) {
111
+ last = { target, from, value: select(pageUrl(target), pageUrl(from)) };
112
+ }
113
+ return last.value;
114
+ };
115
+ }, [select, rendered]);
116
+
117
+ // The same read on the server: no router there, so it reports idle.
118
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
40
119
  }
@@ -158,6 +158,16 @@ export interface TimberUserConfig {
158
158
  * See design/21-dev-server.md §"Dev Hostnames".
159
159
  */
160
160
  hostname?: string | false;
161
+ /**
162
+ * The dev request pill: an on-page pill showing the server spans,
163
+ * fetches and awaits behind the current page (design/50-dev-request-pill.md).
164
+ * `false` turns it off entirely: no pill, no span stream to the browser,
165
+ * no `timber-trace` Server-Timing entry. To get it out of the way for
166
+ * one browser instead, minimize it (×); that choice is remembered.
167
+ *
168
+ * Default: `true`. Automated browsers (`navigator.webdriver`) never get it.
169
+ */
170
+ requestPill?: boolean;
161
171
  };
162
172
  /**
163
173
  * Control Server-Timing header output.
@@ -206,6 +206,16 @@ export function validateConfig(config: TimberUserConfig): ConfigError[] {
206
206
  }
207
207
  }
208
208
 
209
+ // dev.requestPill — not fatal: dev-only, like dev.hostname below.
210
+ if (config.dev?.requestPill !== undefined && typeof config.dev.requestPill !== 'boolean') {
211
+ errors.push({
212
+ field: 'dev.requestPill',
213
+ message: `dev.requestPill must be a boolean, got ${JSON.stringify(config.dev.requestPill)}.`,
214
+ value: config.dev.requestPill,
215
+ suggestion: 'Use dev: { requestPill: false } to turn the dev request pill off.',
216
+ });
217
+ }
218
+
209
219
  // dev.hostname — not fatal: it is dev-only, so a typo must not fail
210
220
  // `timber build`. Dev startup still refuses it (deriveDevHostname throws).
211
221
  if (config.dev?.hostname !== undefined) {
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Dev await wrapper — the runtime half of the dev await transform
3
+ * (`plugins/dev-await.ts`). Each `await x` in app server code calls this
4
+ * with a thunk for `x`, so the awaited work runs inside a `timber.await`
5
+ * span and appears in the terminal tree and the dev request pill nested
6
+ * under the component, middleware or action that awaited it.
7
+ *
8
+ * See design/50-dev-request-pill.md §"Phase 2".
9
+ */
10
+
11
+ import { trace } from '@opentelemetry/api';
12
+ import { AWAIT_SPAN_NAME, DEV_AWAIT_KEY } from '../shared/dev-span.ts';
13
+ import { traceCall } from '../server/tracing.ts';
14
+
15
+ export type DevAwaitWrapper = (
16
+ thunk: () => Promise<unknown>,
17
+ label: string,
18
+ location: string
19
+ ) => Promise<unknown>;
20
+
21
+ /**
22
+ * Install the wrapper on `globalThis[DEV_AWAIT_KEY]`. Transformed modules
23
+ * look it up per call, so a module evaluated before this ran still gets
24
+ * spans once it has. Idempotent: a repeat install replaces the wrapper.
25
+ */
26
+ export function installDevAwait(): void {
27
+ const wrapper: DevAwaitWrapper = (thunk, label, location) => {
28
+ // Outside a request (module init, background work) there is no trace
29
+ // to nest under; a span would only become an orphan trace.
30
+ if (!trace.getActiveSpan()) return thunk();
31
+ return Promise.resolve(
32
+ traceCall(
33
+ AWAIT_SPAN_NAME,
34
+ { 'timber.await_label': label, 'timber.await_location': location },
35
+ thunk
36
+ )
37
+ );
38
+ };
39
+ (globalThis as Record<symbol, unknown>)[DEV_AWAIT_KEY] = wrapper;
40
+ }
@@ -30,6 +30,9 @@ import {
30
30
  type DevLogMode,
31
31
  type DevLoggerConfig,
32
32
  } from './logger.ts';
33
+ import { forwardSpan } from './span-sink.ts';
34
+ import { installDevAwait } from './await-span.ts';
35
+ import { AWAIT_SPAN_MIN_MS, AWAIT_SPAN_NAME } from '../shared/dev-span.ts';
33
36
 
34
37
  // ─── Fetch Instrumentation ──────────────────────────────────────────────────
35
38
 
@@ -135,6 +138,10 @@ function extractFetchInfo(
135
138
  return { method: method.toUpperCase(), url };
136
139
  }
137
140
 
141
+ function hrTimeToMs([seconds, nanos]: [number, number]): number {
142
+ return seconds * 1000 + nanos / 1e6;
143
+ }
144
+
138
145
  // ─── Span Processor ─────────────────────────────────────────────────────────
139
146
 
140
147
  /**
@@ -174,6 +181,10 @@ export class DevSpanProcessor implements SpanProcessor {
174
181
  }
175
182
 
176
183
  onEnd(span: ReadableSpan): void {
184
+ // Awaits of settled values (`await params`) would drown the I/O these
185
+ // spans exist to show; drop them for the terminal and the pill alike.
186
+ if (span.name === AWAIT_SPAN_NAME && hrTimeToMs(span.duration) < AWAIT_SPAN_MIN_MS) return;
187
+
177
188
  const traceId = span.spanContext().traceId;
178
189
 
179
190
  let spans = this.spansByTrace.get(traceId);
@@ -189,6 +200,11 @@ export class DevSpanProcessor implements SpanProcessor {
189
200
  }
190
201
  spans.push(span);
191
202
 
203
+ // Stream every span to the dev request pill as it ends, not at the root:
204
+ // a Suspense boundary that resolves late appears late, the way it does
205
+ // in the page (design/50-dev-request-pill.md §"Transport").
206
+ forwardSpan(span);
207
+
192
208
  // Root span signals request completion — all child spans are already
193
209
  // collected because OTEL ends child spans before parent spans.
194
210
  if (span.name === 'http.server.request') {
@@ -258,4 +274,8 @@ export function registerDevTracing(config: DevLoggerConfig): void {
258
274
  // Patched here, not by the caller, so one guarded import of this module
259
275
  // covers all of tracing setup (TIM-1554).
260
276
  instrumentDevFetch();
277
+
278
+ // `await` in app server code becomes a span too, through the dev await
279
+ // transform (plugins/dev-await.ts). design/50-dev-request-pill.md.
280
+ installDevAwait();
261
281
  }
@@ -18,6 +18,7 @@ import { STATUS_CODES } from 'node:http';
18
18
  import type { InspectColor } from 'node:util';
19
19
  import { styleText } from 'node:util';
20
20
  import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';
21
+ import { devSpanLabel } from '../shared/dev-span.ts';
21
22
 
22
23
  // ─── Configuration ──────────────────────────────────────────────────────────
23
24
 
@@ -75,44 +76,9 @@ function relativeMs(time: HrTime, rootStart: HrTime): number {
75
76
 
76
77
  // ─── Span → Tree Mapping ────────────────────────────────────────────────────
77
78
 
78
- /** Map span names to display labels and environment tags. */
79
+ /** Map a span to its display label and environment tag. */
79
80
  function spanLabel(span: ReadableSpan): { label: string; env: string } {
80
- const attrs = span.attributes;
81
- switch (span.name) {
82
- case 'timber.proxy':
83
- return { label: 'proxy.ts', env: 'proxy' };
84
- case 'timber.middleware':
85
- return { label: 'middleware.ts', env: 'rsc' };
86
- case 'timber.render':
87
- return { label: 'render', env: 'rsc' };
88
- case 'timber.access': {
89
- const seg = attrs['timber.segment'] ?? 'segment';
90
- return { label: `AccessGate (${seg})`, env: 'rsc' };
91
- }
92
- case 'timber.ssr':
93
- return { label: 'hydration render', env: 'ssr' };
94
- case 'timber.action': {
95
- const name = attrs['timber.action_name'] ?? 'action';
96
- return { label: String(name), env: 'rsc' };
97
- }
98
- case 'timber.metadata':
99
- return { label: 'metadata()', env: 'rsc' };
100
- case 'timber.layout': {
101
- const seg = attrs['timber.segment'] ?? '/';
102
- return { label: `layout ${seg}`, env: 'rsc' };
103
- }
104
- case 'timber.page': {
105
- const route = attrs['timber.route'] ?? '/';
106
- return { label: `page ${route}`, env: 'rsc' };
107
- }
108
- case 'timber.fetch': {
109
- const fetchMethod = attrs['http.request.method'] ?? 'GET';
110
- const fetchUrl = attrs['http.url'] ?? '';
111
- return { label: `fetch ${fetchMethod} ${fetchUrl}`, env: 'fetch' };
112
- }
113
- default:
114
- return { label: span.name, env: 'rsc' };
115
- }
81
+ return devSpanLabel(span.name, span.attributes);
116
82
  }
117
83
 
118
84
  // ─── Tree Node ──────────────────────────────────────────────────────────────
@@ -14,6 +14,7 @@
14
14
 
15
15
  import type { Plugin, ViteDevServer, Logger } from 'vite';
16
16
  import type { PluginContext } from '../plugin-context.ts';
17
+ import { installSpanSink } from './span-sink.ts';
17
18
 
18
19
  // ─── Original Console Snapshot ──────────────────────────────────────────
19
20
 
@@ -390,7 +391,15 @@ export function timberDevLogs(_ctx: PluginContext): Plugin {
390
391
  apply: 'serve',
391
392
 
392
393
  configureServer(server: ViteDevServer) {
393
- cleanup = patchConsole(server, _ctx.root);
394
+ const unpatch = patchConsole(server, _ctx.root);
395
+ // Finished request spans ride the same server→browser channel, for the
396
+ // dev request pill (design/50-dev-request-pill.md).
397
+ const uninstallSink =
398
+ _ctx.config.dev?.requestPill === false ? () => {} : installSpanSink(server.hot);
399
+ cleanup = () => {
400
+ unpatch();
401
+ uninstallSink();
402
+ };
394
403
 
395
404
  // Stop forwarding to this server once it closes
396
405
  server.httpServer?.on('close', () => {
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Span sink — streams finished dev spans to the browser over HMR, for the
3
+ * dev request pill. See design/50-dev-request-pill.md §"Transport".
4
+ *
5
+ * Two halves that run in different module graphs of one process:
6
+ * - `installSpanSink()` runs in the dev server plugin, which owns the HMR
7
+ * channel.
8
+ * - `forwardSpan()` runs in `DevSpanProcessor` (RSC graph) on every span end.
9
+ * They meet at `globalThis[DEV_SPAN_SINK_KEY]`. With nothing installed (a
10
+ * production build under TIMBER_DEBUG, unit tests), forwarding is a no-op —
11
+ * this is what keeps the browser channel gated to `vite dev`.
12
+ */
13
+
14
+ import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';
15
+ import {
16
+ DEV_SPAN_ATTRIBUTES,
17
+ DEV_SPAN_EVENT,
18
+ DEV_SPAN_REPLAY_EVENT,
19
+ DEV_SPAN_SINK_KEY,
20
+ DEV_SPAN_URL_ATTRIBUTES,
21
+ type DevSpanPayload,
22
+ type DevSpanSink,
23
+ } from '../shared/dev-span.ts';
24
+
25
+ type HrTime = [number, number];
26
+
27
+ function hrTimeToEpochMs([seconds, nanos]: HrTime): number {
28
+ return seconds * 1000 + nanos / 1e6;
29
+ }
30
+
31
+ /** Drop the query and fragment: they can carry tokens. */
32
+ function stripQuery(url: string): string {
33
+ const end = url.search(/[?#]/);
34
+ return end === -1 ? url : url.slice(0, end);
35
+ }
36
+
37
+ /** Project an OTEL span onto the browser payload. */
38
+ export function toDevSpanPayload(span: ReadableSpan): DevSpanPayload {
39
+ const attributes: DevSpanPayload['attributes'] = {};
40
+ for (const key of DEV_SPAN_ATTRIBUTES) {
41
+ const value = span.attributes[key];
42
+ if (typeof value === 'string') {
43
+ attributes[key] = DEV_SPAN_URL_ATTRIBUTES.has(key) ? stripQuery(value) : value;
44
+ } else if (typeof value === 'number' || typeof value === 'boolean') {
45
+ attributes[key] = value;
46
+ }
47
+ }
48
+ const startMs = hrTimeToEpochMs(span.startTime);
49
+ return {
50
+ traceId: span.spanContext().traceId,
51
+ spanId: span.spanContext().spanId,
52
+ parentSpanId: span.parentSpanContext?.spanId,
53
+ name: span.name,
54
+ startMs,
55
+ endMs: startMs + hrTimeToEpochMs(span.duration),
56
+ // SpanStatusCode.ERROR — a literal, so the browser-facing module does
57
+ // not need @opentelemetry/api for one enum value.
58
+ error: span.status.code === 2,
59
+ attributes,
60
+ events: span.events.map((e) => e.name).filter((n) => n.startsWith('timber.')),
61
+ };
62
+ }
63
+
64
+ /** Called by DevSpanProcessor for every finished span. */
65
+ export function forwardSpan(span: ReadableSpan): void {
66
+ const sink = (globalThis as Record<symbol, unknown>)[DEV_SPAN_SINK_KEY] as
67
+ | DevSpanSink
68
+ | undefined;
69
+ if (!sink) return;
70
+ try {
71
+ sink(toDevSpanPayload(span));
72
+ } catch {
73
+ // A diagnostic channel must never break the request it observes.
74
+ }
75
+ }
76
+
77
+ /** Traces the server keeps for replay. Oldest-inserted is evicted. */
78
+ const MAX_REPLAY_TRACES = 64;
79
+
80
+ /** The slice of Vite's HMR channel the sink uses. */
81
+ export interface SpanSinkChannel {
82
+ send(event: string, data: unknown): void;
83
+ on(
84
+ event: string,
85
+ listener: (data: unknown, client: { send(event: string, data: unknown): void }) => void
86
+ ): void;
87
+ off(event: string, listener: (...args: never[]) => void): void;
88
+ }
89
+
90
+ /**
91
+ * Install the sink that broadcasts spans on the dev server's HMR channel,
92
+ * and answers replay requests from it.
93
+ *
94
+ * Broadcasting alone loses most of a document load: the root span ends when
95
+ * the pipeline returns its Response, tens of milliseconds in, and the page's
96
+ * HMR socket connects later than that. So the sink keeps recent traces, and
97
+ * a tab that learns a trace ID asks for it (`DEV_SPAN_REPLAY_EVENT`); the
98
+ * answer goes to that tab alone. The tab dedupes by span ID, so a span that
99
+ * arrives both ways counts once.
100
+ *
101
+ * Returns the uninstall function; an uninstall only removes its own sink, so
102
+ * a restarted server's sink survives the old server's close.
103
+ */
104
+ export function installSpanSink(hot: SpanSinkChannel): () => void {
105
+ const globals = globalThis as Record<symbol, unknown>;
106
+ const recent = new Map<string, DevSpanPayload[]>();
107
+ const sink: DevSpanSink = (span) => {
108
+ let spans = recent.get(span.traceId);
109
+ if (!spans) {
110
+ if (recent.size >= MAX_REPLAY_TRACES) {
111
+ const oldest = recent.keys().next().value;
112
+ if (oldest !== undefined) recent.delete(oldest);
113
+ }
114
+ spans = [];
115
+ recent.set(span.traceId, spans);
116
+ }
117
+ spans.push(span);
118
+ hot.send(DEV_SPAN_EVENT, span);
119
+ };
120
+ const onReplay = (data: unknown, client: { send(event: string, data: unknown): void }) => {
121
+ if (typeof data !== 'object' || data === null || !('traceId' in data)) return;
122
+ const { traceId } = data;
123
+ if (typeof traceId !== 'string') return;
124
+ for (const span of recent.get(traceId) ?? []) client.send(DEV_SPAN_EVENT, span);
125
+ };
126
+ globals[DEV_SPAN_SINK_KEY] = sink;
127
+ hot.on(DEV_SPAN_REPLAY_EVENT, onReplay);
128
+ return () => {
129
+ hot.off(DEV_SPAN_REPLAY_EVENT, onReplay);
130
+ if (globals[DEV_SPAN_SINK_KEY] === sink) delete globals[DEV_SPAN_SINK_KEY];
131
+ };
132
+ }
package/src/index.ts CHANGED
@@ -39,6 +39,7 @@ import { timberOptimizePackageImports } from './plugins/optimize-package-imports
39
39
  import { timberClientInServerPackageDeps } from './plugins/client-in-server-package-deps.ts';
40
40
  import { timberPrebuilt } from './plugins/prebuilt.ts';
41
41
  import { timberPrerenderSugar } from './plugins/prerender-sugar.ts';
42
+ import { timberDevAwait } from './plugins/dev-await.ts';
42
43
  import { timberCloudflareWasm } from './plugins/cloudflare-wasm.ts';
43
44
  import { timberPostBuild } from './plugins/post-build.ts';
44
45
  import { timberBuildReport } from './plugins/build-report.ts';
@@ -593,6 +594,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
593
594
  buildReport, // Route table with bundle sizes, printed by timber-post-build
594
595
  timberPostBuild(ctx, { fonts: fonts.api, prebuilt: prebuilt.api, report: buildReport.api }),
595
596
  timberDevLogs(ctx), // Dev-only: forward server console.* to browser console
597
+ timberDevAwait(ctx), // Dev-only: `await` in app server code → timber.await spans
596
598
  timberDevServer(ctx), // Must be last — configureServer post-hook runs after all watchers
597
599
  ];
598
600
  }