版博士V2.0程序
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.

chunk-4PXXOGIE.js 17 KiB

пре 1 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/core/helper/emit-helper.ts?raw
  2. var emit_helper_default = "export default(emitFn,key,value,...args)=>{emitFn(key,value);return args.length>0?args[0]:value};\n";
  3. // src/core/helper/use-vmodel.ts?raw
  4. var use_vmodel_default = 'import{getCurrentInstance}from"vue";import{useVModel}from"@vueuse/core";export default(...keys)=>{const props=getCurrentInstance().proxy.$props;const ret={};for(const _k of keys){if(typeof _k==="string"){ret[_k]=useVModel(props,_k,void 0,{eventName:`update:${_k}`,passive:true})}else{const[key,prop=key,eventName=`update:${key}`,options={}]=_k;ret[key]=useVModel(props,prop,void 0,{eventName,passive:true,...options})}}return ret};\n';
  5. // src/core/helper/index.ts
  6. var helperPrefix = "/vue-macros/define-model";
  7. var emitHelperId = `${helperPrefix}/emit-helper`;
  8. var useVmodelHelperId = `${helperPrefix}/use-vmodel`;
  9. // src/core/index.ts
  10. var _astwalkerscope = require('ast-walker-scope');
  11. var _common = require('@vue-macros/common');
  12. function transformDefineModel(code, id, version, unified) {
  13. let hasDefineProps = false;
  14. let hasDefineEmits = false;
  15. let hasDefineModel = false;
  16. let propsTypeDecl;
  17. let propsDestructureDecl;
  18. let emitsTypeDecl;
  19. let emitsIdentifier;
  20. let runtimeDefineFn;
  21. let modelDecl;
  22. let modelDeclKind;
  23. let modelTypeDecl;
  24. let modelIdentifier;
  25. let modelDestructureDecl;
  26. const modelIdentifiers = /* @__PURE__ */ new Set();
  27. const modelVue2 = { prop: "", event: "" };
  28. let mode;
  29. function processDefinePropsOrEmits(node, declId) {
  30. var _a, _b;
  31. if (_common.isCallOf.call(void 0, node, _common.WITH_DEFAULTS)) {
  32. node = node.arguments[0];
  33. }
  34. let type;
  35. if (_common.isCallOf.call(void 0, node, _common.DEFINE_PROPS)) {
  36. type = "props";
  37. } else if (_common.isCallOf.call(void 0, node, _common.DEFINE_EMITS)) {
  38. type = "emits";
  39. } else {
  40. return false;
  41. }
  42. const fnName = type === "props" ? _common.DEFINE_PROPS : _common.DEFINE_EMITS;
  43. if (node.arguments[0]) {
  44. runtimeDefineFn = fnName;
  45. return false;
  46. }
  47. if (type === "props")
  48. hasDefineProps = true;
  49. else
  50. hasDefineEmits = true;
  51. const typeDeclRaw = (_b = (_a = node.typeParameters) == null ? void 0 : _a.params) == null ? void 0 : _b[0];
  52. if (!typeDeclRaw)
  53. throw new SyntaxError(
  54. `${fnName}() expected a type parameter when used with ${_common.DEFINE_MODEL}.`
  55. );
  56. const typeDecl = resolveQualifiedType(
  57. typeDeclRaw,
  58. (node2) => node2.type === "TSTypeLiteral"
  59. );
  60. if (!typeDecl) {
  61. throw new SyntaxError(
  62. `type argument passed to ${fnName}() must be a literal type, or a reference to an interface or literal type.`
  63. );
  64. }
  65. if (type === "props")
  66. propsTypeDecl = typeDecl;
  67. else
  68. emitsTypeDecl = typeDecl;
  69. if (declId) {
  70. if (type === "props" && declId.type === "ObjectPattern") {
  71. propsDestructureDecl = declId;
  72. } else if (type === "emits" && declId.type === "Identifier") {
  73. emitsIdentifier = declId.name;
  74. }
  75. } else if (type === "emits") {
  76. emitsIdentifier = `_${_common.DEFINE_MODEL}_emit`;
  77. s.prependRight(setupOffset + node.start, `const ${emitsIdentifier} = `);
  78. }
  79. return true;
  80. }
  81. function processDefineModel(node, declId, kind) {
  82. var _a;
  83. if (_common.isCallOf.call(void 0, node, _common.DEFINE_MODEL))
  84. mode = "runtime";
  85. else if (_common.isCallOf.call(void 0, node, _common.DEFINE_MODEL_DOLLAR))
  86. mode = "reactivity-transform";
  87. else
  88. return false;
  89. if (hasDefineModel) {
  90. throw new SyntaxError(`duplicate ${_common.DEFINE_MODEL}() call`);
  91. }
  92. hasDefineModel = true;
  93. modelDecl = node;
  94. const propsTypeDeclRaw = (_a = node.typeParameters) == null ? void 0 : _a.params[0];
  95. if (!propsTypeDeclRaw) {
  96. throw new SyntaxError(`expected a type parameter for ${_common.DEFINE_MODEL}.`);
  97. }
  98. modelTypeDecl = resolveQualifiedType(
  99. propsTypeDeclRaw,
  100. (node2) => node2.type === "TSTypeLiteral"
  101. );
  102. if (!modelTypeDecl) {
  103. throw new SyntaxError(
  104. `type argument passed to ${_common.DEFINE_MODEL}() must be a literal type, or a reference to an interface or literal type.`
  105. );
  106. }
  107. if (mode === "reactivity-transform" && declId) {
  108. const ids = _astwalkerscope.extractIdentifiers.call(void 0, declId);
  109. ids.forEach((id2) => modelIdentifiers.add(id2));
  110. if (declId.type === "ObjectPattern") {
  111. modelDestructureDecl = declId;
  112. for (const property of declId.properties) {
  113. if (property.type === "RestElement") {
  114. throw new SyntaxError("rest element is not supported");
  115. }
  116. }
  117. } else {
  118. modelIdentifier = scriptSetup.loc.source.slice(
  119. declId.start,
  120. declId.end
  121. );
  122. }
  123. }
  124. if (kind)
  125. modelDeclKind = kind;
  126. return true;
  127. }
  128. function processDefineOptions(node) {
  129. if (!_common.isCallOf.call(void 0, node, _common.DEFINE_OPTIONS))
  130. return false;
  131. const [arg] = node.arguments;
  132. if (arg)
  133. processVue2Model(arg);
  134. return true;
  135. }
  136. function processVue2Script() {
  137. if (!script)
  138. return;
  139. const scriptAst = getScriptAst().body;
  140. if (scriptAst.length === 0)
  141. return;
  142. for (const node of scriptAst) {
  143. if (node.type === "ExportDefaultDeclaration") {
  144. const { declaration } = node;
  145. if (declaration.type === "ObjectExpression") {
  146. processVue2Model(declaration);
  147. } else if (declaration.type === "CallExpression" && declaration.callee.type === "Identifier" && ["defineComponent", "DO_defineComponent"].includes(
  148. declaration.callee.name
  149. )) {
  150. declaration.arguments.forEach((arg) => {
  151. if (arg.type === "ObjectExpression") {
  152. processVue2Model(arg);
  153. }
  154. });
  155. }
  156. }
  157. }
  158. }
  159. function processVue2Model(node) {
  160. if (node.type !== "ObjectExpression")
  161. return false;
  162. const model = node.properties.find(
  163. (prop) => prop.type === "ObjectProperty" && prop.key.type === "Identifier" && prop.key.name === "model" && prop.value.type === "ObjectExpression" && prop.value.properties.length === 2
  164. );
  165. if (!model)
  166. return false;
  167. model.value.properties.forEach((propertyItem) => {
  168. if (propertyItem.type === "ObjectProperty" && propertyItem.key.type === "Identifier" && propertyItem.value.type === "StringLiteral" && ["prop", "event"].includes(propertyItem.key.name)) {
  169. const key = propertyItem.key.name;
  170. modelVue2[key] = propertyItem.value.value;
  171. }
  172. });
  173. return true;
  174. }
  175. function resolveQualifiedType(node, qualifier) {
  176. if (qualifier(node)) {
  177. return node;
  178. }
  179. if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  180. const refName = node.typeName.name;
  181. const isQualifiedType = (node2) => {
  182. if (node2.type === "TSInterfaceDeclaration" && node2.id.name === refName) {
  183. return node2.body;
  184. } else if (node2.type === "TSTypeAliasDeclaration" && node2.id.name === refName && qualifier(node2.typeAnnotation)) {
  185. return node2.typeAnnotation;
  186. } else if (node2.type === "ExportNamedDeclaration" && node2.declaration) {
  187. return isQualifiedType(node2.declaration);
  188. }
  189. };
  190. for (const node2 of setupAst) {
  191. const qualified = isQualifiedType(node2);
  192. if (qualified) {
  193. return qualified;
  194. }
  195. }
  196. }
  197. }
  198. function extractPropsDefinitions(node) {
  199. var _a, _b, _c, _d;
  200. const members = node.type === "TSTypeLiteral" ? node.members : node.body;
  201. const map2 = {};
  202. for (const m of members) {
  203. if ((m.type === "TSPropertySignature" || m.type === "TSMethodSignature") && m.key.type === "Identifier") {
  204. const type = (_a = m.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  205. let typeAnnotation = "";
  206. let options;
  207. if (type) {
  208. typeAnnotation += `${m.optional ? "?" : ""}: `;
  209. if (type.type === "TSTypeReference" && type.typeName.type === "Identifier" && type.typeName.name === "ModelOptions" && ((_b = type.typeParameters) == null ? void 0 : _b.type) === "TSTypeParameterInstantiation" && type.typeParameters.params[0]) {
  210. typeAnnotation += setupContent.slice(
  211. type.typeParameters.params[0].start,
  212. type.typeParameters.params[0].end
  213. );
  214. if (((_c = type.typeParameters.params[1]) == null ? void 0 : _c.type) === "TSTypeLiteral") {
  215. options = {};
  216. for (const m2 of type.typeParameters.params[1].members) {
  217. if ((m2.type === "TSPropertySignature" || m2.type === "TSMethodSignature") && m2.key.type === "Identifier") {
  218. const type2 = (_d = m2.typeAnnotation) == null ? void 0 : _d.typeAnnotation;
  219. if (type2)
  220. options[setupContent.slice(m2.key.start, m2.key.end)] = setupContent.slice(type2.start, type2.end);
  221. }
  222. }
  223. }
  224. } else
  225. typeAnnotation += `${setupContent.slice(type.start, type.end)}`;
  226. }
  227. map2[m.key.name] = { typeAnnotation, options };
  228. }
  229. }
  230. return map2;
  231. }
  232. function getPropKey(key, omitDefault = false) {
  233. if (unified && version === 2 && key === "modelValue") {
  234. return "value";
  235. }
  236. return !omitDefault ? key : void 0;
  237. }
  238. function getEventKey(key, omitDefault = false) {
  239. if (version === 2) {
  240. if (modelVue2.prop === key) {
  241. return modelVue2.event;
  242. } else if (key === "value" || unified && key === "modelValue") {
  243. return "input";
  244. }
  245. }
  246. return !omitDefault ? `update:${key}` : void 0;
  247. }
  248. function rewriteMacros() {
  249. rewriteDefines();
  250. if (mode === "runtime") {
  251. rewriteRuntime();
  252. }
  253. function rewriteDefines() {
  254. const propsText = Object.entries(map).map(
  255. ([key, { typeAnnotation }]) => `${getPropKey(key)}${typeAnnotation}`
  256. ).join("\n");
  257. const emitsText = Object.entries(map).map(
  258. ([key, { typeAnnotation }]) => `(evt: '${getEventKey(key)}', value${typeAnnotation}): void`
  259. ).join("\n");
  260. if (hasDefineProps) {
  261. s.appendLeft(setupOffset + propsTypeDecl.start + 1, `${propsText}
  262. `);
  263. if (mode === "reactivity-transform" && propsDestructureDecl && modelDestructureDecl)
  264. for (const property of modelDestructureDecl.properties) {
  265. const text = code.slice(
  266. setupOffset + property.start,
  267. setupOffset + property.end
  268. );
  269. s.appendLeft(
  270. setupOffset + propsDestructureDecl.start + 1,
  271. `${text}, `
  272. );
  273. }
  274. } else {
  275. let text = "";
  276. const kind = modelDeclKind || "let";
  277. if (mode === "reactivity-transform") {
  278. if (modelIdentifier) {
  279. text = modelIdentifier;
  280. } else if (modelDestructureDecl) {
  281. text = code.slice(
  282. setupOffset + modelDestructureDecl.start,
  283. setupOffset + modelDestructureDecl.end
  284. );
  285. }
  286. }
  287. s.appendLeft(
  288. setupOffset,
  289. `
  290. ${text ? `${kind} ${text} = ` : ""}defineProps<{
  291. ${propsText}
  292. }>();`
  293. );
  294. }
  295. if (hasDefineEmits) {
  296. s.appendLeft(setupOffset + emitsTypeDecl.start + 1, `${emitsText}
  297. `);
  298. } else {
  299. emitsIdentifier = `${_common.HELPER_PREFIX}emit`;
  300. s.appendLeft(
  301. setupOffset,
  302. `
  303. ${mode === "reactivity-transform" ? `const ${emitsIdentifier} = ` : ""}defineEmits<{
  304. ${emitsText}
  305. }>();`
  306. );
  307. }
  308. }
  309. function rewriteRuntime() {
  310. s.prependLeft(
  311. setupOffset,
  312. `
  313. import ${_common.HELPER_PREFIX}useVModel from '${useVmodelHelperId}';`
  314. );
  315. const text = `${_common.HELPER_PREFIX}useVModel(${Object.entries(map).map(([name, { options }]) => {
  316. const prop = getPropKey(name, true);
  317. const evt = getEventKey(name, true);
  318. if (!prop && !evt && !options)
  319. return stringifyValue(name);
  320. const args = [name, prop, evt].map((arg) => stringifyValue(arg));
  321. if (options) {
  322. const str = Object.entries(options).map(([k, v]) => ` ${stringifyValue(k)}: ${v}`).join(",\n");
  323. args.push(`{
  324. ${str}
  325. }`);
  326. }
  327. return `[${args.join(", ")}]`;
  328. }).join(", ")})`;
  329. s.overwriteNode(modelDecl, text, { offset: setupOffset });
  330. }
  331. }
  332. function processAssignModelVariable() {
  333. if (!emitsIdentifier)
  334. throw new Error(
  335. `Identifier of returning value of ${_common.DEFINE_EMITS} is not found, please report this issue.
  336. ${_common.REPO_ISSUE_URL}`
  337. );
  338. let hasTransformed = false;
  339. function overwrite(node, id2, value, original = false) {
  340. hasTransformed = true;
  341. const eventName = aliasMap[id2.name];
  342. const content = `${_common.HELPER_PREFIX}emitHelper(${emitsIdentifier}, '${getEventKey(
  343. String(eventName)
  344. )}', ${value}${original ? `, ${id2.name}` : ""})`;
  345. s.overwriteNode(node, content, { offset: setupOffset });
  346. }
  347. _astwalkerscope.walkAST.call(void 0, setupAst, {
  348. leave(node) {
  349. if (node.type === "AssignmentExpression") {
  350. if (node.left.type !== "Identifier")
  351. return;
  352. const id2 = this.scope[node.left.name];
  353. if (!modelIdentifiers.has(id2))
  354. return;
  355. const left = s.sliceNode(node.left, { offset: setupOffset });
  356. let right = s.sliceNode(node.right, { offset: setupOffset });
  357. if (node.operator !== "=") {
  358. right = `${left} ${node.operator.replace(/=$/, "")} ${right}`;
  359. }
  360. overwrite(node, id2, right);
  361. } else if (node.type === "UpdateExpression") {
  362. if (node.argument.type !== "Identifier")
  363. return;
  364. const id2 = this.scope[node.argument.name];
  365. if (!modelIdentifiers.has(id2))
  366. return;
  367. let value = node.argument.name;
  368. if (node.operator === "++")
  369. value += " + 1";
  370. else
  371. value += " - 1";
  372. overwrite(node, id2, value, !node.prefix);
  373. }
  374. }
  375. });
  376. if (hasTransformed) {
  377. s.prependLeft(
  378. setupOffset,
  379. `
  380. import ${_common.HELPER_PREFIX}emitHelper from '${emitHelperId}';`
  381. );
  382. }
  383. }
  384. if (!code.includes(_common.DEFINE_MODEL))
  385. return;
  386. const { script, scriptSetup, getSetupAst, getScriptAst } = _common.parseSFC.call(void 0, code, id);
  387. if (!scriptSetup)
  388. return;
  389. const setupOffset = scriptSetup.loc.start.offset;
  390. const setupContent = scriptSetup.content;
  391. const setupAst = getSetupAst().body;
  392. const s = new (0, _common.MagicString)(code);
  393. if (version === 2)
  394. processVue2Script();
  395. for (const node of setupAst) {
  396. if (node.type === "ExpressionStatement") {
  397. processDefinePropsOrEmits(node.expression);
  398. if (version === 2) {
  399. processDefineOptions(node.expression);
  400. }
  401. if (processDefineModel(node.expression) && mode === "reactivity-transform")
  402. s.remove(node.start + setupOffset, node.end + setupOffset);
  403. } else if (node.type === "VariableDeclaration" && !node.declare) {
  404. const total = node.declarations.length;
  405. let left = total;
  406. for (let i = 0; i < total; i++) {
  407. const decl = node.declarations[i];
  408. if (decl.init) {
  409. processDefinePropsOrEmits(decl.init, decl.id);
  410. if (processDefineModel(decl.init, decl.id, node.kind) && mode === "reactivity-transform") {
  411. if (left === 1) {
  412. s.remove(node.start + setupOffset, node.end + setupOffset);
  413. } else {
  414. let start = decl.start + setupOffset;
  415. let end = decl.end + setupOffset;
  416. if (i < total - 1) {
  417. end = node.declarations[i + 1].start + setupOffset;
  418. } else {
  419. start = node.declarations[i - 1].end + setupOffset;
  420. }
  421. s.remove(start, end);
  422. left--;
  423. }
  424. }
  425. }
  426. }
  427. }
  428. }
  429. if (!modelTypeDecl)
  430. return;
  431. if (runtimeDefineFn)
  432. throw new SyntaxError(
  433. `${runtimeDefineFn}() cannot accept non-type arguments when used with ${_common.DEFINE_MODEL}()`
  434. );
  435. if (modelTypeDecl.type !== "TSTypeLiteral") {
  436. throw new SyntaxError(
  437. `type argument passed to ${_common.DEFINE_MODEL}() must be a literal type, or a reference to an interface or literal type.`
  438. );
  439. }
  440. const map = extractPropsDefinitions(modelTypeDecl);
  441. const aliasMap = {};
  442. if (modelDestructureDecl)
  443. for (const p of modelDestructureDecl.properties) {
  444. if (p.type !== "ObjectProperty")
  445. continue;
  446. try {
  447. const key = _common.resolveObjectKey.call(void 0, p.key, p.computed, false);
  448. if (p.value.type !== "Identifier")
  449. continue;
  450. aliasMap[p.value.name] = key;
  451. } catch (e) {
  452. }
  453. }
  454. rewriteMacros();
  455. if (mode === "reactivity-transform" && hasDefineModel)
  456. processAssignModelVariable();
  457. return _common.getTransformResult.call(void 0, s, id);
  458. }
  459. function stringifyValue(value) {
  460. return value !== void 0 ? JSON.stringify(value) : "undefined";
  461. }
  462. exports.emit_helper_default = emit_helper_default; exports.use_vmodel_default = use_vmodel_default; exports.helperPrefix = helperPrefix; exports.emitHelperId = emitHelperId; exports.useVmodelHelperId = useVmodelHelperId; exports.transformDefineModel = transformDefineModel;