index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _core = require("@babel/core");
  8. const TRACE_ID = "__source";
  9. const FILE_NAME_VAR = "_jsxFileName";
  10. const createNodeFromNullish = (val, fn) => val == null ? _core.types.nullLiteral() : fn(val);
  11. var _default = exports.default = (0, _helperPluginUtils.declare)(api => {
  12. api.assertVersion(7);
  13. function makeTrace(fileNameIdentifier, {
  14. line,
  15. column
  16. }) {
  17. const fileLineLiteral = createNodeFromNullish(line, _core.types.numericLiteral);
  18. const fileColumnLiteral = createNodeFromNullish(column, c => _core.types.numericLiteral(c + 1));
  19. return _core.template.expression.ast`{
  20. fileName: ${fileNameIdentifier},
  21. lineNumber: ${fileLineLiteral},
  22. columnNumber: ${fileColumnLiteral},
  23. }`;
  24. }
  25. const isSourceAttr = attr => _core.types.isJSXAttribute(attr) && attr.name.name === TRACE_ID;
  26. return {
  27. name: "transform-react-jsx-source",
  28. visitor: {
  29. JSXOpeningElement(path, state) {
  30. const {
  31. node
  32. } = path;
  33. if (!node.loc || path.node.attributes.some(isSourceAttr)) {
  34. return;
  35. }
  36. if (!state.fileNameIdentifier) {
  37. const fileNameId = path.scope.generateUidIdentifier(FILE_NAME_VAR);
  38. state.fileNameIdentifier = fileNameId;
  39. path.scope.getProgramParent().push({
  40. id: fileNameId,
  41. init: _core.types.stringLiteral(state.filename || "")
  42. });
  43. }
  44. node.attributes.push(_core.types.jsxAttribute(_core.types.jsxIdentifier(TRACE_ID), _core.types.jsxExpressionContainer(makeTrace(_core.types.cloneNode(state.fileNameIdentifier), node.loc.start))));
  45. }
  46. }
  47. };
  48. });
  49. //# sourceMappingURL=index.js.map