@timber-js/app 0.2.0-alpha.234 → 0.2.0-alpha.235

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 (59) hide show
  1. package/dist/_chunks/{cli-check-BAKOSTkg.js → cli-check-Dl3yo3Zv.js} +3 -3
  2. package/dist/_chunks/{cli-check-BAKOSTkg.js.map → cli-check-Dl3yo3Zv.js.map} +1 -1
  3. package/dist/_chunks/{cli-context-BPdyA7Fp.js → cli-context-BbwVqarO.js} +1 -1
  4. package/dist/_chunks/{cli-context-CwTKMjVe.js → cli-context-DZh5v0yd.js} +2 -2
  5. package/dist/_chunks/{cli-context-CwTKMjVe.js.map → cli-context-DZh5v0yd.js.map} +1 -1
  6. package/dist/_chunks/{cli-schema-sync-y_8ijmzO.js → cli-schema-sync-CTWiBMZZ.js} +1 -1
  7. package/dist/_chunks/{cli-schema-sync-CAllbqRB.js → cli-schema-sync-CyrOHbAo.js} +2 -2
  8. package/dist/_chunks/{cli-schema-sync-CAllbqRB.js.map → cli-schema-sync-CyrOHbAo.js.map} +1 -1
  9. package/dist/_chunks/dev-server-DrYBIg66.js +1 -0
  10. package/dist/_chunks/{dev-server-Rq659RR1.js → dev-server-cmWVDgTf.js} +2 -2
  11. package/dist/_chunks/{dev-server-Rq659RR1.js.map → dev-server-cmWVDgTf.js.map} +1 -1
  12. package/dist/_chunks/dev-span-_NzMX-au.js.map +1 -1
  13. package/dist/_chunks/{plugin-context-FCkaNLUB.js → plugin-context-BtaQcMuh.js} +2 -2
  14. package/dist/_chunks/{plugin-context-FCkaNLUB.js.map → plugin-context-BtaQcMuh.js.map} +1 -1
  15. package/dist/_chunks/{plugin-context-BfSRKJfz.js → plugin-context-I1dvGccO.js} +1 -1
  16. package/dist/_chunks/{walkers-D_QHR_nf.js → walkers-DFC9KsBL.js} +2 -2
  17. package/dist/_chunks/{walkers-D_QHR_nf.js.map → walkers-DFC9KsBL.js.map} +1 -1
  18. package/dist/analyze/crawl-entry.js +1 -1
  19. package/dist/analyze/graph-command.js +2 -2
  20. package/dist/cli.js +6 -6
  21. package/dist/client/dev-pill/store.d.ts +0 -18
  22. package/dist/client/dev-pill/store.d.ts.map +1 -1
  23. package/dist/client/dev-pill/view.d.ts.map +1 -1
  24. package/dist/client/dev-pill/waterfall.d.ts +64 -0
  25. package/dist/client/dev-pill/waterfall.d.ts.map +1 -0
  26. package/dist/dev-tools/await-span.d.ts +5 -1
  27. package/dist/dev-tools/await-span.d.ts.map +1 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +113 -12
  30. package/dist/index.js.map +1 -1
  31. package/dist/native/rsc/dev-tools/await-span.js +6 -6
  32. package/dist/native/rsc/dev-tools/await-span.js.map +1 -1
  33. package/dist/native/rsc/manifest.json +1 -2
  34. package/dist/native/rsc/shared/dev-span.js +4 -3
  35. package/dist/native/rsc/shared/dev-span.js.map +1 -1
  36. package/dist/native/ssr/dev-tools/await-span.js +6 -6
  37. package/dist/native/ssr/dev-tools/await-span.js.map +1 -1
  38. package/dist/native/ssr/shared/dev-span.js +4 -3
  39. package/dist/native/ssr/shared/dev-span.js.map +1 -1
  40. package/dist/plugins/dev-await.d.ts +3 -0
  41. package/dist/plugins/dev-await.d.ts.map +1 -1
  42. package/dist/plugins/native-runtime.d.ts +2 -2
  43. package/dist/plugins/native-runtime.d.ts.map +1 -1
  44. package/dist/plugins/plugin-rsc-package.d.ts +35 -0
  45. package/dist/plugins/plugin-rsc-package.d.ts.map +1 -0
  46. package/dist/routing/index.js +1 -1
  47. package/dist/shared/dev-span.d.ts +9 -2
  48. package/dist/shared/dev-span.d.ts.map +1 -1
  49. package/package.json +2 -2
  50. package/src/client/dev-pill/store.ts +5 -64
  51. package/src/client/dev-pill/view.ts +165 -53
  52. package/src/client/dev-pill/waterfall.ts +194 -0
  53. package/src/dev-tools/await-span.ts +22 -13
  54. package/src/index.ts +3 -10
  55. package/src/plugins/dev-await.ts +61 -3
  56. package/src/plugins/native-runtime.ts +4 -3
  57. package/src/plugins/plugin-rsc-package.ts +81 -0
  58. package/src/shared/dev-span.ts +12 -4
  59. package/dist/_chunks/dev-server-L8biS7Az.js +0 -1
@@ -5,8 +5,14 @@
5
5
  * it and it can't reach the app. See design/50-dev-request-pill.md §"The pill".
6
6
  */
7
7
 
8
- import { devSpanLabel, ROOT_SPAN_NAME } from '../../shared/dev-span.ts';
9
- import type { DevPillStore, DevRequest, WaterfallRow, WaterfallView } from './store.ts';
8
+ import {
9
+ AWAIT_SPAN_NAME,
10
+ devSpanLabel,
11
+ ROOT_SPAN_NAME,
12
+ type DevSpanPayload,
13
+ } from '../../shared/dev-span.ts';
14
+ import type { DevPillStore, DevRequest } from './store.ts';
15
+ import { buildWaterfall, type WaterfallRow, type WaterfallView } from './waterfall.ts';
10
16
 
11
17
  /** localStorage keys for per-browser choices, per dev origin. */
12
18
  const MINIMIZED_KEY = 'timber:dev-pill:minimized';
@@ -67,16 +73,40 @@ select {
67
73
  border-radius: 6px; padding: 4px 6px; font: inherit;
68
74
  }
69
75
  .rows { overflow: auto; padding: 4px 0; }
76
+ /* One line per row; rows touch, so the nesting rails run unbroken. */
70
77
  .row {
71
- display: grid; grid-template-columns: minmax(0, 1fr) minmax(80px, 32%) 56px;
72
- align-items: center; gap: 8px; padding: 3px 10px;
78
+ display: grid; grid-template-columns: minmax(0, 1fr) minmax(80px, 30%) 48px;
79
+ align-items: center; gap: 10px; padding: 0 10px; height: 24px;
73
80
  }
74
81
  .row:hover { background: #20241e; }
75
- .label { min-width: 0; overflow-wrap: anywhere; line-height: 1.35; }
76
- /* Location and status on their own line, so a long label never hides them. */
77
- .label .sub { display: block; color: #9aa394; font-size: 11px; }
78
- .row.shared .label { color: #9aa394; }
79
- .bar.shared {
82
+ /* Indentation with one rail per ancestor, under where its label starts. */
83
+ .label {
84
+ --indent: 14px;
85
+ display: flex; align-items: center; gap: 6px; min-width: 0; height: 100%;
86
+ padding-left: calc(var(--depth, 0) * var(--indent)); white-space: nowrap;
87
+ background: repeating-linear-gradient(to right, #343b30 0 1px, transparent 1px var(--indent))
88
+ 4px 0 / calc(var(--depth, 0) * var(--indent)) 100% no-repeat;
89
+ }
90
+ .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
91
+ .row.root-row .name { font-weight: 600; }
92
+ .meta, .loc { flex: none; color: #9aa394; font-size: 11px; }
93
+ .loc { margin-left: auto; padding-left: 8px; }
94
+ .fold {
95
+ flex: none; padding: 0 5px; border: 1px solid #2f352c; border-radius: 4px;
96
+ background: transparent; color: #9aa394; font: 11px/16px ui-sans-serif, system-ui, sans-serif;
97
+ font-variant-numeric: tabular-nums; cursor: pointer;
98
+ }
99
+ .fold:hover { color: #e8ebe6; border-color: #4a5444; }
100
+ .fold:focus-visible, .foot button:focus-visible { outline: 2px solid #8fbf5a; outline-offset: 1px; }
101
+ .row.wait .name { color: #9aa394; }
102
+ .foot {
103
+ display: flex; justify-content: flex-end; padding: 6px 10px; border-top: 1px solid #2f352c;
104
+ color: #9aa394; font-size: 11px;
105
+ }
106
+ .foot button {
107
+ background: none; border: 0; padding: 0 0 0 6px; color: #8fbf5a; font: inherit; cursor: pointer;
108
+ }
109
+ .bar.wait {
80
110
  background: repeating-linear-gradient(135deg, #3f9a8f55 0 3px, transparent 3px 6px);
81
111
  outline: 1px solid #3f9a8f88; outline-offset: -1px;
82
112
  }
@@ -135,21 +165,58 @@ function requestLabel(r: DevRequest): string {
135
165
  return `${r.kind === 'action' ? 'action' : r.method} ${r.path}`;
136
166
  }
137
167
 
138
- function rowSubtitle(row: WaterfallRow): string {
139
- const a = row.span.attributes;
140
- if (row.span.name === 'timber.fetch') {
141
- const parts = [a['http.response.status_code'], a['timber.cache_status']].filter(
142
- (v) => v !== undefined
143
- );
144
- return parts.join(' · ');
145
- }
146
- if (row.span.name === 'timber.await') {
147
- return String(a['timber.await_location'] ?? '');
168
+ /** `GET /api/v4/shows`: the origin is on hover; the path is what tells fetches apart. */
169
+ function fetchLabel(span: DevSpanPayload): string {
170
+ const a = span.attributes;
171
+ const url = String(a['http.url'] ?? '');
172
+ let path = url;
173
+ try {
174
+ path = new URL(url).pathname;
175
+ } catch {
176
+ // Not absolute: show it as recorded.
148
177
  }
149
- if (row.span.name === 'http.server.request') {
150
- return String(a['http.response.status_code'] ?? '');
178
+ return `${String(a['http.request.method'] ?? 'GET')} ${path}`;
179
+ }
180
+
181
+ /** Status and cache result of a fetch; status of the request. */
182
+ function spanMeta(span: DevSpanPayload): string {
183
+ const a = span.attributes;
184
+ if (span.name === 'timber.fetch') {
185
+ return [a['http.response.status_code'], a['timber.cache_status']]
186
+ .filter((v) => v !== undefined)
187
+ .join(' · ');
151
188
  }
152
- return row.span.events.includes('timber.cache.hit') ? 'cache hit' : '';
189
+ if (span.name === ROOT_SPAN_NAME) return String(a['http.response.status_code'] ?? '');
190
+ return span.events.includes('timber.cache.hit') ? 'cache hit' : '';
191
+ }
192
+
193
+ /** In the pill an await row is its source text; the bar color says it's an await. */
194
+ function spanName(span: DevSpanPayload): string {
195
+ if (span.name === AWAIT_SPAN_NAME) return String(span.attributes['timber.await_label'] ?? '');
196
+ if (span.name === 'timber.fetch') return fetchLabel(span);
197
+ return devSpanLabel(span.name, span.attributes).label;
198
+ }
199
+
200
+ /**
201
+ * `page.tsx:11`, with the parallel slot when there is one
202
+ * (`@songs page.tsx:11`): the full path is on hover.
203
+ */
204
+ function shortLocation(location: string): string {
205
+ const parts = location.split('/');
206
+ const slot = parts.filter((p) => p.startsWith('@')).at(-1);
207
+ const file = parts.at(-1) ?? location;
208
+ return slot ? `${slot} ${file}` : file;
209
+ }
210
+
211
+ /** Hover text: every span in the row, with its full location. */
212
+ function rowTitle(row: WaterfallRow): string {
213
+ return [row.span, ...row.folded]
214
+ .map((span) => {
215
+ const where = span.attributes['timber.await_location'];
216
+ const { label: text } = devSpanLabel(span.name, span.attributes);
217
+ return where ? `${text} ${String(where)}` : text;
218
+ })
219
+ .join('\n');
153
220
  }
154
221
 
155
222
  export function mountDevPill(store: DevPillStore): void {
@@ -166,6 +233,9 @@ export function mountDevPill(store: DevPillStore): void {
166
233
  // Awaits by default: the I/O is what the pill is for; framework phases are
167
234
  // a click away.
168
235
  let view: WaterfallView = readPref(VIEW_KEY) === 'all' ? 'all' : 'awaits';
236
+ // Per page load: which folded rows are open, and whether explained waits show.
237
+ const expanded = new Set<string>();
238
+ let showWaits = false;
169
239
  let scheduled = false;
170
240
 
171
241
  const setMinimized = (value: boolean) => {
@@ -262,48 +332,90 @@ export function mountDevPill(store: DevPillStore): void {
262
332
  head.append(toggle);
263
333
 
264
334
  const rows = el('div', 'rows');
265
- const waterfall = store.waterfall(selected.traceId, view);
335
+ const spans = store.spans(selected.traceId);
336
+ const { rows: waterfall, hiddenWaits } = buildWaterfall(spans, { view, showWaits, expanded });
266
337
  if (waterfall.length === 0) {
267
338
  const nothing =
268
- view === 'awaits' && store.spans(selected.traceId).length > 0
339
+ view === 'awaits' && spans.length > 0
269
340
  ? 'No awaits or fetches over 1ms. All shows every span.'
270
341
  : 'Waiting for spans…';
271
342
  rows.append(el('div', 'empty', nothing));
272
343
  }
273
344
  const total = Math.max(1, ...waterfall.map((r) => r.offsetMs + r.durationMs));
274
- for (const row of waterfall) {
275
- const line = el('div', 'row');
276
- const { label } = devSpanLabel(row.span.name, row.span.attributes);
277
- const labelCell = el('div', 'label');
278
- labelCell.style.paddingLeft = `${row.depth * 12}px`;
279
- labelCell.append(document.createTextNode(label));
280
- // Shared: this await waited on a promise another await already took
281
- // (React.cache, an in-flight load) — no new work happened here.
282
- const shared = row.span.attributes['timber.await_shared'] === true;
283
- if (shared) line.classList.add('shared');
284
- const sub = rowSubtitle(row);
285
- if (sub) labelCell.append(el('span', 'sub', sub));
286
-
287
- const track = el('div', 'track');
288
- const bar = el('div', 'bar');
289
- if (row.span.name === 'timber.fetch') bar.classList.add('fetch');
290
- else if (row.span.name === 'timber.await') bar.classList.add(shared ? 'shared' : 'await');
291
- if (row.span.error) bar.classList.add('error');
292
- // The request's own row spans everything; judge it by name, not
293
- // depth, which the awaits view flattens (Codex review on #1274).
294
- else if (!shared && row.span.name !== ROOT_SPAN_NAME && row.durationMs > store.slowMs)
295
- bar.classList.add('slow');
296
- bar.style.left = `${(row.offsetMs / total) * 100}%`;
297
- bar.style.width = `${(row.durationMs / total) * 100}%`;
298
- track.append(bar);
299
-
300
- line.append(labelCell, track, el('div', 'dur', formatMs(row.durationMs)));
301
- rows.append(line);
302
- }
345
+ for (const row of waterfall) rows.append(renderRow(row, total));
303
346
  panel.append(head, rows);
347
+
348
+ // Hiding and folding are the awaits view's; All shows every span as is.
349
+ if (view === 'awaits' && (hiddenWaits > 0 || showWaits)) {
350
+ const foot = el('div', 'foot');
351
+ const toggleWaits = el('button', undefined, showWaits ? 'Hide waits' : 'Show');
352
+ toggleWaits.type = 'button';
353
+ toggleWaits.addEventListener('click', () => {
354
+ showWaits = !showWaits;
355
+ render();
356
+ });
357
+ if (!showWaits) {
358
+ foot.title = 'Awaits of a promise whose work is already on another row';
359
+ foot.append(`${hiddenWaits} wait${hiddenWaits === 1 ? '' : 's'} hidden ·`);
360
+ }
361
+ foot.append(toggleWaits);
362
+ panel.append(foot);
363
+ }
304
364
  return panel;
305
365
  };
306
366
 
367
+ const renderRow = (row: WaterfallRow, total: number): HTMLElement => {
368
+ const line = el('div', 'row');
369
+ line.title = rowTitle(row);
370
+ if (row.wait) line.classList.add('wait');
371
+ if (row.span.name === ROOT_SPAN_NAME) line.classList.add('root-row');
372
+
373
+ // A folded chain that ends in a fetch reads as the fetch: that's the I/O.
374
+ // Otherwise the outer call, which is the code that asked for the work.
375
+ const leaf = row.folded.at(-1);
376
+ const named = leaf?.name === 'timber.fetch' ? leaf : row.span;
377
+ const labelCell = el('div', 'label');
378
+ labelCell.style.setProperty('--depth', String(row.depth));
379
+ labelCell.append(el('span', 'name', spanName(named)));
380
+
381
+ const id = row.span.spanId;
382
+ if (row.folded.length > 0 || (view === 'awaits' && expanded.has(id))) {
383
+ const open = expanded.has(id);
384
+ const fold = el('button', 'fold', open ? '−' : `+${row.folded.length}`);
385
+ fold.type = 'button';
386
+ fold.setAttribute('aria-expanded', String(open));
387
+ fold.setAttribute('aria-label', open ? 'Fold nested awaits' : 'Show nested awaits');
388
+ fold.addEventListener('click', (event) => {
389
+ event.stopPropagation();
390
+ if (open) expanded.delete(id);
391
+ else expanded.add(id);
392
+ render();
393
+ });
394
+ labelCell.append(fold);
395
+ }
396
+ const meta = spanMeta(named);
397
+ if (meta) labelCell.append(el('span', 'meta', meta));
398
+ const location = row.span.attributes['timber.await_location'];
399
+ if (location !== undefined)
400
+ labelCell.append(el('span', 'loc', shortLocation(String(location))));
401
+
402
+ const track = el('div', 'track');
403
+ const bar = el('div', 'bar');
404
+ if (named.name === 'timber.fetch') bar.classList.add('fetch');
405
+ else if (row.span.name === AWAIT_SPAN_NAME) bar.classList.add(row.wait ? 'wait' : 'await');
406
+ if ([row.span, ...row.folded].some((s) => s.error)) bar.classList.add('error');
407
+ // The request's own row spans everything; judge it by name, not
408
+ // depth, which the awaits view flattens (Codex review on #1274).
409
+ else if (!row.wait && row.span.name !== ROOT_SPAN_NAME && row.durationMs > store.slowMs)
410
+ bar.classList.add('slow');
411
+ bar.style.left = `${(row.offsetMs / total) * 100}%`;
412
+ bar.style.width = `${(row.durationMs / total) * 100}%`;
413
+ track.append(bar);
414
+
415
+ line.append(labelCell, track, el('div', 'dur', formatMs(row.durationMs)));
416
+ return line;
417
+ };
418
+
307
419
  // Escape closes the panel.
308
420
  document.addEventListener('keydown', (event) => {
309
421
  if (event.key === 'Escape' && open) {
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Dev request pill — a trace's spans as waterfall rows.
3
+ *
4
+ * Pure: spans in, rows out. The awaits view is built to be read, not to
5
+ * mirror the span tree. Waits whose work other rows already show are
6
+ * hidden, and pass-through wrappers fold into the row they wrap.
7
+ * See design/50-dev-request-pill.md §"Reading the awaits view".
8
+ */
9
+
10
+ import {
11
+ AWAIT_SPAN_NAME,
12
+ AWAIT_WAIT_ATTRIBUTE,
13
+ type DevSpanPayload,
14
+ } from '../../shared/dev-span.ts';
15
+
16
+ /** Every span, or only the I/O: awaits and fetches. */
17
+ export type WaterfallView = 'all' | 'awaits';
18
+
19
+ const FETCH_SPAN_NAME = 'timber.fetch';
20
+ const IO_SPANS = new Set([AWAIT_SPAN_NAME, FETCH_SPAN_NAME]);
21
+
22
+ /**
23
+ * A wait is explained when spans outside its own ancestry cover this much
24
+ * of its time. It waited on the work those spans show.
25
+ */
26
+ const WAIT_COVERAGE = 0.8;
27
+
28
+ /**
29
+ * An await folds into its only child when the child takes this much of the
30
+ * await's time. A wrapper that adds no time of its own adds no information.
31
+ */
32
+ const FOLD_COVERAGE = 0.9;
33
+
34
+ export interface WaterfallOptions {
35
+ view?: WaterfallView;
36
+ /** Show explained waits too (awaits view). */
37
+ showWaits?: boolean;
38
+ /** Rows the user unfolded, by the outer span's ID. */
39
+ expanded?: ReadonlySet<string>;
40
+ }
41
+
42
+ export interface WaterfallRow {
43
+ /** The row's outermost span: its position, depth and location. */
44
+ span: DevSpanPayload;
45
+ /** Spans folded into this row, outermost first. Empty when nothing folded. */
46
+ folded: DevSpanPayload[];
47
+ /** An explained wait: shown only on request, and dimmed. */
48
+ wait: boolean;
49
+ depth: number;
50
+ /** Milliseconds from the trace's start. */
51
+ offsetMs: number;
52
+ durationMs: number;
53
+ }
54
+
55
+ export interface Waterfall {
56
+ rows: WaterfallRow[];
57
+ /** Explained waits left out of `rows`. */
58
+ hiddenWaits: number;
59
+ }
60
+
61
+ const duration = (s: DevSpanPayload) => s.endMs - s.startMs;
62
+
63
+ /** Total length of the union of [start, end) intervals. */
64
+ function unionLength(intervals: Array<[number, number]>): number {
65
+ let total = 0;
66
+ let reach = -Infinity;
67
+ for (const [start, end] of intervals.sort((a, b) => a[0] - b[0])) {
68
+ if (end <= reach) continue;
69
+ total += end - Math.max(start, reach);
70
+ reach = end;
71
+ }
72
+ return total;
73
+ }
74
+
75
+ /**
76
+ * Await spans that waited on work other spans already show, by ID.
77
+ *
78
+ * A wait (`timber.await_wait`) with no children waited on a promise made
79
+ * elsewhere. When that work is traced (an app function's awaits, a fetch),
80
+ * it runs at the same time outside the wait's own ancestry, so it covers the
81
+ * wait. When it isn't (`const p = pool.query(); … await p`, the driver
82
+ * being in node_modules), nothing covers it, and the wait is the only row
83
+ * that shows the time. Then it counts as work.
84
+ *
85
+ * A wait with children started work after all (a getter that returns a new
86
+ * promise), so it counts as work too.
87
+ */
88
+ export function explainedWaits(spans: readonly DevSpanPayload[]): Set<string> {
89
+ const byId = new Map(spans.map((s) => [s.spanId, s]));
90
+ const parents = new Set(spans.map((s) => s.parentSpanId));
91
+ const isCandidate = (s: DevSpanPayload) =>
92
+ s.attributes[AWAIT_WAIT_ATTRIBUTE] === true && !parents.has(s.spanId);
93
+ const work = spans.filter((s) => IO_SPANS.has(s.name) && !isCandidate(s));
94
+ const explained = new Set<string>();
95
+ for (const wait of spans) {
96
+ if (!isCandidate(wait) || duration(wait) <= 0) continue;
97
+ const ancestors = new Set<string>();
98
+ for (let p = wait.parentSpanId; p && !ancestors.has(p); p = byId.get(p)?.parentSpanId) {
99
+ ancestors.add(p);
100
+ }
101
+ const covering: Array<[number, number]> = [];
102
+ for (const s of work) {
103
+ if (ancestors.has(s.spanId)) continue;
104
+ const start = Math.max(s.startMs, wait.startMs);
105
+ const end = Math.min(s.endMs, wait.endMs);
106
+ if (end > start) covering.push([start, end]);
107
+ }
108
+ if (unionLength(covering) >= WAIT_COVERAGE * duration(wait)) explained.add(wait.spanId);
109
+ }
110
+ return explained;
111
+ }
112
+
113
+ /**
114
+ * Spans in tree order (parent before children, siblings by start). The time
115
+ * axis starts at the trace's first span in either view.
116
+ *
117
+ * `view: 'awaits'` keeps only awaits and fetches, each nested under its
118
+ * nearest kept ancestor, so hiding framework phases leaves no gaps in the
119
+ * indentation. On top of that:
120
+ *
121
+ * - Explained waits are hidden unless `showWaits` is set.
122
+ * - An await whose only child takes nearly all its time folds into one row
123
+ * with that child (unless the child is a wait), repeatedly, so `loadShow → def.load → fetch` is one
124
+ * row. A row in `expanded` doesn't fold.
125
+ */
126
+ export function buildWaterfall(
127
+ spans: readonly DevSpanPayload[],
128
+ { view = 'all', showWaits = false, expanded = new Set() }: WaterfallOptions = {}
129
+ ): Waterfall {
130
+ if (spans.length === 0) return { rows: [], hiddenWaits: 0 };
131
+ const ids = new Set(spans.map((s) => s.spanId));
132
+ const children = new Map<string | undefined, DevSpanPayload[]>();
133
+ for (const span of spans) {
134
+ // A span whose parent isn't here (the root still open, or a parent
135
+ // outside this trace's spans) sits at the top level.
136
+ const parent = span.parentSpanId && ids.has(span.parentSpanId) ? span.parentSpanId : undefined;
137
+ const siblings = children.get(parent) ?? [];
138
+ siblings.push(span);
139
+ children.set(parent, siblings);
140
+ }
141
+ for (const siblings of children.values()) siblings.sort((a, b) => a.startMs - b.startMs);
142
+
143
+ const waits = explainedWaits(spans);
144
+ const awaitsView = view === 'awaits';
145
+ const hideWaits = awaitsView && !showWaits;
146
+ const shown = (s: DevSpanPayload) =>
147
+ !awaitsView || (IO_SPANS.has(s.name) && !(hideWaits && waits.has(s.spanId)));
148
+
149
+ /** Shown children, with a hidden child's shown descendants in its place. */
150
+ const visibleChildren = (parent: string | undefined): DevSpanPayload[] =>
151
+ (children.get(parent) ?? []).flatMap((s) => (shown(s) ? [s] : visibleChildren(s.spanId)));
152
+
153
+ const origin = Math.min(...spans.map((s) => s.startMs));
154
+ const rows: WaterfallRow[] = [];
155
+ const emit = (span: DevSpanPayload, depth: number) => {
156
+ const folded: DevSpanPayload[] = [];
157
+ let tail = span;
158
+ let kids = visibleChildren(tail.spanId);
159
+ // A wait never folds: shown on request, it must appear as its own,
160
+ // dimmed row, not vanish into its parent. A child that outlives its
161
+ // parent (a fetch raced against a timeout) never folds either: the row
162
+ // draws the parent's interval, which would drop the rest of the child's
163
+ // time. Codex review on #1288.
164
+ const foldable = (kid: DevSpanPayload | undefined): kid is DevSpanPayload =>
165
+ kid !== undefined &&
166
+ !waits.has(kid.spanId) &&
167
+ tail.name === AWAIT_SPAN_NAME &&
168
+ kid.startMs >= tail.startMs &&
169
+ kid.endMs <= tail.endMs &&
170
+ duration(kid) >= FOLD_COVERAGE * duration(tail);
171
+ if (awaitsView && !expanded.has(span.spanId)) {
172
+ for (
173
+ let only = kids.length === 1 ? kids[0] : undefined;
174
+ foldable(only);
175
+ only = kids.length === 1 ? kids[0] : undefined
176
+ ) {
177
+ tail = only;
178
+ folded.push(tail);
179
+ kids = visibleChildren(tail.spanId);
180
+ }
181
+ }
182
+ rows.push({
183
+ span,
184
+ folded,
185
+ wait: waits.has(span.spanId),
186
+ depth,
187
+ offsetMs: span.startMs - origin,
188
+ durationMs: duration(span),
189
+ });
190
+ for (const kid of kids) emit(kid, depth + 1);
191
+ };
192
+ for (const span of visibleChildren(undefined)) emit(span, 0);
193
+ return { rows, hiddenWaits: hideWaits ? waits.size : 0 };
194
+ }
@@ -9,10 +9,19 @@
9
9
  */
10
10
 
11
11
  import { trace } from '@opentelemetry/api';
12
- import { AWAIT_SPAN_NAME, DEV_AWAIT_KEY } from '../shared/dev-span.ts';
12
+ import { AWAIT_SPAN_NAME, AWAIT_WAIT_ATTRIBUTE, DEV_AWAIT_KEY } from '../shared/dev-span.ts';
13
13
  import { traceCall } from '../server/tracing.ts';
14
14
 
15
- export type DevAwaitWrapper = (thunk: () => unknown, label: string, location: string) => unknown;
15
+ /**
16
+ * `startsNoWork`: the transform saw an operand that only reads existing
17
+ * promises (`await call`, `await Promise.all([a, b])`).
18
+ */
19
+ export type DevAwaitWrapper = (
20
+ thunk: () => unknown,
21
+ label: string,
22
+ location: string,
23
+ startsNoWork?: boolean
24
+ ) => unknown;
16
25
 
17
26
  /**
18
27
  * Promises some await has already waited on. A later await of the same
@@ -25,22 +34,22 @@ export type DevAwaitWrapper = (thunk: () => unknown, label: string, location: st
25
34
  const awaited = new WeakSet<object>();
26
35
 
27
36
  /**
28
- * Mark the active await span shared when its operand is a promise another
29
- * await already took.
37
+ * Mark the active await span a wait — no new work happened under it — when
38
+ * its operand is a native promise that either another await already took or
39
+ * that existed before this await began (`startsNoWork`).
30
40
  *
31
41
  * Plain native promises only: one of those settles once, whoever awaits it.
32
42
  * A thenable may start its work on every `then()` — Drizzle's query builders
33
- * run the query each time they are awaited — so a second await of one is new
34
- * work, not a wait (Codex review on #1274).
43
+ * run the query each time they are awaited — so awaiting one is new work,
44
+ * not a wait (Codex review on #1274).
35
45
  */
36
- function noteShared(value: unknown): void {
46
+ function noteWait(value: unknown, startsNoWork: boolean): void {
37
47
  if (typeof value !== 'object' || value === null) return;
38
48
  if (Object.getPrototypeOf(value) !== Promise.prototype) return;
39
- if (awaited.has(value)) {
40
- trace.getActiveSpan()?.setAttribute('timber.await_shared', true);
41
- } else {
42
- awaited.add(value);
49
+ if (startsNoWork || awaited.has(value)) {
50
+ trace.getActiveSpan()?.setAttribute(AWAIT_WAIT_ATTRIBUTE, true);
43
51
  }
52
+ awaited.add(value);
44
53
  }
45
54
 
46
55
  /**
@@ -49,7 +58,7 @@ function noteShared(value: unknown): void {
49
58
  * spans once it has. Idempotent: a repeat install replaces the wrapper.
50
59
  */
51
60
  export function installDevAwait(): void {
52
- const wrapper: DevAwaitWrapper = (thunk, label, location) => {
61
+ const wrapper: DevAwaitWrapper = (thunk, label, location, startsNoWork = false) => {
53
62
  // Outside a request (module init, background work) there is no trace
54
63
  // to nest under; a span would only become an orphan trace.
55
64
  if (!trace.getActiveSpan()) return thunk();
@@ -60,7 +69,7 @@ export function installDevAwait(): void {
60
69
  { 'timber.await_label': label, 'timber.await_location': location },
61
70
  () => {
62
71
  const value = thunk();
63
- noteShared(value);
72
+ noteWait(value, startsNoWork);
64
73
  return value;
65
74
  }
66
75
  );
package/src/index.ts CHANGED
@@ -14,7 +14,6 @@ import type { Plugin, PluginOption } from 'vite';
14
14
  import type { ReactCompilerOptions } from '@vitejs/plugin-react';
15
15
  import { createLogger } from 'vite';
16
16
  import { join, relative, resolve } from 'node:path';
17
- import { createRequire } from 'node:module';
18
17
  import react from '@vitejs/plugin-react';
19
18
  import { timberContent } from './plugins/content.ts';
20
19
  import { timberDevServer } from './plugins/dev-server.ts';
@@ -38,6 +37,7 @@ import { timberRequestDep } from './plugins/request-dep/index.ts';
38
37
  import { timberOptimizePackageImports } from './plugins/optimize-package-imports.ts';
39
38
  import { timberClientInServerPackageDeps } from './plugins/client-in-server-package-deps.ts';
40
39
  import { timberNodeFlightBuilds } from './plugins/node-flight-builds.ts';
40
+ import { loadPluginRsc, timberPluginRscDeps } from './plugins/plugin-rsc-package.ts';
41
41
  import { timberNativeRuntime } from './plugins/native-runtime.ts';
42
42
  import { timberPrebuilt } from './plugins/prebuilt.ts';
43
43
  import { timberPrerenderSugar } from './plugins/prerender-sugar.ts';
@@ -227,17 +227,9 @@ function patchReactCompilerForProdJsx(plugins: PluginOption[]): PluginOption[] {
227
227
  export function timber(config?: TimberUserConfig): PluginOption[] {
228
228
  const ctx = createPluginContext(config);
229
229
 
230
- // Resolve dependencies from the consumer's project (process.cwd()),
231
- // not from timber's own node_modules. This is critical for pnpm link:
232
- // when linked, timber's node_modules has a separate vite instance, and
233
- // the RSC plugin must use the same vite instance as the dev server.
234
- const consumerRequire = createRequire(join(process.cwd(), 'package.json'));
235
-
236
230
  // ── Step 1: Load @vitejs/plugin-rsc ─────────────────────────────────
237
- // Synchronous require() works for ESM modules on Node 22.12+.
238
231
  ctx.timer.start('rsc-plugin-import');
239
- const rscMod = consumerRequire('@vitejs/plugin-rsc');
240
- const vitePluginRsc = rscMod.default ?? rscMod;
232
+ const vitePluginRsc = loadPluginRsc(process.cwd());
241
233
  ctx.timer.end('rsc-plugin-import');
242
234
 
243
235
  // ── Step 2: Compute config-dependent options ────────────────────────
@@ -569,6 +561,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
569
561
  timberReactResolve(),
570
562
  timberNodeFlightBuilds(), // Dev: one (Node, pre-bundled) Flight build per server environment
571
563
  timberNativeRuntime(), // Dev, installed timber: load the runtime natively (design/51)
564
+ timberPluginRscDeps(), // Dev, installed timber: pre-bundle plugin-rsc's deps through timber
572
565
  timberReactProd(),
573
566
  // @vitejs/plugin-react provides React Fast Refresh (state-preserving HMR)
574
567
  // for client components via Babel transform. Placed before @vitejs/plugin-rsc
@@ -9,6 +9,9 @@
9
9
  * const rows = await __timber_await$(() => (db.select().from(users)),
10
10
  * "db.select().from(users)", "app/users/page.tsx:12");
11
11
  *
12
+ * An operand that starts no work (`await call`, `await Promise.all([a, b])`)
13
+ * gets a fourth argument, `true`, so the wrapper can mark the await a wait.
14
+ *
12
15
  * `__timber_await$` is declared once per module and looks the wrapper up on
13
16
  * `globalThis[DEV_AWAIT_KEY]` at call time (installed with dev tracing,
14
17
  * `dev-tools/await-span.ts`); with none installed it calls the thunk. A
@@ -89,6 +92,60 @@ function containsAwait(node: Node): boolean {
89
92
  return children(node).some(containsAwait);
90
93
  }
91
94
 
95
+ /** Wrappers that change nothing about what the operand is. */
96
+ const TRANSPARENT_TYPES = new Set([
97
+ 'ParenthesizedExpression',
98
+ 'TSAsExpression',
99
+ 'TSSatisfiesExpression',
100
+ 'TSNonNullExpression',
101
+ ]);
102
+
103
+ const PROMISE_COMBINATORS = new Set(['all', 'allSettled', 'any', 'race']);
104
+
105
+ /** `p`, `this.p`, `state.pending?.p`: a value that already exists. */
106
+ function isReference(node: Node): boolean {
107
+ if (TRANSPARENT_TYPES.has(node.type) && isNode(node.expression)) {
108
+ return isReference(node.expression);
109
+ }
110
+ if (node.type === 'ChainExpression' && isNode(node.expression)) {
111
+ return isReference(node.expression);
112
+ }
113
+ return node.type === 'Identifier' || node.type === 'MemberExpression';
114
+ }
115
+
116
+ /**
117
+ * The operand starts no work of its own: it reads a promise that already
118
+ * exists (`await call`, `await this.pending`), or combines such promises
119
+ * (`await Promise.all([a, b])`). The work began when the promise was made,
120
+ * so its spans nest wherever that happened, not under this await. The
121
+ * wrapper marks the await a wait if the value is a native promise; a getter
122
+ * that starts work shows up as a wait with children, which the pill treats
123
+ * as work.
124
+ */
125
+ function startsNoWork(node: Node): boolean {
126
+ if (TRANSPARENT_TYPES.has(node.type) && isNode(node.expression)) {
127
+ return startsNoWork(node.expression);
128
+ }
129
+ if (isReference(node)) return true;
130
+ if (node.type !== 'CallExpression') return false;
131
+ const callee = node.callee;
132
+ const args = (node.arguments as Node[] | undefined) ?? [];
133
+ const array = args[0];
134
+ return (
135
+ isNode(callee) &&
136
+ callee.type === 'MemberExpression' &&
137
+ isNode(callee.object) &&
138
+ callee.object.type === 'Identifier' &&
139
+ callee.object.name === 'Promise' &&
140
+ isNode(callee.property) &&
141
+ PROMISE_COMBINATORS.has(String(callee.property.name)) &&
142
+ args.length === 1 &&
143
+ isNode(array) &&
144
+ array.type === 'ArrayExpression' &&
145
+ ((array.elements as unknown[] | undefined) ?? []).every((e) => isNode(e) && isReference(e))
146
+ );
147
+ }
148
+
92
149
  /** Parser dialect for a module path: the transform sees original source. */
93
150
  export function langFor(file: string): 'ts' | 'tsx' | 'jsx' {
94
151
  if (/\.tsx$/.test(file)) return 'tsx';
@@ -313,7 +370,8 @@ export function instrumentAwaits(
313
370
  // (React.cache, an in-flight load) from new work.
314
371
  const thunk = containsAwait(arg) ? 'async () => (' : '() => (';
315
372
  s.prependRight(arg.start, `${HELPER}(${thunk}`);
316
- s.appendLeft(arg.end, `), ${text}, ${location})`);
373
+ const wait = startsNoWork(arg) ? ', true' : '';
374
+ s.appendLeft(arg.end, `), ${text}, ${location}${wait})`);
317
375
  count++;
318
376
  };
319
377
  visit(program, false);
@@ -322,8 +380,8 @@ export function instrumentAwaits(
322
380
  // After the directive prologue — a statement before `'use server'` would
323
381
  // demote it to a plain string.
324
382
  const helper =
325
- `\nconst ${HELPER} = (f, l, c) => ` +
326
- `(globalThis[Symbol.for("timber.dev.await")] ?? ((g) => g()))(f, l, c);\n`;
383
+ `\nconst ${HELPER} = (f, l, c, w) => ` +
384
+ `(globalThis[Symbol.for("timber.dev.await")] ?? ((g) => g()))(f, l, c, w);\n`;
327
385
  s.appendLeft(prologue.end, helper);
328
386
 
329
387
  return { code: s.toString(), map: s.generateMap({ hires: true }) };