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

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.
@@ -1 +1 @@
1
- {"version":3,"file":"dev-span-_NzMX-au.js","names":[],"sources":["../../src/server/build-manifest.ts","../../src/shared/dev-span.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","/**\n * The wire contract between the dev server's span sink and the dev request\n * pill in the browser. Dev-only; see design/50-dev-request-pill.md.\n *\n * Isomorphic: no server, client, or build-time imports.\n */\n\n/** HMR event that carries one finished span to the browser. */\nexport const DEV_SPAN_EVENT = 'timber:span';\n\n/** HMR event a tab sends to ask for a trace's spans that ended before it connected. */\nexport const DEV_SPAN_REPLAY_EVENT = 'timber:span-replay';\n\n/**\n * `globalThis` key holding the span sink. The dev server plugin installs it\n * and `DevSpanProcessor` (RSC module graph, same process, separate module\n * instances) reads it, so the hand-off is a `Symbol.for` global.\n */\nexport const DEV_SPAN_SINK_KEY = Symbol.for('timber.dev.span-sink');\n\n/** The `Server-Timing` metric whose `desc` is the response's trace ID. */\nexport const TRACE_TIMING_NAME = 'timber-trace';\n\n/**\n * `globalThis` key holding the dev await wrapper. The dev await transform\n * (`plugins/dev-await.ts`) rewrites `await x` in app server code to call\n * it, looked up at call time; dev tracing installs it. With nothing\n * installed the call is a plain await. See design/50-dev-request-pill.md\n * §\"Phase 2\".\n */\nexport const DEV_AWAIT_KEY = Symbol.for('timber.dev.await');\n\n/** Span name for one awaited call in app server code. */\nexport const AWAIT_SPAN_NAME = 'timber.await';\n\n/**\n * Await spans shorter than this are dropped before they reach the terminal\n * tree or the pill: `await params` and other awaits of settled values would\n * otherwise drown the I/O the spans exist to show.\n */\nexport const AWAIT_SPAN_MIN_MS = 1;\n\n/** Root span of every pipeline request. */\nexport const ROOT_SPAN_NAME = 'http.server.request';\n\n/**\n * The span attributes that may reach the browser — the ones the pill reads,\n * and nothing else. An allowlist of keys, not of prefixes: a prefix let\n * through `timber.fetch_error` (an error message that can quote a full URL)\n * and user attributes such as `url.full` or\n * `http.request.header.authorization`. Typing the payload with this list\n * means the pill cannot read an attribute that isn't on it.\n */\nexport const DEV_SPAN_ATTRIBUTES = [\n 'http.request.method',\n 'http.response.status_code',\n /** Query and fragment stripped. */\n 'http.url',\n /** Query and fragment stripped. */\n 'url.path',\n 'timber.route',\n 'timber.segment',\n 'timber.slot',\n 'timber.action_name',\n 'timber.cache_status',\n /** The awaited expression's source text, whitespace collapsed, truncated. */\n 'timber.await_label',\n /** `path/relative/to/root.ts:line` of the await. */\n 'timber.await_location',\n] as const;\n\nexport type DevSpanAttribute = (typeof DEV_SPAN_ATTRIBUTES)[number];\n\n/** Attributes that hold a URL; sent without query or fragment. */\nexport const DEV_SPAN_URL_ATTRIBUTES: ReadonlySet<DevSpanAttribute> = new Set([\n 'http.url',\n 'url.path',\n]);\n\nexport type DevSpanSink = (span: DevSpanPayload) => void;\n\n/** One finished span, projected for the browser. */\nexport interface DevSpanPayload {\n traceId: string;\n spanId: string;\n /** Absent for the root span. */\n parentSpanId?: string;\n name: string;\n /** Epoch milliseconds. */\n startMs: number;\n /** Epoch milliseconds. */\n endMs: number;\n error: boolean;\n /** Only `DEV_SPAN_ATTRIBUTES`; URLs without query or fragment. */\n attributes: Partial<Record<DevSpanAttribute, string | number | boolean>>;\n /** Names of `timber.*` span events, e.g. `timber.cache.hit`. */\n events: string[];\n}\n\n/**\n * Read the trace ID from `Server-Timing` metrics, either a raw header value\n * or the `serverTiming` entries of a `PerformanceResourceTiming`.\n */\nexport function traceIdFromServerTiming(\n timing: string | null | readonly { name: string; description: string }[]\n): string | null {\n if (timing == null) return null;\n if (typeof timing !== 'string') {\n return timing.find((t) => t.name === TRACE_TIMING_NAME)?.description || null;\n }\n // `timber-trace;desc=\"<32 hex>\"` — the ID is hex, so no escaping to undo.\n const match = new RegExp(`(?:^|,)\\\\s*${TRACE_TIMING_NAME}\\\\s*;\\\\s*desc=\"?([0-9a-f]+)\"?`).exec(\n timing\n );\n return match?.[1] ?? null;\n}\n\n/** The `Server-Timing` entry that carries a trace ID. */\nexport function traceTimingEntry(traceId: string): string {\n return `${TRACE_TIMING_NAME};desc=\"${traceId}\"`;\n}\n\n// ─── Labels ─────────────────────────────────────────────────────────────────\n\n/** Span attributes as either side holds them (OTEL also allows arrays). */\ntype SpanAttributes = Readonly<Record<string, unknown>>;\n\n/** `@slot ` for a span from a parallel slot, so it reads apart from the main route. */\nfunction slotPrefix(attrs: SpanAttributes): string {\n const slot = attrs['timber.slot'];\n return slot ? `${String(slot)} ` : '';\n}\n\n/**\n * Map a span to its display label and environment tag. One mapping for the\n * terminal tree and the dev request pill, so the two never name a span\n * differently.\n */\nexport function devSpanLabel(name: string, attrs: SpanAttributes): { label: string; env: string } {\n switch (name) {\n case ROOT_SPAN_NAME: {\n const method = attrs['http.request.method'] ?? 'GET';\n const path = attrs['url.path'] ?? '/';\n return { label: `${String(method)} ${String(path)}`, env: 'rsc' };\n }\n case 'timber.proxy':\n return { label: 'proxy.ts', env: 'proxy' };\n case 'timber.middleware':\n return { label: 'middleware.ts', env: 'rsc' };\n case 'timber.render':\n return { label: 'render', env: 'rsc' };\n case 'timber.access': {\n const seg = attrs['timber.segment'] ?? 'segment';\n return { label: `AccessGate (${String(seg)})`, env: 'rsc' };\n }\n case 'timber.ssr':\n return { label: 'hydration render', env: 'ssr' };\n case 'timber.action': {\n const actionName = attrs['timber.action_name'] ?? 'action';\n return { label: String(actionName), env: 'rsc' };\n }\n case 'timber.metadata':\n return { label: 'metadata()', env: 'rsc' };\n case 'timber.layout': {\n const seg = attrs['timber.segment'] ?? '/';\n return { label: `layout ${slotPrefix(attrs)}${String(seg)}`, env: 'rsc' };\n }\n case 'timber.page': {\n const route = attrs['timber.route'] ?? '/';\n return { label: `page ${slotPrefix(attrs)}${String(route)}`, env: 'rsc' };\n }\n case AWAIT_SPAN_NAME:\n return { label: `await ${String(attrs['timber.await_label'] ?? '')}`, env: 'await' };\n case 'timber.fetch': {\n const fetchMethod = attrs['http.request.method'] ?? 'GET';\n const fetchUrl = attrs['http.url'] ?? '';\n return { label: `fetch ${String(fetchMethod)} ${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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;;;;;;;;;AC/LA,IAAa,iBAAiB;;AAG9B,IAAa,wBAAwB;;;;;;AAOrC,IAAa,oBAAoB,OAAO,IAAI,sBAAsB;;AAGlE,IAAa,oBAAoB;;AAiGjC,SAAgB,iBAAiB,SAAyB;CACxD,OAAO,GAAG,kBAAkB,SAAS,QAAQ;AAC/C"}
1
+ {"version":3,"file":"dev-span-_NzMX-au.js","names":[],"sources":["../../src/server/build-manifest.ts","../../src/shared/dev-span.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","/**\n * The wire contract between the dev server's span sink and the dev request\n * pill in the browser. Dev-only; see design/50-dev-request-pill.md.\n *\n * Isomorphic: no server, client, or build-time imports.\n */\n\n/** HMR event that carries one finished span to the browser. */\nexport const DEV_SPAN_EVENT = 'timber:span';\n\n/** HMR event a tab sends to ask for a trace's spans that ended before it connected. */\nexport const DEV_SPAN_REPLAY_EVENT = 'timber:span-replay';\n\n/**\n * `globalThis` key holding the span sink. The dev server plugin installs it\n * and `DevSpanProcessor` (RSC module graph, same process, separate module\n * instances) reads it, so the hand-off is a `Symbol.for` global.\n */\nexport const DEV_SPAN_SINK_KEY = Symbol.for('timber.dev.span-sink');\n\n/** The `Server-Timing` metric whose `desc` is the response's trace ID. */\nexport const TRACE_TIMING_NAME = 'timber-trace';\n\n/**\n * `globalThis` key holding the dev await wrapper. The dev await transform\n * (`plugins/dev-await.ts`) rewrites `await x` in app server code to call\n * it, looked up at call time; dev tracing installs it. With nothing\n * installed the call is a plain await. See design/50-dev-request-pill.md\n * §\"Phase 2\".\n */\nexport const DEV_AWAIT_KEY = Symbol.for('timber.dev.await');\n\n/** Span name for one awaited call in app server code. */\nexport const AWAIT_SPAN_NAME = 'timber.await';\n\n/**\n * Await spans shorter than this are dropped before they reach the terminal\n * tree or the pill: `await params` and other awaits of settled values would\n * otherwise drown the I/O the spans exist to show.\n */\nexport const AWAIT_SPAN_MIN_MS = 1;\n\n/** Root span of every pipeline request. */\nexport const ROOT_SPAN_NAME = 'http.server.request';\n\n/**\n * The span attributes that may reach the browser — the ones the pill reads,\n * and nothing else. An allowlist of keys, not of prefixes: a prefix let\n * through `timber.fetch_error` (an error message that can quote a full URL)\n * and user attributes such as `url.full` or\n * `http.request.header.authorization`. Typing the payload with this list\n * means the pill cannot read an attribute that isn't on it.\n */\nexport const DEV_SPAN_ATTRIBUTES = [\n 'http.request.method',\n 'http.response.status_code',\n /** Query and fragment stripped. */\n 'http.url',\n /** Query and fragment stripped. */\n 'url.path',\n 'timber.route',\n 'timber.segment',\n 'timber.slot',\n 'timber.action_name',\n 'timber.cache_status',\n /** The awaited expression's source text, whitespace collapsed, truncated. */\n 'timber.await_label',\n /** `path/relative/to/root.ts:line` of the await. */\n 'timber.await_location',\n /** The awaited promise was already awaited elsewhere: a wait on shared work, not new work. */\n 'timber.await_shared',\n] as const;\n\nexport type DevSpanAttribute = (typeof DEV_SPAN_ATTRIBUTES)[number];\n\n/** Attributes that hold a URL; sent without query or fragment. */\nexport const DEV_SPAN_URL_ATTRIBUTES: ReadonlySet<DevSpanAttribute> = new Set([\n 'http.url',\n 'url.path',\n]);\n\nexport type DevSpanSink = (span: DevSpanPayload) => void;\n\n/** One finished span, projected for the browser. */\nexport interface DevSpanPayload {\n traceId: string;\n spanId: string;\n /** Absent for the root span. */\n parentSpanId?: string;\n name: string;\n /** Epoch milliseconds. */\n startMs: number;\n /** Epoch milliseconds. */\n endMs: number;\n error: boolean;\n /** Only `DEV_SPAN_ATTRIBUTES`; URLs without query or fragment. */\n attributes: Partial<Record<DevSpanAttribute, string | number | boolean>>;\n /** Names of `timber.*` span events, e.g. `timber.cache.hit`. */\n events: string[];\n}\n\n/**\n * Read the trace ID from `Server-Timing` metrics, either a raw header value\n * or the `serverTiming` entries of a `PerformanceResourceTiming`.\n */\nexport function traceIdFromServerTiming(\n timing: string | null | readonly { name: string; description: string }[]\n): string | null {\n if (timing == null) return null;\n if (typeof timing !== 'string') {\n return timing.find((t) => t.name === TRACE_TIMING_NAME)?.description || null;\n }\n // `timber-trace;desc=\"<32 hex>\"` — the ID is hex, so no escaping to undo.\n const match = new RegExp(`(?:^|,)\\\\s*${TRACE_TIMING_NAME}\\\\s*;\\\\s*desc=\"?([0-9a-f]+)\"?`).exec(\n timing\n );\n return match?.[1] ?? null;\n}\n\n/** The `Server-Timing` entry that carries a trace ID. */\nexport function traceTimingEntry(traceId: string): string {\n return `${TRACE_TIMING_NAME};desc=\"${traceId}\"`;\n}\n\n// ─── Labels ─────────────────────────────────────────────────────────────────\n\n/** Span attributes as either side holds them (OTEL also allows arrays). */\ntype SpanAttributes = Readonly<Record<string, unknown>>;\n\n/** `@slot ` for a span from a parallel slot, so it reads apart from the main route. */\nfunction slotPrefix(attrs: SpanAttributes): string {\n const slot = attrs['timber.slot'];\n return slot ? `${String(slot)} ` : '';\n}\n\n/**\n * Map a span to its display label and environment tag. One mapping for the\n * terminal tree and the dev request pill, so the two never name a span\n * differently.\n */\nexport function devSpanLabel(name: string, attrs: SpanAttributes): { label: string; env: string } {\n switch (name) {\n case ROOT_SPAN_NAME: {\n const method = attrs['http.request.method'] ?? 'GET';\n const path = attrs['url.path'] ?? '/';\n return { label: `${String(method)} ${String(path)}`, env: 'rsc' };\n }\n case 'timber.proxy':\n return { label: 'proxy.ts', env: 'proxy' };\n case 'timber.middleware':\n return { label: 'middleware.ts', env: 'rsc' };\n case 'timber.render':\n return { label: 'render', env: 'rsc' };\n case 'timber.access': {\n const seg = attrs['timber.segment'] ?? 'segment';\n return { label: `AccessGate (${String(seg)})`, env: 'rsc' };\n }\n case 'timber.ssr':\n return { label: 'hydration render', env: 'ssr' };\n case 'timber.action': {\n const actionName = attrs['timber.action_name'] ?? 'action';\n return { label: String(actionName), env: 'rsc' };\n }\n case 'timber.metadata':\n return { label: 'metadata()', env: 'rsc' };\n case 'timber.layout': {\n const seg = attrs['timber.segment'] ?? '/';\n return { label: `layout ${slotPrefix(attrs)}${String(seg)}`, env: 'rsc' };\n }\n case 'timber.page': {\n const route = attrs['timber.route'] ?? '/';\n return { label: `page ${slotPrefix(attrs)}${String(route)}`, env: 'rsc' };\n }\n case AWAIT_SPAN_NAME:\n // Shared: waited on a promise another await already took — no new work.\n return {\n label: `await ${String(attrs['timber.await_label'] ?? '')}${attrs['timber.await_shared'] === true ? ' (shared)' : ''}`,\n env: 'await',\n };\n case 'timber.fetch': {\n const fetchMethod = attrs['http.request.method'] ?? 'GET';\n const fetchUrl = attrs['http.url'] ?? '';\n return { label: `fetch ${String(fetchMethod)} ${String(fetchUrl)}`, env: 'fetch' };\n }\n default:\n return { label: name, env: 'rsc' };\n }\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;;;;;;;;;AC/LA,IAAa,iBAAiB;;AAG9B,IAAa,wBAAwB;;;;;;AAOrC,IAAa,oBAAoB,OAAO,IAAI,sBAAsB;;AAGlE,IAAa,oBAAoB;;AAmGjC,SAAgB,iBAAiB,SAAyB;CACxD,OAAO,GAAG,kBAAkB,SAAS,QAAQ;AAC/C"}
@@ -35,6 +35,8 @@ export interface TraceSummary {
35
35
  slow: boolean;
36
36
  error: boolean;
37
37
  }
38
+ /** Every span, or only the I/O: awaits and fetches. */
39
+ export type WaterfallView = 'all' | 'awaits';
38
40
  export interface WaterfallRow {
39
41
  span: DevSpanPayload;
40
42
  depth: number;
@@ -82,8 +84,15 @@ export declare class DevPillStore {
82
84
  select(traceId: string): void;
83
85
  spans(traceId: string): readonly DevSpanPayload[];
84
86
  summary(traceId: string): TraceSummary;
85
- /** Spans in tree order (parent before children, siblings by start). */
86
- waterfall(traceId: string): WaterfallRow[];
87
+ /**
88
+ * Spans in tree order (parent before children, siblings by start).
89
+ *
90
+ * `view: 'awaits'` keeps only awaits and fetches — the I/O — each nested
91
+ * under its nearest kept ancestor, so hiding framework phases leaves no
92
+ * gaps in the indentation. The time axis still starts at the request's
93
+ * first span.
94
+ */
95
+ waterfall(traceId: string, view?: WaterfallView): WaterfallRow[];
87
96
  /**
88
97
  * Keep the newest requests, and always the selected one: a page that polls
89
98
  * a route handler would otherwise push its own trace out, leaving the pill
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/client/dev-pill/store.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAkB,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG/E,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG,YAAY,GAAG,QAAQ,GAAG,OAAO,CAAC;AAE5E,8DAA8D;AAC9D,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,cAAc,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb;;;;;OAKG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,EAAE,OAAO,CAAC;IACd,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,cAAc,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,C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IG;IACH,OAAO,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAWlC;IAED;;;;;OAKG;IACH,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,CASpC;IAED,+EAA+E;IAC/E,mBAAmB,IAAI,IAAI,CAS1B;IAED,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAG5B;IAED,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,cAAc,EAAE,CAEhD;IAED,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,YAAY,CAqBrC;IAED;;;;;;;OAOG;IACH,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,aAAqB,GAAG,YAAY,EAAE,CAiCtE;IAED;;;;OAIG;IACH,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,IAAI;CAGb"}
@@ -1 +1 @@
1
- {"version":3,"file":"view.d.ts","sourceRoot":"","sources":["../../../src/client/dev-pill/view.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,YAAY,EAA4B,MAAM,YAAY,CAAC;AAkIzE,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CA2ItD"}
1
+ {"version":3,"file":"view.d.ts","sourceRoot":"","sources":["../../../src/client/dev-pill/view.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,YAAY,EAA2C,MAAM,YAAY,CAAC;AAkJxF,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CA2KtD"}
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * See design/50-dev-request-pill.md §"Phase 2".
9
9
  */
10
- export type DevAwaitWrapper = (thunk: () => Promise<unknown>, label: string, location: string) => Promise<unknown>;
10
+ export type DevAwaitWrapper = (thunk: () => unknown, label: string, location: string) => unknown;
11
11
  /**
12
12
  * Install the wrapper on `globalThis[DEV_AWAIT_KEY]`. Transformed modules
13
13
  * look it up per call, so a module evaluated before this ran still gets
@@ -1 +1 @@
1
- {"version":3,"file":"await-span.d.ts","sourceRoot":"","sources":["../../src/dev-tools/await-span.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,MAAM,MAAM,eAAe,GAAG,CAC5B,KAAK,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,EAC7B,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,KACb,OAAO,CAAC,OAAO,CAAC,CAAC;AAEtB;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,IAAI,CActC"}
1
+ {"version":3,"file":"await-span.d.ts","sourceRoot":"","sources":["../../src/dev-tools/await-span.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAMH,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,MAAM,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC;AA+BjG;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,IAAI,CAkBtC"}
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ import { i as detectDirective } from "./_chunks/classify-_W0RWa5w.js";
16
16
  import { t as formatSize } from "./_chunks/format-DuPOoXUP.js";
17
17
  import { createLogger, esmExternalRequirePlugin, isRunnableDevEnvironment, parseAst } from "vite";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, win32 } from "node:path";
19
- import { builtinModules, createRequire } from "node:module";
19
+ import { SourceMap, builtinModules, createRequire } from "node:module";
20
20
  import react from "@vitejs/plugin-react";
21
21
  import { existsSync, readFileSync } from "node:fs";
22
22
  import nodeHTTP from "node:http";
@@ -3046,7 +3046,7 @@ function getBtoa() {
3046
3046
  /* v8 ignore stop */
3047
3047
  }
3048
3048
  var btoa = /* #__PURE__ */ getBtoa();
3049
- var SourceMap = class {
3049
+ var SourceMap$1 = class {
3050
3050
  constructor(properties) {
3051
3051
  this.version = 3;
3052
3052
  this.file = properties.file;
@@ -3647,7 +3647,7 @@ var MagicString = class MagicString {
3647
3647
  const encoder = new MappingsEncoder();
3648
3648
  const mappings = new Mappings(options.hires, encoder);
3649
3649
  const names = this._generateMappings(mappings);
3650
- return new SourceMap({
3650
+ return new SourceMap$1({
3651
3651
  ...this._mapProperties(options, names),
3652
3652
  mappings: encoder.finish(mappings.rawSegments),
3653
3653
  rangeMappings: mappings.rawRangeMappings
@@ -9159,7 +9159,7 @@ function timberPrerenderSugar(ctx) {
9159
9159
  *
9160
9160
  * const rows = await db.select().from(users);
9161
9161
  * // becomes
9162
- * const rows = await __timber_await$(async () => (db.select().from(users)),
9162
+ * const rows = await __timber_await$(() => (db.select().from(users)),
9163
9163
  * "db.select().from(users)", "app/users/page.tsx:12");
9164
9164
  *
9165
9165
  * `__timber_await$` is declared once per module and looks the wrapper up on
@@ -9168,6 +9168,11 @@ function timberPrerenderSugar(ctx) {
9168
9168
  * global rather than an injected import, so the rewrite needs no resolvable
9169
9169
  * specifier from a workspace package outside the app.
9170
9170
  *
9171
+ * Vite 8 compiles TS/JSX before any plugin transform runs (`enforce: 'pre'`
9172
+ * included), so the module this sees has moved lines and reprinted text.
9173
+ * Labels and locations are mapped back through the module's combined source
9174
+ * map (`originalFromMap`), so they are the code and lines as written.
9175
+ *
9171
9176
  * Scope: the RSC environment, `vite dev` only; every module outside
9172
9177
  * node_modules and outside timber itself, so a monorepo's `packages/db`
9173
9178
  * (where the query actually is) is covered. Skipped: `'use client'`
@@ -9181,7 +9186,7 @@ function timberPrerenderSugar(ctx) {
9181
9186
  /** The per-module helper's name; `$` keeps it out of the way of app identifiers. */
9182
9187
  var HELPER = "__timber_await$";
9183
9188
  /** Longest label kept, in characters. */
9184
- var LABEL_MAX = 80;
9189
+ var LABEL_MAX = 140;
9185
9190
  var SCRIPT_RE = /\.[cm]?[jt]sx?$/;
9186
9191
  function isNode(value) {
9187
9192
  return typeof value === "object" && value !== null && typeof value.type === "string" && typeof value.start === "number";
@@ -9201,6 +9206,18 @@ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
9201
9206
  "FunctionExpression",
9202
9207
  "ArrowFunctionExpression"
9203
9208
  ]);
9209
+ /** An await in the operand itself (not in a nested function) needs an async thunk. */
9210
+ function containsAwait(node) {
9211
+ if (node.type === "AwaitExpression") return true;
9212
+ if (FUNCTION_TYPES.has(node.type)) return false;
9213
+ return children(node).some(containsAwait);
9214
+ }
9215
+ /** Parser dialect for a module path: the transform sees original source. */
9216
+ function langFor(file) {
9217
+ if (/\.tsx$/.test(file)) return "tsx";
9218
+ if (/\.[cm]?ts$/.test(file)) return "ts";
9219
+ return "jsx";
9220
+ }
9204
9221
  function containsYield(node) {
9205
9222
  if (node.type === "YieldExpression") return true;
9206
9223
  if (FUNCTION_TYPES.has(node.type)) return false;
@@ -9291,35 +9308,76 @@ function redactedSource(code, arg) {
9291
9308
  }
9292
9309
  function label(source) {
9293
9310
  const collapsed = source.replace(/\s+/g, " ").trim();
9294
- return collapsed.length > LABEL_MAX ? `${collapsed.slice(0, 79)}…` : collapsed;
9311
+ return collapsed.length > LABEL_MAX ? `${collapsed.slice(0, 139)}…` : collapsed;
9312
+ }
9313
+ function lineStartsOf(text) {
9314
+ const starts = [0];
9315
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
9316
+ return starts;
9317
+ }
9318
+ /** 1-based line of an offset. */
9319
+ function lineAt(starts, offset) {
9320
+ let lo = 0;
9321
+ let hi = starts.length - 1;
9322
+ while (lo < hi) {
9323
+ const mid = lo + hi + 1 >> 1;
9324
+ if (starts[mid] <= offset) lo = mid;
9325
+ else hi = mid - 1;
9326
+ }
9327
+ return lo + 1;
9328
+ }
9329
+ /**
9330
+ * The operand's label from the original source, redacted. Null when the
9331
+ * mapping doesn't give a sane slice; the caller falls back to the
9332
+ * transformed text.
9333
+ */
9334
+ function originalLabel(original, arg) {
9335
+ const start = original.offsetOf(arg.start);
9336
+ const last = original.offsetOf(arg.end - 1);
9337
+ if (start === null || last === null || last < start) return null;
9338
+ const slice = original.code.slice(start, last + 1);
9339
+ if (slice.length > (arg.end - arg.start) * 4 + 40) return null;
9340
+ try {
9341
+ const parsed = parseAst(`(${slice});`, { lang: original.lang });
9342
+ if (!isNode(parsed)) return null;
9343
+ let expr = (parsed.body?.[0])?.expression;
9344
+ if (isNode(expr) && expr.type === "ParenthesizedExpression") expr = expr.expression;
9345
+ if (!isNode(expr)) return null;
9346
+ return label(redactedSource(`(${slice});`, expr));
9347
+ } catch {
9348
+ return null;
9349
+ }
9295
9350
  }
9296
9351
  /**
9297
9352
  * Rewrite the awaits in one module. Returns null when nothing changed.
9298
9353
  * Exported for tests; `relPath` is the location prefix shown in the pill.
9354
+ * With `original`, labels and lines come from the source as written.
9299
9355
  */
9300
- function instrumentAwaits(code, relPath) {
9356
+ function instrumentAwaits(code, relPath, options = {}) {
9301
9357
  if (!code.includes("await")) return null;
9302
9358
  let parsed;
9303
9359
  try {
9304
- parsed = parseAst(code, { lang: "jsx" });
9360
+ parsed = parseAst(code, { lang: options.lang ?? langFor(relPath) });
9305
9361
  } catch {
9306
9362
  return null;
9307
9363
  }
9308
9364
  if (!isNode(parsed)) return null;
9309
9365
  const program = parsed;
9366
+ let original;
9367
+ let originalStarts = [];
9368
+ const getOriginal = () => {
9369
+ if (original === void 0) {
9370
+ original = options.original?.() ?? null;
9371
+ if (original) originalStarts = lineStartsOf(original.code);
9372
+ }
9373
+ return original;
9374
+ };
9310
9375
  const prologue = directives(program);
9311
9376
  if (prologue.names.includes("use client")) return null;
9312
- const lineStarts = [0];
9313
- for (let i = 0; i < code.length; i++) if (code[i] === "\n") lineStarts.push(i + 1);
9377
+ const lineStarts = lineStartsOf(code);
9314
9378
  const lineOf = (offset) => {
9315
- let lo = 0;
9316
- let hi = lineStarts.length - 1;
9317
- while (lo < hi) {
9318
- const mid = lo + hi + 1 >> 1;
9319
- if (lineStarts[mid] <= offset) lo = mid;
9320
- else hi = mid - 1;
9321
- }
9322
- return lo + 1;
9379
+ const mapped = getOriginal()?.offsetOf(offset) ?? null;
9380
+ return mapped === null ? lineAt(lineStarts, offset) : lineAt(originalStarts, mapped);
9323
9381
  };
9324
9382
  const s = new MagicString(code);
9325
9383
  let count = 0;
@@ -9330,9 +9388,11 @@ function instrumentAwaits(code, relPath) {
9330
9388
  const arg = node.argument;
9331
9389
  if (!isNode(arg) || arg.type === "Literal" || containsYield(arg)) return;
9332
9390
  if (arg.type === "ImportExpression") return;
9333
- const text = JSON.stringify(label(redactedSource(code, arg)));
9391
+ const source = getOriginal();
9392
+ const text = JSON.stringify((source && originalLabel(source, arg)) ?? label(redactedSource(code, arg)));
9334
9393
  const location = JSON.stringify(`${relPath}:${lineOf(node.start)}`);
9335
- s.prependRight(arg.start, `${HELPER}(async () => (`);
9394
+ const thunk = containsAwait(arg) ? "async () => (" : "() => (";
9395
+ s.prependRight(arg.start, `${HELPER}(${thunk}`);
9336
9396
  s.appendLeft(arg.end, `), ${text}, ${location})`);
9337
9397
  count++;
9338
9398
  };
@@ -9345,6 +9405,43 @@ function instrumentAwaits(code, relPath) {
9345
9405
  map: s.generateMap({ hires: true })
9346
9406
  };
9347
9407
  }
9408
+ /**
9409
+ * Map the transformed module back to its original text through its combined
9410
+ * source map, using Node's built-in `module.SourceMap`.
9411
+ */
9412
+ function originalFromMap(map, file, generated) {
9413
+ const text = map.sourcesContent?.[0] ?? (existsSync(file) ? readFileSync(file, "utf8") : null);
9414
+ if (!text || !map.mappings) return null;
9415
+ let consumer;
9416
+ try {
9417
+ consumer = new SourceMap({
9418
+ version: map.version,
9419
+ file: map.file ?? file,
9420
+ sources: map.sources.map((source) => source ?? ""),
9421
+ sourcesContent: (map.sourcesContent ?? []).map((content) => content ?? ""),
9422
+ names: map.names,
9423
+ mappings: map.mappings,
9424
+ sourceRoot: ""
9425
+ });
9426
+ } catch {
9427
+ return null;
9428
+ }
9429
+ const originalStarts = lineStartsOf(text);
9430
+ const generatedStarts = lineStartsOf(generated);
9431
+ return {
9432
+ code: text,
9433
+ lang: langFor(file),
9434
+ offsetOf(offset) {
9435
+ const line = lineAt(generatedStarts, offset) - 1;
9436
+ const column = offset - generatedStarts[line];
9437
+ const entry = consumer.findEntry(line, column);
9438
+ if (!("originalLine" in entry)) return null;
9439
+ const delta = entry.generatedLine === line ? column - entry.generatedColumn : 0;
9440
+ const lineStart = originalStarts[entry.originalLine];
9441
+ return lineStart === void 0 ? null : lineStart + entry.originalColumn + delta;
9442
+ }
9443
+ };
9444
+ }
9348
9445
  /** Directory of the nearest package.json above this file: timber itself. */
9349
9446
  function findTimberRoot() {
9350
9447
  let dir = dirname(fileURLToPath(import.meta.url));
@@ -9366,7 +9463,11 @@ function timberDevAwait(ctx) {
9366
9463
  const file = id.split("?")[0];
9367
9464
  if (!SCRIPT_RE.test(file) || file.includes("/node_modules/")) return;
9368
9465
  if (file.startsWith(`${timberRoot}/`)) return;
9369
- return instrumentAwaits(code, relative(ctx.root, file)) ?? void 0;
9466
+ const original = () => originalFromMap(this.getCombinedSourcemap(), file, code);
9467
+ return instrumentAwaits(code, relative(ctx.root, file), {
9468
+ lang: "jsx",
9469
+ original
9470
+ }) ?? void 0;
9370
9471
  }
9371
9472
  };
9372
9473
  }