@vue-jsx/macros 3.3.0-beta.0

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.
@@ -0,0 +1,935 @@
1
+ import "@babel/parser";
2
+ import MagicString from "magic-string";
3
+ import hash from "hash-sum";
4
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
5
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
6
+ function normalizeWindowsPath(input = "") {
7
+ if (!input) return input;
8
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
9
+ }
10
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
11
+ const extname = function(p) {
12
+ if (p === "..") return "";
13
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
14
+ return match && match[1] || "";
15
+ };
16
+ //#endregion
17
+ //#region ../../node_modules/.pnpm/ast-kit@2.2.0/node_modules/ast-kit/dist/index.js
18
+ /**
19
+ * Checks if the given node is a function type.
20
+ *
21
+ * @param node - The node to check.
22
+ * @returns True if the node is a function type, false otherwise.
23
+ */
24
+ function isFunctionType(node) {
25
+ return !!node && !node.type.startsWith("TS") && /Function(?:Expression|Declaration)$|Method$/.test(node.type);
26
+ }
27
+ /* v8 ignore next -- @preserve */
28
+ /**
29
+ * Checks if the input `node` is a reference to a bound variable.
30
+ *
31
+ * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
32
+ *
33
+ * To avoid runtime dependency on `@babel/types` (which includes process references)
34
+ * This file should not change very often in babel but we may need to keep it
35
+ * up-to-date from time to time.
36
+ *
37
+ * @param node - The node to check.
38
+ * @param parent - The parent node of the input `node`.
39
+ * @param grandparent - The grandparent node of the input `node`.
40
+ * @returns True if the input `node` is a reference to a bound variable, false otherwise.
41
+ */
42
+ function isReferenced(node, parent, grandparent) {
43
+ switch (parent.type) {
44
+ case "MemberExpression":
45
+ case "OptionalMemberExpression":
46
+ if (parent.property === node) return !!parent.computed;
47
+ return parent.object === node;
48
+ case "JSXMemberExpression": return parent.object === node;
49
+ case "VariableDeclarator": return parent.init === node;
50
+ case "ArrowFunctionExpression": return parent.body === node;
51
+ case "PrivateName": return false;
52
+ case "ClassMethod":
53
+ case "ClassPrivateMethod":
54
+ case "ObjectMethod":
55
+ if (parent.key === node) return !!parent.computed;
56
+ return false;
57
+ case "ObjectProperty":
58
+ if (parent.key === node) return !!parent.computed;
59
+ return !grandparent || grandparent.type !== "ObjectPattern";
60
+ case "ClassProperty":
61
+ case "ClassAccessorProperty":
62
+ if (parent.key === node) return !!parent.computed;
63
+ return true;
64
+ case "ClassPrivateProperty": return parent.key !== node;
65
+ case "ClassDeclaration":
66
+ case "ClassExpression": return parent.superClass === node;
67
+ case "AssignmentExpression": return parent.right === node;
68
+ case "AssignmentPattern": return parent.right === node;
69
+ case "LabeledStatement": return false;
70
+ case "CatchClause": return false;
71
+ case "RestElement": return false;
72
+ case "BreakStatement":
73
+ case "ContinueStatement": return false;
74
+ case "FunctionDeclaration":
75
+ case "FunctionExpression": return false;
76
+ case "ExportNamespaceSpecifier":
77
+ case "ExportDefaultSpecifier": return false;
78
+ case "ExportSpecifier":
79
+ if (grandparent?.source) return false;
80
+ return parent.local === node;
81
+ case "ImportDefaultSpecifier":
82
+ case "ImportNamespaceSpecifier":
83
+ case "ImportSpecifier": return false;
84
+ case "ImportAttribute": return false;
85
+ case "JSXAttribute":
86
+ case "JSXNamespacedName": return false;
87
+ case "ObjectPattern":
88
+ case "ArrayPattern": return false;
89
+ case "MetaProperty": return false;
90
+ case "ObjectTypeProperty": return parent.key !== node;
91
+ case "TSEnumMember": return parent.id !== node;
92
+ case "TSPropertySignature":
93
+ if (parent.key === node) return !!parent.computed;
94
+ return true;
95
+ }
96
+ return true;
97
+ }
98
+ function isIdentifier(node) {
99
+ return !!node && (node.type === "Identifier" || node.type === "JSXIdentifier");
100
+ }
101
+ function isForStatement(stmt) {
102
+ return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement";
103
+ }
104
+ function isReferencedIdentifier(id, parent, parentStack) {
105
+ if (!parent) return true;
106
+ if (id.name === "arguments") return false;
107
+ if (isReferenced(id, parent, parentStack.at(-2))) return true;
108
+ switch (parent.type) {
109
+ case "AssignmentExpression":
110
+ case "AssignmentPattern": return true;
111
+ case "ObjectProperty": return parent.key !== id && isInDestructureAssignment(parent, parentStack);
112
+ case "ArrayPattern": return isInDestructureAssignment(parent, parentStack);
113
+ }
114
+ return false;
115
+ }
116
+ function isInDestructureAssignment(parent, parentStack) {
117
+ if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
118
+ let i = parentStack.length;
119
+ while (i--) {
120
+ const p = parentStack[i];
121
+ if (p.type === "AssignmentExpression") return true;
122
+ else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) break;
123
+ }
124
+ }
125
+ return false;
126
+ }
127
+ /**
128
+ * Extract identifiers of the given node.
129
+ * @param node The node to extract.
130
+ * @param identifiers The array to store the extracted identifiers.
131
+ * @see https://github.com/vuejs/core/blob/1f6a1102aa09960f76a9af2872ef01e7da8538e3/packages/compiler-core/src/babelUtils.ts#L208
132
+ */
133
+ function extractIdentifiers(node, identifiers = []) {
134
+ switch (node.type) {
135
+ case "Identifier":
136
+ case "JSXIdentifier":
137
+ identifiers.push(node);
138
+ break;
139
+ case "MemberExpression":
140
+ case "JSXMemberExpression": {
141
+ let object = node;
142
+ while (object.type === "MemberExpression") object = object.object;
143
+ identifiers.push(object);
144
+ break;
145
+ }
146
+ case "ObjectPattern":
147
+ for (const prop of node.properties) if (prop.type === "RestElement") extractIdentifiers(prop.argument, identifiers);
148
+ else extractIdentifiers(prop.value, identifiers);
149
+ break;
150
+ case "ArrayPattern":
151
+ node.elements.forEach((element) => {
152
+ element && extractIdentifiers(element, identifiers);
153
+ });
154
+ break;
155
+ case "RestElement":
156
+ extractIdentifiers(node.argument, identifiers);
157
+ break;
158
+ case "AssignmentPattern":
159
+ extractIdentifiers(node.left, identifiers);
160
+ break;
161
+ }
162
+ return identifiers;
163
+ }
164
+ const REGEX_DTS = /\.d\.[cm]?ts(\?.*)?$/;
165
+ /**
166
+ * Returns the language (extension name) of a given filename.
167
+ * @param filename - The name of the file.
168
+ * @returns The language of the file.
169
+ */
170
+ function getLang(filename) {
171
+ if (isDts(filename)) return "dts";
172
+ return extname(filename).replace(/^\./, "").replace(/\?.*$/, "");
173
+ }
174
+ /**
175
+ * Checks if a filename represents a TypeScript declaration file (.d.ts).
176
+ * @param filename - The name of the file to check.
177
+ * @returns A boolean value indicating whether the filename is a TypeScript declaration file.
178
+ */
179
+ function isDts(filename) {
180
+ return REGEX_DTS.test(filename);
181
+ }
182
+ /**
183
+ * @typedef { import('estree').Node} Node
184
+ * @typedef {{
185
+ * skip: () => void;
186
+ * remove: () => void;
187
+ * replace: (node: Node) => void;
188
+ * }} WalkerContext
189
+ */
190
+ var WalkerBase = class {
191
+ constructor() {
192
+ /** @type {boolean} */
193
+ this.should_skip = false;
194
+ /** @type {boolean} */
195
+ this.should_remove = false;
196
+ /** @type {Node | null} */
197
+ this.replacement = null;
198
+ /** @type {WalkerContext} */
199
+ this.context = {
200
+ skip: () => this.should_skip = true,
201
+ remove: () => this.should_remove = true,
202
+ replace: (node) => this.replacement = node
203
+ };
204
+ }
205
+ /**
206
+ * @template {Node} Parent
207
+ * @param {Parent | null | undefined} parent
208
+ * @param {keyof Parent | null | undefined} prop
209
+ * @param {number | null | undefined} index
210
+ * @param {Node} node
211
+ */
212
+ replace(parent, prop, index, node) {
213
+ if (parent && prop) if (index != null)
214
+ /** @type {Array<Node>} */ parent[prop][index] = node;
215
+ else
216
+ /** @type {Node} */ parent[prop] = node;
217
+ }
218
+ /**
219
+ * @template {Node} Parent
220
+ * @param {Parent | null | undefined} parent
221
+ * @param {keyof Parent | null | undefined} prop
222
+ * @param {number | null | undefined} index
223
+ */
224
+ remove(parent, prop, index) {
225
+ if (parent && prop) if (index !== null && index !== void 0)
226
+ /** @type {Array<Node>} */ parent[prop].splice(index, 1);
227
+ else delete parent[prop];
228
+ }
229
+ };
230
+ /**
231
+ * @typedef { import('estree').Node} Node
232
+ * @typedef { import('./walker.js').WalkerContext} WalkerContext
233
+ * @typedef {(
234
+ * this: WalkerContext,
235
+ * node: Node,
236
+ * parent: Node | null,
237
+ * key: string | number | symbol | null | undefined,
238
+ * index: number | null | undefined
239
+ * ) => void} SyncHandler
240
+ */
241
+ var SyncWalker = class extends WalkerBase {
242
+ /**
243
+ *
244
+ * @param {SyncHandler} [enter]
245
+ * @param {SyncHandler} [leave]
246
+ */
247
+ constructor(enter, leave) {
248
+ super();
249
+ /** @type {boolean} */
250
+ this.should_skip = false;
251
+ /** @type {boolean} */
252
+ this.should_remove = false;
253
+ /** @type {Node | null} */
254
+ this.replacement = null;
255
+ /** @type {WalkerContext} */
256
+ this.context = {
257
+ skip: () => this.should_skip = true,
258
+ remove: () => this.should_remove = true,
259
+ replace: (node) => this.replacement = node
260
+ };
261
+ /** @type {SyncHandler | undefined} */
262
+ this.enter = enter;
263
+ /** @type {SyncHandler | undefined} */
264
+ this.leave = leave;
265
+ }
266
+ /**
267
+ * @template {Node} Parent
268
+ * @param {Node} node
269
+ * @param {Parent | null} parent
270
+ * @param {keyof Parent} [prop]
271
+ * @param {number | null} [index]
272
+ * @returns {Node | null}
273
+ */
274
+ visit(node, parent, prop, index) {
275
+ if (node) {
276
+ if (this.enter) {
277
+ const _should_skip = this.should_skip;
278
+ const _should_remove = this.should_remove;
279
+ const _replacement = this.replacement;
280
+ this.should_skip = false;
281
+ this.should_remove = false;
282
+ this.replacement = null;
283
+ this.enter.call(this.context, node, parent, prop, index);
284
+ if (this.replacement) {
285
+ node = this.replacement;
286
+ this.replace(parent, prop, index, node);
287
+ }
288
+ if (this.should_remove) this.remove(parent, prop, index);
289
+ const skipped = this.should_skip;
290
+ const removed = this.should_remove;
291
+ this.should_skip = _should_skip;
292
+ this.should_remove = _should_remove;
293
+ this.replacement = _replacement;
294
+ if (skipped) return node;
295
+ if (removed) return null;
296
+ }
297
+ /** @type {keyof Node} */
298
+ let key;
299
+ for (key in node) {
300
+ /** @type {unknown} */
301
+ const value = node[key];
302
+ if (value && typeof value === "object") {
303
+ if (Array.isArray(value)) {
304
+ const nodes = value;
305
+ for (let i = 0; i < nodes.length; i += 1) {
306
+ const item = nodes[i];
307
+ if (isNode$1(item)) {
308
+ if (!this.visit(item, node, key, i)) i--;
309
+ }
310
+ }
311
+ } else if (isNode$1(value)) this.visit(value, node, key, null);
312
+ }
313
+ }
314
+ if (this.leave) {
315
+ const _replacement = this.replacement;
316
+ const _should_remove = this.should_remove;
317
+ this.replacement = null;
318
+ this.should_remove = false;
319
+ this.leave.call(this.context, node, parent, prop, index);
320
+ if (this.replacement) {
321
+ node = this.replacement;
322
+ this.replace(parent, prop, index, node);
323
+ }
324
+ if (this.should_remove) this.remove(parent, prop, index);
325
+ const removed = this.should_remove;
326
+ this.replacement = _replacement;
327
+ this.should_remove = _should_remove;
328
+ if (removed) return null;
329
+ }
330
+ }
331
+ return node;
332
+ }
333
+ };
334
+ /**
335
+ * Ducktype a node.
336
+ *
337
+ * @param {unknown} value
338
+ * @returns {value is Node}
339
+ */
340
+ function isNode$1(value) {
341
+ return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
342
+ }
343
+ /**
344
+ * @typedef {import('estree').Node} Node
345
+ * @typedef {import('./sync.js').SyncHandler} SyncHandler
346
+ * @typedef {import('./async.js').AsyncHandler} AsyncHandler
347
+ */
348
+ /**
349
+ * @param {Node} ast
350
+ * @param {{
351
+ * enter?: SyncHandler
352
+ * leave?: SyncHandler
353
+ * }} walker
354
+ * @returns {Node | null}
355
+ */
356
+ function walk(ast, { enter, leave }) {
357
+ return new SyncWalker(enter, leave).visit(ast, null);
358
+ }
359
+ const TS_NODE_TYPES = [
360
+ "TSAsExpression",
361
+ "TSTypeAssertion",
362
+ "TSNonNullExpression",
363
+ "TSInstantiationExpression",
364
+ "TSSatisfiesExpression"
365
+ ];
366
+ /**
367
+ * Walks the AST and applies the provided handlers.
368
+ *
369
+ * @template T - The type of the AST node.
370
+ * @param {T} node - The root node of the AST.
371
+ * @param {WalkHandlers<T, void>} hooks - The handlers to be applied during the walk.
372
+ * @returns {T | null} - The modified AST node or null if the node is removed.
373
+ */
374
+ const walkAST = walk;
375
+ /**
376
+ * Modified from https://github.com/vuejs/core/blob/main/packages/compiler-core/src/babelUtils.ts
377
+ * To support browser environments and JSX.
378
+ *
379
+ * https://github.com/vuejs/core/blob/main/LICENSE
380
+ */
381
+ /**
382
+ * Return value indicates whether the AST walked can be a constant
383
+ */
384
+ function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
385
+ const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root;
386
+ walkAST(root, {
387
+ enter(node, parent) {
388
+ parent && parentStack.push(parent);
389
+ if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) return this.skip();
390
+ if (isIdentifier(node)) {
391
+ const isLocal = !!knownIds[node.name];
392
+ const isRefed = isReferencedIdentifier(node, parent, parentStack);
393
+ if (includeAll || isRefed && !isLocal) onIdentifier(node, parent, parentStack, isRefed, isLocal);
394
+ } else if (node.type === "ObjectProperty" && parent?.type === "ObjectPattern") node.inPattern = true;
395
+ else if (isFunctionType(node))
396
+ /* v8 ignore if -- @preserve */
397
+ if (node.scopeIds) node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
398
+ else walkFunctionParams(node, (id) => markScopeIdentifier(node, id, knownIds));
399
+ else if (node.type === "BlockStatement")
400
+ /* v8 ignore if -- @preserve */
401
+ if (node.scopeIds) node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
402
+ else walkBlockDeclarations(node, (id) => markScopeIdentifier(node, id, knownIds));
403
+ else if (node.type === "CatchClause" && node.param) for (const id of extractIdentifiers(node.param)) markScopeIdentifier(node, id, knownIds);
404
+ else if (isForStatement(node)) walkForStatement(node, false, (id) => markScopeIdentifier(node, id, knownIds));
405
+ },
406
+ leave(node, parent) {
407
+ parent && parentStack.pop();
408
+ if (node !== rootExp && node.scopeIds) for (const id of node.scopeIds) {
409
+ knownIds[id]--;
410
+ if (knownIds[id] === 0) delete knownIds[id];
411
+ }
412
+ }
413
+ });
414
+ }
415
+ function walkFunctionParams(node, onIdent) {
416
+ for (const p of node.params) for (const id of extractIdentifiers(p)) onIdent(id);
417
+ }
418
+ function walkBlockDeclarations(block, onIdent) {
419
+ for (const stmt of block.body) if (stmt.type === "VariableDeclaration") {
420
+ if (stmt.declare) continue;
421
+ for (const decl of stmt.declarations) for (const id of extractIdentifiers(decl.id)) onIdent(id);
422
+ } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
423
+ /* v8 ignore if -- @preserve */
424
+ if (stmt.declare || !stmt.id) continue;
425
+ onIdent(stmt.id);
426
+ } else if (isForStatement(stmt)) walkForStatement(stmt, true, onIdent);
427
+ }
428
+ function walkForStatement(stmt, isVar, onIdent) {
429
+ const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left;
430
+ if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) for (const decl of variable.declarations) for (const id of extractIdentifiers(decl.id)) onIdent(id);
431
+ }
432
+ function markKnownIds(name, knownIds) {
433
+ if (name in knownIds) knownIds[name]++;
434
+ else knownIds[name] = 1;
435
+ }
436
+ function markScopeIdentifier(node, child, knownIds) {
437
+ const { name } = child;
438
+ /* v8 ignore if -- @preserve */
439
+ if (node.scopeIds && node.scopeIds.has(name)) return;
440
+ markKnownIds(name, knownIds);
441
+ (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name);
442
+ }
443
+ //#endregion
444
+ //#region src/core/helper/use-model.ts?raw
445
+ var use_model_default = "import { customRef, watchSyncEffect } from \"vue\";\nconst EMPTY_OBJ = {};\nexport function useModel(props, name, options = EMPTY_OBJ) {\n const res = customRef((track, trigger) => {\n let localValue = options && options.default;\n let prevSetValue = EMPTY_OBJ;\n watchSyncEffect(() => {\n let propValue = props[name];\n if (propValue === void 0) {\n propValue = options && options.default;\n }\n if (!Object.is(localValue, propValue)) {\n localValue = propValue;\n trigger();\n }\n });\n return {\n get() {\n track();\n return options.get ? options.get(localValue) : localValue;\n },\n set(value) {\n const emittedValue = options.set ? options.set(value) : value;\n if (Object.is(emittedValue, localValue) && (prevSetValue === EMPTY_OBJ || Object.is(value, prevSetValue)))\n return;\n localValue = emittedValue;\n trigger();\n for (const emit of [props[`onUpdate:${name}`]].flat()) {\n if (typeof emit === \"function\") emit(emittedValue);\n }\n prevSetValue = value;\n }\n };\n });\n res[Symbol.iterator] = () => {\n let i = 0;\n return {\n next() {\n if (i < 2) {\n return {\n value: i++ ? props[`${name}Modifiers`] || {} : res,\n done: false\n };\n } else {\n return { done: true };\n }\n }\n };\n };\n return res;\n}\n";
446
+ //#endregion
447
+ //#region src/core/helper/use-slots.ts?raw
448
+ var use_slots_default = "import { useSlots as _useSlots } from \"vue\";\nexport function useSlots(defaultSlots = {}) {\n const slots = _useSlots();\n return new Proxy(defaultSlots, {\n get(target, key) {\n return key in slots ? slots[key] : target[key];\n }\n });\n}\n";
449
+ //#endregion
450
+ //#region src/core/helper/with-defaults.ts?raw
451
+ var with_defaults_default = "function resolveDefaultProps(paths) {\n const result = {};\n for (const path of Object.keys(paths)) {\n const segments = path.split(/[.?[\\]]/).filter(Boolean);\n let current = result;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n if (i === segments.length - 1) {\n current[segment] = paths[path];\n } else {\n if (!current[segment]) {\n current[segment] = Number.isNaN(Number(segments[i + 1])) ? {} : [];\n }\n current = current[segment];\n }\n }\n }\n return result;\n}\nexport function createPropsDefaultProxy(props, defaults) {\n const defaultProps = resolveDefaultProps(defaults);\n const result = {};\n for (const key of /* @__PURE__ */ new Set([\n ...Object.keys(props),\n ...Object.keys(defaultProps)\n ])) {\n Object.defineProperty(result, key, {\n enumerable: true,\n get: () => props[key] === void 0 ? defaultProps[key] : props[key]\n });\n }\n return result;\n}\n";
452
+ //#endregion
453
+ //#region src/core/helper/index.ts
454
+ const helperPrefix = "/vue-jsx-vapor/macros";
455
+ const useModelHelperId = `${helperPrefix}/use-model`;
456
+ const withDefaultsHelperId = `${helperPrefix}/with-defaults`;
457
+ const useSlotsHelperId = `${helperPrefix}/use-slots`;
458
+ //#endregion
459
+ //#region src/core/utils.ts
460
+ function prependFunctionalNode(node, s, result) {
461
+ const isBlockStatement = node.body.type === "BlockStatement";
462
+ const start = node.body.extra?.parenthesized ? node.body.extra.parenStart : node.body.start;
463
+ s.appendRight(start + (isBlockStatement ? 1 : 0), `${result};${isBlockStatement ? "" : "return "}`);
464
+ if (!isBlockStatement) {
465
+ s.appendLeft(start, "{");
466
+ s.appendRight(node.end, "}");
467
+ }
468
+ }
469
+ function isFunctionalNode(node) {
470
+ return !!(node && (node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression"));
471
+ }
472
+ function getParamsStart(node, code) {
473
+ return node.params[0] ? node.params[0].start : node.start + (code.slice(node.start, node.body.start).match(/\(\s*\)/)?.index || 0) + 1;
474
+ }
475
+ function getDefaultValue(node) {
476
+ if (node.type === "TSNonNullExpression") return getDefaultValue(node.expression);
477
+ if (node.type === "TSAsExpression") return getDefaultValue(node.expression);
478
+ return node;
479
+ }
480
+ let require;
481
+ function getRequire() {
482
+ if (require) return require;
483
+ try {
484
+ if (globalThis.process?.getBuiltinModule) {
485
+ const module = process.getBuiltinModule("node:module");
486
+ if (module?.createRequire) return require = module.createRequire(import.meta.url);
487
+ }
488
+ } catch {}
489
+ }
490
+ const importedMap = /* @__PURE__ */ new WeakMap();
491
+ function importHelperFn(s, imported, local = imported, from = "vue") {
492
+ const cacheKey = `${from}@${imported}`;
493
+ if (!importedMap.get(s)?.has(cacheKey)) {
494
+ s.appendLeft(0, `\nimport ${imported === "default" ? "__" + local : `{ ${imported} as ${"__" + local} }`} from ${JSON.stringify(from)};`);
495
+ if (importedMap.has(s)) importedMap.get(s).add(cacheKey);
496
+ else importedMap.set(s, new Set([cacheKey]));
497
+ }
498
+ return `__${local}`;
499
+ }
500
+ //#endregion
501
+ //#region src/core/restructure.ts
502
+ function restructure(s, node, options = {}) {
503
+ let index = 0;
504
+ const propList = [];
505
+ for (const param of node.params) {
506
+ const path = `__props${index++ || ""}`;
507
+ const props = getProps(s, options, param, path);
508
+ if (props) {
509
+ s.overwrite(param.start, param.end, path);
510
+ propList.push(...props);
511
+ }
512
+ }
513
+ if (propList.length) {
514
+ const defaultValues = {};
515
+ const rests = [];
516
+ for (const prop of propList) {
517
+ if (prop.isRest) rests.push(prop);
518
+ if (prop.defaultValue) {
519
+ const paths = prop.path.split(/\.|\[/);
520
+ if (!options.skipDefaultProps || paths.length !== 1) (defaultValues[paths[0]] ??= []).push(prop);
521
+ }
522
+ }
523
+ for (const [index, rest] of rests.entries()) prependFunctionalNode(node, s, options.generateRestProps?.(rest.name, index, rests) ?? `\nconst ${rest.name} = ${importHelperFn(s, "createPropsRestProxy")}(${rest.path}, [${rest.value}])`);
524
+ for (const [path, values] of Object.entries(defaultValues)) prependFunctionalNode(node, s, `\n${path} = ${importHelperFn(s, "createPropsDefaultProxy", void 0, options.withDefaultsFrom ?? withDefaultsHelperId)}(${path}, {${values.map((i) => `'${i.path.replace(path, "")}${i.value}': ${i.defaultValue}`).join(", ")}})`);
525
+ walkIdentifiers(node.body, (id, parent) => {
526
+ const prop = propList.find((i) => i.name === id.name);
527
+ if (prop && !prop.isRest) s.overwrite(id.start, id.end, `${parent?.type === "ObjectProperty" && parent.shorthand ? `${id.name}: ` : ""}${prop.path}${prop.value}`);
528
+ }, false);
529
+ }
530
+ return propList;
531
+ }
532
+ function getProps(s, options, node, path = "", props = []) {
533
+ const properties = node.type === "ObjectPattern" ? node.properties : node.type === "ArrayPattern" ? node.elements : [];
534
+ if (!properties.length) return;
535
+ const propNames = [];
536
+ properties.forEach((prop, index) => {
537
+ if (prop?.type === "Identifier") {
538
+ props.push({
539
+ name: prop.name,
540
+ path,
541
+ value: `[${index}]`
542
+ });
543
+ propNames.push(`'${prop.name}'`);
544
+ } else if (prop?.type === "AssignmentPattern" && prop.left.type === "Identifier") {
545
+ const defaultValue = getDefaultValue(prop.right);
546
+ props.push({
547
+ path,
548
+ name: prop.left.name,
549
+ value: `[${index}]`,
550
+ defaultValue: s.slice(defaultValue.start, defaultValue.end)
551
+ });
552
+ propNames.push(`'${prop.left.name}'`);
553
+ } else if (prop?.type === "ObjectProperty" && prop.key.type === "Identifier") {
554
+ if (prop.value.type === "AssignmentPattern") if (prop.value.left.type === "Identifier") {
555
+ const defaultValue = getDefaultValue(prop.value.right);
556
+ props.push({
557
+ path,
558
+ name: prop.value.left.name,
559
+ value: `.${prop.key.name}`,
560
+ defaultValue: s.slice(defaultValue.start, defaultValue.end)
561
+ });
562
+ } else getProps(s, options, prop.value.left, `${path}.${prop.key.name}`, props);
563
+ else if (!getProps(s, options, prop.value, `${path}.${prop.key.name}`, props)) {
564
+ const name = prop.value.type === "Identifier" ? prop.value.name : prop.key.name;
565
+ props.push({
566
+ path,
567
+ name,
568
+ value: `.${prop.key.name}`
569
+ });
570
+ }
571
+ propNames.push(`'${prop.key.name}'`);
572
+ } else if (prop?.type === "RestElement" && prop.argument.type === "Identifier" && !prop.argument.name.startsWith(`__props`)) props.push({
573
+ path,
574
+ name: prop.argument.name,
575
+ value: propNames.join(", "),
576
+ isRest: true
577
+ });
578
+ else if (prop) getProps(s, options, prop, `${path}[${index}]`, props);
579
+ });
580
+ return props.length ? props : void 0;
581
+ }
582
+ //#endregion
583
+ //#region src/core/define-component/await.ts
584
+ function transformAwait(root, s) {
585
+ if (root.body.type !== "BlockStatement") return;
586
+ let hasAwait = false;
587
+ for (const node of root.body.body) if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
588
+ const scope = [root.body.body];
589
+ walkAST(node, {
590
+ enter(child, parent) {
591
+ if (isFunctionType(child)) this.skip();
592
+ if (child.type === "BlockStatement") scope.push(child.body);
593
+ if (child.type === "AwaitExpression") {
594
+ hasAwait = true;
595
+ processAwait(s, child, !!scope.at(-1)?.some((n, i) => {
596
+ return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
597
+ }), parent.type === "ExpressionStatement");
598
+ }
599
+ },
600
+ leave(node) {
601
+ if (node.type === "BlockStatement") scope.pop();
602
+ }
603
+ });
604
+ }
605
+ if (hasAwait) s.prependLeft(root.body.start + 1, `\nlet __temp, __restore\n`);
606
+ }
607
+ function processAwait(s, node, needSemi, isStatement) {
608
+ const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
609
+ const argumentStr = s.slice(argumentStart, node.argument.end);
610
+ const containsNestedAwait = /\bawait\b/.test(argumentStr);
611
+ s.overwrite(node.start, argumentStart, `${needSemi ? `;` : ``}(\n ([__temp,__restore] = ${importHelperFn(s, `withAsyncContext`)}(${containsNestedAwait ? `async ` : ``}() => `);
612
+ s.appendLeft(node.end, `)),\n ${isStatement ? `` : `__temp = `}await __temp,\n __restore()${isStatement ? `` : `,\n __temp`}\n)`);
613
+ }
614
+ //#endregion
615
+ //#region src/core/define-component/index.ts
616
+ function transformDefineComponent(root, propsName, macros, s) {
617
+ if (!macros.defineComponent) return;
618
+ let hasRestProp = false;
619
+ const props = {};
620
+ if (root.params[0]) {
621
+ if (root.params[0].type === "Identifier") {
622
+ getWalkedIds(root, propsName).forEach((id) => props[id] = null);
623
+ prependFunctionalNode(root, s, `const ${propsName} = ${importHelperFn(s, "useFullProps", void 0, "/vue-jsx-vapor/props")}()`);
624
+ s.overwrite(root.params[0].start, root.params[0].end, root.params.length > 1 ? `__props` : root.start === root.params[0].start ? "()" : "");
625
+ } else if (root.params[0].type === "ObjectPattern") {
626
+ const restructuredProps = root.params[0];
627
+ for (const prop of restructuredProps.properties) {
628
+ if (prop.type !== "ObjectProperty" || prop.key.type !== "Identifier") continue;
629
+ const propName = prop.key.name;
630
+ if (prop.value.type !== "AssignmentPattern") {
631
+ props[propName] = null;
632
+ continue;
633
+ }
634
+ const defaultValue = getDefaultValue(prop.value.right);
635
+ const isRequired = prop.value.right.type === "TSNonNullExpression";
636
+ const propOptions = [];
637
+ if (isRequired) propOptions.push("required: true");
638
+ if (defaultValue) {
639
+ const { value, type, skipFactory } = getTypeAndValue(s, defaultValue);
640
+ if (type) propOptions.push(`type: ${type}`);
641
+ if (value) propOptions.push(`default: ${value}`);
642
+ if (skipFactory) propOptions.push("skipFactory: true");
643
+ }
644
+ if (propOptions.length) props[propName] = `{ ${propOptions.join(", ")} }`;
645
+ else props[propName] = null;
646
+ }
647
+ restructure(s, root, {
648
+ skipDefaultProps: true,
649
+ generateRestProps: (restPropsName, index, list) => {
650
+ if (index === list.length - 1) {
651
+ hasRestProp = true;
652
+ return `const ${restPropsName} = ${importHelperFn(s, "useAttrs")}()`;
653
+ }
654
+ }
655
+ });
656
+ }
657
+ }
658
+ transformDefineModel$1(s, macros.defineModel, props);
659
+ const propsString = Object.entries(props).map(([key, value]) => `'${key}': ${value}`).join(", \n");
660
+ if (propsString || hasRestProp) {
661
+ const resolvedPropsString = `${hasRestProp ? "inheritAttrs: false, " : ""}${propsString ? `props: {\n${propsString}\n}, ` : ""}`;
662
+ const compOptions = macros.defineComponent.arguments[1];
663
+ if (compOptions) {
664
+ s.appendLeft(compOptions.start, `{ ${resolvedPropsString}...`);
665
+ s.appendRight(compOptions.end, " }");
666
+ } else s.appendRight(root.end, `, { ${resolvedPropsString}}`);
667
+ }
668
+ transformAwait(root, s);
669
+ }
670
+ function getWalkedIds(root, propsName) {
671
+ const walkedIds = /* @__PURE__ */ new Set();
672
+ walkIdentifiers(root.body, (id, parent) => {
673
+ if (id.name === propsName && (parent?.type === "MemberExpression" || parent?.type === "JSXMemberExpression" || parent?.type === "OptionalMemberExpression")) {
674
+ const prop = parent.property.type === "Identifier" || parent.property.type === "JSXIdentifier" ? parent.property.name : parent.property.type === "StringLiteral" ? parent.property.value : "";
675
+ if (prop) walkedIds.add(prop);
676
+ }
677
+ });
678
+ return walkedIds;
679
+ }
680
+ function transformDefineModel$1(s, defineModel, props) {
681
+ for (const { expression, isRequired } of defineModel || []) {
682
+ const modelOptions = expression.arguments[0]?.type === "ObjectExpression" ? expression.arguments[0] : expression.arguments[1]?.type === "ObjectExpression" ? expression.arguments[1] : void 0;
683
+ const options = {};
684
+ if (isRequired) options.required = true;
685
+ let defaultValueNode;
686
+ for (const prop of modelOptions?.properties || []) if (prop.type === "ObjectProperty" && prop.key.type === "Identifier" && [
687
+ "validator",
688
+ "type",
689
+ "required",
690
+ "default"
691
+ ].includes(prop.key.name)) {
692
+ if (prop.key.name === "default") defaultValueNode = prop.value;
693
+ options[prop.key.name] = s.slice(prop.value.start, prop.value.end);
694
+ }
695
+ if (defaultValueNode && !options.type) {
696
+ const { value, type, skipFactory } = getTypeAndValue(s, defaultValueNode);
697
+ if (type) options.type = type;
698
+ if (value) options.default = value;
699
+ if (skipFactory) options.skipFactory = "true";
700
+ }
701
+ const propName = expression.arguments[0]?.type === "StringLiteral" ? expression.arguments[0].value : "modelValue";
702
+ props[propName] = Object.keys(options).length ? `{ ${Object.entries(options).map(([key, value]) => `${key}: ${value}`).join(", ")} }` : null;
703
+ props[`onUpdate:${propName}`] = null;
704
+ props[`${propName === "modelValue" ? "model" : propName}Modifiers`] = null;
705
+ }
706
+ }
707
+ function getTypeAndValue(s, node) {
708
+ let value = "";
709
+ let type = "";
710
+ let skipFactory = false;
711
+ switch (node.type) {
712
+ case "StringLiteral":
713
+ type = "String";
714
+ value = `'${node.value}'`;
715
+ break;
716
+ case "BooleanLiteral":
717
+ type = "Boolean";
718
+ value = String(node.value);
719
+ break;
720
+ case "NumericLiteral":
721
+ type = "Number";
722
+ value = String(node.value);
723
+ break;
724
+ case "ObjectExpression":
725
+ type = "Object";
726
+ value = `() => (${s.slice(node.start, node.end)})`;
727
+ break;
728
+ case "ArrayExpression":
729
+ type = "Array";
730
+ value = `() => (${s.slice(node.start, node.end)})`;
731
+ break;
732
+ default: if (isFunctionalNode(node)) {
733
+ type = "Function";
734
+ value = s.slice(node.start, node.end);
735
+ } else if (node.type === "Identifier") if (node.name === "undefined") value = "undefined";
736
+ else {
737
+ skipFactory = true;
738
+ value = s.slice(node.start, node.end);
739
+ }
740
+ else if (node.type === "NullLiteral") value = "null";
741
+ }
742
+ return {
743
+ value,
744
+ type,
745
+ skipFactory
746
+ };
747
+ }
748
+ //#endregion
749
+ //#region src/core/define-expose.ts
750
+ function transformDefineExpose(node, s) {
751
+ const argument = node.arguments[0];
752
+ const typeParameters = node.typeParameters ?? node.typeArguments;
753
+ s.overwrite(node.callee.start, typeParameters?.end ?? node.callee.end, ";");
754
+ s.appendRight(argument?.start ?? node.end - 1, `${importHelperFn(s, "getCurrentInstance", void 0, "/vue-jsx-vapor/props")}().exposed = ${argument ? "" : "{}"}`);
755
+ }
756
+ //#endregion
757
+ //#region src/core/define-model.ts
758
+ function transformDefineModel(node, propsName, s) {
759
+ s.overwrite(node.callee.start, node.callee.end, importHelperFn(s, "useModel", void 0, useModelHelperId));
760
+ s.appendRight(node.arguments[0]?.start || node.end - 1, `${propsName}, ${node.arguments[0]?.type === "StringLiteral" ? "" : `'modelValue',`}`);
761
+ }
762
+ //#endregion
763
+ //#region src/core/define-slots.ts
764
+ function transformDefineSlots(node, s) {
765
+ s.overwrite(node.callee.start, node.callee.end, importHelperFn(s, "useSlots", void 0, useSlotsHelperId));
766
+ }
767
+ //#endregion
768
+ //#region src/core/define-style.ts
769
+ function transformDefineStyle(defineStyle, index, root, s, importMap, { defineSlots }) {
770
+ const { expression, lang, isCssModules } = defineStyle;
771
+ if (expression.arguments[0]?.type !== "TemplateLiteral") return;
772
+ let css = s.slice(expression.arguments[0].start, expression.arguments[0].end).slice(1, -1);
773
+ const scopeId = hash(css);
774
+ const vars = /* @__PURE__ */ new Map();
775
+ expression.arguments[0].expressions.forEach((exp) => {
776
+ const cssVar = s.slice(exp.start, exp.end);
777
+ const cssVarId = toCssVarId(cssVar, `--${scopeId}-`);
778
+ s.overwrite(exp.start - 2, exp.end + 1, `var(${cssVarId})`);
779
+ vars.set(cssVarId, cssVar);
780
+ });
781
+ let returnExpression = root && getReturnStatement(root);
782
+ if (isFunctionalNode(returnExpression)) returnExpression = getReturnStatement(returnExpression);
783
+ if (vars.size && returnExpression) {
784
+ const children = returnExpression.type === "JSXElement" ? [returnExpression] : returnExpression.type === "JSXFragment" ? returnExpression.children : [];
785
+ const varString = Array.from(vars.entries()).map(([key, value]) => `'${key}': ${value}`).join(", ");
786
+ for (const child of children) if (child.type === "JSXElement") s.appendRight(child.openingElement.name.end, ` {...{style:{${varString}}}}`);
787
+ }
788
+ let scoped = !!root;
789
+ if (expression.arguments[1]?.type === "ObjectExpression") {
790
+ for (const prop of expression.arguments[1].properties) if (prop.type === "ObjectProperty" && prop.key.type === "Identifier" && prop.key.name === "scoped" && prop.value.type === "BooleanLiteral") scoped = prop.value.value;
791
+ }
792
+ if (scoped && root) {
793
+ const slotNames = defineSlots?.id ? defineSlots.id.type === "Identifier" ? defineSlots.id.name : defineSlots.id.type === "ObjectPattern" ? defineSlots.id.properties.map((prop) => {
794
+ const value = prop.type === "RestElement" ? prop.argument : prop.value;
795
+ return s.slice(value.start, value.end);
796
+ }) : [] : [];
797
+ walkAST(root, { enter(node) {
798
+ if (node.type === "JSXElement" && s.slice(node.openingElement.name.start, node.openingElement.name.end) !== "template") {
799
+ let subfix = "";
800
+ if (slotNames.length) {
801
+ const tagName = node.openingElement.name.type === "JSXMemberExpression" ? node.openingElement.name.object : node.openingElement.name;
802
+ const name = s.slice(tagName.start, tagName.end);
803
+ subfix = slotNames.includes(name) ? "-s" : "";
804
+ }
805
+ s.appendRight(node.openingElement.name.end, ` data-v-${scopeId}${subfix}=""`);
806
+ }
807
+ } });
808
+ }
809
+ css = s.slice(expression.arguments[0].start, expression.arguments[0].end).slice(1, -1).replaceAll(/^([ \t]*)\/\/([^\r\n]*)/gm, "$1/*$2 */");
810
+ const importId = `${helperPrefix}/define-style/${index}?scopeId=${scopeId}&scoped=${scoped}&lang.${isCssModules ? "module." : ""}${lang}`;
811
+ importMap.set(importId, css);
812
+ s.appendLeft(0, isCssModules ? `import style${index} from "${importId}";` : `import "${importId}";`);
813
+ s.overwrite(expression.start, expression.end, isCssModules ? `style${index}` : "");
814
+ }
815
+ function getReturnStatement(root) {
816
+ if (root.body.type === "BlockStatement") {
817
+ const returnStatement = root.body.body.find((node) => node.type === "ReturnStatement");
818
+ if (returnStatement) return returnStatement.argument;
819
+ } else return root.body;
820
+ }
821
+ function toCssVarId(name, prefix = "") {
822
+ return prefix + name.replaceAll(/\W/g, (searchValue, replaceValue) => {
823
+ return searchValue === "." ? "-" : name.charCodeAt(replaceValue).toString();
824
+ });
825
+ }
826
+ //#endregion
827
+ //#region src/core/index.ts
828
+ let babelParse;
829
+ async function getBabelParse() {
830
+ if (babelParse) return babelParse;
831
+ const require = getRequire();
832
+ try {
833
+ return babelParse = require ? require("vue/compiler-sfc").babelParse : (await import("https://esm.sh/@vue/compiler-sfc")).babelParse;
834
+ } catch {}
835
+ }
836
+ async function transformJsxMacros(code, id, importMap, options) {
837
+ const s = new MagicString(code);
838
+ const lang = getLang(id);
839
+ if (lang === "dts") return;
840
+ const ast = (await getBabelParse())(s.original, {
841
+ sourceType: "module",
842
+ plugins: lang === "tsx" ? ["typescript", "jsx"] : lang === "jsx" ? ["jsx"] : lang === "ts" ? ["typescript"] : []
843
+ }).program;
844
+ const rootMap = getRootMap(ast, s, options);
845
+ let defineStyleIndex = 0;
846
+ for (const [root, macros] of rootMap) {
847
+ macros.defineStyle?.forEach((defineStyle) => {
848
+ transformDefineStyle(defineStyle, defineStyleIndex++, root, s, importMap, macros);
849
+ });
850
+ if (root === void 0) continue;
851
+ let propsName = `__props`;
852
+ if (root.params[0]) {
853
+ if (root.params[0].type === "Identifier") propsName = root.params[0].name;
854
+ else if (root.params[0].type === "ObjectPattern") {
855
+ const lastProp = root.params[0].properties.at(-1);
856
+ if (!macros.defineComponent && lastProp?.type === "RestElement" && lastProp.argument.type === "Identifier") propsName = lastProp.argument.name;
857
+ else s.appendRight(root.params[0].extra?.trailingComma ? root.params[0].extra?.trailingComma + 1 : lastProp?.end || root.params[0].end - 1, `${!root.params[0].extra?.trailingComma && root.params[0].properties.length ? "," : ""} ...__props`);
858
+ }
859
+ } else if (macros.defineModel?.length) s.appendRight(getParamsStart(root, s.original), propsName);
860
+ if (macros.defineComponent) transformDefineComponent(root, propsName, macros, s);
861
+ if (macros.defineModel?.length) macros.defineModel.forEach(({ expression }) => {
862
+ transformDefineModel(expression, propsName, s);
863
+ });
864
+ if (macros.defineSlots) transformDefineSlots(macros.defineSlots.expression, s);
865
+ if (macros.defineExpose) transformDefineExpose(macros.defineExpose, s);
866
+ }
867
+ if (s.hasChanged()) return {
868
+ code: s.toString(),
869
+ get map() {
870
+ return s.generateMap({
871
+ source: id,
872
+ includeContent: true,
873
+ hires: "boundary"
874
+ });
875
+ }
876
+ };
877
+ }
878
+ function getRootMap(ast, s, options) {
879
+ const parents = [];
880
+ const rootMap = /* @__PURE__ */ new Map();
881
+ walkAST(ast, {
882
+ enter(node, parent) {
883
+ parents.unshift(parent);
884
+ const root = isFunctionalNode(parents[1]) ? parents[1] : void 0;
885
+ if (root && parents[2]?.type === "CallExpression" && options.defineComponent.alias.includes(s.slice(parents[2].callee.start, parents[2].callee.end))) {
886
+ if (!rootMap.has(root)) rootMap.set(root, {});
887
+ if (!rootMap.get(root).defineComponent) rootMap.get(root).defineComponent = parents[2];
888
+ }
889
+ const expression = node.type === "VariableDeclaration" ? node.declarations[0].init?.type === "CallExpression" && s.slice(node.declarations[0].init.callee.start, node.declarations[0].init.callee.end) === "$" ? node.declarations[0].init.arguments[0] : node.declarations[0].init : node.type === "ExpressionStatement" ? node.expression : void 0;
890
+ if (!expression) return;
891
+ const macroExpression = getMacroExpression(expression, options);
892
+ if (!macroExpression) return;
893
+ if (!rootMap.has(root)) rootMap.set(root, {});
894
+ const macro = macroExpression.callee.type === "MemberExpression" ? macroExpression.callee.object : macroExpression.callee;
895
+ const macroName = s.slice(macro.start, macro.end);
896
+ if (macroName) {
897
+ if (options.defineModel.alias.includes(macroName)) (rootMap.get(root).defineModel ??= []).push({
898
+ expression: macroExpression,
899
+ isRequired: expression.type === "TSNonNullExpression"
900
+ });
901
+ else if (options.defineStyle.alias.includes(macroName)) {
902
+ const lang = macroExpression.callee.type === "MemberExpression" && macroExpression.callee.property.type === "Identifier" ? macroExpression.callee.property.name : "css";
903
+ (rootMap.get(root).defineStyle ??= []).push({
904
+ expression: macroExpression,
905
+ isCssModules: node.type === "VariableDeclaration",
906
+ lang
907
+ });
908
+ } else if (options.defineSlots.alias.includes(macroName)) rootMap.get(root).defineSlots = {
909
+ expression: macroExpression,
910
+ id: node.type === "VariableDeclaration" ? node.declarations[0].id : void 0
911
+ };
912
+ else if (options.defineExpose.alias.includes(macroName)) rootMap.get(root).defineExpose = macroExpression;
913
+ }
914
+ },
915
+ leave() {
916
+ parents.shift();
917
+ }
918
+ });
919
+ return rootMap;
920
+ }
921
+ function getMacroExpression(node, options) {
922
+ if (node.type === "TSNonNullExpression") node = node.expression;
923
+ if (node.type === "CallExpression") {
924
+ if (node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "defineStyle") return node;
925
+ else if (node.callee.type === "Identifier" && [
926
+ ...options.defineComponent.alias,
927
+ ...options.defineSlots.alias,
928
+ ...options.defineModel.alias,
929
+ ...options.defineExpose.alias,
930
+ ...options.defineStyle.alias
931
+ ].includes(node.callee.name)) return node;
932
+ }
933
+ }
934
+ //#endregion
935
+ export { isFunctionalNode as a, withDefaultsHelperId as c, use_model_default as d, getRequire as i, with_defaults_default as l, transformJsxMacros as n, useModelHelperId as o, restructure as r, useSlotsHelperId as s, getMacroExpression as t, use_slots_default as u };