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.

1012 lines
34 KiB

3 months ago
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __defProps = Object.defineProperties;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  7. var __getOwnPropNames = Object.getOwnPropertyNames;
  8. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  9. var __getProtoOf = Object.getPrototypeOf;
  10. var __hasOwnProp = Object.prototype.hasOwnProperty;
  11. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  12. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  13. var __spreadValues = (a, b) => {
  14. for (var prop in b || (b = {}))
  15. if (__hasOwnProp.call(b, prop))
  16. __defNormalProp(a, prop, b[prop]);
  17. if (__getOwnPropSymbols)
  18. for (var prop of __getOwnPropSymbols(b)) {
  19. if (__propIsEnum.call(b, prop))
  20. __defNormalProp(a, prop, b[prop]);
  21. }
  22. return a;
  23. };
  24. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  25. var __export = (target, all) => {
  26. for (var name in all)
  27. __defProp(target, name, { get: all[name], enumerable: true });
  28. };
  29. var __copyProps = (to, from, except, desc) => {
  30. if (from && typeof from === "object" || typeof from === "function") {
  31. for (let key of __getOwnPropNames(from))
  32. if (!__hasOwnProp.call(to, key) && key !== except)
  33. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  34. }
  35. return to;
  36. };
  37. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  38. // If the importer is in node compatibility mode or this is not an ESM
  39. // file that has been converted to a CommonJS file using a Babel-
  40. // compatible transform (i.e. "__esModule" has not been set), then set
  41. // "default" to the CommonJS "module.exports" for node compatibility.
  42. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  43. mod
  44. ));
  45. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  46. // src/index.ts
  47. var src_exports = {};
  48. __export(src_exports, {
  49. default: () => src_default
  50. });
  51. module.exports = __toCommonJS(src_exports);
  52. var t5 = __toESM(require("@babel/types"));
  53. var import_template = __toESM(require("@babel/template"));
  54. var import_plugin_syntax_jsx = __toESM(require("@babel/plugin-syntax-jsx"));
  55. var import_helper_module_imports2 = require("@babel/helper-module-imports");
  56. var import_babel_plugin_resolve_type = __toESM(require("@vue/babel-plugin-resolve-type"));
  57. var import_helper_plugin_utils = require("@babel/helper-plugin-utils");
  58. // src/transform-vue-jsx.ts
  59. var t3 = __toESM(require("@babel/types"));
  60. var import_helper_module_imports = require("@babel/helper-module-imports");
  61. // src/utils.ts
  62. var t = __toESM(require("@babel/types"));
  63. var import_html_tags = __toESM(require("html-tags"));
  64. var import_svg_tags = __toESM(require("svg-tags"));
  65. // src/slotFlags.ts
  66. var SlotFlags = /* @__PURE__ */ ((SlotFlags2) => {
  67. SlotFlags2[SlotFlags2["STABLE"] = 1] = "STABLE";
  68. SlotFlags2[SlotFlags2["DYNAMIC"] = 2] = "DYNAMIC";
  69. SlotFlags2[SlotFlags2["FORWARDED"] = 3] = "FORWARDED";
  70. return SlotFlags2;
  71. })(SlotFlags || {});
  72. var slotFlags_default = SlotFlags;
  73. // src/utils.ts
  74. var FRAGMENT = "Fragment";
  75. var KEEP_ALIVE = "KeepAlive";
  76. var createIdentifier = (state, name) => state.get(name)();
  77. var isDirective = (src) => src.startsWith("v-") || src.startsWith("v") && src.length >= 2 && src[1] >= "A" && src[1] <= "Z";
  78. var shouldTransformedToSlots = (tag) => !(tag.match(RegExp(`^_?${FRAGMENT}\\d*$`)) || tag === KEEP_ALIVE);
  79. var checkIsComponent = (path, state) => {
  80. var _a, _b;
  81. const namePath = path.get("name");
  82. if (namePath.isJSXMemberExpression()) {
  83. return shouldTransformedToSlots(namePath.node.property.name);
  84. }
  85. const tag = namePath.node.name;
  86. return !((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, tag)) && shouldTransformedToSlots(tag) && !import_html_tags.default.includes(tag) && !import_svg_tags.default.includes(tag);
  87. };
  88. var transformJSXMemberExpression = (path) => {
  89. const objectPath = path.node.object;
  90. const propertyPath = path.node.property;
  91. const transformedObject = t.isJSXMemberExpression(objectPath) ? transformJSXMemberExpression(
  92. path.get("object")
  93. ) : t.isJSXIdentifier(objectPath) ? t.identifier(objectPath.name) : t.nullLiteral();
  94. const transformedProperty = t.identifier(propertyPath.name);
  95. return t.memberExpression(transformedObject, transformedProperty);
  96. };
  97. var getTag = (path, state) => {
  98. var _a, _b;
  99. const namePath = path.get("openingElement").get("name");
  100. if (namePath.isJSXIdentifier()) {
  101. const { name } = namePath.node;
  102. if (!import_html_tags.default.includes(name) && !import_svg_tags.default.includes(name)) {
  103. return name === FRAGMENT ? createIdentifier(state, FRAGMENT) : path.scope.hasBinding(name) ? t.identifier(name) : ((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, name)) ? t.stringLiteral(name) : t.callExpression(createIdentifier(state, "resolveComponent"), [
  104. t.stringLiteral(name)
  105. ]);
  106. }
  107. return t.stringLiteral(name);
  108. }
  109. if (namePath.isJSXMemberExpression()) {
  110. return transformJSXMemberExpression(namePath);
  111. }
  112. throw new Error(`getTag: ${namePath.type} is not supported`);
  113. };
  114. var getJSXAttributeName = (path) => {
  115. const nameNode = path.node.name;
  116. if (t.isJSXIdentifier(nameNode)) {
  117. return nameNode.name;
  118. }
  119. return `${nameNode.namespace.name}:${nameNode.name.name}`;
  120. };
  121. var transformJSXText = (path) => {
  122. const str = transformText(path.node.value);
  123. return str !== "" ? t.stringLiteral(str) : null;
  124. };
  125. var transformText = (text) => {
  126. const lines = text.split(/\r\n|\n|\r/);
  127. let lastNonEmptyLine = 0;
  128. for (let i = 0; i < lines.length; i++) {
  129. if (lines[i].match(/[^ \t]/)) {
  130. lastNonEmptyLine = i;
  131. }
  132. }
  133. let str = "";
  134. for (let i = 0; i < lines.length; i++) {
  135. const line = lines[i];
  136. const isFirstLine = i === 0;
  137. const isLastLine = i === lines.length - 1;
  138. const isLastNonEmptyLine = i === lastNonEmptyLine;
  139. let trimmedLine = line.replace(/\t/g, " ");
  140. if (!isFirstLine) {
  141. trimmedLine = trimmedLine.replace(/^[ ]+/, "");
  142. }
  143. if (!isLastLine) {
  144. trimmedLine = trimmedLine.replace(/[ ]+$/, "");
  145. }
  146. if (trimmedLine) {
  147. if (!isLastNonEmptyLine) {
  148. trimmedLine += " ";
  149. }
  150. str += trimmedLine;
  151. }
  152. }
  153. return str;
  154. };
  155. var transformJSXExpressionContainer = (path) => path.get("expression").node;
  156. var transformJSXSpreadChild = (path) => t.spreadElement(path.get("expression").node);
  157. var walksScope = (path, name, slotFlag) => {
  158. if (path.scope.hasBinding(name) && path.parentPath) {
  159. if (t.isJSXElement(path.parentPath.node)) {
  160. path.parentPath.setData("slotFlag", slotFlag);
  161. }
  162. walksScope(path.parentPath, name, slotFlag);
  163. }
  164. };
  165. var buildIIFE = (path, children) => {
  166. const { parentPath } = path;
  167. if (parentPath.isAssignmentExpression()) {
  168. const { left } = parentPath.node;
  169. if (t.isIdentifier(left)) {
  170. return children.map((child) => {
  171. if (t.isIdentifier(child) && child.name === left.name) {
  172. const insertName = path.scope.generateUidIdentifier(child.name);
  173. parentPath.insertBefore(
  174. t.variableDeclaration("const", [
  175. t.variableDeclarator(
  176. insertName,
  177. t.callExpression(
  178. t.functionExpression(
  179. null,
  180. [],
  181. t.blockStatement([t.returnStatement(child)])
  182. ),
  183. []
  184. )
  185. )
  186. ])
  187. );
  188. return insertName;
  189. }
  190. return child;
  191. });
  192. }
  193. }
  194. return children;
  195. };
  196. var onRE = /^on[^a-z]/;
  197. var isOn = (key) => onRE.test(key);
  198. var mergeAsArray = (existing, incoming) => {
  199. if (t.isArrayExpression(existing.value)) {
  200. existing.value.elements.push(incoming.value);
  201. } else {
  202. existing.value = t.arrayExpression([
  203. existing.value,
  204. incoming.value
  205. ]);
  206. }
  207. };
  208. var dedupeProperties = (properties = [], mergeProps) => {
  209. if (!mergeProps) {
  210. return properties;
  211. }
  212. const knownProps = /* @__PURE__ */ new Map();
  213. const deduped = [];
  214. properties.forEach((prop) => {
  215. if (t.isStringLiteral(prop.key)) {
  216. const { value: name } = prop.key;
  217. const existing = knownProps.get(name);
  218. if (existing) {
  219. if (name === "style" || name === "class" || name.startsWith("on")) {
  220. mergeAsArray(existing, prop);
  221. }
  222. } else {
  223. knownProps.set(name, prop);
  224. deduped.push(prop);
  225. }
  226. } else {
  227. deduped.push(prop);
  228. }
  229. });
  230. return deduped;
  231. };
  232. var isConstant = (node) => {
  233. if (t.isIdentifier(node)) {
  234. return node.name === "undefined";
  235. }
  236. if (t.isArrayExpression(node)) {
  237. const { elements } = node;
  238. return elements.every((element) => element && isConstant(element));
  239. }
  240. if (t.isObjectExpression(node)) {
  241. return node.properties.every(
  242. (property) => isConstant(property.value)
  243. );
  244. }
  245. if (t.isLiteral(node)) {
  246. return true;
  247. }
  248. return false;
  249. };
  250. var transformJSXSpreadAttribute = (nodePath, path, mergeProps, args) => {
  251. const argument = path.get("argument");
  252. const properties = t.isObjectExpression(argument.node) ? argument.node.properties : void 0;
  253. if (!properties) {
  254. if (argument.isIdentifier()) {
  255. walksScope(
  256. nodePath,
  257. argument.node.name,
  258. slotFlags_default.DYNAMIC
  259. );
  260. }
  261. args.push(mergeProps ? argument.node : t.spreadElement(argument.node));
  262. } else if (mergeProps) {
  263. args.push(t.objectExpression(properties));
  264. } else {
  265. args.push(...properties);
  266. }
  267. };
  268. // src/parseDirectives.ts
  269. var t2 = __toESM(require("@babel/types"));
  270. var getType = (path) => {
  271. const typePath = path.get("attributes").find((attribute) => {
  272. if (!attribute.isJSXAttribute()) {
  273. return false;
  274. }
  275. return attribute.get("name").isJSXIdentifier() && attribute.get("name").node.name === "type";
  276. });
  277. return typePath ? typePath.get("value").node : null;
  278. };
  279. var parseModifiers = (value) => t2.isArrayExpression(value) ? value.elements.map((el) => t2.isStringLiteral(el) ? el.value : "").filter(Boolean) : [];
  280. var parseDirectives = (params) => {
  281. var _a, _b;
  282. const { path, value, state, tag, isComponent } = params;
  283. const args = [];
  284. const vals = [];
  285. const modifiersSet = [];
  286. let directiveName;
  287. let directiveArgument;
  288. let directiveModifiers;
  289. if ("namespace" in path.node.name) {
  290. [directiveName, directiveArgument] = params.name.split(":");
  291. directiveName = path.node.name.namespace.name;
  292. directiveArgument = path.node.name.name.name;
  293. directiveModifiers = directiveArgument.split("_").slice(1);
  294. } else {
  295. const underscoreModifiers = params.name.split("_");
  296. directiveName = underscoreModifiers.shift() || "";
  297. directiveModifiers = underscoreModifiers;
  298. }
  299. directiveName = directiveName.replace(/^v/, "").replace(/^-/, "").replace(/^\S/, (s) => s.toLowerCase());
  300. if (directiveArgument) {
  301. args.push(t2.stringLiteral(directiveArgument.split("_")[0]));
  302. }
  303. const isVModels = directiveName === "models";
  304. const isVModel = directiveName === "model";
  305. if (isVModel && !path.get("value").isJSXExpressionContainer()) {
  306. throw new Error("You have to use JSX Expression inside your v-model");
  307. }
  308. if (isVModels && !isComponent) {
  309. throw new Error("v-models can only use in custom components");
  310. }
  311. const shouldResolve = !["html", "text", "model", "slots", "models"].includes(directiveName) || isVModel && !isComponent;
  312. let modifiers = directiveModifiers;
  313. if (t2.isArrayExpression(value)) {
  314. const elementsList = isVModels ? value.elements : [value];
  315. elementsList.forEach((element) => {
  316. if (isVModels && !t2.isArrayExpression(element)) {
  317. throw new Error("You should pass a Two-dimensional Arrays to v-models");
  318. }
  319. const { elements } = element;
  320. const [first, second, third] = elements;
  321. if (second && !t2.isArrayExpression(second) && !t2.isSpreadElement(second)) {
  322. args.push(second);
  323. modifiers = parseModifiers(third);
  324. } else if (t2.isArrayExpression(second)) {
  325. if (!shouldResolve) {
  326. args.push(t2.nullLiteral());
  327. }
  328. modifiers = parseModifiers(second);
  329. } else if (!shouldResolve) {
  330. args.push(t2.nullLiteral());
  331. }
  332. modifiersSet.push(new Set(modifiers));
  333. vals.push(first);
  334. });
  335. } else if (isVModel && !shouldResolve) {
  336. args.push(t2.nullLiteral());
  337. modifiersSet.push(new Set(directiveModifiers));
  338. } else {
  339. modifiersSet.push(new Set(directiveModifiers));
  340. }
  341. return {
  342. directiveName,
  343. modifiers: modifiersSet,
  344. values: vals.length ? vals : [value],
  345. args,
  346. directive: shouldResolve ? [
  347. resolveDirective(path, state, tag, directiveName),
  348. vals[0] || value,
  349. ((_a = modifiersSet[0]) == null ? void 0 : _a.size) ? args[0] || t2.unaryExpression("void", t2.numericLiteral(0), true) : args[0],
  350. !!((_b = modifiersSet[0]) == null ? void 0 : _b.size) && t2.objectExpression(
  351. [...modifiersSet[0]].map(
  352. (modifier) => t2.objectProperty(t2.identifier(modifier), t2.booleanLiteral(true))
  353. )
  354. )
  355. ].filter(Boolean) : void 0
  356. };
  357. };
  358. var resolveDirective = (path, state, tag, directiveName) => {
  359. if (directiveName === "show") {
  360. return createIdentifier(state, "vShow");
  361. }
  362. if (directiveName === "model") {
  363. let modelToUse;
  364. const type = getType(path.parentPath);
  365. switch (tag.value) {
  366. case "select":
  367. modelToUse = createIdentifier(state, "vModelSelect");
  368. break;
  369. case "textarea":
  370. modelToUse = createIdentifier(state, "vModelText");
  371. break;
  372. default:
  373. if (t2.isStringLiteral(type) || !type) {
  374. switch (type == null ? void 0 : type.value) {
  375. case "checkbox":
  376. modelToUse = createIdentifier(state, "vModelCheckbox");
  377. break;
  378. case "radio":
  379. modelToUse = createIdentifier(state, "vModelRadio");
  380. break;
  381. default:
  382. modelToUse = createIdentifier(state, "vModelText");
  383. }
  384. } else {
  385. modelToUse = createIdentifier(state, "vModelDynamic");
  386. }
  387. }
  388. return modelToUse;
  389. }
  390. return t2.callExpression(createIdentifier(state, "resolveDirective"), [
  391. t2.stringLiteral(directiveName)
  392. ]);
  393. };
  394. var parseDirectives_default = parseDirectives;
  395. // src/transform-vue-jsx.ts
  396. var xlinkRE = /^xlink([A-Z])/;
  397. var getJSXAttributeValue = (path, state) => {
  398. const valuePath = path.get("value");
  399. if (valuePath.isJSXElement()) {
  400. return transformJSXElement(valuePath, state);
  401. }
  402. if (valuePath.isStringLiteral()) {
  403. return t3.stringLiteral(transformText(valuePath.node.value));
  404. }
  405. if (valuePath.isJSXExpressionContainer()) {
  406. return transformJSXExpressionContainer(valuePath);
  407. }
  408. return null;
  409. };
  410. var buildProps = (path, state) => {
  411. const tag = getTag(path, state);
  412. const isComponent = checkIsComponent(path.get("openingElement"), state);
  413. const props = path.get("openingElement").get("attributes");
  414. const directives = [];
  415. const dynamicPropNames = /* @__PURE__ */ new Set();
  416. let slots = null;
  417. let patchFlag = 0;
  418. if (props.length === 0) {
  419. return {
  420. tag,
  421. isComponent,
  422. slots,
  423. props: t3.nullLiteral(),
  424. directives,
  425. patchFlag,
  426. dynamicPropNames
  427. };
  428. }
  429. let properties = [];
  430. let hasRef = false;
  431. let hasClassBinding = false;
  432. let hasStyleBinding = false;
  433. let hasHydrationEventBinding = false;
  434. let hasDynamicKeys = false;
  435. const mergeArgs = [];
  436. const { mergeProps = true } = state.opts;
  437. props.forEach((prop) => {
  438. if (prop.isJSXAttribute()) {
  439. let name = getJSXAttributeName(prop);
  440. const attributeValue = getJSXAttributeValue(prop, state);
  441. if (!isConstant(attributeValue) || name === "ref") {
  442. if (!isComponent && isOn(name) && // omit the flag for click handlers becaues hydration gives click
  443. // dedicated fast path.
  444. name.toLowerCase() !== "onclick" && // omit v-model handlers
  445. name !== "onUpdate:modelValue") {
  446. hasHydrationEventBinding = true;
  447. }
  448. if (name === "ref") {
  449. hasRef = true;
  450. } else if (name === "class" && !isComponent) {
  451. hasClassBinding = true;
  452. } else if (name === "style" && !isComponent) {
  453. hasStyleBinding = true;
  454. } else if (name !== "key" && !isDirective(name) && name !== "on") {
  455. dynamicPropNames.add(name);
  456. }
  457. }
  458. if (state.opts.transformOn && (name === "on" || name === "nativeOn")) {
  459. if (!state.get("transformOn")) {
  460. state.set(
  461. "transformOn",
  462. (0, import_helper_module_imports.addDefault)(path, "@vue/babel-helper-vue-transform-on", {
  463. nameHint: "_transformOn"
  464. })
  465. );
  466. }
  467. mergeArgs.push(
  468. t3.callExpression(state.get("transformOn"), [
  469. attributeValue || t3.booleanLiteral(true)
  470. ])
  471. );
  472. return;
  473. }
  474. if (isDirective(name)) {
  475. const { directive, modifiers, values, args, directiveName } = parseDirectives_default({
  476. tag,
  477. isComponent,
  478. name,
  479. path: prop,
  480. state,
  481. value: attributeValue
  482. });
  483. if (directiveName === "slots") {
  484. slots = attributeValue;
  485. return;
  486. }
  487. if (directive) {
  488. directives.push(t3.arrayExpression(directive));
  489. } else if (directiveName === "html") {
  490. properties.push(
  491. t3.objectProperty(t3.stringLiteral("innerHTML"), values[0])
  492. );
  493. dynamicPropNames.add("innerHTML");
  494. } else if (directiveName === "text") {
  495. properties.push(
  496. t3.objectProperty(t3.stringLiteral("textContent"), values[0])
  497. );
  498. dynamicPropNames.add("textContent");
  499. }
  500. if (["models", "model"].includes(directiveName)) {
  501. values.forEach((value, index) => {
  502. var _a;
  503. const propName = args[index];
  504. const isDynamic = propName && !t3.isStringLiteral(propName) && !t3.isNullLiteral(propName);
  505. if (!directive) {
  506. properties.push(
  507. t3.objectProperty(
  508. t3.isNullLiteral(propName) ? t3.stringLiteral("modelValue") : propName,
  509. value,
  510. isDynamic
  511. )
  512. );
  513. if (!isDynamic) {
  514. dynamicPropNames.add(
  515. (propName == null ? void 0 : propName.value) || "modelValue"
  516. );
  517. }
  518. if ((_a = modifiers[index]) == null ? void 0 : _a.size) {
  519. properties.push(
  520. t3.objectProperty(
  521. isDynamic ? t3.binaryExpression(
  522. "+",
  523. propName,
  524. t3.stringLiteral("Modifiers")
  525. ) : t3.stringLiteral(
  526. `${(propName == null ? void 0 : propName.value) || "model"}Modifiers`
  527. ),
  528. t3.objectExpression(
  529. [...modifiers[index]].map(
  530. (modifier) => t3.objectProperty(
  531. t3.stringLiteral(modifier),
  532. t3.booleanLiteral(true)
  533. )
  534. )
  535. ),
  536. isDynamic
  537. )
  538. );
  539. }
  540. }
  541. const updateName = isDynamic ? t3.binaryExpression("+", t3.stringLiteral("onUpdate:"), propName) : t3.stringLiteral(
  542. `onUpdate:${(propName == null ? void 0 : propName.value) || "modelValue"}`
  543. );
  544. properties.push(
  545. t3.objectProperty(
  546. updateName,
  547. t3.arrowFunctionExpression(
  548. [t3.identifier("$event")],
  549. t3.assignmentExpression(
  550. "=",
  551. value,
  552. t3.identifier("$event")
  553. )
  554. ),
  555. isDynamic
  556. )
  557. );
  558. if (!isDynamic) {
  559. dynamicPropNames.add(updateName.value);
  560. } else {
  561. hasDynamicKeys = true;
  562. }
  563. });
  564. }
  565. } else {
  566. if (name.match(xlinkRE)) {
  567. name = name.replace(
  568. xlinkRE,
  569. (_, firstCharacter) => `xlink:${firstCharacter.toLowerCase()}`
  570. );
  571. }
  572. properties.push(
  573. t3.objectProperty(
  574. t3.stringLiteral(name),
  575. attributeValue || t3.booleanLiteral(true)
  576. )
  577. );
  578. }
  579. } else {
  580. if (properties.length && mergeProps) {
  581. mergeArgs.push(
  582. t3.objectExpression(dedupeProperties(properties, mergeProps))
  583. );
  584. properties = [];
  585. }
  586. hasDynamicKeys = true;
  587. transformJSXSpreadAttribute(
  588. path,
  589. prop,
  590. mergeProps,
  591. mergeProps ? mergeArgs : properties
  592. );
  593. }
  594. });
  595. if (hasDynamicKeys) {
  596. patchFlag |= 16 /* FULL_PROPS */;
  597. } else {
  598. if (hasClassBinding) {
  599. patchFlag |= 2 /* CLASS */;
  600. }
  601. if (hasStyleBinding) {
  602. patchFlag |= 4 /* STYLE */;
  603. }
  604. if (dynamicPropNames.size) {
  605. patchFlag |= 8 /* PROPS */;
  606. }
  607. if (hasHydrationEventBinding) {
  608. patchFlag |= 32 /* HYDRATE_EVENTS */;
  609. }
  610. }
  611. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) && (hasRef || directives.length > 0)) {
  612. patchFlag |= 512 /* NEED_PATCH */;
  613. }
  614. let propsExpression = t3.nullLiteral();
  615. if (mergeArgs.length) {
  616. if (properties.length) {
  617. mergeArgs.push(
  618. t3.objectExpression(dedupeProperties(properties, mergeProps))
  619. );
  620. }
  621. if (mergeArgs.length > 1) {
  622. propsExpression = t3.callExpression(
  623. createIdentifier(state, "mergeProps"),
  624. mergeArgs
  625. );
  626. } else {
  627. propsExpression = mergeArgs[0];
  628. }
  629. } else if (properties.length) {
  630. if (properties.length === 1 && t3.isSpreadElement(properties[0])) {
  631. propsExpression = properties[0].argument;
  632. } else {
  633. propsExpression = t3.objectExpression(
  634. dedupeProperties(properties, mergeProps)
  635. );
  636. }
  637. }
  638. return {
  639. tag,
  640. props: propsExpression,
  641. isComponent,
  642. slots,
  643. directives,
  644. patchFlag,
  645. dynamicPropNames
  646. };
  647. };
  648. var getChildren = (paths, state) => paths.map((path) => {
  649. if (path.isJSXText()) {
  650. const transformedText = transformJSXText(path);
  651. if (transformedText) {
  652. return t3.callExpression(createIdentifier(state, "createTextVNode"), [
  653. transformedText
  654. ]);
  655. }
  656. return transformedText;
  657. }
  658. if (path.isJSXExpressionContainer()) {
  659. const expression = transformJSXExpressionContainer(path);
  660. if (t3.isIdentifier(expression)) {
  661. const { name } = expression;
  662. const { referencePaths = [] } = path.scope.getBinding(name) || {};
  663. referencePaths.forEach((referencePath) => {
  664. walksScope(referencePath, name, slotFlags_default.DYNAMIC);
  665. });
  666. }
  667. return expression;
  668. }
  669. if (path.isJSXSpreadChild()) {
  670. return transformJSXSpreadChild(path);
  671. }
  672. if (path.isCallExpression()) {
  673. return path.node;
  674. }
  675. if (path.isJSXElement()) {
  676. return transformJSXElement(path, state);
  677. }
  678. throw new Error(`getChildren: ${path.type} is not supported`);
  679. }).filter(
  680. (value) => value != null && !t3.isJSXEmptyExpression(value)
  681. );
  682. var transformJSXElement = (path, state) => {
  683. const children = getChildren(path.get("children"), state);
  684. const {
  685. tag,
  686. props,
  687. isComponent,
  688. directives,
  689. patchFlag,
  690. dynamicPropNames,
  691. slots
  692. } = buildProps(path, state);
  693. const { optimize = false } = state.opts;
  694. const slotFlag = path.getData("slotFlag") || slotFlags_default.STABLE;
  695. let VNodeChild;
  696. if (children.length > 1 || slots) {
  697. VNodeChild = isComponent ? children.length ? t3.objectExpression(
  698. [
  699. !!children.length && t3.objectProperty(
  700. t3.identifier("default"),
  701. t3.arrowFunctionExpression(
  702. [],
  703. t3.arrayExpression(buildIIFE(path, children))
  704. )
  705. ),
  706. ...slots ? t3.isObjectExpression(slots) ? slots.properties : [t3.spreadElement(slots)] : [],
  707. optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
  708. ].filter(Boolean)
  709. ) : slots : t3.arrayExpression(children);
  710. } else if (children.length === 1) {
  711. const { enableObjectSlots = true } = state.opts;
  712. const child = children[0];
  713. const objectExpression4 = t3.objectExpression(
  714. [
  715. t3.objectProperty(
  716. t3.identifier("default"),
  717. t3.arrowFunctionExpression(
  718. [],
  719. t3.arrayExpression(buildIIFE(path, [child]))
  720. )
  721. ),
  722. optimize && t3.objectProperty(
  723. t3.identifier("_"),
  724. t3.numericLiteral(slotFlag)
  725. )
  726. ].filter(Boolean)
  727. );
  728. if (t3.isIdentifier(child) && isComponent) {
  729. VNodeChild = enableObjectSlots ? t3.conditionalExpression(
  730. t3.callExpression(
  731. state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
  732. [child]
  733. ),
  734. child,
  735. objectExpression4
  736. ) : objectExpression4;
  737. } else if (t3.isCallExpression(child) && child.loc && isComponent) {
  738. if (enableObjectSlots) {
  739. const { scope } = path;
  740. const slotId = scope.generateUidIdentifier("slot");
  741. if (scope) {
  742. scope.push({
  743. id: slotId,
  744. kind: "let"
  745. });
  746. }
  747. const alternate = t3.objectExpression(
  748. [
  749. t3.objectProperty(
  750. t3.identifier("default"),
  751. t3.arrowFunctionExpression(
  752. [],
  753. t3.arrayExpression(buildIIFE(path, [slotId]))
  754. )
  755. ),
  756. optimize && t3.objectProperty(
  757. t3.identifier("_"),
  758. t3.numericLiteral(slotFlag)
  759. )
  760. ].filter(Boolean)
  761. );
  762. const assignment = t3.assignmentExpression("=", slotId, child);
  763. const condition = t3.callExpression(
  764. state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
  765. [assignment]
  766. );
  767. VNodeChild = t3.conditionalExpression(condition, slotId, alternate);
  768. } else {
  769. VNodeChild = objectExpression4;
  770. }
  771. } else if (t3.isFunctionExpression(child) || t3.isArrowFunctionExpression(child)) {
  772. VNodeChild = t3.objectExpression([
  773. t3.objectProperty(t3.identifier("default"), child)
  774. ]);
  775. } else if (t3.isObjectExpression(child)) {
  776. VNodeChild = t3.objectExpression(
  777. [
  778. ...child.properties,
  779. optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
  780. ].filter(Boolean)
  781. );
  782. } else {
  783. VNodeChild = isComponent ? t3.objectExpression([
  784. t3.objectProperty(
  785. t3.identifier("default"),
  786. t3.arrowFunctionExpression([], t3.arrayExpression([child]))
  787. )
  788. ]) : t3.arrayExpression([child]);
  789. }
  790. }
  791. const createVNode = t3.callExpression(
  792. createIdentifier(state, "createVNode"),
  793. [
  794. tag,
  795. props,
  796. VNodeChild || t3.nullLiteral(),
  797. !!patchFlag && optimize && t3.numericLiteral(patchFlag),
  798. !!dynamicPropNames.size && optimize && t3.arrayExpression(
  799. [...dynamicPropNames.keys()].map((name) => t3.stringLiteral(name))
  800. )
  801. ].filter(Boolean)
  802. );
  803. if (!directives.length) {
  804. return createVNode;
  805. }
  806. return t3.callExpression(createIdentifier(state, "withDirectives"), [
  807. createVNode,
  808. t3.arrayExpression(directives)
  809. ]);
  810. };
  811. var visitor = {
  812. JSXElement: {
  813. exit(path, state) {
  814. path.replaceWith(transformJSXElement(path, state));
  815. }
  816. }
  817. };
  818. var transform_vue_jsx_default = visitor;
  819. // src/sugar-fragment.ts
  820. var t4 = __toESM(require("@babel/types"));
  821. var transformFragment = (path, Fragment) => {
  822. const children = path.get("children") || [];
  823. return t4.jsxElement(
  824. t4.jsxOpeningElement(Fragment, []),
  825. t4.jsxClosingElement(Fragment),
  826. children.map(({ node }) => node),
  827. false
  828. );
  829. };
  830. var visitor2 = {
  831. JSXFragment: {
  832. enter(path, state) {
  833. const fragmentCallee = createIdentifier(state, FRAGMENT);
  834. path.replaceWith(
  835. transformFragment(
  836. path,
  837. t4.isIdentifier(fragmentCallee) ? t4.jsxIdentifier(fragmentCallee.name) : t4.jsxMemberExpression(
  838. t4.jsxIdentifier(fragmentCallee.object.name),
  839. t4.jsxIdentifier(fragmentCallee.property.name)
  840. )
  841. )
  842. );
  843. }
  844. }
  845. };
  846. var sugar_fragment_default = visitor2;
  847. // src/index.ts
  848. var hasJSX = (parentPath) => {
  849. let fileHasJSX = false;
  850. parentPath.traverse({
  851. JSXElement(path) {
  852. fileHasJSX = true;
  853. path.stop();
  854. },
  855. JSXFragment(path) {
  856. fileHasJSX = true;
  857. path.stop();
  858. }
  859. });
  860. return fileHasJSX;
  861. };
  862. var JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/;
  863. // @__NO_SIDE_EFFECTS__
  864. function interopDefault(m) {
  865. return m.default || m;
  866. }
  867. var syntaxJsx = /* @__PURE__ */ interopDefault(import_plugin_syntax_jsx.default);
  868. var template = /* @__PURE__ */ interopDefault(import_template.default);
  869. var src_default = (0, import_helper_plugin_utils.declare)(
  870. (api, opt, dirname) => {
  871. const { types } = api;
  872. let resolveType;
  873. if (opt.resolveType) {
  874. if (typeof opt.resolveType === "boolean") opt.resolveType = {};
  875. resolveType = (0, import_babel_plugin_resolve_type.default)(api, opt.resolveType, dirname);
  876. }
  877. return __spreadProps(__spreadValues({}, resolveType || {}), {
  878. name: "babel-plugin-jsx",
  879. inherits: /* @__PURE__ */ interopDefault(syntaxJsx),
  880. visitor: __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, resolveType == null ? void 0 : resolveType.visitor), transform_vue_jsx_default), sugar_fragment_default), {
  881. Program: {
  882. enter(path, state) {
  883. if (hasJSX(path)) {
  884. const importNames = [
  885. "createVNode",
  886. "Fragment",
  887. "resolveComponent",
  888. "withDirectives",
  889. "vShow",
  890. "vModelSelect",
  891. "vModelText",
  892. "vModelCheckbox",
  893. "vModelRadio",
  894. "vModelText",
  895. "vModelDynamic",
  896. "resolveDirective",
  897. "mergeProps",
  898. "createTextVNode",
  899. "isVNode"
  900. ];
  901. if ((0, import_helper_module_imports2.isModule)(path)) {
  902. const importMap = {};
  903. importNames.forEach((name) => {
  904. state.set(name, () => {
  905. if (importMap[name]) {
  906. return types.cloneNode(importMap[name]);
  907. }
  908. const identifier5 = (0, import_helper_module_imports2.addNamed)(path, name, "vue", {
  909. ensureLiveReference: true
  910. });
  911. importMap[name] = identifier5;
  912. return identifier5;
  913. });
  914. });
  915. const { enableObjectSlots = true } = state.opts;
  916. if (enableObjectSlots) {
  917. state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
  918. if (importMap.runtimeIsSlot) {
  919. return importMap.runtimeIsSlot;
  920. }
  921. const { name: isVNodeName } = state.get(
  922. "isVNode"
  923. )();
  924. const isSlot = path.scope.generateUidIdentifier("isSlot");
  925. const ast = template.ast`
  926. function ${isSlot.name}(s) {
  927. return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${isVNodeName}(s));
  928. }
  929. `;
  930. const lastImport = path.get("body").filter((p) => p.isImportDeclaration()).pop();
  931. if (lastImport) {
  932. lastImport.insertAfter(ast);
  933. }
  934. importMap.runtimeIsSlot = isSlot;
  935. return isSlot;
  936. });
  937. }
  938. } else {
  939. let sourceName;
  940. importNames.forEach((name) => {
  941. state.set(name, () => {
  942. if (!sourceName) {
  943. sourceName = (0, import_helper_module_imports2.addNamespace)(path, "vue", {
  944. ensureLiveReference: true
  945. });
  946. }
  947. return t5.memberExpression(sourceName, t5.identifier(name));
  948. });
  949. });
  950. const helpers = {};
  951. const { enableObjectSlots = true } = state.opts;
  952. if (enableObjectSlots) {
  953. state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
  954. if (helpers.runtimeIsSlot) {
  955. return helpers.runtimeIsSlot;
  956. }
  957. const isSlot = path.scope.generateUidIdentifier("isSlot");
  958. const { object: objectName } = state.get(
  959. "isVNode"
  960. )();
  961. const ast = template.ast`
  962. function ${isSlot.name}(s) {
  963. return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${objectName.name}.isVNode(s));
  964. }
  965. `;
  966. const nodePaths = path.get("body");
  967. const lastImport = nodePaths.filter(
  968. (p) => p.isVariableDeclaration() && p.node.declarations.some(
  969. (d) => {
  970. var _a;
  971. return ((_a = d.id) == null ? void 0 : _a.name) === sourceName.name;
  972. }
  973. )
  974. ).pop();
  975. if (lastImport) {
  976. lastImport.insertAfter(ast);
  977. }
  978. return isSlot;
  979. });
  980. }
  981. }
  982. const {
  983. opts: { pragma = "" },
  984. file
  985. } = state;
  986. if (pragma) {
  987. state.set("createVNode", () => t5.identifier(pragma));
  988. }
  989. if (file.ast.comments) {
  990. for (const comment of file.ast.comments) {
  991. const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
  992. if (jsxMatches) {
  993. state.set("createVNode", () => t5.identifier(jsxMatches[1]));
  994. }
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. })
  1001. });
  1002. }
  1003. );