|
- // src/core/impl.ts
- import MagicString from "magic-string";
-
- // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
- var WalkerBase = class {
- constructor() {
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- this.context = {
- skip: () => this.should_skip = true,
- remove: () => this.should_remove = true,
- replace: (node) => this.replacement = node
- };
- }
- /**
- * @template {Node} Parent
- * @param {Parent | null | undefined} parent
- * @param {keyof Parent | null | undefined} prop
- * @param {number | null | undefined} index
- * @param {Node} node
- */
- replace(parent, prop, index, node) {
- if (parent && prop) {
- if (index != null) {
- parent[prop][index] = node;
- } else {
- parent[prop] = node;
- }
- }
- }
- /**
- * @template {Node} Parent
- * @param {Parent | null | undefined} parent
- * @param {keyof Parent | null | undefined} prop
- * @param {number | null | undefined} index
- */
- remove(parent, prop, index) {
- if (parent && prop) {
- if (index !== null && index !== void 0) {
- parent[prop].splice(index, 1);
- } else {
- delete parent[prop];
- }
- }
- }
- };
-
- // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
- var SyncWalker = class extends WalkerBase {
- /**
- *
- * @param {SyncHandler} [enter]
- * @param {SyncHandler} [leave]
- */
- constructor(enter, leave) {
- super();
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- this.context = {
- skip: () => this.should_skip = true,
- remove: () => this.should_remove = true,
- replace: (node) => this.replacement = node
- };
- this.enter = enter;
- this.leave = leave;
- }
- /**
- * @template {Node} Parent
- * @param {Node} node
- * @param {Parent | null} parent
- * @param {keyof Parent} [prop]
- * @param {number | null} [index]
- * @returns {Node | null}
- */
- visit(node, parent, prop, index) {
- if (node) {
- if (this.enter) {
- const _should_skip = this.should_skip;
- const _should_remove = this.should_remove;
- const _replacement = this.replacement;
- this.should_skip = false;
- this.should_remove = false;
- this.replacement = null;
- this.enter.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) {
- this.remove(parent, prop, index);
- }
- const skipped = this.should_skip;
- const removed = this.should_remove;
- this.should_skip = _should_skip;
- this.should_remove = _should_remove;
- this.replacement = _replacement;
- if (skipped)
- return node;
- if (removed)
- return null;
- }
- let key;
- for (key in node) {
- const value = node[key];
- if (value && typeof value === "object") {
- if (Array.isArray(value)) {
- const nodes = (
- /** @type {Array<unknown>} */
- value
- );
- for (let i = 0; i < nodes.length; i += 1) {
- const item = nodes[i];
- if (isNode(item)) {
- if (!this.visit(item, node, key, i)) {
- i--;
- }
- }
- }
- } else if (isNode(value)) {
- this.visit(value, node, key, null);
- }
- }
- }
- if (this.leave) {
- const _replacement = this.replacement;
- const _should_remove = this.should_remove;
- this.replacement = null;
- this.should_remove = false;
- this.leave.call(this.context, node, parent, prop, index);
- if (this.replacement) {
- node = this.replacement;
- this.replace(parent, prop, index, node);
- }
- if (this.should_remove) {
- this.remove(parent, prop, index);
- }
- const removed = this.should_remove;
- this.replacement = _replacement;
- this.should_remove = _should_remove;
- if (removed)
- return null;
- }
- }
- return node;
- }
- };
- function isNode(value) {
- return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
- }
-
- // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
- function walk(ast, { enter, leave }) {
- const instance = new SyncWalker(enter, leave);
- return instance.visit(ast, null);
- }
-
- // src/core/impl.ts
- import {
- extractIdentifiers,
- isFunctionType,
- isInDestructureAssignment,
- isReferencedIdentifier,
- isStaticProperty,
- walkFunctionParams
- } from "@vue/compiler-core";
- import { parse } from "@babel/parser";
- import { genPropsAccessExp, hasOwn, isArray, isString } from "@vue/shared";
- import { TS_NODE_TYPES, unwrapTSNode } from "@vue-macros/common";
- var CONVERT_SYMBOL = "$";
- var ESCAPE_SYMBOL = "$$";
- var IMPORT_SOURCE = "vue/macros";
- var shorthands = ["ref", "computed", "shallowRef", "toRef", "customRef"];
- var transformCheckRE = /\W\$(?:\$|ref|computed|shallowRef|toRef|customRef)?\s*([(<])/;
- function shouldTransform(src) {
- return transformCheckRE.test(src);
- }
- function transform(src, {
- filename,
- sourceMap,
- parserPlugins,
- importHelpersFrom = "vue"
- } = {}) {
- const plugins = parserPlugins || [];
- if (filename) {
- if (/\.tsx?$/.test(filename)) {
- plugins.push("typescript");
- }
- if (filename.endsWith("x")) {
- plugins.push("jsx");
- }
- }
- const ast = parse(src, {
- sourceType: "module",
- plugins
- });
- const s = new MagicString(src);
- const res = transformAST(ast.program, s, 0);
- if (res.importedHelpers.length > 0) {
- s.prepend(
- `import { ${res.importedHelpers.map((h) => `${h} as _${h}`).join(", ")} } from '${importHelpersFrom}'
- `
- );
- }
- return {
- ...res,
- code: s.toString(),
- map: sourceMap ? s.generateMap({
- source: filename,
- hires: true,
- includeContent: true
- }) : null
- };
- }
- function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
- const userImports = /* @__PURE__ */ Object.create(null);
- for (const node of ast.body) {
- if (node.type !== "ImportDeclaration")
- continue;
- walkImportDeclaration(node);
- }
- let convertSymbol;
- let escapeSymbol;
- for (const { local, imported, source, specifier } of Object.values(
- userImports
- )) {
- if (source === IMPORT_SOURCE) {
- if (imported === ESCAPE_SYMBOL) {
- escapeSymbol = local;
- } else if (imported === CONVERT_SYMBOL) {
- convertSymbol = local;
- } else if (imported !== local) {
- error(
- `macro imports for ref-creating methods do not support aliasing.`,
- specifier
- );
- }
- }
- }
- if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
- convertSymbol = CONVERT_SYMBOL;
- }
- if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
- escapeSymbol = ESCAPE_SYMBOL;
- }
- const importedHelpers = /* @__PURE__ */ new Set();
- const rootScope = {};
- const scopeStack = [rootScope];
- let currentScope = rootScope;
- let escapeScope;
- const excludedIds = /* @__PURE__ */ new WeakSet();
- const parentStack = [];
- const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
- if (knownRefs) {
- for (const key of knownRefs) {
- rootScope[key] = {};
- }
- }
- if (knownProps) {
- for (const key in knownProps) {
- const { local, isConst } = knownProps[key];
- rootScope[local] = {
- isProp: true,
- isConst: !!isConst
- };
- propsLocalToPublicMap[local] = key;
- }
- }
- function walkImportDeclaration(node) {
- const source = node.source.value;
- if (source === IMPORT_SOURCE) {
- s.remove(node.start + offset, node.end + offset);
- }
- for (const specifier of node.specifiers) {
- const local = specifier.local.name;
- const imported = specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name || "default";
- userImports[local] = {
- source,
- local,
- imported,
- specifier
- };
- }
- }
- function isRefCreationCall(callee) {
- if (!convertSymbol || getCurrentScope()[convertSymbol] !== void 0) {
- return false;
- }
- if (callee === convertSymbol) {
- return convertSymbol;
- }
- if (callee[0] === "$" && shorthands.includes(callee.slice(1))) {
- return callee;
- }
- return false;
- }
- function error(msg, node) {
- const e = new Error(msg);
- e.node = node;
- throw e;
- }
- function helper(msg) {
- importedHelpers.add(msg);
- return `_${msg}`;
- }
- function getCurrentScope() {
- return scopeStack.reduce((prev, curr) => ({ ...prev, ...curr }), {});
- }
- function registerBinding(id, binding) {
- excludedIds.add(id);
- if (currentScope) {
- currentScope[id.name] = binding ? binding : false;
- } else {
- error(
- "registerBinding called without active scope, something is wrong.",
- id
- );
- }
- }
- const registerRefBinding = (id, isConst = false) => registerBinding(id, { isConst });
- let tempVarCount = 0;
- function genTempVar() {
- return `__$temp_${++tempVarCount}`;
- }
- function snip(node) {
- return s.original.slice(node.start + offset, node.end + offset);
- }
- function findUpParent() {
- return parentStack.slice().reverse().find(({ type }) => !TS_NODE_TYPES.includes(type));
- }
- function walkScope(node, isRoot = false) {
- for (const stmt of node.body) {
- if (stmt.type === "VariableDeclaration") {
- walkVariableDeclaration(stmt, isRoot);
- } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
- if (stmt.declare || !stmt.id)
- continue;
- registerBinding(stmt.id);
- } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
- walkVariableDeclaration(stmt.left);
- } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
- walkVariableDeclaration(stmt.declaration, isRoot);
- } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
- walkVariableDeclaration(stmt.body, isRoot);
- }
- }
- }
- function walkVariableDeclaration(stmt, isRoot = false) {
- if (stmt.declare) {
- return;
- }
- for (const decl of stmt.declarations) {
- let refCall;
- const init = decl.init ? unwrapTSNode(decl.init) : null;
- const isCall = init && init.type === "CallExpression" && init.callee.type === "Identifier";
- if (isCall && (refCall = isRefCreationCall(init.callee.name))) {
- processRefDeclaration(
- refCall,
- decl.id,
- decl.init,
- init,
- stmt.kind === "const"
- );
- } else {
- const isProps = isRoot && isCall && init.callee.name === "defineProps";
- for (const id of extractIdentifiers(decl.id)) {
- if (isProps) {
- excludedIds.add(id);
- } else {
- registerBinding(id);
- }
- }
- }
- }
- }
- function processRefDeclaration(method, id, init, call, isConst) {
- excludedIds.add(call.callee);
- if (method === convertSymbol) {
- s.remove(call.callee.start + offset, call.callee.end + offset);
- if (id.type === "Identifier") {
- registerRefBinding(id, isConst);
- } else if (id.type === "ObjectPattern") {
- processRefObjectPattern(id, init, isConst);
- } else if (id.type === "ArrayPattern") {
- processRefArrayPattern(id, init, isConst);
- }
- } else if (id.type === "Identifier") {
- registerRefBinding(id, isConst);
- s.overwrite(
- call.start + offset,
- call.start + method.length + offset,
- helper(method.slice(1))
- );
- } else {
- error(`${method}() cannot be used with destructure patterns.`, call);
- }
- }
- function processRefObjectPattern(pattern, value, isConst, tempVar, path = []) {
- if (!tempVar) {
- tempVar = genTempVar();
- s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
- }
- let nameId;
- for (const p of pattern.properties) {
- let key;
- let defaultValue;
- if (p.type === "ObjectProperty") {
- if (p.key.start === p.value.start) {
- nameId = p.key;
- if (p.value.type === "Identifier") {
- excludedIds.add(p.value);
- } else if (p.value.type === "AssignmentPattern" && p.value.left.type === "Identifier") {
- excludedIds.add(p.value.left);
- defaultValue = p.value.right;
- }
- } else {
- key = p.computed ? p.key : p.key.name;
- if (p.value.type === "Identifier") {
- nameId = p.value;
- } else if (p.value.type === "ObjectPattern") {
- processRefObjectPattern(p.value, value, isConst, tempVar, [
- ...path,
- key
- ]);
- } else if (p.value.type === "ArrayPattern") {
- processRefArrayPattern(p.value, value, isConst, tempVar, [
- ...path,
- key
- ]);
- } else if (p.value.type === "AssignmentPattern") {
- if (p.value.left.type === "Identifier") {
- nameId = p.value.left;
- defaultValue = p.value.right;
- } else if (p.value.left.type === "ObjectPattern") {
- processRefObjectPattern(p.value.left, value, isConst, tempVar, [
- ...path,
- [key, p.value.right]
- ]);
- } else if (p.value.left.type === "ArrayPattern") {
- processRefArrayPattern(p.value.left, value, isConst, tempVar, [
- ...path,
- [key, p.value.right]
- ]);
- } else {
- }
- }
- }
- } else {
- error(`reactivity destructure does not support rest elements.`, p);
- }
- if (nameId) {
- registerRefBinding(nameId, isConst);
- const source = pathToString(tempVar, path);
- const keyStr = isString(key) ? `'${key}'` : key ? snip(key) : `'${nameId.name}'`;
- const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
- s.appendLeft(
- value.end + offset,
- `,
- ${nameId.name} = ${helper(
- "toRef"
- )}(${source}, ${keyStr}${defaultStr})`
- );
- }
- }
- if (nameId) {
- s.appendLeft(value.end + offset, ";");
- }
- }
- function processRefArrayPattern(pattern, value, isConst, tempVar, path = []) {
- if (!tempVar) {
- tempVar = genTempVar();
- s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
- }
- let nameId;
- for (let i = 0; i < pattern.elements.length; i++) {
- const e = pattern.elements[i];
- if (!e)
- continue;
- let defaultValue;
- if (e.type === "Identifier") {
- nameId = e;
- } else if (e.type === "AssignmentPattern") {
- nameId = e.left;
- defaultValue = e.right;
- } else if (e.type === "RestElement") {
- error(`reactivity destructure does not support rest elements.`, e);
- } else if (e.type === "ObjectPattern") {
- processRefObjectPattern(e, value, isConst, tempVar, [...path, i]);
- } else if (e.type === "ArrayPattern") {
- processRefArrayPattern(e, value, isConst, tempVar, [...path, i]);
- }
- if (nameId) {
- registerRefBinding(nameId, isConst);
- const source = pathToString(tempVar, path);
- const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
- s.appendLeft(
- value.end + offset,
- `,
- ${nameId.name} = ${helper(
- "toRef"
- )}(${source}, ${i}${defaultStr})`
- );
- }
- }
- if (nameId) {
- s.appendLeft(value.end + offset, ";");
- }
- }
- function pathToString(source, path) {
- if (path.length > 0) {
- for (const seg of path) {
- if (isArray(seg)) {
- source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
- } else {
- source += segToString(seg);
- }
- }
- }
- return source;
- }
- function segToString(seg) {
- if (typeof seg === "number") {
- return `[${seg}]`;
- } else if (typeof seg === "string") {
- return `.${seg}`;
- } else {
- return snip(seg);
- }
- }
- function rewriteId(scope, id, parent, parentStack2) {
- if (hasOwn(scope, id.name)) {
- const binding = scope[id.name];
- if (binding) {
- if (binding.isConst && (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression")) {
- error(`Assignment to constant variable.`, id);
- }
- const { isProp } = binding;
- if (isStaticProperty(parent) && parent.shorthand) {
- if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) {
- if (isProp) {
- if (escapeScope) {
- registerEscapedPropBinding(id);
- s.appendLeft(
- id.end + offset,
- `: __props_${propsLocalToPublicMap[id.name]}`
- );
- } else {
- s.appendLeft(
- id.end + offset,
- `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`
- );
- }
- } else {
- s.appendLeft(id.end + offset, `: ${id.name}.value`);
- }
- }
- } else if (isProp) {
- if (escapeScope) {
- registerEscapedPropBinding(id);
- s.overwrite(
- id.start + offset,
- id.end + offset,
- `__props_${propsLocalToPublicMap[id.name]}`
- );
- } else {
- s.overwrite(
- id.start + offset,
- id.end + offset,
- genPropsAccessExp(propsLocalToPublicMap[id.name])
- );
- }
- } else {
- s.appendLeft(id.end + offset, ".value");
- }
- }
- return true;
- }
- return false;
- }
- const propBindingRefs = {};
- function registerEscapedPropBinding(id) {
- if (!propBindingRefs.hasOwnProperty(id.name)) {
- propBindingRefs[id.name] = true;
- const publicKey = propsLocalToPublicMap[id.name];
- s.prependRight(
- offset,
- `const __props_${publicKey} = ${helper(
- `toRef`
- )}(__props, '${publicKey}');
- `
- );
- }
- }
- walkScope(ast, true);
- walk(ast, {
- enter(node, parent) {
- parent && parentStack.push(parent);
- if (isFunctionType(node)) {
- scopeStack.push(currentScope = {});
- walkFunctionParams(node, registerBinding);
- if (node.body.type === "BlockStatement") {
- walkScope(node.body);
- }
- return;
- }
- if (node.type === "CatchClause") {
- scopeStack.push(currentScope = {});
- if (node.param && node.param.type === "Identifier") {
- registerBinding(node.param);
- }
- walkScope(node.body);
- return;
- }
- if (node.type === "BlockStatement" && !isFunctionType(parent)) {
- scopeStack.push(currentScope = {});
- walkScope(node);
- return;
- }
- if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
- return this.skip();
- }
- if (node.type === "Identifier") {
- const binding = rootScope[node.name];
- if (
- // if inside $$(), skip unless this is a destructured prop binding
- !(escapeScope && (!binding || !binding.isProp)) && isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)
- ) {
- let i = scopeStack.length;
- while (i--) {
- if (rewriteId(scopeStack[i], node, parent, parentStack)) {
- return;
- }
- }
- }
- }
- if (node.type === "CallExpression" && node.callee.type === "Identifier") {
- const callee = node.callee.name;
- const refCall = isRefCreationCall(callee);
- const parent2 = findUpParent();
- if (refCall && (!parent2 || parent2.type !== "VariableDeclarator")) {
- return error(
- `${refCall} can only be used as the initializer of a variable declaration.`,
- node
- );
- }
- if (escapeSymbol && getCurrentScope()[escapeSymbol] === void 0 && callee === escapeSymbol) {
- escapeScope = node;
- s.remove(node.callee.start + offset, node.callee.end + offset);
- if ((parent2 == null ? void 0 : parent2.type) === "ExpressionStatement") {
- let i = (node.leadingComments ? node.leadingComments[0].start : node.start) + offset;
- while (i--) {
- const char = s.original.charAt(i);
- if (char === "\n") {
- s.prependRight(node.start + offset, ";");
- break;
- } else if (!/\s/.test(char)) {
- break;
- }
- }
- }
- }
- }
- },
- leave(node, parent) {
- parent && parentStack.pop();
- if (node.type === "BlockStatement" && !isFunctionType(parent) || isFunctionType(node)) {
- scopeStack.pop();
- currentScope = scopeStack[scopeStack.length - 1] || null;
- }
- if (node === escapeScope) {
- escapeScope = void 0;
- }
- }
- });
- return {
- rootRefs: Object.keys(rootScope).filter((key) => {
- const binding = rootScope[key];
- return binding && !binding.isProp;
- }),
- importedHelpers: [...importedHelpers]
- };
- }
-
- // src/core/helper/code.ts?raw
- var code_default = "export function createPropsRestProxy(props,excludedKeys){const ret={};for(const key in props){if(!excludedKeys.includes(key)){Object.defineProperty(ret,key,{enumerable:true,get:()=>props[key]})}}return ret}\n";
-
- // src/core/helper/index.ts
- var helperId = "/vue-macros/reactivity-transform/helper";
-
- // src/core/index.ts
- import {
- DEFINE_PROPS,
- MagicString as MagicString2,
- getTransformResult,
- isCallOf,
- parseSFC,
- resolveObjectKey
- } from "@vue-macros/common";
- function transformVueSFC(code, id) {
- const s = new MagicString2(code);
- const { script, scriptSetup, getScriptAst, getSetupAst } = parseSFC(code, id);
- let refBindings;
- let propsDestructuredBindings;
- if (script && shouldTransform(script.content)) {
- const offset = script.loc.start.offset;
- const { importedHelpers, rootRefs } = transformAST(
- getScriptAst(),
- s,
- offset
- );
- refBindings = rootRefs;
- importHelpers(s, script.loc.start.offset, importedHelpers);
- }
- if (scriptSetup) {
- const ast = getSetupAst();
- for (const node of ast.body) {
- processDefineProps(node);
- }
- if (propsDestructuredBindings || refBindings || shouldTransform(scriptSetup.content)) {
- const { importedHelpers } = transformAST(
- ast,
- s,
- scriptSetup.loc.start.offset,
- refBindings,
- propsDestructuredBindings
- );
- importHelpers(s, scriptSetup.loc.start.offset, importedHelpers);
- }
- }
- return getTransformResult(s, id);
- function processDefineProps(node) {
- if (node.type !== "VariableDeclaration")
- return;
- const decl = node.declarations.find(
- (decl2) => isCallOf(decl2.init, DEFINE_PROPS)
- );
- if (!decl || decl.id.type !== "ObjectPattern")
- return;
- if (node.declarations.length > 1)
- throw new SyntaxError(
- `${DEFINE_PROPS}() don't support multiple declarations.`
- );
- const offset = scriptSetup.loc.start.offset;
- let defaultStr = "";
- propsDestructuredBindings = {};
- for (const prop of decl.id.properties) {
- if (prop.type === "ObjectProperty") {
- const propKey = resolveObjectKey(prop.key, prop.computed, false);
- if (!propKey) {
- throw new SyntaxError(
- `${DEFINE_PROPS}() destructure cannot use computed key.`
- );
- }
- if (prop.value.type === "AssignmentPattern") {
- const { left, right } = prop.value;
- if (left.type !== "Identifier") {
- throw new SyntaxError(
- `${DEFINE_PROPS}() destructure does not support nested patterns.`
- );
- }
- propsDestructuredBindings[propKey] = {
- local: left.name
- };
- defaultStr += `${propKey}: ${s.sliceNode(right, { offset })},`;
- } else if (prop.value.type === "Identifier") {
- propsDestructuredBindings[propKey] = {
- local: prop.value.name
- };
- } else {
- throw new SyntaxError(
- `${DEFINE_PROPS}() destructure does not support nested patterns.`
- );
- }
- } else {
- s.prependLeft(
- offset,
- `import { createPropsRestProxy } from '${helperId}';
- const ${prop.argument.name} = createPropsRestProxy(__props, ${JSON.stringify(
- Object.keys(propsDestructuredBindings)
- )});
- `
- );
- }
- }
- const declStr = `withDefaults(${s.sliceNode(decl.init, {
- offset
- })}, { ${defaultStr} })`;
- s.overwriteNode(node, declStr, { offset });
- }
- }
- function importHelpers(s, offset, helpers) {
- if (helpers.length === 0)
- return;
- s.prependLeft(
- offset,
- `import { ${helpers.map((h) => `${h} as _${h}`).join(", ")} } from 'vue';
- `
- );
- }
-
- export {
- shouldTransform,
- transform,
- transformAST,
- code_default,
- helperId,
- transformVueSFC
- };
|