react-code-locator 0.1.9 → 0.1.13

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 (52) hide show
  1. package/README.md +49 -44
  2. package/dist/babel.cjs +428 -40
  3. package/dist/babel.cjs.map +1 -1
  4. package/dist/babel.d.cts +12 -1
  5. package/dist/babel.d.ts +12 -1
  6. package/dist/babel.js +425 -29
  7. package/dist/babel.js.map +1 -1
  8. package/dist/babelInjectComponentSource.cjs +400 -38
  9. package/dist/babelInjectComponentSource.cjs.map +1 -1
  10. package/dist/babelInjectComponentSource.d.cts +3 -4
  11. package/dist/babelInjectComponentSource.d.ts +3 -4
  12. package/dist/babelInjectComponentSource.js +400 -28
  13. package/dist/babelInjectComponentSource.js.map +1 -1
  14. package/dist/client-sm5wi0uT.d.cts +15 -0
  15. package/dist/client-sm5wi0uT.d.ts +15 -0
  16. package/dist/client.cjs +157 -28
  17. package/dist/client.cjs.map +1 -1
  18. package/dist/client.d.cts +1 -14
  19. package/dist/client.d.ts +1 -14
  20. package/dist/client.js +157 -28
  21. package/dist/client.js.map +1 -1
  22. package/dist/esbuild.cjs +616 -0
  23. package/dist/esbuild.cjs.map +1 -0
  24. package/dist/esbuild.d.cts +25 -0
  25. package/dist/esbuild.d.ts +25 -0
  26. package/dist/esbuild.js +589 -0
  27. package/dist/esbuild.js.map +1 -0
  28. package/dist/index.cjs +843 -30
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +9 -1
  31. package/dist/index.d.ts +9 -1
  32. package/dist/index.js +830 -29
  33. package/dist/index.js.map +1 -1
  34. package/dist/sourceAdapter-DLWo_ABo.d.cts +15 -0
  35. package/dist/sourceAdapter-DLWo_ABo.d.ts +15 -0
  36. package/dist/swc.cjs +589 -0
  37. package/dist/swc.cjs.map +1 -0
  38. package/dist/swc.d.cts +29 -0
  39. package/dist/swc.d.ts +29 -0
  40. package/dist/swc.js +560 -0
  41. package/dist/swc.js.map +1 -0
  42. package/dist/vite.cjs +529 -84
  43. package/dist/vite.cjs.map +1 -1
  44. package/dist/vite.d.cts +20 -6
  45. package/dist/vite.d.ts +20 -6
  46. package/dist/vite.js +524 -72
  47. package/dist/vite.js.map +1 -1
  48. package/dist/webpackRuntimeEntry.cjs +157 -28
  49. package/dist/webpackRuntimeEntry.cjs.map +1 -1
  50. package/dist/webpackRuntimeEntry.js +157 -28
  51. package/dist/webpackRuntimeEntry.js.map +1 -1
  52. package/package.json +12 -1
package/dist/index.js CHANGED
@@ -1,5 +1,74 @@
1
1
  // src/constants.ts
2
2
  var SOURCE_PROP = "__componentSourceLoc";
3
+ var JSX_SOURCE_PROP = "$componentSourceLoc";
4
+ var JSX_SOURCE_REGISTRY_SYMBOL = "react-code-locator.jsxSourceRegistry";
5
+
6
+ // src/sourceMetadata.ts
7
+ function normalizeSlashes(value) {
8
+ return value.replace(/\\/g, "/");
9
+ }
10
+ function trimTrailingSlash(value) {
11
+ return value.replace(/\/+$/, "");
12
+ }
13
+ function splitPathSegments(value) {
14
+ return normalizeSlashes(value).split("/").filter(Boolean);
15
+ }
16
+ function computeRelativePath(fromPath, toPath) {
17
+ const fromSegments = splitPathSegments(fromPath);
18
+ const toSegments = splitPathSegments(toPath);
19
+ let sharedIndex = 0;
20
+ while (sharedIndex < fromSegments.length && sharedIndex < toSegments.length && fromSegments[sharedIndex] === toSegments[sharedIndex]) {
21
+ sharedIndex += 1;
22
+ }
23
+ const upSegments = new Array(Math.max(0, fromSegments.length - sharedIndex)).fill("..");
24
+ const downSegments = toSegments.slice(sharedIndex);
25
+ const relativeSegments = [...upSegments, ...downSegments];
26
+ return relativeSegments.length > 0 ? relativeSegments.join("/") : ".";
27
+ }
28
+ function normalizeProjectRoot(projectRoot) {
29
+ if (projectRoot) {
30
+ return trimTrailingSlash(normalizeSlashes(projectRoot));
31
+ }
32
+ return "";
33
+ }
34
+ function toRelativeSource(filename, loc, projectRoot) {
35
+ if (!filename || !loc) {
36
+ return null;
37
+ }
38
+ const root = normalizeProjectRoot(projectRoot);
39
+ const normalizedFilename = normalizeSlashes(filename);
40
+ const relPath = root && normalizedFilename.startsWith(`${root}/`) ? normalizedFilename.slice(root.length + 1) : root ? computeRelativePath(root, normalizedFilename) : normalizedFilename;
41
+ return `${relPath}:${loc.line}:${loc.column + 1}`;
42
+ }
43
+ function getSourceFile(source) {
44
+ if (!source) {
45
+ return null;
46
+ }
47
+ const match = source.match(/^(.*):\d+:\d+$/);
48
+ return match?.[1] ?? null;
49
+ }
50
+ function isProjectLocalFile(filename, projectRoot) {
51
+ if (!filename) {
52
+ return false;
53
+ }
54
+ const root = normalizeProjectRoot(projectRoot);
55
+ const normalizedFilename = normalizeSlashes(filename);
56
+ if (!root) {
57
+ return !normalizedFilename.startsWith("../") && !normalizedFilename.startsWith("/") && !/^[A-Za-z]:\//.test(normalizedFilename);
58
+ }
59
+ if (normalizedFilename.startsWith(`${root}/`) || normalizedFilename === root) {
60
+ return true;
61
+ }
62
+ const relativePath = computeRelativePath(root, normalizedFilename);
63
+ return !relativePath.startsWith("../");
64
+ }
65
+ function isExternalToProjectRoot(filename, projectRoot) {
66
+ return !isProjectLocalFile(filename, projectRoot);
67
+ }
68
+ function isProjectLocalSource(source, projectRoot) {
69
+ const file = getSourceFile(source);
70
+ return isProjectLocalFile(file ?? void 0, projectRoot);
71
+ }
3
72
 
4
73
  // src/runtime.ts
5
74
  function isTriggerPressed(event, triggerKey) {
@@ -47,7 +116,16 @@ function getSourceFromType(type) {
47
116
  return typeof source === "string" ? source : null;
48
117
  }
49
118
  function getSourceFromProps(props) {
50
- const source = props?.[SOURCE_PROP];
119
+ if (props && typeof props === "object") {
120
+ const registry = globalThis[Symbol.for(JSX_SOURCE_REGISTRY_SYMBOL)];
121
+ if (registry instanceof WeakMap) {
122
+ const intrinsicSource = registry.get(props);
123
+ if (typeof intrinsicSource === "string") {
124
+ return intrinsicSource;
125
+ }
126
+ }
127
+ }
128
+ const source = props?.[JSX_SOURCE_PROP];
51
129
  return typeof source === "string" ? source : null;
52
130
  }
53
131
  function resolveComponentSourceFromFiber(fiber) {
@@ -68,35 +146,69 @@ function getDirectDebugSource(fiber) {
68
146
  }
69
147
  return null;
70
148
  }
71
- function resolveOwnerJsxSource(fiber) {
72
- let current = fiber?._debugOwner ?? null;
73
- while (current) {
74
- const source = getSourceFromProps(current.pendingProps) ?? getSourceFromProps(current.memoizedProps) ?? getDirectDebugSource(current);
75
- if (source) {
76
- return source;
77
- }
78
- current = current._debugOwner ?? null;
79
- }
80
- return null;
81
- }
82
- function resolveNearestJsxSource(fiber) {
149
+ function resolveSourceCandidates(fiber) {
83
150
  let current = fiber;
151
+ const jsxCandidates = [];
152
+ const componentCandidates = [];
84
153
  while (current) {
85
- const source = getSourceFromProps(current.pendingProps) ?? getSourceFromProps(current.memoizedProps) ?? getDirectDebugSource(current);
86
- if (source) {
87
- return source;
154
+ const jsxSource = getSourceFromProps(current.pendingProps) ?? getSourceFromProps(current.memoizedProps) ?? getDirectDebugSource(current);
155
+ if (jsxSource) {
156
+ const file = getSourceFile(jsxSource);
157
+ if (file && !jsxCandidates.some((candidate) => candidate.source === jsxSource)) {
158
+ jsxCandidates.push({ source: jsxSource, file });
159
+ }
160
+ }
161
+ const componentSource = getSourceFromType(current.type) ?? getSourceFromType(current.elementType);
162
+ if (componentSource) {
163
+ const file = getSourceFile(componentSource);
164
+ if (file && !componentCandidates.some((candidate) => candidate.source === componentSource)) {
165
+ componentCandidates.push({ source: componentSource, file });
166
+ }
88
167
  }
89
168
  current = current.return ?? null;
90
169
  }
91
- return null;
170
+ const direct = jsxCandidates[0]?.source ?? null;
171
+ const nearestProjectLocalComponentFile = componentCandidates.find((candidate) => isProjectLocalSource(candidate.source))?.file;
172
+ let screen = null;
173
+ if (nearestProjectLocalComponentFile) {
174
+ const matchingJsxCandidate = jsxCandidates.find((candidate) => candidate.file === nearestProjectLocalComponentFile);
175
+ if (matchingJsxCandidate) {
176
+ screen = matchingJsxCandidate.source;
177
+ } else {
178
+ const matchingComponentCandidate = componentCandidates.find(
179
+ (candidate) => candidate.file === nearestProjectLocalComponentFile
180
+ );
181
+ if (matchingComponentCandidate) {
182
+ screen = matchingComponentCandidate.source;
183
+ }
184
+ }
185
+ }
186
+ const implementationComponentCandidate = componentCandidates.find((candidate) => !isProjectLocalSource(candidate.source))?.source ?? null;
187
+ const implementationJsxCandidate = jsxCandidates.find((candidate) => !isProjectLocalSource(candidate.source))?.source ?? null;
188
+ const projectLocalJsxCandidate = jsxCandidates.find((candidate) => isProjectLocalSource(candidate.source))?.source ?? null;
189
+ const screenFallback = screen ?? projectLocalJsxCandidate ?? componentCandidates.find((candidate) => isProjectLocalSource(candidate.source))?.source ?? null;
190
+ return {
191
+ direct: direct ?? screenFallback,
192
+ screen: screenFallback,
193
+ implementation: implementationComponentCandidate ?? implementationJsxCandidate ?? screenFallback
194
+ };
195
+ }
196
+ function getModeDescription(mode) {
197
+ if (mode === "direct") {
198
+ return "Direct JSX";
199
+ }
200
+ if (mode === "screen") {
201
+ return "Screen source";
202
+ }
203
+ return "Implementation source";
92
204
  }
93
205
  function createStatusOverlay(triggerKey) {
94
206
  if (typeof document === "undefined") {
95
207
  return null;
96
208
  }
97
209
  const element = document.createElement("div");
98
- let currentText = "";
99
210
  let copyValue = null;
211
+ let currentMode = "screen";
100
212
  let hideTimer = null;
101
213
  element.setAttribute("data-react-code-locator", "true");
102
214
  Object.assign(element.style, {
@@ -120,7 +232,6 @@ function createStatusOverlay(triggerKey) {
120
232
  transition: "opacity 120ms ease"
121
233
  });
122
234
  const show = (message, tone) => {
123
- currentText = message;
124
235
  element.textContent = message;
125
236
  element.style.background = tone === "success" ? "rgba(6, 95, 70, 0.92)" : tone === "error" ? "rgba(153, 27, 27, 0.94)" : "rgba(17, 24, 39, 0.92)";
126
237
  element.style.opacity = "1";
@@ -131,7 +242,7 @@ function createStatusOverlay(triggerKey) {
131
242
  hideTimer = setTimeout(() => {
132
243
  element.style.opacity = "0";
133
244
  element.style.pointerEvents = "none";
134
- }, 1500);
245
+ }, 2e3);
135
246
  };
136
247
  element.addEventListener("click", async () => {
137
248
  if (!copyValue) {
@@ -144,7 +255,7 @@ function createStatusOverlay(triggerKey) {
144
255
  show(`[react-code-locator] copy failed`, "error");
145
256
  }
146
257
  });
147
- show(`[react-code-locator] enabled (${triggerKey}+click)`, "idle");
258
+ show(`[react-code-locator] enabled (${triggerKey}+click, alt+1/2/3 to switch mode)`, "idle");
148
259
  const mount = () => {
149
260
  if (!element.isConnected && document.body) {
150
261
  document.body.appendChild(element);
@@ -162,6 +273,10 @@ function createStatusOverlay(triggerKey) {
162
273
  setCopyValue(value) {
163
274
  copyValue = value;
164
275
  },
276
+ setMode(mode) {
277
+ currentMode = mode;
278
+ show(`[react-code-locator] ${getModeDescription(mode)}`, "idle");
279
+ },
165
280
  remove() {
166
281
  if (hideTimer) {
167
282
  clearTimeout(hideTimer);
@@ -170,17 +285,18 @@ function createStatusOverlay(triggerKey) {
170
285
  }
171
286
  };
172
287
  }
173
- function locateComponentSource(target) {
288
+ function locateComponentSource(target, mode = "screen") {
174
289
  const elementTarget = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
175
290
  const fiber = getClosestReactFiber(elementTarget);
176
291
  if (!fiber) {
177
292
  return null;
178
293
  }
179
- const jsxSource = resolveOwnerJsxSource(fiber) ?? resolveNearestJsxSource(fiber);
180
- if (jsxSource) {
294
+ const candidates = resolveSourceCandidates(fiber);
295
+ const source = candidates[mode] ?? candidates.screen ?? candidates.direct ?? candidates.implementation;
296
+ if (source) {
181
297
  return {
182
- source: jsxSource,
183
- mode: "jsx"
298
+ source,
299
+ mode
184
300
  };
185
301
  }
186
302
  const componentSource = resolveComponentSourceFromFiber(fiber);
@@ -189,11 +305,12 @@ function locateComponentSource(target) {
189
305
  }
190
306
  return {
191
307
  source: componentSource,
192
- mode: "component"
308
+ mode
193
309
  };
194
310
  }
195
311
  function enableReactComponentJump(options = {}) {
196
312
  const overlay = createStatusOverlay(options.triggerKey ?? "shift");
313
+ let currentMode = "screen";
197
314
  const {
198
315
  triggerKey = "shift",
199
316
  onLocate = (result) => {
@@ -209,6 +326,28 @@ function enableReactComponentJump(options = {}) {
209
326
  }
210
327
  } = options;
211
328
  console.log("[react-code-locator] enabled", { triggerKey });
329
+ const keyHandler = (event) => {
330
+ if (!event.altKey) {
331
+ return;
332
+ }
333
+ if (event.code === "Digit1") {
334
+ currentMode = "direct";
335
+ overlay?.setMode(currentMode);
336
+ event.preventDefault();
337
+ return;
338
+ }
339
+ if (event.code === "Digit2") {
340
+ currentMode = "screen";
341
+ overlay?.setMode(currentMode);
342
+ event.preventDefault();
343
+ return;
344
+ }
345
+ if (event.code === "Digit3") {
346
+ currentMode = "implementation";
347
+ overlay?.setMode(currentMode);
348
+ event.preventDefault();
349
+ }
350
+ };
212
351
  const handler = (event) => {
213
352
  console.log("[react-code-locator] click", {
214
353
  triggerKey,
@@ -221,7 +360,7 @@ function enableReactComponentJump(options = {}) {
221
360
  if (!isTriggerPressed(event, triggerKey)) {
222
361
  return;
223
362
  }
224
- const result = locateComponentSource(event.target);
363
+ const result = locateComponentSource(event.target, currentMode);
225
364
  if (!result) {
226
365
  onError(new Error("No React component source metadata found for clicked element."));
227
366
  return;
@@ -231,13 +370,675 @@ function enableReactComponentJump(options = {}) {
231
370
  onLocate(result);
232
371
  };
233
372
  document.addEventListener("click", handler, true);
373
+ document.addEventListener("keydown", keyHandler, true);
234
374
  return () => {
235
375
  document.removeEventListener("click", handler, true);
376
+ document.removeEventListener("keydown", keyHandler, true);
236
377
  overlay?.remove();
237
378
  };
238
379
  }
380
+
381
+ // src/sourceAdapter.ts
382
+ function defineSourceAdapter(descriptor) {
383
+ return descriptor;
384
+ }
385
+
386
+ // src/babelInjectComponentSource.ts
387
+ import { types as t } from "@babel/core";
388
+ var SOURCE_PROP_LOCAL = "_componentSourceLoc";
389
+ var SOURCE_PROPS_REST = "__reactCodeLocatorProps";
390
+ function isComponentName(name) {
391
+ return /^[A-Z]/.test(name);
392
+ }
393
+ function isCustomComponentTag(name) {
394
+ if (t.isJSXIdentifier(name)) {
395
+ return isComponentName(name.name);
396
+ }
397
+ if (t.isJSXMemberExpression(name)) {
398
+ return true;
399
+ }
400
+ return false;
401
+ }
402
+ function isIntrinsicElementTag(name) {
403
+ return t.isJSXIdentifier(name) && /^[a-z]/.test(name.name);
404
+ }
405
+ function isElementFactoryIdentifier(name) {
406
+ return name === "jsx" || name === "jsxs" || name === "jsxDEV" || name === "_jsx" || name === "_jsxs" || name === "_jsxDEV" || name === "createElement";
407
+ }
408
+ function isReactElementFactoryCall(pathNode) {
409
+ const callee = pathNode.node.callee;
410
+ if (t.isIdentifier(callee)) {
411
+ return isElementFactoryIdentifier(callee.name);
412
+ }
413
+ return t.isMemberExpression(callee) && t.isIdentifier(callee.object, { name: "React" }) && t.isIdentifier(callee.property, { name: "createElement" });
414
+ }
415
+ function getRootJsxIdentifierName(name) {
416
+ if (t.isJSXIdentifier(name)) {
417
+ return name.name;
418
+ }
419
+ if (t.isJSXMemberExpression(name)) {
420
+ return getRootJsxIdentifierName(name.object);
421
+ }
422
+ return null;
423
+ }
424
+ function isStyledModuleImport(binding) {
425
+ if (!binding) {
426
+ return false;
427
+ }
428
+ if (!binding.path.isImportSpecifier() && !binding.path.isImportDefaultSpecifier() && !binding.path.isImportNamespaceSpecifier()) {
429
+ return false;
430
+ }
431
+ const source = binding.path.parentPath.isImportDeclaration() ? binding.path.parentPath.node.source.value : null;
432
+ if (typeof source !== "string") {
433
+ return false;
434
+ }
435
+ const normalized = source.replace(/\\/g, "/");
436
+ return normalized === "./styled" || normalized === "../styled" || normalized.endsWith("/styled");
437
+ }
438
+ function isSupportedComponentInit(node) {
439
+ if (!node) {
440
+ return false;
441
+ }
442
+ if (t.isArrowFunctionExpression(node) || t.isFunctionExpression(node)) {
443
+ return true;
444
+ }
445
+ if (!t.isCallExpression(node)) {
446
+ return false;
447
+ }
448
+ if (t.isIdentifier(node.callee) && (node.callee.name === "memo" || node.callee.name === "forwardRef")) {
449
+ return true;
450
+ }
451
+ return t.isMemberExpression(node.callee) && t.isIdentifier(node.callee.object, { name: "React" }) && t.isIdentifier(node.callee.property) && (node.callee.property.name === "memo" || node.callee.property.name === "forwardRef");
452
+ }
453
+ function hasSourcePropBinding(pattern) {
454
+ return pattern.properties.some((property) => {
455
+ if (!t.isObjectProperty(property)) {
456
+ return false;
457
+ }
458
+ return t.isIdentifier(property.key) && property.key.name === JSX_SOURCE_PROP;
459
+ });
460
+ }
461
+ function injectSourcePropBinding(pattern) {
462
+ if (hasSourcePropBinding(pattern)) {
463
+ return;
464
+ }
465
+ const sourceBinding = t.objectProperty(
466
+ t.identifier(JSX_SOURCE_PROP),
467
+ t.identifier(SOURCE_PROP_LOCAL),
468
+ false,
469
+ false
470
+ );
471
+ const restIndex = pattern.properties.findIndex(
472
+ (property) => t.isRestElement(property)
473
+ );
474
+ if (restIndex === -1) {
475
+ pattern.properties.push(sourceBinding);
476
+ return;
477
+ }
478
+ pattern.properties.splice(restIndex, 0, sourceBinding);
479
+ }
480
+ function injectSourcePropIntoIdentifierParam(node, param) {
481
+ if (!t.isBlockStatement(node.body)) {
482
+ node.body = t.blockStatement([t.returnStatement(node.body)]);
483
+ }
484
+ const alreadyInjected = node.body.body.some(
485
+ (statement) => t.isVariableDeclaration(statement) && statement.declarations.some(
486
+ (declaration) => t.isIdentifier(declaration.id) && declaration.id.name === SOURCE_PROPS_REST
487
+ )
488
+ );
489
+ if (alreadyInjected) {
490
+ return;
491
+ }
492
+ node.body.body.unshift(
493
+ t.variableDeclaration("const", [
494
+ t.variableDeclarator(
495
+ t.objectPattern([
496
+ t.objectProperty(
497
+ t.identifier(JSX_SOURCE_PROP),
498
+ t.identifier(SOURCE_PROP_LOCAL),
499
+ false,
500
+ false
501
+ ),
502
+ t.restElement(t.identifier(SOURCE_PROPS_REST))
503
+ ]),
504
+ param
505
+ )
506
+ ]),
507
+ t.expressionStatement(
508
+ t.assignmentExpression(
509
+ "=",
510
+ t.identifier(param.name),
511
+ t.identifier(SOURCE_PROPS_REST)
512
+ )
513
+ )
514
+ );
515
+ }
516
+ function injectSourcePropIntoFunctionParams(node) {
517
+ const firstParam = node.params[0];
518
+ if (!firstParam) {
519
+ return;
520
+ }
521
+ if (t.isObjectPattern(firstParam)) {
522
+ injectSourcePropBinding(firstParam);
523
+ return;
524
+ }
525
+ if (t.isIdentifier(firstParam)) {
526
+ injectSourcePropIntoIdentifierParam(node, firstParam);
527
+ }
528
+ }
529
+ function injectSourcePropIntoExpression(node) {
530
+ if (!node) {
531
+ return;
532
+ }
533
+ if (t.isFunctionExpression(node) || t.isArrowFunctionExpression(node)) {
534
+ injectSourcePropIntoFunctionParams(node);
535
+ return;
536
+ }
537
+ if (!t.isCallExpression(node)) {
538
+ return;
539
+ }
540
+ const firstArg = node.arguments[0];
541
+ if (firstArg && !t.isSpreadElement(firstArg) && (t.isFunctionExpression(firstArg) || t.isArrowFunctionExpression(firstArg))) {
542
+ injectSourcePropIntoFunctionParams(firstArg);
543
+ }
544
+ }
545
+ function getSourceValue(state, loc, projectRoot) {
546
+ const filename = state.file?.opts?.filename;
547
+ if (!filename || !loc) {
548
+ return null;
549
+ }
550
+ return toRelativeSource(filename, loc, projectRoot);
551
+ }
552
+ function buildAssignment(name, sourceValue) {
553
+ return t.expressionStatement(
554
+ t.assignmentExpression(
555
+ "=",
556
+ t.memberExpression(t.identifier(name), t.identifier(SOURCE_PROP)),
557
+ t.stringLiteral(sourceValue)
558
+ )
559
+ );
560
+ }
561
+ function buildIntrinsicSourceHelper() {
562
+ return t.functionDeclaration(
563
+ t.identifier("_markIntrinsicElementSource"),
564
+ [t.identifier("element"), t.identifier("source")],
565
+ t.blockStatement([
566
+ t.variableDeclaration("const", [
567
+ t.variableDeclarator(
568
+ t.identifier("registryKey"),
569
+ t.callExpression(
570
+ t.memberExpression(t.identifier("Symbol"), t.identifier("for")),
571
+ [t.stringLiteral(JSX_SOURCE_REGISTRY_SYMBOL)]
572
+ )
573
+ )
574
+ ]),
575
+ t.variableDeclaration("let", [
576
+ t.variableDeclarator(
577
+ t.identifier("registry"),
578
+ t.memberExpression(t.identifier("globalThis"), t.identifier("registryKey"), true)
579
+ )
580
+ ]),
581
+ t.ifStatement(
582
+ t.unaryExpression(
583
+ "!",
584
+ t.binaryExpression("instanceof", t.identifier("registry"), t.identifier("WeakMap"))
585
+ ),
586
+ t.blockStatement([
587
+ t.expressionStatement(
588
+ t.assignmentExpression(
589
+ "=",
590
+ t.identifier("registry"),
591
+ t.assignmentExpression(
592
+ "=",
593
+ t.memberExpression(t.identifier("globalThis"), t.identifier("registryKey"), true),
594
+ t.newExpression(t.identifier("WeakMap"), [])
595
+ )
596
+ )
597
+ )
598
+ ])
599
+ ),
600
+ t.ifStatement(
601
+ t.logicalExpression(
602
+ "&&",
603
+ t.identifier("element"),
604
+ t.logicalExpression(
605
+ "&&",
606
+ t.binaryExpression("===", t.unaryExpression("typeof", t.identifier("element")), t.stringLiteral("object")),
607
+ t.binaryExpression(
608
+ "===",
609
+ t.unaryExpression("typeof", t.memberExpression(t.identifier("element"), t.identifier("props"))),
610
+ t.stringLiteral("object")
611
+ )
612
+ )
613
+ ),
614
+ t.blockStatement([
615
+ t.expressionStatement(
616
+ t.callExpression(
617
+ t.memberExpression(t.identifier("registry"), t.identifier("set")),
618
+ [t.memberExpression(t.identifier("element"), t.identifier("props")), t.identifier("source")]
619
+ )
620
+ )
621
+ ])
622
+ ),
623
+ t.returnStatement(t.identifier("element"))
624
+ ])
625
+ );
626
+ }
627
+ function ensureIntrinsicSourceHelper(programPath, state) {
628
+ if (state.injectedIntrinsicHelper) {
629
+ return;
630
+ }
631
+ const alreadyExists = programPath.node.body.some(
632
+ (node) => t.isFunctionDeclaration(node) && t.isIdentifier(node.id, { name: "_markIntrinsicElementSource" })
633
+ );
634
+ if (!alreadyExists) {
635
+ programPath.unshiftContainer("body", buildIntrinsicSourceHelper());
636
+ }
637
+ state.injectedIntrinsicHelper = true;
638
+ }
639
+ function visitDeclaration(declarationPath, insertAfterPath, state, seen, projectRoot) {
640
+ if (declarationPath.isFunctionDeclaration() || declarationPath.isClassDeclaration()) {
641
+ const name = declarationPath.node.id?.name;
642
+ if (!name || !isComponentName(name) || seen.has(name)) {
643
+ return;
644
+ }
645
+ if (declarationPath.isFunctionDeclaration()) {
646
+ injectSourcePropIntoFunctionParams(declarationPath.node);
647
+ }
648
+ const sourceValue = getSourceValue(
649
+ state,
650
+ declarationPath.node.loc?.start,
651
+ projectRoot
652
+ );
653
+ if (!sourceValue) {
654
+ return;
655
+ }
656
+ seen.add(name);
657
+ insertAfterPath.insertAfter(buildAssignment(name, sourceValue));
658
+ return;
659
+ }
660
+ if (!declarationPath.isVariableDeclaration()) {
661
+ return;
662
+ }
663
+ const assignments = declarationPath.node.declarations.flatMap(
664
+ (declarator) => {
665
+ if (!t.isIdentifier(declarator.id) || !isComponentName(declarator.id.name) || seen.has(declarator.id.name)) {
666
+ return [];
667
+ }
668
+ if (!declarator.init) {
669
+ return [];
670
+ }
671
+ if (!isSupportedComponentInit(declarator.init)) {
672
+ return [];
673
+ }
674
+ injectSourcePropIntoExpression(declarator.init);
675
+ const sourceValue = getSourceValue(
676
+ state,
677
+ declarator.loc?.start ?? declarator.init.loc?.start,
678
+ projectRoot
679
+ );
680
+ if (!sourceValue) {
681
+ return [];
682
+ }
683
+ seen.add(declarator.id.name);
684
+ return [buildAssignment(declarator.id.name, sourceValue)];
685
+ }
686
+ );
687
+ if (assignments.length > 0) {
688
+ insertAfterPath.insertAfter(assignments);
689
+ }
690
+ }
691
+ function babelInjectComponentSource(options = {}) {
692
+ const {
693
+ injectJsxSource = true,
694
+ injectComponentSource = true,
695
+ projectRoot
696
+ } = options;
697
+ return {
698
+ name: "babel-inject-component-source",
699
+ visitor: {
700
+ CallExpression(pathNode, state) {
701
+ if (!injectJsxSource) {
702
+ return;
703
+ }
704
+ if (!isReactElementFactoryCall(pathNode)) {
705
+ return;
706
+ }
707
+ if (pathNode.parentPath.isCallExpression() && t.isIdentifier(pathNode.parentPath.node.callee, {
708
+ name: "_markIntrinsicElementSource"
709
+ })) {
710
+ return;
711
+ }
712
+ const sourceValue = getSourceValue(
713
+ state,
714
+ pathNode.node.loc?.start,
715
+ projectRoot
716
+ );
717
+ if (!sourceValue) {
718
+ return;
719
+ }
720
+ const programPath = pathNode.findParent((parent) => parent.isProgram());
721
+ if (!programPath || !programPath.isProgram()) {
722
+ return;
723
+ }
724
+ ensureIntrinsicSourceHelper(programPath, state);
725
+ pathNode.replaceWith(
726
+ t.callExpression(t.identifier("_markIntrinsicElementSource"), [
727
+ pathNode.node,
728
+ t.stringLiteral(sourceValue)
729
+ ])
730
+ );
731
+ pathNode.skip();
732
+ },
733
+ JSXElement: {
734
+ exit(pathNode, state) {
735
+ if (!injectJsxSource) {
736
+ return;
737
+ }
738
+ if (!isIntrinsicElementTag(pathNode.node.openingElement.name)) {
739
+ return;
740
+ }
741
+ if (pathNode.parentPath.isCallExpression() && t.isIdentifier(pathNode.parentPath.node.callee, { name: "_markIntrinsicElementSource" })) {
742
+ return;
743
+ }
744
+ const sourceValue = getSourceValue(
745
+ state,
746
+ pathNode.node.openingElement.loc?.start,
747
+ projectRoot
748
+ );
749
+ if (!sourceValue) {
750
+ return;
751
+ }
752
+ const programPath = pathNode.findParent((parent) => parent.isProgram());
753
+ if (!programPath || !programPath.isProgram()) {
754
+ return;
755
+ }
756
+ ensureIntrinsicSourceHelper(programPath, state);
757
+ const wrappedNode = t.callExpression(t.identifier("_markIntrinsicElementSource"), [
758
+ pathNode.node,
759
+ t.stringLiteral(sourceValue)
760
+ ]);
761
+ if (pathNode.parentPath.isJSXElement() || pathNode.parentPath.isJSXFragment()) {
762
+ pathNode.replaceWith(t.jsxExpressionContainer(wrappedNode));
763
+ return;
764
+ }
765
+ if (pathNode.parentPath.isJSXExpressionContainer()) {
766
+ pathNode.parentPath.replaceWith(t.jsxExpressionContainer(wrappedNode));
767
+ return;
768
+ }
769
+ pathNode.replaceWith(wrappedNode);
770
+ }
771
+ },
772
+ JSXOpeningElement(pathNode, state) {
773
+ if (!injectJsxSource) {
774
+ return;
775
+ }
776
+ if (!isCustomComponentTag(pathNode.node.name)) {
777
+ return;
778
+ }
779
+ const rootIdentifierName = getRootJsxIdentifierName(pathNode.node.name);
780
+ if (rootIdentifierName && isExternalToProjectRoot(state.file?.opts?.filename, projectRoot) && isStyledModuleImport(pathNode.scope.getBinding(rootIdentifierName))) {
781
+ return;
782
+ }
783
+ const hasSourceProp = pathNode.node.attributes.some(
784
+ (attr) => t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name) && attr.name.name === JSX_SOURCE_PROP
785
+ );
786
+ if (hasSourceProp) {
787
+ return;
788
+ }
789
+ const filename = state.file?.opts?.filename;
790
+ const loc = pathNode.node.loc?.start;
791
+ if (!filename || !loc) {
792
+ return;
793
+ }
794
+ pathNode.node.attributes.push(
795
+ t.jsxAttribute(
796
+ t.jsxIdentifier(JSX_SOURCE_PROP),
797
+ t.stringLiteral(
798
+ getSourceValue(state, loc, projectRoot) ?? `${filename.replace(/\\/g, "/")}:${loc.line}:${loc.column + 1}`
799
+ )
800
+ )
801
+ );
802
+ },
803
+ Program(programPath, state) {
804
+ if (!injectComponentSource) {
805
+ return;
806
+ }
807
+ const seen = /* @__PURE__ */ new Set();
808
+ for (const childPath of programPath.get("body")) {
809
+ if (childPath.isExportNamedDeclaration() || childPath.isExportDefaultDeclaration()) {
810
+ const declarationPath = childPath.get("declaration");
811
+ if (!Array.isArray(declarationPath) && declarationPath.node) {
812
+ visitDeclaration(declarationPath, childPath, state, seen, projectRoot);
813
+ }
814
+ continue;
815
+ }
816
+ visitDeclaration(childPath, childPath, state, seen, projectRoot);
817
+ }
818
+ }
819
+ }
820
+ };
821
+ }
822
+
823
+ // src/babel.ts
824
+ function createBabelSourceAdapter(options = {}) {
825
+ const resolvedOptions = {
826
+ projectRoot: process.cwd(),
827
+ ...options
828
+ };
829
+ return defineSourceAdapter({
830
+ kind: "babel",
831
+ name: "react-code-locator/babel",
832
+ options: resolvedOptions,
833
+ config: {
834
+ plugins: [[babelInjectComponentSource, resolvedOptions]]
835
+ }
836
+ });
837
+ }
838
+ var babelSourceAdapter = createBabelSourceAdapter();
839
+
840
+ // src/sourceTransform.ts
841
+ import { transformAsync } from "@babel/core";
842
+ async function transformSourceWithLocator(code, options) {
843
+ const { filename, sourceMaps = true, projectRoot = process.cwd(), ...pluginOptions } = options;
844
+ const result = await transformAsync(code, {
845
+ filename,
846
+ babelrc: false,
847
+ configFile: false,
848
+ sourceMaps,
849
+ parserOpts: {
850
+ sourceType: "module",
851
+ plugins: ["jsx", "typescript"]
852
+ },
853
+ generatorOpts: {
854
+ retainLines: true
855
+ },
856
+ plugins: [[babelInjectComponentSource, { ...pluginOptions, projectRoot }]]
857
+ });
858
+ return {
859
+ code: result?.code ?? code,
860
+ map: result?.map ?? null
861
+ };
862
+ }
863
+
864
+ // src/viteClientInjector.ts
865
+ var VIRTUAL_CLIENT_MODULE_ID = "virtual:react-code-locator/client";
866
+ var RESOLVED_VIRTUAL_CLIENT_MODULE_ID = `\0${VIRTUAL_CLIENT_MODULE_ID}`;
867
+ function createClientInjector(locatorOptions = {}) {
868
+ const serialized = JSON.stringify(locatorOptions);
869
+ return {
870
+ name: "react-code-locator-client-injector",
871
+ apply: "serve",
872
+ resolveId(id) {
873
+ if (id === VIRTUAL_CLIENT_MODULE_ID) {
874
+ return RESOLVED_VIRTUAL_CLIENT_MODULE_ID;
875
+ }
876
+ return null;
877
+ },
878
+ load(id) {
879
+ if (id !== RESOLVED_VIRTUAL_CLIENT_MODULE_ID) {
880
+ return null;
881
+ }
882
+ return `
883
+ import { enableReactComponentJump } from "react-code-locator/client";
884
+
885
+ enableReactComponentJump(${serialized});
886
+ `;
887
+ },
888
+ transformIndexHtml() {
889
+ return [
890
+ {
891
+ tag: "script",
892
+ attrs: {
893
+ type: "module",
894
+ src: `/@id/__x00__${VIRTUAL_CLIENT_MODULE_ID}`
895
+ },
896
+ injectTo: "head"
897
+ }
898
+ ];
899
+ }
900
+ };
901
+ }
902
+ function createViteClientInjector(options = {}) {
903
+ const { command = "serve", locator = {}, injectClient = true } = options;
904
+ const isServe = command === "serve";
905
+ return [isServe && injectClient ? createClientInjector(locator) : null].filter(Boolean);
906
+ }
907
+
908
+ // src/vite.ts
909
+ function shouldTransformSource(id) {
910
+ if (id.includes("/node_modules/") || id.startsWith("\0")) {
911
+ return false;
912
+ }
913
+ return /\.[mc]?[jt]sx?$/.test(id);
914
+ }
915
+ function viteSourceTransformPlugin(options = {}) {
916
+ return {
917
+ name: "react-code-locator-source-transform",
918
+ enforce: "pre",
919
+ async transform(code, id) {
920
+ if (!shouldTransformSource(id)) {
921
+ return null;
922
+ }
923
+ return transformSourceWithLocator(code, {
924
+ filename: id,
925
+ ...options
926
+ });
927
+ }
928
+ };
929
+ }
930
+ function createViteSourceAdapter(options = {}) {
931
+ const { babel = {}, ...viteOptions } = options;
932
+ const resolvedBabelOptions = {
933
+ projectRoot: process.cwd(),
934
+ ...babel
935
+ };
936
+ const plugins = [
937
+ viteSourceTransformPlugin(resolvedBabelOptions),
938
+ ...createViteClientInjector(viteOptions)
939
+ ].filter(Boolean);
940
+ return defineSourceAdapter({
941
+ kind: "vite",
942
+ name: "react-code-locator/vite",
943
+ options: {
944
+ ...viteOptions,
945
+ babel: resolvedBabelOptions
946
+ },
947
+ config: {
948
+ plugins
949
+ }
950
+ });
951
+ }
952
+ var viteSourceAdapter = createViteSourceAdapter();
953
+
954
+ // src/esbuild.ts
955
+ import { readFile } from "fs/promises";
956
+ function getEsbuildLoader(filename) {
957
+ if (filename.endsWith(".tsx")) {
958
+ return "tsx";
959
+ }
960
+ if (filename.endsWith(".ts")) {
961
+ return "ts";
962
+ }
963
+ if (filename.endsWith(".jsx")) {
964
+ return "jsx";
965
+ }
966
+ return "js";
967
+ }
968
+ function esbuildSourceTransformPlugin(options = {}) {
969
+ return {
970
+ name: "react-code-locator-source-transform",
971
+ setup(build) {
972
+ build.onLoad({ filter: /\.[mc]?[jt]sx?$/ }, async ({ path }) => {
973
+ if (path.includes("/node_modules/")) {
974
+ return null;
975
+ }
976
+ const code = await readFile(path, "utf8");
977
+ const result = await transformSourceWithLocator(code, {
978
+ filename: path,
979
+ ...options
980
+ });
981
+ return {
982
+ contents: result.code,
983
+ loader: getEsbuildLoader(path)
984
+ };
985
+ });
986
+ }
987
+ };
988
+ }
989
+ function createEsbuildSourceAdapter(options = {}) {
990
+ const resolvedOptions = {
991
+ projectRoot: process.cwd(),
992
+ ...options
993
+ };
994
+ return defineSourceAdapter({
995
+ kind: "esbuild",
996
+ name: "react-code-locator/esbuild",
997
+ options: resolvedOptions,
998
+ config: {
999
+ plugins: [esbuildSourceTransformPlugin(resolvedOptions)]
1000
+ }
1001
+ });
1002
+ }
1003
+ var esbuildSourceAdapter = createEsbuildSourceAdapter();
1004
+
1005
+ // src/swc.ts
1006
+ async function transformSourceWithSwcLocator(code, options) {
1007
+ return transformSourceWithLocator(code, options);
1008
+ }
1009
+ function createSwcSourceAdapter(options = {}) {
1010
+ const resolvedOptions = {
1011
+ projectRoot: process.cwd(),
1012
+ ...options
1013
+ };
1014
+ const transform = (code, transformOptions) => transformSourceWithSwcLocator(code, {
1015
+ ...resolvedOptions,
1016
+ ...transformOptions
1017
+ });
1018
+ return defineSourceAdapter({
1019
+ kind: "swc",
1020
+ name: "react-code-locator/swc",
1021
+ options: resolvedOptions,
1022
+ config: {
1023
+ transform
1024
+ }
1025
+ });
1026
+ }
1027
+ var swcSourceAdapter = createSwcSourceAdapter();
239
1028
  export {
1029
+ babelInjectComponentSource,
1030
+ babelSourceAdapter,
1031
+ createBabelSourceAdapter,
1032
+ createEsbuildSourceAdapter,
1033
+ createSwcSourceAdapter,
1034
+ createViteClientInjector,
1035
+ createViteSourceAdapter,
1036
+ defineSourceAdapter,
240
1037
  enableReactComponentJump,
241
- locateComponentSource
1038
+ esbuildSourceAdapter,
1039
+ locateComponentSource,
1040
+ createViteClientInjector as reactComponentJump,
1041
+ swcSourceAdapter,
1042
+ viteSourceAdapter
242
1043
  };
243
1044
  //# sourceMappingURL=index.js.map