@treelocator/runtime 0.2.0 → 0.3.1

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 (30) hide show
  1. package/.turbo/turbo-build.log +14 -14
  2. package/.turbo/turbo-test.log +6 -55
  3. package/dist/adapters/createTreeNode.js +10 -1
  4. package/dist/adapters/react/findDebugSource.d.ts +13 -0
  5. package/dist/adapters/react/findDebugSource.js +37 -0
  6. package/dist/adapters/react/findFiberByHtmlElement.js +23 -1
  7. package/dist/adapters/react/getAllParentsElementsAndRootComponent.d.ts +1 -1
  8. package/dist/adapters/react/getAllParentsElementsAndRootComponent.js +6 -4
  9. package/dist/adapters/react/getAllWrappingParents.js +1 -1
  10. package/dist/adapters/react/reactAdapter.js +5 -1
  11. package/dist/adapters/react/resolveSourceMap.d.ts +29 -0
  12. package/dist/adapters/react/resolveSourceMap.js +236 -0
  13. package/dist/browserApi.d.ts +4 -4
  14. package/dist/browserApi.js +13 -15
  15. package/dist/components/MaybeOutline.js +2 -2
  16. package/dist/components/Runtime.js +13 -0
  17. package/dist/functions/enrichAncestrySourceMaps.d.ts +7 -0
  18. package/dist/functions/enrichAncestrySourceMaps.js +80 -0
  19. package/package.json +3 -3
  20. package/src/adapters/createTreeNode.ts +10 -1
  21. package/src/adapters/react/findDebugSource.ts +40 -0
  22. package/src/adapters/react/findFiberByHtmlElement.ts +26 -1
  23. package/src/adapters/react/getAllParentsElementsAndRootComponent.ts +7 -7
  24. package/src/adapters/react/getAllWrappingParents.ts +1 -1
  25. package/src/adapters/react/reactAdapter.ts +7 -3
  26. package/src/adapters/react/resolveSourceMap.ts +316 -0
  27. package/src/browserApi.ts +27 -25
  28. package/src/components/MaybeOutline.tsx +1 -1
  29. package/src/components/Runtime.tsx +15 -0
  30. package/src/functions/enrichAncestrySourceMaps.ts +103 -0
@@ -84,8 +84,8 @@ export function MaybeOutline(props) {
84
84
  return () => _c$() ? `#${props.currentElement.id}` : "";
85
85
  })(), null);
86
86
  _$insert(_el$6, (() => {
87
- var _c$2 = _$memo(() => !!props.currentElement.className);
88
- return () => _c$2() ? `.${props.currentElement.className.split(" ")[0]}` : "";
87
+ var _c$2 = _$memo(() => !!props.currentElement.getAttribute('class'));
88
+ return () => _c$2() ? `.${props.currentElement.getAttribute('class').split(" ")[0]}` : "";
89
89
  })(), null);
90
90
  _$effect(_p$ => {
91
91
  var _v$7 = box().x + "px",
@@ -13,6 +13,7 @@ import { MaybeOutline } from "./MaybeOutline";
13
13
  import { isLocatorsOwnElement } from "../functions/isLocatorsOwnElement";
14
14
  import { Toast } from "./Toast";
15
15
  import { collectAncestry, formatAncestryChain } from "../functions/formatAncestryChain";
16
+ import { enrichAncestryWithSourceMaps } from "../functions/enrichAncestrySourceMaps";
16
17
  import { createTreeNode } from "../adapters/createTreeNode";
17
18
  import treeIconUrl from "../_generated_tree_icon";
18
19
  function Runtime(props) {
@@ -128,10 +129,22 @@ function Runtime(props) {
128
129
  const treeNode = createTreeNode(element, props.adapterId);
129
130
  if (treeNode) {
130
131
  const ancestry = collectAncestry(treeNode);
132
+
133
+ // Write immediately with component names (preserves user gesture for clipboard API)
131
134
  const formatted = formatAncestryChain(ancestry);
132
135
  navigator.clipboard.writeText(formatted).then(() => {
133
136
  setToastMessage("Copied to clipboard");
134
137
  });
138
+
139
+ // For React 19+: try to enrich with source map file paths and re-copy
140
+ enrichAncestryWithSourceMaps(ancestry, element).then(enriched => {
141
+ const enrichedFormatted = formatAncestryChain(enriched);
142
+ if (enrichedFormatted !== formatted) {
143
+ navigator.clipboard.writeText(enrichedFormatted).then(() => {
144
+ setToastMessage("Copied to clipboard");
145
+ });
146
+ }
147
+ });
135
148
  }
136
149
 
137
150
  // Deactivate toggle after click
@@ -0,0 +1,7 @@
1
+ import { AncestryItem } from "./formatAncestryChain";
2
+ /**
3
+ * Enrich ancestry items that are missing filePath by resolving via source maps.
4
+ * This is an async operation that fetches source maps for React 19 environments.
5
+ * For React 18 (where _debugSource exists), this is a no-op.
6
+ */
7
+ export declare function enrichAncestryWithSourceMaps(items: AncestryItem[], element?: HTMLElement): Promise<AncestryItem[]>;
@@ -0,0 +1,80 @@
1
+ import { resolveSourceLocation, parseDebugStack } from "../adapters/react/resolveSourceMap";
2
+ import { normalizeFilePath } from "./normalizeFilePath";
3
+
4
+ /**
5
+ * Check if any DOM element has React 19 fibers (with _debugStack instead of _debugSource).
6
+ */
7
+ function isReact19Environment() {
8
+ const el = document.querySelector("[class]") || document.body;
9
+ if (!el) return false;
10
+ const fiberKey = Object.keys(el).find(k => k.startsWith("__reactFiber$"));
11
+ if (!fiberKey) return false;
12
+ const fiber = el[fiberKey];
13
+ return !fiber?._debugSource && !!fiber?._debugStack;
14
+ }
15
+
16
+ /**
17
+ * Walk a fiber's _debugOwner chain and collect _debugStack stack traces for each component.
18
+ * Returns a map from component name to its parsed stack location.
19
+ */
20
+ function collectFiberStacks(element) {
21
+ const stacks = new Map();
22
+ const fiberKey = Object.keys(element).find(k => k.startsWith("__reactFiber$"));
23
+ if (!fiberKey) return stacks;
24
+ let fiber = element[fiberKey];
25
+
26
+ // Collect stacks from the fiber itself and its _debugOwner chain
27
+ while (fiber) {
28
+ const debugStack = fiber._debugStack;
29
+ if (debugStack?.stack) {
30
+ const parsed = parseDebugStack(debugStack.stack);
31
+ if (parsed) {
32
+ const name = fiber.type?.name || fiber.type?.displayName || fiber.type;
33
+ if (typeof name === "string") {
34
+ stacks.set(name, parsed);
35
+ }
36
+ }
37
+ }
38
+ fiber = fiber._debugOwner || null;
39
+ }
40
+ return stacks;
41
+ }
42
+
43
+ /**
44
+ * Enrich ancestry items that are missing filePath by resolving via source maps.
45
+ * This is an async operation that fetches source maps for React 19 environments.
46
+ * For React 18 (where _debugSource exists), this is a no-op.
47
+ */
48
+ export async function enrichAncestryWithSourceMaps(items, element) {
49
+ // Skip if all items already have file paths, or not React 19
50
+ const needsEnrichment = items.some(item => item.componentName && !item.filePath);
51
+ if (!needsEnrichment || !isReact19Environment()) {
52
+ return items;
53
+ }
54
+
55
+ // Collect _debugStack info from the DOM element's fiber chain
56
+ const stacks = element ? collectFiberStacks(element) : new Map();
57
+
58
+ // Resolve source maps in parallel for items missing filePath
59
+ const enriched = await Promise.all(items.map(async item => {
60
+ if (item.filePath || !item.componentName) return item;
61
+
62
+ // Find the stack trace for this component
63
+ const stack = stacks.get(item.componentName);
64
+ if (!stack) return item;
65
+ try {
66
+ const source = await resolveSourceLocation(stack.url, stack.line, stack.column);
67
+ if (source) {
68
+ return {
69
+ ...item,
70
+ filePath: normalizeFilePath(source.fileName),
71
+ line: source.lineNumber
72
+ };
73
+ }
74
+ } catch {
75
+ // Source map resolution failed — keep item as-is
76
+ }
77
+ return item;
78
+ }));
79
+ return enriched;
80
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@treelocator/runtime",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "TreeLocatorJS runtime for component ancestry tracking. Alt+click any element to copy its component tree to clipboard. Exposes window.__treelocator__ API for browser automation (Playwright, Puppeteer, Selenium, Cypress).",
5
5
  "keywords": [
6
6
  "locator",
@@ -54,7 +54,7 @@
54
54
  "@babel/cli": "^7.25.9",
55
55
  "@babel/core": "^7.26.0",
56
56
  "@tailwindcss/forms": "^0.5.11",
57
- "@treelocator/dev-config": "^0.2.0",
57
+ "@treelocator/dev-config": "^0.3.0",
58
58
  "@types/jsdom": "^21.1.7",
59
59
  "babel-preset-solid": "^1.9.2",
60
60
  "concurrently": "^9.1.0",
@@ -73,5 +73,5 @@
73
73
  "directory": "packages/runtime"
74
74
  },
75
75
  "license": "MIT",
76
- "gitHead": "5d53daa18f4fef5e815c3fd281b899608f8673ea"
76
+ "gitHead": "f53c9d698aaee64837698b5c6803df5485d2a229"
77
77
  }
@@ -11,6 +11,15 @@ import {
11
11
  } from "@locator/shared";
12
12
  import { detectPhoenix } from "./phoenix/detectPhoenix";
13
13
 
14
+ /**
15
+ * Fallback React detection: check if any DOM element has __reactFiber$ keys.
16
+ * Works without React DevTools extension (where detectReact() fails because
17
+ * the renderers Map is empty).
18
+ */
19
+ function hasReactFiberKeys(element: HTMLElement): boolean {
20
+ return Object.keys(element).some((k) => k.startsWith("__reactFiber$"));
21
+ }
22
+
14
23
  export function createTreeNode(
15
24
  element: HTMLElement,
16
25
  adapterId?: string
@@ -38,7 +47,7 @@ export function createTreeNode(
38
47
  return new VueTreeNodeElement(element);
39
48
  }
40
49
 
41
- if (detectReact()) {
50
+ if (detectReact() || hasReactFiberKeys(element)) {
42
51
  return new ReactTreeNodeElement(element);
43
52
  }
44
53
 
@@ -1,10 +1,15 @@
1
1
  import { Fiber, Source } from "@locator/shared";
2
+ import {
3
+ resolveSourceFromDebugStack,
4
+ parseDebugStack,
5
+ } from "./resolveSourceMap";
2
6
 
3
7
  export function findDebugSource(
4
8
  fiber: Fiber
5
9
  ): { fiber: Fiber; source: Source } | null {
6
10
  let current: Fiber | null = fiber;
7
11
  while (current) {
12
+ // React 18 and earlier: _debugSource is a structured object
8
13
  if (current._debugSource) {
9
14
  return { fiber: current, source: current._debugSource };
10
15
  }
@@ -13,3 +18,38 @@ export function findDebugSource(
13
18
 
14
19
  return null;
15
20
  }
21
+
22
+ /**
23
+ * Async version of findDebugSource that supports React 19's _debugStack.
24
+ * Falls back to synchronous _debugSource check first (React 18).
25
+ * If that fails, parses _debugStack and resolves via source maps.
26
+ */
27
+ export async function findDebugSourceAsync(
28
+ fiber: Fiber
29
+ ): Promise<{ fiber: Fiber; source: Source } | null> {
30
+ // Try synchronous path first (React 18)
31
+ const syncResult = findDebugSource(fiber);
32
+ if (syncResult) return syncResult;
33
+
34
+ // React 19: try resolving via _debugStack + source maps
35
+ let current: Fiber | null = fiber;
36
+ while (current) {
37
+ const debugStack = (current as any)._debugStack;
38
+ if (debugStack?.stack) {
39
+ const source = await resolveSourceFromDebugStack(debugStack);
40
+ if (source) {
41
+ return { fiber: current, source };
42
+ }
43
+ }
44
+ current = current._debugOwner || null;
45
+ }
46
+
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * Check if this is a React 19+ environment (has _debugStack but not _debugSource).
52
+ */
53
+ export function isReact19Fiber(fiber: Fiber): boolean {
54
+ return !fiber._debugSource && !!(fiber as any)._debugStack;
55
+ }
@@ -1,12 +1,26 @@
1
1
  import { Fiber, Renderer } from "@locator/shared";
2
2
  import { findDebugSource } from "./findDebugSource";
3
3
 
4
+ /**
5
+ * Find the React fiber key on a DOM element (e.g., "__reactFiber$abc123").
6
+ * Works across all React versions that attach fibers to DOM nodes.
7
+ */
8
+ function findFiberFromDOMElement(element: HTMLElement): Fiber | null {
9
+ const fiberKey = Object.keys(element).find((k) =>
10
+ k.startsWith("__reactFiber$")
11
+ );
12
+ if (fiberKey) {
13
+ return (element as any)[fiberKey] as Fiber;
14
+ }
15
+ return null;
16
+ }
17
+
4
18
  export function findFiberByHtmlElement(
5
19
  target: HTMLElement,
6
20
  shouldHaveDebugSource: boolean
7
21
  ): Fiber | null {
22
+ // Try via DevTools renderers first (available when React DevTools extension is installed)
8
23
  const renderers = window.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers;
9
- // console.log("RENDERERS: ", renderers);
10
24
  const renderersValues = renderers?.values();
11
25
  if (renderersValues) {
12
26
  for (const renderer of Array.from(renderersValues) as Renderer[]) {
@@ -23,5 +37,16 @@ export function findFiberByHtmlElement(
23
37
  }
24
38
  }
25
39
  }
40
+
41
+ // Fallback: read fiber directly from DOM element's __reactFiber$ property.
42
+ // This works without the React DevTools extension and across React 16-19.
43
+ const fiber = findFiberFromDOMElement(target);
44
+ if (fiber) {
45
+ if (shouldHaveDebugSource) {
46
+ return findDebugSource(fiber)?.fiber || null;
47
+ }
48
+ return fiber;
49
+ }
50
+
26
51
  return null;
27
52
  }
@@ -10,13 +10,12 @@ export function getAllParentsElementsAndRootComponent(fiber: Fiber): {
10
10
  component: Fiber;
11
11
  componentBox: SimpleDOMRect;
12
12
  parentElements: ElementInfo[];
13
- } {
13
+ } | null {
14
14
  const parentElements: ElementInfo[] = [];
15
15
  const deepestElement = fiber.stateNode;
16
- if (!deepestElement || !(deepestElement instanceof HTMLElement)) {
17
- throw new Error(
18
- "This functions works only for Fibres with HTMLElement stateNode"
19
- );
16
+ if (!deepestElement || !(deepestElement instanceof Element)) {
17
+ console.warn("[TreeLocator] Skipping fiber with non-Element stateNode:", fiber.type, fiber.stateNode);
18
+ return null;
20
19
  }
21
20
  let componentBox: SimpleDOMRect = deepestElement.getBoundingClientRect();
22
21
 
@@ -26,7 +25,7 @@ export function getAllParentsElementsAndRootComponent(fiber: Fiber): {
26
25
  while (currentFiber._debugOwner || currentFiber.return) {
27
26
  currentFiber = currentFiber._debugOwner || currentFiber.return!;
28
27
  const currentElement = currentFiber.stateNode;
29
- if (!currentElement || !(currentElement instanceof HTMLElement)) {
28
+ if (!currentElement || !(currentElement instanceof Element)) {
30
29
  return {
31
30
  component: currentFiber,
32
31
  parentElements,
@@ -48,5 +47,6 @@ export function getAllParentsElementsAndRootComponent(fiber: Fiber): {
48
47
  link: null,
49
48
  });
50
49
  }
51
- throw new Error("Could not find root component");
50
+ console.warn("[TreeLocator] Could not find root component for fiber:", fiber.type);
51
+ return null;
52
52
  }
@@ -9,7 +9,7 @@ export function getAllWrappingParents(fiber: Fiber): Fiber[] {
9
9
  currentFiber = currentFiber.return;
10
10
  if (
11
11
  currentFiber.stateNode &&
12
- currentFiber.stateNode instanceof HTMLElement
12
+ currentFiber.stateNode instanceof Element
13
13
  ) {
14
14
  return parents;
15
15
  }
@@ -1,5 +1,6 @@
1
- import { findDebugSource } from "./findDebugSource";
1
+ import { findDebugSource, findDebugSourceAsync, isReact19Fiber } from "./findDebugSource";
2
2
  import { findFiberByHtmlElement } from "./findFiberByHtmlElement";
3
+ import { resolveSourceFromDebugStack } from "./resolveSourceMap";
3
4
  import { getFiberLabel } from "./getFiberLabel";
4
5
  import { getAllWrappingParents } from "./getAllWrappingParents";
5
6
  import { deduplicateLabels } from "../../functions/deduplicateLabels";
@@ -24,8 +25,11 @@ export function getElementInfo(found: HTMLElement): FullElementInfo | null {
24
25
 
25
26
  const fiber = findFiberByHtmlElement(found, false);
26
27
  if (fiber) {
27
- const { component, componentBox, parentElements } =
28
- getAllParentsElementsAndRootComponent(fiber);
28
+ const result = getAllParentsElementsAndRootComponent(fiber);
29
+ if (!result) {
30
+ return null;
31
+ }
32
+ const { component, componentBox, parentElements } = result;
29
33
 
30
34
  const allPotentialComponentFibers = getAllWrappingParents(component);
31
35
 
@@ -0,0 +1,316 @@
1
+ import { Source } from "@locator/shared";
2
+
3
+ interface SourceMapSection {
4
+ offset: { line: number; column: number };
5
+ map: {
6
+ version: number;
7
+ sources: string[];
8
+ mappings: string;
9
+ sourcesContent?: (string | null)[];
10
+ };
11
+ }
12
+
13
+ interface IndexedSourceMap {
14
+ version: number;
15
+ sections: SourceMapSection[];
16
+ }
17
+
18
+ interface BasicSourceMap {
19
+ version: number;
20
+ sources: string[];
21
+ mappings: string;
22
+ sourcesContent?: (string | null)[];
23
+ }
24
+
25
+ type SourceMap = IndexedSourceMap | BasicSourceMap;
26
+
27
+ // Cache: bundled script URL -> source map
28
+ const sourceMapCache = new Map<string, Promise<SourceMap | null>>();
29
+
30
+ /**
31
+ * Parse the React 19 _debugStack Error.stack to extract the caller's location.
32
+ *
33
+ * Stack format:
34
+ * Error: react-stack-top-frame
35
+ * at exports.jsxDEV (http://localhost:3000/_next/.../chunk.js:410:33)
36
+ * at Home (http://localhost:3000/_next/.../chunk.js:8789:416)
37
+ * at Object.react_stack_bottom_frame (...)
38
+ *
39
+ * The second frame (after jsxDEV/jsx) is the component that created the element.
40
+ */
41
+ export function parseDebugStack(
42
+ stack: string
43
+ ): { url: string; line: number; column: number } | null {
44
+ const lines = stack.split("\n");
45
+
46
+ // Find the component caller frame (skip react-stack-top-frame and jsx factory)
47
+ for (let i = 1; i < lines.length; i++) {
48
+ const line = lines[i]?.trim();
49
+ if (!line) continue;
50
+
51
+ // Skip react internal frames
52
+ if (
53
+ line.includes("react-stack-top-frame") ||
54
+ line.includes("react_stack_bottom_frame")
55
+ ) {
56
+ continue;
57
+ }
58
+
59
+ // Skip JSX factory frames (jsxDEV, jsx, jsxs)
60
+ if (
61
+ line.includes("jsxDEV") ||
62
+ line.includes("exports.jsx ") ||
63
+ line.includes("exports.jsxs ")
64
+ ) {
65
+ continue;
66
+ }
67
+
68
+ // Parse "at Name (url:line:col)" or "at url:line:col"
69
+ const match =
70
+ line.match(/at\s+(?:\S+\s+)?\(?(https?:\/\/.+?):(\d+):(\d+)\)?/) ||
71
+ line.match(/at\s+(https?:\/\/.+?):(\d+):(\d+)/);
72
+
73
+ if (match && match[1] && match[2] && match[3]) {
74
+ return {
75
+ url: match[1],
76
+ line: parseInt(match[2], 10),
77
+ column: parseInt(match[3], 10),
78
+ };
79
+ }
80
+ }
81
+
82
+ return null;
83
+ }
84
+
85
+ async function fetchSourceMap(scriptUrl: string): Promise<SourceMap | null> {
86
+ if (sourceMapCache.has(scriptUrl)) {
87
+ return sourceMapCache.get(scriptUrl)!;
88
+ }
89
+
90
+ const promise = (async () => {
91
+ try {
92
+ // Fetch the script to find sourceMappingURL
93
+ const scriptResp = await fetch(scriptUrl);
94
+ if (!scriptResp.ok) return null;
95
+
96
+ const scriptText = await scriptResp.text();
97
+ const match = scriptText.match(
98
+ /\/\/[#@]\s*sourceMappingURL=(.+?)(?:\s|$)/
99
+ );
100
+ if (!match || !match[1]) return null;
101
+
102
+ // Resolve the source map URL relative to the script URL
103
+ let mapUrl = match[1];
104
+ if (!mapUrl.startsWith("http")) {
105
+ const base = scriptUrl.substring(0, scriptUrl.lastIndexOf("/") + 1);
106
+ mapUrl = base + mapUrl;
107
+ }
108
+
109
+ const mapResp = await fetch(mapUrl);
110
+ if (!mapResp.ok) return null;
111
+
112
+ return (await mapResp.json()) as SourceMap;
113
+ } catch {
114
+ return null;
115
+ }
116
+ })();
117
+
118
+ sourceMapCache.set(scriptUrl, promise);
119
+ return promise;
120
+ }
121
+
122
+ // Decode a single VLQ value from a mappings string, returns [value, charsConsumed]
123
+ const VLQ_BASE_SHIFT = 5;
124
+ const VLQ_BASE = 1 << VLQ_BASE_SHIFT; // 32
125
+ const VLQ_BASE_MASK = VLQ_BASE - 1; // 31
126
+ const VLQ_CONTINUATION_BIT = VLQ_BASE; // 32
127
+ const BASE64_CHARS =
128
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
129
+ const base64Map = new Map<string, number>();
130
+ for (let i = 0; i < BASE64_CHARS.length; i++) {
131
+ base64Map.set(BASE64_CHARS[i]!, i);
132
+ }
133
+
134
+ function decodeVLQ(str: string, index: number): [number, number] {
135
+ let result = 0;
136
+ let shift = 0;
137
+ let continuation: boolean;
138
+ let i = index;
139
+
140
+ do {
141
+ const char = str[i];
142
+ if (!char) return [0, i];
143
+ const digit = base64Map.get(char);
144
+ if (digit === undefined) return [0, i];
145
+ i++;
146
+ continuation = (digit & VLQ_CONTINUATION_BIT) !== 0;
147
+ result += (digit & VLQ_BASE_MASK) << shift;
148
+ shift += VLQ_BASE_SHIFT;
149
+ } while (continuation);
150
+
151
+ // Convert from VLQ signed
152
+ const isNegative = (result & 1) === 1;
153
+ result >>= 1;
154
+ return [isNegative ? -result : result, i];
155
+ }
156
+
157
+ /**
158
+ * Find the original source location for a generated line/column in a basic source map.
159
+ */
160
+ function resolveInBasicMap(
161
+ map: BasicSourceMap,
162
+ targetLine: number,
163
+ targetColumn: number
164
+ ): Source | null {
165
+ const mappings = map.mappings;
166
+ if (!mappings) return null;
167
+
168
+ let generatedLine = 1;
169
+ let generatedColumn = 0;
170
+ let sourceIndex = 0;
171
+ let sourceLine = 0;
172
+ let sourceColumn = 0;
173
+
174
+ let bestSource: Source | null = null;
175
+ let i = 0;
176
+
177
+ while (i < mappings.length) {
178
+ const char = mappings[i];
179
+
180
+ if (char === ";") {
181
+ generatedLine++;
182
+ generatedColumn = 0;
183
+ i++;
184
+ continue;
185
+ }
186
+
187
+ if (char === ",") {
188
+ i++;
189
+ continue;
190
+ }
191
+
192
+ // Decode segment
193
+ let colDelta: number;
194
+ [colDelta, i] = decodeVLQ(mappings, i);
195
+ generatedColumn += colDelta;
196
+
197
+ // Check if there's source info (segments can be 1, 4, or 5 fields)
198
+ if (i < mappings.length && mappings[i] !== "," && mappings[i] !== ";") {
199
+ let srcDelta: number, lineDelta: number, srcColDelta: number;
200
+ [srcDelta, i] = decodeVLQ(mappings, i);
201
+ sourceIndex += srcDelta;
202
+ [lineDelta, i] = decodeVLQ(mappings, i);
203
+ sourceLine += lineDelta;
204
+ [srcColDelta, i] = decodeVLQ(mappings, i);
205
+ sourceColumn += srcColDelta;
206
+
207
+ // Skip optional name index
208
+ if (i < mappings.length && mappings[i] !== "," && mappings[i] !== ";") {
209
+ [, i] = decodeVLQ(mappings, i);
210
+ }
211
+
212
+ // Check if this mapping is at or before our target
213
+ if (
214
+ generatedLine === targetLine &&
215
+ generatedColumn <= targetColumn
216
+ ) {
217
+ const fileName = map.sources[sourceIndex];
218
+ if (fileName) {
219
+ bestSource = {
220
+ fileName: cleanSourcePath(fileName),
221
+ lineNumber: sourceLine + 1, // source maps are 0-indexed
222
+ columnNumber: sourceColumn,
223
+ };
224
+ }
225
+ }
226
+
227
+ // If we've passed the target line, we can stop
228
+ if (generatedLine > targetLine) {
229
+ break;
230
+ }
231
+ }
232
+ }
233
+
234
+ return bestSource;
235
+ }
236
+
237
+ /**
238
+ * Clean up source file paths from source maps.
239
+ * Strips file:// protocol and common project root prefixes.
240
+ */
241
+ function cleanSourcePath(filePath: string): string {
242
+ // Strip file:// protocol
243
+ let cleaned = filePath.replace(/^file:\/\//, "");
244
+
245
+ // Strip webpack/turbopack internal prefixes
246
+ cleaned = cleaned.replace(/^\[project\]\//, "");
247
+ cleaned = cleaned.replace(/^webpack:\/\/[^/]*\//, "");
248
+
249
+ return cleaned;
250
+ }
251
+
252
+ /**
253
+ * Resolve a bundled location to its original source using source maps.
254
+ * Returns null if resolution fails.
255
+ */
256
+ export async function resolveSourceLocation(
257
+ url: string,
258
+ line: number,
259
+ column: number
260
+ ): Promise<Source | null> {
261
+ const sourceMap = await fetchSourceMap(url);
262
+ if (!sourceMap) return null;
263
+
264
+ // Handle indexed/sectioned source maps (used by Turbopack)
265
+ if ("sections" in sourceMap && sourceMap.sections) {
266
+ const sections = sourceMap.sections;
267
+
268
+ // Find the section that contains our target line
269
+ let targetSection: SourceMapSection | null = null;
270
+ for (let i = sections.length - 1; i >= 0; i--) {
271
+ const section = sections[i];
272
+ if (!section) continue;
273
+ if (section.offset.line < line) {
274
+ targetSection = section;
275
+ break;
276
+ }
277
+ if (section.offset.line === line && section.offset.column <= column) {
278
+ targetSection = section;
279
+ break;
280
+ }
281
+ }
282
+
283
+ if (!targetSection) return null;
284
+
285
+ // Resolve within the section's map (adjust line/column relative to section offset)
286
+ const relLine = line - targetSection.offset.line;
287
+ const relCol =
288
+ line === targetSection.offset.line
289
+ ? column - targetSection.offset.column
290
+ : column;
291
+
292
+ return resolveInBasicMap(
293
+ targetSection.map as BasicSourceMap,
294
+ relLine,
295
+ relCol
296
+ );
297
+ }
298
+
299
+ // Handle basic source maps
300
+ return resolveInBasicMap(sourceMap as BasicSourceMap, line, column);
301
+ }
302
+
303
+ /**
304
+ * Given a React 19 fiber's _debugStack, resolve the source location
305
+ * by parsing the stack trace and looking up source maps.
306
+ */
307
+ export async function resolveSourceFromDebugStack(
308
+ debugStack: { stack?: string }
309
+ ): Promise<Source | null> {
310
+ if (!debugStack?.stack) return null;
311
+
312
+ const parsed = parseDebugStack(debugStack.stack);
313
+ if (!parsed) return null;
314
+
315
+ return resolveSourceLocation(parsed.url, parsed.line, parsed.column);
316
+ }