web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

588 lines
20 KiB

  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = createPlugin;
  6. var _pluginSyntaxJsx = _interopRequireDefault(require("@babel/plugin-syntax-jsx"));
  7. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  8. var _core = require("@babel/core");
  9. var _helperModuleImports = require("@babel/helper-module-imports");
  10. var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. const DEFAULT = {
  13. importSource: "react",
  14. runtime: "automatic",
  15. pragma: "React.createElement",
  16. pragmaFrag: "React.Fragment"
  17. };
  18. const JSX_SOURCE_ANNOTATION_REGEX = /\*?\s*@jsxImportSource\s+([^\s]+)/;
  19. const JSX_RUNTIME_ANNOTATION_REGEX = /\*?\s*@jsxRuntime\s+([^\s]+)/;
  20. const JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/;
  21. const JSX_FRAG_ANNOTATION_REGEX = /\*?\s*@jsxFrag\s+([^\s]+)/;
  22. const get = (pass, name) => pass.get(`@babel/plugin-react-jsx/${name}`);
  23. const set = (pass, name, v) => pass.set(`@babel/plugin-react-jsx/${name}`, v);
  24. function createPlugin({
  25. name,
  26. development
  27. }) {
  28. return (0, _helperPluginUtils.declare)((api, options) => {
  29. const {
  30. pure: PURE_ANNOTATION,
  31. throwIfNamespace = true,
  32. filter,
  33. runtime: RUNTIME_DEFAULT = development ? "automatic" : "classic",
  34. importSource: IMPORT_SOURCE_DEFAULT = DEFAULT.importSource,
  35. pragma: PRAGMA_DEFAULT = DEFAULT.pragma,
  36. pragmaFrag: PRAGMA_FRAG_DEFAULT = DEFAULT.pragmaFrag
  37. } = options;
  38. {
  39. var {
  40. useSpread = false,
  41. useBuiltIns = false
  42. } = options;
  43. if (RUNTIME_DEFAULT === "classic") {
  44. if (typeof useSpread !== "boolean") {
  45. throw new Error("transform-react-jsx currently only accepts a boolean option for " + "useSpread (defaults to false)");
  46. }
  47. if (typeof useBuiltIns !== "boolean") {
  48. throw new Error("transform-react-jsx currently only accepts a boolean option for " + "useBuiltIns (defaults to false)");
  49. }
  50. if (useSpread && useBuiltIns) {
  51. throw new Error("transform-react-jsx currently only accepts useBuiltIns or useSpread " + "but not both");
  52. }
  53. }
  54. }
  55. const injectMetaPropertiesVisitor = {
  56. JSXOpeningElement(path, state) {
  57. for (const attr of path.get("attributes")) {
  58. if (!attr.isJSXElement()) continue;
  59. const {
  60. name
  61. } = attr.node.name;
  62. if (name === "__source" || name === "__self") {
  63. throw path.buildCodeFrameError(`__source and __self should not be defined in props and are reserved for internal usage.`);
  64. }
  65. }
  66. const self = _core.types.jsxAttribute(_core.types.jsxIdentifier("__self"), _core.types.jsxExpressionContainer(_core.types.thisExpression()));
  67. const source = _core.types.jsxAttribute(_core.types.jsxIdentifier("__source"), _core.types.jsxExpressionContainer(makeSource(path, state)));
  68. path.pushContainer("attributes", [self, source]);
  69. }
  70. };
  71. return {
  72. name,
  73. inherits: _pluginSyntaxJsx.default,
  74. visitor: {
  75. JSXNamespacedName(path) {
  76. if (throwIfNamespace) {
  77. throw path.buildCodeFrameError(`Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \
  78. You can set \`throwIfNamespace: false\` to bypass this warning.`);
  79. }
  80. },
  81. JSXSpreadChild(path) {
  82. throw path.buildCodeFrameError("Spread children are not supported in React.");
  83. },
  84. Program: {
  85. enter(path, state) {
  86. const {
  87. file
  88. } = state;
  89. let runtime = RUNTIME_DEFAULT;
  90. let source = IMPORT_SOURCE_DEFAULT;
  91. let pragma = PRAGMA_DEFAULT;
  92. let pragmaFrag = PRAGMA_FRAG_DEFAULT;
  93. let sourceSet = !!options.importSource;
  94. let pragmaSet = !!options.pragma;
  95. let pragmaFragSet = !!options.pragmaFrag;
  96. if (file.ast.comments) {
  97. for (const comment of file.ast.comments) {
  98. const sourceMatches = JSX_SOURCE_ANNOTATION_REGEX.exec(comment.value);
  99. if (sourceMatches) {
  100. source = sourceMatches[1];
  101. sourceSet = true;
  102. }
  103. const runtimeMatches = JSX_RUNTIME_ANNOTATION_REGEX.exec(comment.value);
  104. if (runtimeMatches) {
  105. runtime = runtimeMatches[1];
  106. }
  107. const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
  108. if (jsxMatches) {
  109. pragma = jsxMatches[1];
  110. pragmaSet = true;
  111. }
  112. const jsxFragMatches = JSX_FRAG_ANNOTATION_REGEX.exec(comment.value);
  113. if (jsxFragMatches) {
  114. pragmaFrag = jsxFragMatches[1];
  115. pragmaFragSet = true;
  116. }
  117. }
  118. }
  119. set(state, "runtime", runtime);
  120. if (runtime === "classic") {
  121. if (sourceSet) {
  122. throw path.buildCodeFrameError(`importSource cannot be set when runtime is classic.`);
  123. }
  124. const createElement = toMemberExpression(pragma);
  125. const fragment = toMemberExpression(pragmaFrag);
  126. set(state, "id/createElement", () => _core.types.cloneNode(createElement));
  127. set(state, "id/fragment", () => _core.types.cloneNode(fragment));
  128. set(state, "defaultPure", pragma === DEFAULT.pragma);
  129. } else if (runtime === "automatic") {
  130. if (pragmaSet || pragmaFragSet) {
  131. throw path.buildCodeFrameError(`pragma and pragmaFrag cannot be set when runtime is automatic.`);
  132. }
  133. const define = (name, id) => set(state, name, createImportLazily(state, path, id, source));
  134. define("id/jsx", development ? "jsxDEV" : "jsx");
  135. define("id/jsxs", development ? "jsxDEV" : "jsxs");
  136. define("id/createElement", "createElement");
  137. define("id/fragment", "Fragment");
  138. set(state, "defaultPure", source === DEFAULT.importSource);
  139. } else {
  140. throw path.buildCodeFrameError(`Runtime must be either "classic" or "automatic".`);
  141. }
  142. if (development) {
  143. path.traverse(injectMetaPropertiesVisitor, state);
  144. }
  145. }
  146. },
  147. JSXElement: {
  148. exit(path, file) {
  149. let callExpr;
  150. if (get(file, "runtime") === "classic" || shouldUseCreateElement(path)) {
  151. callExpr = buildCreateElementCall(path, file);
  152. } else {
  153. callExpr = buildJSXElementCall(path, file);
  154. }
  155. path.replaceWith(_core.types.inherits(callExpr, path.node));
  156. }
  157. },
  158. JSXFragment: {
  159. exit(path, file) {
  160. let callExpr;
  161. if (get(file, "runtime") === "classic") {
  162. callExpr = buildCreateElementFragmentCall(path, file);
  163. } else {
  164. callExpr = buildJSXFragmentCall(path, file);
  165. }
  166. path.replaceWith(_core.types.inherits(callExpr, path.node));
  167. }
  168. },
  169. JSXAttribute(path) {
  170. if (_core.types.isJSXElement(path.node.value)) {
  171. path.node.value = _core.types.jsxExpressionContainer(path.node.value);
  172. }
  173. }
  174. }
  175. };
  176. function call(pass, name, args) {
  177. const node = _core.types.callExpression(get(pass, `id/${name}`)(), args);
  178. if (PURE_ANNOTATION != null ? PURE_ANNOTATION : get(pass, "defaultPure")) (0, _helperAnnotateAsPure.default)(node);
  179. return node;
  180. }
  181. function shouldUseCreateElement(path) {
  182. const openingPath = path.get("openingElement");
  183. const attributes = openingPath.node.attributes;
  184. let seenPropsSpread = false;
  185. for (let i = 0; i < attributes.length; i++) {
  186. const attr = attributes[i];
  187. if (seenPropsSpread && _core.types.isJSXAttribute(attr) && attr.name.name === "key") {
  188. return true;
  189. } else if (_core.types.isJSXSpreadAttribute(attr)) {
  190. seenPropsSpread = true;
  191. }
  192. }
  193. return false;
  194. }
  195. function convertJSXIdentifier(node, parent) {
  196. if (_core.types.isJSXIdentifier(node)) {
  197. if (node.name === "this" && _core.types.isReferenced(node, parent)) {
  198. return _core.types.thisExpression();
  199. } else if (_core.types.isValidIdentifier(node.name, false)) {
  200. node.type = "Identifier";
  201. } else {
  202. return _core.types.stringLiteral(node.name);
  203. }
  204. } else if (_core.types.isJSXMemberExpression(node)) {
  205. return _core.types.memberExpression(convertJSXIdentifier(node.object, node), convertJSXIdentifier(node.property, node));
  206. } else if (_core.types.isJSXNamespacedName(node)) {
  207. return _core.types.stringLiteral(`${node.namespace.name}:${node.name.name}`);
  208. }
  209. return node;
  210. }
  211. function convertAttributeValue(node) {
  212. if (_core.types.isJSXExpressionContainer(node)) {
  213. return node.expression;
  214. } else {
  215. return node;
  216. }
  217. }
  218. function accumulateAttribute(array, attribute) {
  219. if (_core.types.isJSXSpreadAttribute(attribute.node)) {
  220. const arg = attribute.node.argument;
  221. if (_core.types.isObjectExpression(arg)) {
  222. array.push(...arg.properties);
  223. } else {
  224. array.push(_core.types.spreadElement(arg));
  225. }
  226. return array;
  227. }
  228. const value = convertAttributeValue(attribute.node.name.name !== "key" ? attribute.node.value || _core.types.booleanLiteral(true) : attribute.node.value);
  229. if (attribute.node.name.name === "key" && value === null) {
  230. throw attribute.buildCodeFrameError('Please provide an explicit key value. Using "key" as a shorthand for "key={true}" is not allowed.');
  231. }
  232. if (_core.types.isStringLiteral(value) && !_core.types.isJSXExpressionContainer(attribute.node.value)) {
  233. var _value$extra;
  234. value.value = value.value.replace(/\n\s+/g, " ");
  235. (_value$extra = value.extra) == null ? true : delete _value$extra.raw;
  236. }
  237. if (_core.types.isJSXNamespacedName(attribute.node.name)) {
  238. attribute.node.name = _core.types.stringLiteral(attribute.node.name.namespace.name + ":" + attribute.node.name.name.name);
  239. } else if (_core.types.isValidIdentifier(attribute.node.name.name, false)) {
  240. attribute.node.name.type = "Identifier";
  241. } else {
  242. attribute.node.name = _core.types.stringLiteral(attribute.node.name.name);
  243. }
  244. array.push(_core.types.inherits(_core.types.objectProperty(attribute.node.name, value), attribute.node));
  245. return array;
  246. }
  247. function buildChildrenProperty(children) {
  248. let childrenNode;
  249. if (children.length === 1) {
  250. childrenNode = children[0];
  251. } else if (children.length > 1) {
  252. childrenNode = _core.types.arrayExpression(children);
  253. } else {
  254. return undefined;
  255. }
  256. return _core.types.objectProperty(_core.types.identifier("children"), childrenNode);
  257. }
  258. function buildJSXElementCall(path, file) {
  259. const openingPath = path.get("openingElement");
  260. const args = [getTag(openingPath)];
  261. let attribs = [];
  262. const extracted = Object.create(null);
  263. for (const attr of openingPath.get("attributes")) {
  264. if (attr.isJSXAttribute() && _core.types.isJSXIdentifier(attr.node.name)) {
  265. const {
  266. name
  267. } = attr.node.name;
  268. switch (name) {
  269. case "__source":
  270. case "__self":
  271. if (extracted[name]) throw sourceSelfError(path, name);
  272. case "key":
  273. {
  274. const keyValue = convertAttributeValue(attr.node.value);
  275. if (keyValue === null) {
  276. throw attr.buildCodeFrameError('Please provide an explicit key value. Using "key" as a shorthand for "key={true}" is not allowed.');
  277. }
  278. extracted[name] = keyValue;
  279. break;
  280. }
  281. default:
  282. attribs.push(attr);
  283. }
  284. } else {
  285. attribs.push(attr);
  286. }
  287. }
  288. const children = _core.types.react.buildChildren(path.node);
  289. if (attribs.length || children.length) {
  290. attribs = buildJSXOpeningElementAttributes(attribs, file, children);
  291. } else {
  292. attribs = _core.types.objectExpression([]);
  293. }
  294. args.push(attribs);
  295. if (development) {
  296. var _extracted$key, _extracted$__source, _extracted$__self;
  297. args.push((_extracted$key = extracted.key) != null ? _extracted$key : path.scope.buildUndefinedNode(), _core.types.booleanLiteral(children.length > 1), (_extracted$__source = extracted.__source) != null ? _extracted$__source : path.scope.buildUndefinedNode(), (_extracted$__self = extracted.__self) != null ? _extracted$__self : _core.types.thisExpression());
  298. } else if (extracted.key !== undefined) {
  299. args.push(extracted.key);
  300. }
  301. return call(file, children.length > 1 ? "jsxs" : "jsx", args);
  302. }
  303. function buildJSXOpeningElementAttributes(attribs, file, children) {
  304. const props = attribs.reduce(accumulateAttribute, []);
  305. if ((children == null ? void 0 : children.length) > 0) {
  306. props.push(buildChildrenProperty(children));
  307. }
  308. return _core.types.objectExpression(props);
  309. }
  310. function buildJSXFragmentCall(path, file) {
  311. const args = [get(file, "id/fragment")()];
  312. const children = _core.types.react.buildChildren(path.node);
  313. args.push(_core.types.objectExpression(children.length > 0 ? [buildChildrenProperty(children)] : []));
  314. if (development) {
  315. args.push(path.scope.buildUndefinedNode(), _core.types.booleanLiteral(children.length > 1));
  316. }
  317. return call(file, children.length > 1 ? "jsxs" : "jsx", args);
  318. }
  319. function buildCreateElementFragmentCall(path, file) {
  320. if (filter && !filter(path.node, file)) return;
  321. return call(file, "createElement", [get(file, "id/fragment")(), _core.types.nullLiteral(), ..._core.types.react.buildChildren(path.node)]);
  322. }
  323. function buildCreateElementCall(path, file) {
  324. const openingPath = path.get("openingElement");
  325. return call(file, "createElement", [getTag(openingPath), buildCreateElementOpeningElementAttributes(file, path, openingPath.get("attributes")), ..._core.types.react.buildChildren(path.node)]);
  326. }
  327. function getTag(openingPath) {
  328. const tagExpr = convertJSXIdentifier(openingPath.node.name, openingPath.node);
  329. let tagName;
  330. if (_core.types.isIdentifier(tagExpr)) {
  331. tagName = tagExpr.name;
  332. } else if (_core.types.isLiteral(tagExpr)) {
  333. tagName = tagExpr.value;
  334. }
  335. if (_core.types.react.isCompatTag(tagName)) {
  336. return _core.types.stringLiteral(tagName);
  337. } else {
  338. return tagExpr;
  339. }
  340. }
  341. function buildCreateElementOpeningElementAttributes(file, path, attribs) {
  342. const runtime = get(file, "runtime");
  343. {
  344. if (runtime !== "automatic") {
  345. const objs = [];
  346. const props = attribs.reduce(accumulateAttribute, []);
  347. if (!useSpread) {
  348. let start = 0;
  349. props.forEach((prop, i) => {
  350. if (_core.types.isSpreadElement(prop)) {
  351. if (i > start) {
  352. objs.push(_core.types.objectExpression(props.slice(start, i)));
  353. }
  354. objs.push(prop.argument);
  355. start = i + 1;
  356. }
  357. });
  358. if (props.length > start) {
  359. objs.push(_core.types.objectExpression(props.slice(start)));
  360. }
  361. } else if (props.length) {
  362. objs.push(_core.types.objectExpression(props));
  363. }
  364. if (!objs.length) {
  365. return _core.types.nullLiteral();
  366. }
  367. if (objs.length === 1) {
  368. return objs[0];
  369. }
  370. if (!_core.types.isObjectExpression(objs[0])) {
  371. objs.unshift(_core.types.objectExpression([]));
  372. }
  373. const helper = useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
  374. return _core.types.callExpression(helper, objs);
  375. }
  376. }
  377. const props = [];
  378. const found = Object.create(null);
  379. for (const attr of attribs) {
  380. const name = _core.types.isJSXAttribute(attr) && _core.types.isJSXIdentifier(attr.name) && attr.name.name;
  381. if (runtime === "automatic" && (name === "__source" || name === "__self")) {
  382. if (found[name]) throw sourceSelfError(path, name);
  383. found[name] = true;
  384. }
  385. accumulateAttribute(props, attr);
  386. }
  387. return props.length === 1 && _core.types.isSpreadElement(props[0]) ? props[0].argument : props.length > 0 ? _core.types.objectExpression(props) : _core.types.nullLiteral();
  388. }
  389. });
  390. function getSource(source, importName) {
  391. switch (importName) {
  392. case "Fragment":
  393. return `${source}/${development ? "jsx-dev-runtime" : "jsx-runtime"}`;
  394. case "jsxDEV":
  395. return `${source}/jsx-dev-runtime`;
  396. case "jsx":
  397. case "jsxs":
  398. return `${source}/jsx-runtime`;
  399. case "createElement":
  400. return source;
  401. }
  402. }
  403. function createImportLazily(pass, path, importName, source) {
  404. return () => {
  405. const actualSource = getSource(source, importName);
  406. if ((0, _helperModuleImports.isModule)(path)) {
  407. let reference = get(pass, `imports/${importName}`);
  408. if (reference) return _core.types.cloneNode(reference);
  409. reference = (0, _helperModuleImports.addNamed)(path, importName, actualSource, {
  410. importedInterop: "uncompiled",
  411. importPosition: "after"
  412. });
  413. set(pass, `imports/${importName}`, reference);
  414. return reference;
  415. } else {
  416. let reference = get(pass, `requires/${actualSource}`);
  417. if (reference) {
  418. reference = _core.types.cloneNode(reference);
  419. } else {
  420. reference = (0, _helperModuleImports.addNamespace)(path, actualSource, {
  421. importedInterop: "uncompiled"
  422. });
  423. set(pass, `requires/${actualSource}`, reference);
  424. }
  425. return _core.types.memberExpression(reference, _core.types.identifier(importName));
  426. }
  427. };
  428. }
  429. }
  430. function toMemberExpression(id) {
  431. return id.split(".").map(name => _core.types.identifier(name)).reduce((object, property) => _core.types.memberExpression(object, property));
  432. }
  433. function makeSource(path, state) {
  434. const location = path.node.loc;
  435. if (!location) {
  436. return path.scope.buildUndefinedNode();
  437. }
  438. if (!state.fileNameIdentifier) {
  439. const {
  440. filename = ""
  441. } = state;
  442. const fileNameIdentifier = path.scope.generateUidIdentifier("_jsxFileName");
  443. const scope = path.hub.getScope();
  444. if (scope) {
  445. scope.push({
  446. id: fileNameIdentifier,
  447. init: _core.types.stringLiteral(filename)
  448. });
  449. }
  450. state.fileNameIdentifier = fileNameIdentifier;
  451. }
  452. return makeTrace(_core.types.cloneNode(state.fileNameIdentifier), location.start.line, location.start.column);
  453. }
  454. function makeTrace(fileNameIdentifier, lineNumber, column0Based) {
  455. const fileLineLiteral = lineNumber != null ? _core.types.numericLiteral(lineNumber) : _core.types.nullLiteral();
  456. const fileColumnLiteral = column0Based != null ? _core.types.numericLiteral(column0Based + 1) : _core.types.nullLiteral();
  457. const fileNameProperty = _core.types.objectProperty(_core.types.identifier("fileName"), fileNameIdentifier);
  458. const lineNumberProperty = _core.types.objectProperty(_core.types.identifier("lineNumber"), fileLineLiteral);
  459. const columnNumberProperty = _core.types.objectProperty(_core.types.identifier("columnNumber"), fileColumnLiteral);
  460. return _core.types.objectExpression([fileNameProperty, lineNumberProperty, columnNumberProperty]);
  461. }
  462. function sourceSelfError(path, name) {
  463. const pluginName = `transform-react-jsx-${name.slice(2)}`;
  464. return path.buildCodeFrameError(`Duplicate ${name} prop found. You are most likely using the deprecated ${pluginName} Babel plugin. Both __source and __self are automatically set when using the automatic runtime. Please remove transform-react-jsx-source and transform-react-jsx-self from your Babel config.`);
  465. }