@wevu/compiler 7.6.0 → 7.7.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.
package/dist/index.mjs CHANGED
@@ -21,11 +21,11 @@ const __weapp_defineThemeJson = (config) => (__weapp_json_macro_values.push(conf
21
21
  `.trimStart()+ms.toString()+`\nexport default __weapp_json_macro_values\n`;const extension=resolveScriptSetupExtension$1(lang);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.json-macro.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const resolved=mod?.default??mod;const values=Array.isArray(resolved)?resolved:[resolved];let accumulator={};for(const raw of values){if(raw===void 0)continue;let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`宏的返回值必须解析为对象。`);if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}if(!Object.keys(accumulator).length)return{dependencies};return{config:accumulator,dependencies}}finally{try{await remove(tempDir)}catch{}}})}const JSON_MACROS=/* @__PURE__ */ new Set([`defineAppJson`,`definePageJson`,`defineComponentJson`,`defineSitemapJson`,`defineThemeJson`]);const JSON_MACRO_HINT_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;function mayContainJsonMacro(content){return JSON_MACRO_HINT_RE.test(content)}function parseScriptSetupAst(content,filename){try{return parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 中的 <script setup> 失败:${message}`)}}function collectMacroCallPaths(ast,filename){const macroNames=/* @__PURE__ */ new Set;const macroStatements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee))return;if(!JSON_MACROS.has(callee.name))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))throw new Error(`${callee.name}() 必须在 <script setup> 顶层语句中使用(${filename})。`);macroNames.add(callee.name);macroStatements.push(path.parentPath)}});return{macroNames,macroStatements}}function assertSingleMacro(macroNames,filename){if(macroNames.size>1)throw new Error(`同一个 <script setup> 仅能使用 ${[...JSON_MACROS].join(`, `)} 中的一个(${filename})。`);return macroNames.values().next().value}function findProgramPath(ast){let programPath;traverse(ast,{Program(path){programPath=path;path.stop()}});return programPath}function stripScriptSetupMacroStatements(content,ast,filename,sourceMap){const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);const macroStatementSources=[];const body=ast.program?.body??[];for(const statement of body){if(!t.isExpressionStatement(statement))continue;const expr=statement.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))continue;const name=expr.callee.name;if(!JSON_MACROS.has(name))continue;if(expr.arguments.length!==1)throw new Error(`${name}() 在 ${filename} 中必须且只能传 1 个参数。`);if(typeof statement.start===`number`&&typeof statement.end===`number`)macroStatementSources.push(content.slice(statement.start,statement.end));if(typeof statement.start===`number`&&typeof statement.end===`number`)ms.remove(statement.start,statement.end)}const stripped=sourceMap?ms.slice(0,content.length):ms.toString();const result={stripped,macroStatementSources};if(!sourceMap||stripped===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}function splitJsonMacroCallsFromCode(code,filename){let ast;try{ast=parse$3(code,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){try{ast=parseJsLike(code)}catch(fallbackError){const message=error instanceof Error?error.message:String(error);const fallbackMessage=fallbackError instanceof Error?fallbackError.message:String(fallbackError);throw new Error(`解析 ${filename} 的编译脚本失败:${message};兜底解析失败:${fallbackMessage}`)}}const ms=new MagicString(code);const macroSources=[];traverse(ast,{ExpressionStatement(path){const expr=path.node.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))return;if(!JSON_MACROS.has(expr.callee.name))return;const start=path.node.start;const end=path.node.end;if(typeof start===`number`&&typeof end===`number`){macroSources.push(code.slice(start,end));ms.remove(start,end)}}});return{macroSources,stripped:ms.toString()}}function stripJsonMacroCallsFromCode(code,filename){return splitJsonMacroCallsFromCode(code,filename).stripped}function unwrapTsExpression$1(node){if(t.isTSAsExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node))return unwrapTsExpression$1(node.expression);return node}function resolveStaticLiteralValue(node){const normalized=unwrapTsExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized))return normalized.value;if(t.isNullLiteral(normalized))return null;if(t.isUnaryExpression(normalized)&&(normalized.operator===`-`||normalized.operator===`+`)&&t.isNumericLiteral(normalized.argument))return normalized.operator===`-`?-normalized.argument.value:normalized.argument.value;if(t.isArrayExpression(normalized)){const values=[];for(const element of normalized.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element))throw new Error(`unsupported static json macro array item`);values.push(resolveStaticLiteralValue(element))}return values}if(t.isObjectExpression(normalized)){const value={};for(const property of normalized.properties){if(!t.isObjectProperty(property)||property.computed||!t.isExpression(property.value))throw new Error(`unsupported static json macro object property`);const key=property.key;const keyName=t.isIdentifier(key)?key.name:t.isStringLiteral(key)||t.isNumericLiteral(key)?String(key.value):void 0;if(!keyName)throw new Error(`unsupported static json macro object key`);value[keyName]=resolveStaticLiteralValue(property.value)}return value}throw new Error(`unsupported static json macro value`)}function resolveStaticJsonMacroConfig(macroStatements,options){let accumulator={};for(const statementPath of macroStatements){const arg=statementPath.get(`expression`).get(`arguments.0`)?.node;if(!arg||!t.isExpression(arg))return;let next;try{next=resolveStaticLiteralValue(arg)}catch{return}if(!next||typeof next!==`object`||Array.isArray(next))return;if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}return Object.keys(accumulator).length?accumulator:void 0}function withSourceMap(result,rewrite){if(!(`map`in rewrite))return result;return{...result,get map(){return rewrite.map}}}async function evaluateJsonMacroConfig(content,filename,lang,options){const contentForEval=options?.preambleContent?`${options.preambleContent}\n${content}`:content;const ast=parseScriptSetupAst(contentForEval,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);const macroName=assertSingleMacro(macroNames,filename);if(!macroName||!macroStatements.length)return;const programPath=findProgramPath(ast);if(!programPath)return;const{bodyPaths,keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatements);return await evaluateScriptSetupJsonMacro({preambleContent:options?.preambleContent,originalContent:content,filename,lang,macroName,macroStatements,bodyPaths,keptStatementPaths,options})}async function extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap){if(!mayContainJsonMacro(content))return{stripped:content};const ast=parseScriptSetupAst(content,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);assertSingleMacro(macroNames,filename);const rewrite=stripScriptSetupMacroStatements(content,ast,filename,sourceMap);const{stripped,macroStatementSources}=rewrite;if(macroNames.size===0)return withSourceMap({stripped},rewrite);const macroHash=createHash(`sha256`).update(macroStatementSources.join(`
22
22
  `)).digest(`hex`).slice(0,12);const staticConfig=resolveStaticJsonMacroConfig(macroStatements,options);if(staticConfig)return withSourceMap({stripped,config:staticConfig,macroHash,dependencies:[]},rewrite);const result=await evaluateJsonMacroConfig(content,filename,lang,options);return withSourceMap(result?{stripped,config:result.config,macroHash,dependencies:result.dependencies}:{stripped,macroHash},rewrite)}async function extractJsonMacroFromScriptSetup(content,filename,lang,options){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options)}async function extractJsonMacroFromScriptSetupWithSourceMap(content,filename,lang,options,sourceMap){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap)}function toPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function mergeJsonWithStrategy(target,source,strategy,context){const base={...toPlainRecord(target)};const incoming=toPlainRecord(source);if(typeof strategy===`function`){const maybeNext=strategy(base,incoming,context);if(maybeNext&&typeof maybeNext===`object`&&!Array.isArray(maybeNext))return maybeNext;return base}if(strategy===`replace`)return{...incoming};if(strategy===`assign`)return{...base,...incoming};const merged={...base};recursive(merged,incoming);return merged}function createJsonMerger(strategy,baseContext){return(target,source,stage)=>{return mergeJsonWithStrategy(target,source,strategy,{...baseContext,stage})}}function resolveWarnHandler(warn){return warn??(message=>{console.warn(message)})}function isStaticObjectKeyMatch$1(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$3(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch$1(prop.key,key))return prop}return null}function buildInjectedFeaturesObject(enabled){return t.objectExpression(Array.from(enabled,key=>{return t.objectProperty(t.identifier(key),t.booleanLiteral(true))}))}function getObjectMemberIndexByKey(node,key){return node.properties.findIndex(prop=>{if(t.isObjectProperty(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);if(t.isObjectMethod(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);return false})}function isTopLevel(path){return path.getFunctionParent()==null}function injectWevuShareLifecycleHooksIntoOptionsObject(_optionsObject,_enabled){return false}function collectWevuPageFeatureFlags(ast){const namedHookLocals=/* @__PURE__ */ new Map;const namespaceLocals=/* @__PURE__ */ new Set;for(const stmt of ast.program.body){if(!t.isImportDeclaration(stmt)||!isWevuPageFeatureModuleId(stmt.source.value))continue;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)namedHookLocals.set(specifier.local.name,matched)}else if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name)}if(namedHookLocals.size===0&&namespaceLocals.size===0)return/* @__PURE__ */ new Set;const enabled=/* @__PURE__ */ new Set;function consumeHookCallByName(name){const matched=namedHookLocals.get(name);if(matched)enabled.add(matched)}function consumeNamespaceHookCall(namespace,hookName){if(!namespaceLocals.has(namespace))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hookName];if(matched)enabled.add(matched)}traverse(ast,{CallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}},OptionalCallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}}});return enabled}function injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled){if(!enabled.size)return false;const expectedKeys=[...enabled];const existingFeaturesProp=getObjectPropertyByKey$3(optionsObject,`features`);let changed=false;if(!existingFeaturesProp){const featuresObject=buildInjectedFeaturesObject(enabled);const setupIndex=getObjectMemberIndexByKey(optionsObject,`setup`);const insertAt=setupIndex>=0?setupIndex:0;optionsObject.properties.splice(insertAt,0,t.objectProperty(t.identifier(`features`),featuresObject));changed=true}else if(t.isObjectExpression(existingFeaturesProp.value)){const featuresObject=existingFeaturesProp.value;const injectedProps=[];for(const key of expectedKeys){if(getObjectPropertyByKey$3(featuresObject,key))continue;injectedProps.push(t.objectProperty(t.identifier(key),t.booleanLiteral(true)))}if(injectedProps.length){featuresObject.properties.splice(0,0,...injectedProps);changed=true}}else if(t.isIdentifier(existingFeaturesProp.value)||t.isMemberExpression(existingFeaturesProp.value)){const base=t.cloneNode(existingFeaturesProp.value,true);const injected=buildInjectedFeaturesObject(enabled);injected.properties.push(t.spreadElement(base));existingFeaturesProp.value=injected;changed=true}changed=injectWevuShareLifecycleHooksIntoOptionsObject(optionsObject,enabled)||changed;return changed}function createEmptyModuleAnalysis(id,engine){return{id,engine,wevuNamedHookLocals:/* @__PURE__ */ new Map,wevuNamespaceLocals:/* @__PURE__ */ new Set,importedBindings:/* @__PURE__ */ new Map,localFunctions:/* @__PURE__ */ new Map,exports:/* @__PURE__ */ new Map}}const externalModuleAnalysisCache=new LRUCache({max:256});const moduleAnalysisCache=new LRUCache({max:512});function createExternalModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function createModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function getFunctionLikeFromExpression(node){if(!node)return null;if(t.isFunctionExpression(node)||t.isArrowFunctionExpression(node))return node;return null}function isOxcFunctionLike(node){return node?.type===`FunctionDeclaration`||node?.type===`FunctionExpression`||node?.type===`ArrowFunctionExpression`}function getImportedSpecifierName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function createModuleAnalysis(id,ast){const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(!node.id||!node.id.name)return;localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(!t.isIdentifier(node.id))return;const fn=getFunctionLikeFromExpression(node.init);if(!fn)return;localFunctions.set(node.id.name,fn)}for(const stmt of ast.program.body){if(t.isFunctionDeclaration(stmt)){registerFunctionDeclaration(stmt);continue}if(t.isVariableDeclaration(stmt)){for(const decl of stmt.declarations)registerVariableFunction(decl);continue}if(t.isImportDeclaration(stmt)){const source=stmt.source.value;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)){const imported=specifier.imported;if(isWevuPageFeatureModuleId(source)&&t.isIdentifier(imported)){const importedName=imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName:t.isIdentifier(imported)?imported.name:String(imported.value)})}else if(t.isImportDefaultSpecifier(specifier))importedBindings.set(specifier.local.name,{kind:`default`,source});else if(t.isImportNamespaceSpecifier(specifier)){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(t.isExportNamedDeclaration(stmt)){if(stmt.declaration){if(t.isFunctionDeclaration(stmt.declaration)&&stmt.declaration.id){registerFunctionDeclaration(stmt.declaration);exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name})}else if(t.isVariableDeclaration(stmt.declaration))for(const decl of stmt.declaration.declarations){registerVariableFunction(decl);if(t.isIdentifier(decl.id))exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}if(stmt.source){const source=stmt.source.value;for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const importedName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!importedName)continue;exports.set(exportedName,{type:`reexport`,source,importedName})}}else for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const localName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!localName)continue;exports.set(exportedName,{type:`local`,localName})}continue}if(t.isExportDefaultDeclaration(stmt)){const decl=stmt.declaration;if(t.isFunctionDeclaration(decl)){registerFunctionDeclaration(decl);if(decl.id)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(t.isIdentifier(decl))exports.set(`default`,{type:`local`,localName:decl.name});else{const fn=getFunctionLikeFromExpression(decl);if(fn)exports.set(`default`,{type:`inline`,node:fn})}}}return{id,engine:`babel`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}function resolveOxcParseFilename(id){if(path.extname(id))return id;return`${id}.js`}function createModuleAnalysisWithOxc(id,code){const ast=parseJsLikeWithEngine(code,{engine:`oxc`,filename:resolveOxcParseFilename(id)});const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(node?.id?.type===`Identifier`)localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(node?.id?.type!==`Identifier`||!isOxcFunctionLike(node.init))return;localFunctions.set(node.id.name,node.init)}for(const stmt of ast.body??[]){if(stmt?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt);continue}if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])registerVariableFunction(decl);continue}if(stmt?.type===`ImportDeclaration`){const source=getImportedSpecifierName(stmt.source);if(!source)continue;for(const specifier of stmt.specifiers??[])if(specifier.type===`ImportSpecifier`&&specifier.local?.type===`Identifier`){const importedName=getImportedSpecifierName(specifier.imported);if(!importedName)continue;if(isWevuPageFeatureModuleId(source)){const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName})}else if(specifier.type===`ImportDefaultSpecifier`&&specifier.local?.type===`Identifier`)importedBindings.set(specifier.local.name,{kind:`default`,source});else if(specifier.type===`ImportNamespaceSpecifier`&&specifier.local?.type===`Identifier`){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(stmt?.type===`ExportNamedDeclaration`){if(stmt.declaration?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt.declaration);if(stmt.declaration.id?.type===`Identifier`)exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name});continue}if(stmt.declaration?.type===`VariableDeclaration`){for(const decl of stmt.declaration.declarations??[]){registerVariableFunction(decl);if(decl.id?.type===`Identifier`)exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}const source=getImportedSpecifierName(stmt.source);for(const spec of stmt.specifiers??[]){if(spec?.type!==`ExportSpecifier`)continue;const exportedName=getImportedSpecifierName(spec.exported);const localName=getImportedSpecifierName(spec.local);if(!exportedName||!localName)continue;if(source)exports.set(exportedName,{type:`reexport`,source,importedName:localName});else exports.set(exportedName,{type:`local`,localName})}continue}if(stmt?.type===`ExportDefaultDeclaration`){const decl=stmt.declaration;if(decl?.type===`FunctionDeclaration`){registerFunctionDeclaration(decl);if(decl.id?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(decl?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.name});else if(isOxcFunctionLike(decl))exports.set(`default`,{type:`inline`,node:decl})}}return{id,engine:`oxc`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}const TS_WITHOUT_JSX_RE=/\.[cm]?ts(?:[?#].*)?$/i;function parseModuleAnalysisAst(id,code){const plugins=TS_WITHOUT_JSX_RE.test(id)?BABEL_TS_MODULE_PLUGINS.filter(plugin=>plugin!==`jsx`):BABEL_TS_MODULE_PLUGINS;return parse$3(code,{sourceType:`module`,plugins})}function createModuleAnalysisFromCode(id,code,options){const engine=options?.astEngine??`babel`;const cacheKey=createModuleAnalysisCacheKey(id,engine);const cached=moduleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;let analysis;if(engine===`oxc`){if(!code.includes(`import`)&&!code.includes(`export`))analysis=createEmptyModuleAnalysis(id,`oxc`);else analysis=createModuleAnalysisWithOxc(id,code)}else{const ast=parseModuleAnalysisAst(id,code);analysis=createModuleAnalysis(id,ast)}moduleAnalysisCache.set(cacheKey,{code,analysis});return analysis}function getOrCreateExternalModuleAnalysis(moduleId,code,options){const cacheKey=createExternalModuleAnalysisCacheKey(moduleId,options?.astEngine);const cached=externalModuleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;const analysis=createModuleAnalysisFromCode(moduleId,code,options);externalModuleAnalysisCache.set(cacheKey,{code,analysis});return analysis}const CALL_EXPRESSION_TEXT_RE=/\b[a-z_$][\w$]*(?:\s*<[^(){};]+>)?\s*(?:\?\.\s*)?\(/i;const WEVU_PAGE_HOOK_NAMES=Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE);function mayContainWevuPageFeatureHints(code){return WE_VU_RUNTIME_MODULE_IDS.some(moduleId=>code.includes(moduleId))&&CALL_EXPRESSION_TEXT_RE.test(code)&&WEVU_PAGE_HOOK_NAMES.some(hookName=>code.includes(hookName))}function collectWithBabel(code){const ast=parseJsLike(code);return collectWevuPageFeatureFlags(ast)}function collectWithOxc(code){const enabled=/* @__PURE__ */ new Set;const module=createModuleAnalysisFromCode(`<inline>`,code,{astEngine:`oxc`});if(module.wevuNamedHookLocals.size===0&&module.wevuNamespaceLocals.size===0)return enabled;const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(module.ast);return enabled}function collectWevuPageFeatureFlagsFromCode(code,options){if(!mayContainWevuPageFeatureHints(code))return/* @__PURE__ */ new Set;const engine=options?.astEngine??`babel`;try{return engine===`oxc`?collectWithOxc(code):collectWithBabel(code)}catch{return/* @__PURE__ */ new Set}}const WEVU_FACTORY_NAMES=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,WE_VU_RUNTIME_APIS.createWevuComponent]);const REGEXP_META_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_META_CHARS_RE,`\\$&`)}function mayContainNamedFactoryCall(code,localName){return new RegExp(`\\b${escapeRegExp(localName)}\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayContainNamespaceFactoryCall(code,namespaceName){const factoryAlternation=Array.from(WEVU_FACTORY_NAMES,name=>escapeRegExp(name)).join(`|`);return new RegExp(`\\b${escapeRegExp(namespaceName)}\\b\\s*\\.\\s*(?:${factoryAlternation})\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayCallWevuFactoryByText(code,module){for(const[localName,binding]of module.importedBindings.entries()){if(!isWevuRuntimeModuleId(binding.source))continue;if(binding.kind===`named`&&WEVU_FACTORY_NAMES.has(binding.importedName)){if(mayContainNamedFactoryCall(code,localName))return true;continue}if(binding.kind===`namespace`&&mayContainNamespaceFactoryCall(code,localName))return true}return false}function unwrapTypeLikeExpression$2(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$2(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$2(node.expression);return node}function resolveOptionsObjectFromExpression(node){const normalized=unwrapTypeLikeExpression$2(node);if(t.isObjectExpression(normalized))return normalized;if(t.isIdentifier(normalized))return null;if(t.isCallExpression(normalized)){const callee=normalized.callee;if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`}))for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(t.isSpreadElement(argument)||!t.isExpression(argument))continue;const candidate=resolveOptionsObjectFromExpression(argument);if(candidate)return candidate}}return null}function getOxcStaticPropertyName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function getSetupFunctionFromOptionsObject(options){for(const prop of options.properties)if(t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`)){if(t.isFunctionExpression(prop.value)||t.isArrowFunctionExpression(prop.value))return prop.value}else if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`))return prop;else if(prop?.type===`Property`&&!prop.computed&&getOxcStaticPropertyName(prop.key)===`setup`){if(prop.value?.type===`FunctionExpression`||prop.value?.type===`ArrowFunctionExpression`)return prop.value}return null}function collectTargetOptionsObjectsWithModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];traverse(ast,{VariableDeclarator(path){if(!isTopLevel(path))return;if(!t.isIdentifier(path.node.id))return;const init=path.node.init;if(t.isObjectExpression(init))constObjectBindings.set(path.node.id.name,init)},CallExpression(path){if(!isTopLevel(path))return;const node=path.node;if(t.isV8IntrinsicIdentifier(node.callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;const binding=t.isIdentifier(node.callee)?module.importedBindings.get(node.callee.name):void 0;if(t.isIdentifier(node.callee)){if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object)&&t.isIdentifier(node.callee.property)){const objectBinding=module.importedBindings.get(node.callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(node.callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&node.callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}},OptionalCallExpression(path){if(!isTopLevel(path))return;const node=path.node;const callee=node.callee;if(t.isV8IntrinsicIdentifier(callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;if(t.isIdentifier(callee)){const binding=module.importedBindings.get(callee.name);if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property)){const objectBinding=module.importedBindings.get(callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}}});for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function unwrapOxcTypeLikeExpression(node){if(node?.type===`TSAsExpression`||node?.type===`TSSatisfiesExpression`||node?.type===`TSNonNullExpression`||node?.type===`TSTypeAssertion`||node?.type===`ParenthesizedExpression`)return unwrapOxcTypeLikeExpression(node.expression);return node}function getOxcCallExpression(node){if(node?.type===`ChainExpression`)return getOxcCallExpression(node.expression);if(node?.type===`CallExpression`)return node;return null}function resolveOxcOptionsObjectFromExpression(node,bindings){const normalized=unwrapOxcTypeLikeExpression(node);if(normalized?.type===`ObjectExpression`)return normalized;if(normalized?.type===`Identifier`)return bindings.get(normalized.name)??null;if(normalized?.type!==`CallExpression`)return null;const callee=unwrapOxcTypeLikeExpression(normalized.callee);if(callee?.type!==`MemberExpression`||callee.computed||callee.object?.type!==`Identifier`||callee.object.name!==`Object`||callee.property?.type!==`Identifier`||callee.property.name!==`assign`)return null;for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(argument?.type===`SpreadElement`)continue;const candidate=resolveOxcOptionsObjectFromExpression(argument,bindings);if(candidate)return candidate}return null}function isOxcWevuFactoryCall(call,module){const callee=unwrapOxcTypeLikeExpression(call.callee);if(callee?.type===`Identifier`){const binding=module.importedBindings.get(callee.name);return binding?.kind===`named`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(binding.importedName)}if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){const binding=module.importedBindings.get(callee.object.name);return binding?.kind===`namespace`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(callee.property.name)}return false}function collectTargetOptionsObjectsWithOxcModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];for(const stmt of ast?.body??[]){if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])if(decl?.id?.type===`Identifier`&&decl.init?.type===`ObjectExpression`)constObjectBindings.set(decl.id.name,decl.init);continue}if(stmt?.type!==`ExpressionStatement`)continue;const call=getOxcCallExpression(stmt.expression);if(!call||!isOxcWevuFactoryCall(call,module))continue;const first=call.arguments?.[0];if(!first)continue;const inlineObject=resolveOxcOptionsObjectFromExpression(first,constObjectBindings);if(inlineObject)optionsObjects.push(inlineObject);else if(first.type===`Identifier`)pendingConstObjectRefs.push(first.name)}for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function collectTargetOptionsObjects(ast,moduleId){return collectTargetOptionsObjectsWithModule(ast,createModuleAnalysis(moduleId,ast))}function collectTargetOptionsObjectsFromCode(code,moduleId,options){if(options?.astEngine===`oxc`){if(!(code.includes(`wevu`)&&(code.includes(WE_VU_RUNTIME_APIS.defineComponent)||code.includes(WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module:createEmptyModuleAnalysis(moduleId,`oxc`)};const module=createModuleAnalysisFromCode(moduleId,code,options);if(![...module.importedBindings.values()].some(binding=>isWevuRuntimeModuleId(binding.source)&&(binding.kind===`namespace`||binding.kind===`named`&&(binding.importedName===WE_VU_RUNTIME_APIS.defineComponent||binding.importedName===WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module};if(!mayCallWevuFactoryByText(code,module))return{optionsObjects:[],module};return collectTargetOptionsObjectsWithOxcModule(module.ast,module)}const module=createModuleAnalysisFromCode(moduleId,code,options);return collectTargetOptionsObjectsWithModule(module.ast,module)}function getCallCalleeName(callee){if(t.isV8IntrinsicIdentifier(callee))return null;if(t.isIdentifier(callee))return{type:`ident`,name:callee.name};if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};return null}function collectCalledBindingsFromFunctionBody(fn,engine=`babel`){const called=[];if(engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`)called.push({type:`ident`,name:callee.name});else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`)called.push({type:`member`,object:callee.object.name,property:callee.property.name})}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return called}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}else if(t.isOptionalCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}});return called}function getMemberHookName(callee){if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};return null}function addNamespaceHookFeature(module,callee,enabled){const memberHook=getMemberHookName(callee);if(!memberHook||!module.wevuNamespaceLocals.has(memberHook.object))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[memberHook.hook];if(matched)enabled.add(matched)}function collectWevuHookCallsInFunctionBody(module,fn){const enabled=/* @__PURE__ */ new Set;if(module.engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return enabled}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}else if(t.isOptionalCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}});return enabled}function resolveExportedFunctionNode(module,exportName){const target=module.exports.get(exportName);if(!target)return null;if(target.type===`local`){const fn=module.localFunctions.get(target.localName);return fn?{type:`inline`,node:fn}:null}if(target.type===`reexport`)return target;if(target.type===`inline`)return target;return null}async function resolveExternalFunction(resolver,importerId,source,exportName,moduleCache,options){if(source===`wevu`)return null;const resolvedId=await resolver.resolveId(source,importerId);if(!resolvedId)return null;const code=await resolver.loadCode(resolvedId);if(!code)return null;let analysis=moduleCache.get(resolvedId);if(!analysis){analysis=getOrCreateExternalModuleAnalysis(resolvedId,code,options);moduleCache.set(resolvedId,analysis)}const target=resolveExportedFunctionNode(analysis,exportName);if(!target)return null;if(target.type===`reexport`)return{moduleId:resolvedId,reexport:{source:target.source,importedName:target.importedName}};if(target.type===`inline`)return{moduleId:resolvedId,fn:target.node,module:analysis};return null}async function walkReachableWevuFeatures(options){const{pageModule,setupFn,resolver,moduleCache}=options;const enabled=/* @__PURE__ */ new Set;const seedCalls=collectCalledBindingsFromFunctionBody(setupFn,pageModule.engine);const queue=[];const visitedLocal=/* @__PURE__ */ new Set;const visitedExternal=/* @__PURE__ */ new Set;const enqueueLocal=(moduleId,name)=>{const key=`${moduleId}::${name}`;if(visitedLocal.has(key))return;visitedLocal.add(key);queue.push({kind:`local`,moduleId,name})};const enqueueExternal=(importerId,source,exportName)=>{const key=`${importerId}::${source}::${exportName}`;if(visitedExternal.has(key))return;visitedExternal.add(key);queue.push({kind:`external`,importerId,source,exportName})};const seedFromCall=call=>{if(call.type===`ident`){const binding=pageModule.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(pageModule.id,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(pageModule.id,binding.source,`default`);else if(!binding&&pageModule.localFunctions.has(call.name))enqueueLocal(pageModule.id,call.name);return}const binding=pageModule.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(pageModule.id,binding.source,call.property)};for(const call of seedCalls)seedFromCall(call);let steps=0;const MAX_STEPS=128;while(queue.length&&steps<MAX_STEPS){steps+=1;const item=queue.shift();if(item.kind===`local`){if(item.moduleId!==pageModule.id)continue;const fn=pageModule.localFunctions.get(item.name);if(!fn)continue;for(const f of collectWevuHookCallsInFunctionBody(pageModule,fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(fn,pageModule.engine);for(const call of calls)seedFromCall(call);continue}const resolved=await resolveExternalFunction(resolver,item.importerId,item.source,item.exportName,moduleCache,{astEngine:options.astEngine});if(!resolved)continue;if(`reexport`in resolved){enqueueExternal(resolved.moduleId,resolved.reexport.source,resolved.reexport.importedName);continue}for(const f of collectWevuHookCallsInFunctionBody(resolved.module,resolved.fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(resolved.fn,resolved.module.engine);for(const call of calls)if(call.type===`ident`){const binding=resolved.module.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(resolved.moduleId,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(resolved.moduleId,binding.source,`default`);else if(!binding&&resolved.module.localFunctions.has(call.name)){const key=`${resolved.moduleId}::${call.name}`;if(!visitedLocal.has(key)){visitedLocal.add(key);const localFn=resolved.module.localFunctions.get(call.name);if(localFn){for(const f of collectWevuHookCallsInFunctionBody(resolved.module,localFn))enabled.add(f);for(const inner of collectCalledBindingsFromFunctionBody(localFn,resolved.module.engine))if(inner.type===`ident`){const innerBinding=resolved.module.importedBindings.get(inner.name);if(innerBinding?.kind===`named`)enqueueExternal(resolved.moduleId,innerBinding.source,innerBinding.importedName);else if(innerBinding?.kind==="default")enqueueExternal(resolved.moduleId,innerBinding.source,`default`)}}}}}else{const binding=resolved.module.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(resolved.moduleId,binding.source,call.property)}}return enabled}async function collectWevuFeaturesFromSetupReachableImports(pageModule,setupFn,resolver,moduleCache,options){return await walkReachableWevuFeatures({pageModule,setupFn,resolver,moduleCache,astEngine:options?.astEngine})}async function collectWevuFeaturesFromCodeReachableImports(code,options){const{optionsObjects,module}=collectTargetOptionsObjectsFromCode(code,options.id,{astEngine:options.astEngine});if(!optionsObjects.length)return/* @__PURE__ */ new Set;const moduleCache=/* @__PURE__ */ new Map([[options.id,module]]);const enabled=/* @__PURE__ */ new Set;for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const reachable=await collectWevuFeaturesFromSetupReachableImports(module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const feature of reachable)enabled.add(feature)}return enabled}function injectWevuPageFeaturesInJs(source,options){const enabled=collectWevuPageFeatureFlagsFromCode(source,options);if(!enabled.size)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,`<inline>`);if(!optionsObjects.length)return{code:source,transformed:false};let changed=false;for(const target of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(target,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}async function injectWevuPageFeaturesInJsWithResolver(source,options){const preflight=collectTargetOptionsObjectsFromCode(source,options.id,{astEngine:options.astEngine});if(!preflight.optionsObjects.length)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,options.id);if(!optionsObjects.length)return{code:source,transformed:false};const enabled=/* @__PURE__ */ new Set;for(const flag of collectWevuPageFeatureFlagsFromCode(source,options))enabled.add(flag);const moduleCache=/* @__PURE__ */ new Map;moduleCache.set(options.id,preflight.module);for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const fromImports=await collectWevuFeaturesFromSetupReachableImports(preflight.module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const flag of fromImports)enabled.add(flag)}if(!enabled.size)return{code:source,transformed:false};let changed=false;for(const optionsObject of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}function createPageEntryMatcher(source){let cached;const warn=resolveWarnHandler(source.warn);async function ensure(){if(cached)return cached;let entries;try{entries=await source.loadEntries()}catch(error){const message=error instanceof Error?error.message:String(error);warn(`[wevu] 解析页面入口失败:${message}`);return/* @__PURE__ */ new Set}const set=/* @__PURE__ */ new Set;for(const pageEntry of entries.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,normalized))}for(const meta of entries.subPackages??[]){const root=meta.root??``;for(const pageEntry of meta.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,root,normalized))}}for(const entry of entries.pluginPages??[]){const normalized=stripLeadingSlashes(String(entry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,removeExtensionDeep(normalized)))}cached=set;return set}return{markDirty(){cached=void 0},async isPageFile(filePath){const pages=await ensure();const normalized=removeExtensionDeep(filePath);return pages.has(normalized)}}}function isDefineComponentCall(node,aliases){return t.isIdentifier(node.callee)&&aliases.has(node.callee.name)}function isObjectAssignCall$1(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function unwrapTypeLikeExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSTypeAssertion(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$1(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$1(node.expression);return node}function resolveObjectExpressionFromAssignCall(node){if(!isObjectAssignCall$1(node))return null;for(let index=node.arguments.length-1;index>=0;index-=1){const arg=node.arguments[index];if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const normalized=unwrapTypeLikeExpression$1(arg);if(t.isObjectExpression(normalized))return normalized}return null}function unwrapDefineComponent(node,aliases){if(t.isCallExpression(node)&&isDefineComponentCall(node,aliases)){const arg=node.arguments[0];if(t.isObjectExpression(arg))return arg}return null}function resolveComponentExpression(declaration,defineComponentDecls,aliases){if(!declaration)return null;if(t.isObjectExpression(declaration))return declaration;if(t.isCallExpression(declaration)&&isDefineComponentCall(declaration,aliases)){const arg=declaration.arguments[0];if(t.isObjectExpression(arg))return arg;if(t.isIdentifier(arg)){const matched=defineComponentDecls.get(arg.name);return matched?t.cloneNode(matched,true):null}if(t.isExpression(arg))return arg;return null}if(t.isCallExpression(declaration)&&isObjectAssignCall$1(declaration))return declaration;if(t.isIdentifier(declaration)){const matched=defineComponentDecls.get(declaration.name);return matched?t.cloneNode(matched,true):null}return null}function resolveComponentOptionsObject(componentExpr){if(!componentExpr)return null;const normalized=unwrapTypeLikeExpression$1(componentExpr);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized))return resolveObjectExpressionFromAssignCall(normalized);return null}function isScriptSetupReturnedObject(path){const parent=path.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id,{name:`__returned__`}))return true;if(parent?.isReturnStatement())return true;return false}function isTemplateReturnGetterReference(path){const objectMethod=path.findParent(parent=>parent.isObjectMethod());if(objectMethod?.isObjectMethod()&&objectMethod.node.kind===`get`&&!objectMethod.node.computed&&t.isIdentifier(objectMethod.node.key,{name:path.node.name})&&objectMethod.parentPath?.isObjectExpression()&&isScriptSetupReturnedObject(objectMethod.parentPath)){const getter=objectMethod.node.body.body.find(statement=>t.isReturnStatement(statement));return Boolean(getter&&t.isReturnStatement(getter)&&t.isIdentifier(getter.argument,{name:path.node.name}))}return false}function isTemplateReturnPropertyReference(path){const property=path.parentPath;if(!property?.isObjectProperty())return false;if(!property.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(property.parentPath)||property.node.computed)return false;const key=property.node.key;const value=property.node.value;if(!t.isIdentifier(value,{name:path.node.name}))return false;if(t.isIdentifier(key,{name:path.node.name})||t.isStringLiteral(key,{value:path.node.name}))return true;return false}function isStaticPropertyNamed(node,name){return!node.computed&&(t.isIdentifier(node.key,{name})||t.isStringLiteral(node.key,{value:name}))}function isOptionsApiComponentsObject(path){const componentsProperty=path.parentPath;if(!componentsProperty?.isObjectProperty()||!isStaticPropertyNamed(componentsProperty.node,`components`))return false;const optionsObject=componentsProperty.parentPath;if(!optionsObject?.isObjectExpression())return false;const optionsParent=optionsObject.parentPath;if(optionsParent?.isExportDefaultDeclaration())return true;return Boolean(optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===optionsObject.node&&optionsParent.parentPath?.isExportDefaultDeclaration())}function isOptionsApiComponentRegistrationReference(path){const property=path.parentPath;return Boolean(property?.isObjectProperty()&&property.node.value===path.node&&property.parentPath?.isObjectExpression()&&isOptionsApiComponentsObject(property.parentPath))}function isReferencedOutsideTemplateReturn(path){if(!path.isReferencedIdentifier())return false;if(isTemplateReturnGetterReference(path)||isTemplateReturnPropertyReference(path)||isOptionsApiComponentRegistrationReference(path))return false;return true}function collectReferencedNames(ast,candidateNames){const referencedNames=/* @__PURE__ */ new Set;traverse(ast,{Identifier(path){const name=path.node.name;if(!candidateNames.has(name))return;if(isReferencedOutsideTemplateReturn(path))referencedNames.add(name)}});return referencedNames}function removeSetupReturnProperties(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectMethod(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.key))return;const name=path.node.key.name;if(!removableNames.has(name))return;if(path.node.kind!==`get`)return;const getter=path.node.body.body.find(statement=>t.isReturnStatement(statement));if(!getter||!t.isReturnStatement(getter)||!t.isIdentifier(getter.argument,{name}))return;path.remove();changed=true},ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.value))return;const name=path.node.value.name;if(!removableNames.has(name))return;if(!t.isIdentifier(path.node.key,{name})&&!t.isStringLiteral(path.node.key,{value:name}))return;path.remove();changed=true}});return changed}function removeOptionsApiComponentRegistrations(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isOptionsApiComponentsObject(path.parentPath)||!t.isIdentifier(path.node.value)||!removableNames.has(path.node.value.name))return;path.remove();changed=true}});traverse(ast,{ObjectProperty(path){if(!t.isObjectExpression(path.node.value)||!isStaticPropertyNamed(path.node,`components`)||path.node.value.properties.length>0||!path.parentPath?.isObjectExpression())return;const optionsParent=path.parentPath.parentPath;if(optionsParent?.isExportDefaultDeclaration()||optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===path.parentPath.node&&optionsParent.parentPath?.isExportDefaultDeclaration())path.remove()}});return changed}function pruneTemplateComponentMeta(ast,templateComponentMeta){if(!Object.keys(templateComponentMeta).length)return false;const candidateNames=new Set(Object.keys(templateComponentMeta));const referencedNames=collectReferencedNames(ast,candidateNames);const removableNames=new Set([...candidateNames].filter(name=>!referencedNames.has(name)));let changed=false;traverse(ast,{ImportDeclaration(path){if(!path.node.specifiers.length)return;const kept=path.node.specifiers.filter(specifier=>{if(!(`local`in specifier)||!t.isIdentifier(specifier.local))return true;const localName=specifier.local.name;return!removableNames.has(localName)});if(kept.length!==path.node.specifiers.length){changed=true;if(kept.length===0){path.remove();return}path.node.specifiers=kept}}});changed=removeSetupReturnProperties(ast,removableNames)||changed;changed=removeOptionsApiComponentRegistrations(ast,removableNames)||changed;return changed}function vueSfcTransformPlugin(){return{name:`vue-sfc-transform`,visitor:{ImportDeclaration(path){if(path.node.source.value===`vue`){const specifiers=path.node.specifiers;const filteredSpecifiers=specifiers.filter(s=>{if(s.type===`ImportSpecifier`&&t.isIdentifier(s.imported)&&s.imported.name===WE_VU_RUNTIME_APIS.defineComponent)return false;return true});if(filteredSpecifiers.length===0)path.remove();else if(filteredSpecifiers.length!==specifiers.length)path.node.specifiers=filteredSpecifiers}},ObjectExpression(path){const filtered=path.node.properties.filter(p=>{if(p.type===`ObjectProperty`){const key=p.key;if(key.type===`Identifier`&&key.name===`__name`)return false}return true});path.node.properties=filtered},CallExpression(path){if(t.isMemberExpression(path.node.callee)&&t.isIdentifier(path.node.callee.object,{name:`Object`})&&t.isIdentifier(path.node.callee.property,{name:`defineProperty`})&&t.isIdentifier(path.node.arguments[0],{name:`__returned__`})&&t.isStringLiteral(path.node.arguments[1],{value:`__isScriptSetup`})&&path.parentPath?.isExpressionStatement()){path.parentPath.remove();return}if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()&&path.node.arguments.length===0)path.parentPath.remove()}}}}function createCollectVisitors(state){return{VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))state.defineComponentDecls.set(path.node.id.name,t.cloneNode(path.node.init,true));const unwrapped=unwrapDefineComponent(path.node.init,state.defineComponentAliases);if(unwrapped){state.defineComponentDecls.set(path.node.id.name,t.cloneNode(unwrapped,true));path.node.init=unwrapped;state.transformed=true}},ExportDefaultDeclaration(path){state.defaultExportPath=path}}}const RUNTIME_IMPORT_PATH=WE_VU_COMPILER_RUNTIME_MODULE_ID;const COMPILED_DEFINE_COMPONENT_IMPORT_RE=/^import\s+\{\s*defineComponent\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s+from\s+['"]vue['"];?\n/;const EXPORT_DEFAULT_PURE_RE=/export\s+default\s+\/\*@__PURE__\*\/\s*/;const JSON_MACRO_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;const PAGE_META_RE=/\bdefinePageMeta\s*\(/;const OPTION_CAPABILITY_RE=/\b(?:createApp|createWevuComponent|setData|setWevuDefaults)\b/;const WEVU_RUNTIME_IMPORT_RE=/\bfrom\s*['"](?:wevu(?:\/internal-runtime)?|virtual:weapp-vite\/runtime)['"]/;const DYNAMIC_OPTIONS_PROPERTY_RE=/\.\.\.|\[/;function hasMetadataInjectionOptions(source,options){const hasWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0;return Boolean(options?.isTypeScript||options?.isApp||options?.skipComponentTransform||options?.minify||options?.sourceMap!==false||options?.templateComponentMeta||hasWevuDefaults||options?.classStyleBindings?.length||options?.templateRefs?.length||options?.layoutHosts?.length||options?.inlineExpressions?.length||options?.runtimeCapabilities?.required.length||options?.functionPropPaths?.length||options?.propsAliases||options?.propsDerivedKeys?.length||options?.relaxStructuredTypeOnlyProps||options?.bindingManifest||options?.pageLayout||options?.scopedSlotHostProperties||options?.nativeSlotContext||options?.stabilizeCssVarsRuntime||/\b(?:useSlots|options|extends|mixins|definitionFilter|behaviors)\b|\\/.test(source))}function findMatchingCallEnd(source,openParenIndex){let depth=0;let quote;let escaped=false;let lineComment=false;let blockComment=false;for(let index=openParenIndex;index<source.length;index+=1){const current=source[index];const next=source[index+1];if(lineComment){if(current===`
23
23
  `||current===`\r`)lineComment=false;continue}if(blockComment){if(current===`*`&&next===`/`){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(current===`\\`)escaped=true;else if(current===quote)quote=void 0;continue}if(current===`/`&&next===`/`){lineComment=true;index+=1;continue}if(current===`/`&&next===`*`){blockComment=true;index+=1;continue}if(current===`"`||current===`'`||current==="`"){quote=current;continue}if(current===`(`){depth+=1;continue}if(current===`)`){depth-=1;if(depth===0)return index}}return-1}function stripCompiledScriptSetupMarkers(optionsSource){return optionsSource.replace(/^\s*__name:\s*['"][^'"]+['"],?\n?/m,``).replace(/\{\s*expose:\s*__expose\s*\}/g,`{ expose }`).replace(/\b__expose(?=\s*\()/g,`expose`).replace(/^\s*Object\.defineProperty\(\s*__returned__\s*,\s*['"]__isScriptSetup['"]\s*,\s*\{\s*enumerable:\s*false\s*,\s*value:\s*true\s*\}\s*\);?\n?/m,``)}function tryFastTransformCompiledScriptSetup(source,options){if(hasMetadataInjectionOptions(source,options))return;if(JSON_MACRO_RE.test(source)||PAGE_META_RE.test(source))return;const importMatch=source.match(COMPILED_DEFINE_COMPONENT_IMPORT_RE);if(!importMatch)return;const defineComponentLocal=importMatch[1];const afterImport=source.slice(importMatch[0].length);if(/from\s+['"]vue['"]/.test(afterImport))return;const exportMatch=EXPORT_DEFAULT_PURE_RE.exec(afterImport);if(!exportMatch||exportMatch.index<0)return;const beforeExport=afterImport.slice(0,exportMatch.index);const callStart=exportMatch.index+exportMatch[0].length;const expectedCall=`${defineComponentLocal}(`;if(!afterImport.startsWith(expectedCall,callStart))return;const openParenIndex=callStart+defineComponentLocal.length;const callEnd=findMatchingCallEnd(afterImport,openParenIndex);if(callEnd<0)return;const trailing=afterImport.slice(callEnd+1).trim();if(trailing&&trailing!==`;`)return;const componentOptions=stripCompiledScriptSetupMarkers(afterImport.slice(openParenIndex+1,callEnd).trim());if(!componentOptions.startsWith(`{`)||!componentOptions.endsWith(`}`)||OPTION_CAPABILITY_RE.test(source)||DYNAMIC_OPTIONS_PROPERTY_RE.test(componentOptions)||WEVU_RUNTIME_IMPORT_RE.test(source))return;const pageMarker=` __wevu_isPage: ${options?.isPage===true},\n`;return{code:[`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from "${RUNTIME_IMPORT_PATH}";`,beforeExport.trim(),`const __wevuOptions = {\n${pageMarker}${componentOptions.replace(/^\{\s*/,``).replace(/\s*\}$/,``)}\n};`,`export default __wevuOptions;`,`${WE_VU_RUNTIME_APIS.createWevuComponent}(__wevuOptions);`].filter(Boolean).join(`
24
- `),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent={kind:`absent`};const unknown={kind:`unknown`};function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,next))}function resolve(node,scope,visited){node=unwrap(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive$1(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent:unknown;let result=absent;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown;if(name.kind!==`known`)result=unknown;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown,addGlobalClass:unknown};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent;return value.kind===`expression`?primitive$1(value.node,value.scope):unknown};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function buildInlineMapExpression(inlineExpressions){const entries=inlineExpressions.map(entry=>{const keysExpr=t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)));const exprAst=parseBabelExpression(entry.expression)??t.identifier(`undefined`);const{parameterNames}=entry;const fnExpr=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],exprAst);const entryObjProps=[t.objectProperty(t.identifier(`keys`),keysExpr),t.objectProperty(t.identifier(`fn`),fnExpr)];if(entry.indexBindings?.length){const indexKeysExpr=t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)));entryObjProps.push(t.objectProperty(t.identifier(`indexKeys`),indexKeysExpr))}if(entry.scopeResolvers?.length){const resolverMap=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));const resolverExpr=t.arrayExpression(entry.scopeKeys.map(key=>{const source=resolverMap.get(key);if(!source)return t.identifier(`undefined`);return parseBabelExpression(source)??t.identifier(`undefined`)}));entryObjProps.push(t.objectProperty(t.identifier(`scopeResolvers`),resolverExpr))}const entryObj=t.objectExpression(entryObjProps);return t.objectProperty(t.stringLiteral(entry.id),entryObj)});return t.objectExpression(entries)}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions){if(!inlineExpressions.length)return false;const inlineMapExpr=buildInlineMapExpression(inlineExpressions);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&!options?.isApp&&options?.nativeSlotContext){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_NATIVE_SLOT_CONTEXT_KEY),t.booleanLiteral(true)));transformed=true}if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`,jsxIslands:`__wevuInstallJsxIslands`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers){if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&specifier.importKind!==`type`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent||specifier.imported.type===`StringLiteral`&&specifier.imported.value===WE_VU_RUNTIME_APIS.defineComponent))state.defineComponentAliases.add(specifier.local.name);if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name)}runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function createJsxDiagnostics(warnings,filename){return warnings.map(warning=>{return{code:`WV1003`,severity:`warning`,message:warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`,filename,source:`jsx`}})}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression$1(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression$1(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression$1(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ensureRuntimeImport(ast.program,`normalizeJsxIsland`,`__wevuNormalizeJsxIsland`);ensureRuntimeImport(ast.program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(ast.program,`normalizeStyle`,`__wevuNormalizeStyle`);return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function isMissingFile(error){return Boolean(error&&typeof error===`object`&&`code`in error&&[`ENOENT`,`ENOTDIR`,`EISDIR`].includes(String(error.code)))}function resolveFile(source,importer,readSource){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings,readSource=filename=>readFileSync(filename,`utf8`)){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readSource(filename);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename,readSource);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename,readSource);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Teleport`){context.warnings.push(`小程序不支持 JSX <Teleport>,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings,options?.jsx?.readFile);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}function printExpression(expression){return expression&&generate(expression,{compact:true}).code}function serializeForScope(scope){const{listExpAst,rawListExpAst,projectedListExpAst,...values}=scope;return{...values,listExpression:printExpression(listExpAst),rawListExpression:printExpression(rawListExpAst),projectedListExpression:printExpression(projectedListExpAst)}}function createJsxTemplateRegistrationSignature(options){const bindings=options.classStyleBindings.map(({expAst,forStack,conditions,...binding})=>({...binding,expression:printExpression(expAst),forStack:forStack.map(serializeForScope),conditions:conditions?.map(condition=>({expression:printExpression(condition.expAst),rawExpression:printExpression(condition.rawExpAst),forDepth:condition.forDepth}))}));return createHash(`sha256`).update(JSON.stringify([options.template,options.inlineExpressions,bindings,options.dynamicIslands])).digest(`hex`)}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const{transformVueJsxScript}=await import(`./vueJsxTransform-C4lhnLbg.mjs`);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename):void 0;if(diagnostics&&options?.warn)diagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message));let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,templateRegistrationSignature:createJsxTemplateRegistrationSignature({template:compiledTemplateStr,inlineExpressions,classStyleBindings,dynamicIslands}),...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
24
+ `),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent$1={kind:`absent`};const unknown$1={kind:`unknown`};function unwrap$1(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap$1(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference$1(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference$1(reference,next))}function resolve(node,scope,visited){node=unwrap$1(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive$1(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown$1;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown$1}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown$1;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent$1;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown$1;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent$1:unknown$1;let result=absent$1;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;if(name.kind!==`known`)result=unknown$1;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown$1}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive$1(entry.key,resolved.scope):unknown$1;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown$1,addGlobalClass:unknown$1};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent$1;return value.kind===`expression`?primitive$1(value.node,value.scope):unknown$1};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function buildInlineMapExpression(inlineExpressions){const entries=inlineExpressions.map(entry=>{const keysExpr=t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)));const exprAst=parseBabelExpression(entry.expression)??t.identifier(`undefined`);const{parameterNames}=entry;const fnExpr=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],exprAst);const entryObjProps=[t.objectProperty(t.identifier(`keys`),keysExpr),t.objectProperty(t.identifier(`fn`),fnExpr)];if(entry.indexBindings?.length){const indexKeysExpr=t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)));entryObjProps.push(t.objectProperty(t.identifier(`indexKeys`),indexKeysExpr))}if(entry.scopeResolvers?.length){const resolverMap=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));const resolverExpr=t.arrayExpression(entry.scopeKeys.map(key=>{const source=resolverMap.get(key);if(!source)return t.identifier(`undefined`);return parseBabelExpression(source)??t.identifier(`undefined`)}));entryObjProps.push(t.objectProperty(t.identifier(`scopeResolvers`),resolverExpr))}const entryObj=t.objectExpression(entryObjProps);return t.objectProperty(t.stringLiteral(entry.id),entryObj)});return t.objectExpression(entries)}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions){if(!inlineExpressions.length)return false;const inlineMapExpr=buildInlineMapExpression(inlineExpressions);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&!options?.isApp&&options?.nativeSlotContext){componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_NATIVE_SLOT_CONTEXT_KEY),t.booleanLiteral(true)));transformed=true}if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`,jsxIslands:`__wevuInstallJsxIslands`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers){if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&specifier.importKind!==`type`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent||specifier.imported.type===`StringLiteral`&&specifier.imported.value===WE_VU_RUNTIME_APIS.defineComponent))state.defineComponentAliases.add(specifier.local.name);if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name)}runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function createJsxDiagnostics(warnings,filename){return warnings.map(warning=>{return{code:`WV1003`,severity:`warning`,message:warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`,filename,source:`jsx`}})}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression$1(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression$1(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression$1(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ensureRuntimeImport(ast.program,`normalizeJsxIsland`,`__wevuNormalizeJsxIsland`);ensureRuntimeImport(ast.program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(ast.program,`normalizeStyle`,`__wevuNormalizeStyle`);return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function isMissingFile(error){return Boolean(error&&typeof error===`object`&&`code`in error&&[`ENOENT`,`ENOTDIR`,`EISDIR`].includes(String(error.code)))}function resolveFile(source,importer,readSource){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readSource(candidate)!==void 0)return candidate}catch(error){if(!isMissingFile(error))throw error}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings,readSource=filename=>readFileSync(filename,`utf8`)){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readSource(filename);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename,readSource);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename,readSource);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Teleport`){context.warnings.push(`小程序不支持 JSX <Teleport>,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings,options?.jsx?.readFile);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}function printExpression(expression){return expression&&generate(expression,{compact:true}).code}function serializeForScope(scope){const{listExpAst,rawListExpAst,projectedListExpAst,...values}=scope;return{...values,listExpression:printExpression(listExpAst),rawListExpression:printExpression(rawListExpAst),projectedListExpression:printExpression(projectedListExpAst)}}function createJsxTemplateRegistrationSignature(options){const bindings=options.classStyleBindings.map(({expAst,forStack,conditions,...binding})=>({...binding,expression:printExpression(expAst),forStack:forStack.map(serializeForScope),conditions:conditions?.map(condition=>({expression:printExpression(condition.expAst),rawExpression:printExpression(condition.rawExpAst),forDepth:condition.forDepth}))}));return createHash(`sha256`).update(JSON.stringify([options.template,options.inlineExpressions,bindings,options.dynamicIslands])).digest(`hex`)}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const{transformVueJsxScript}=await import(`./vueJsxTransform-C4lhnLbg.mjs`);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename):void 0;if(diagnostics&&options?.warn)diagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message));let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,templateRegistrationSignature:createJsxTemplateRegistrationSignature({template:compiledTemplateStr,inlineExpressions,classStyleBindings,dynamicIslands}),...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
25
25
  `).length-1;const directiveSource=match[0].slice(match[0].indexOf(`#`));const directiveMatch=directiveSource.match(/^#(ifdef|ifndef|else|endif)\b/);if(!directiveMatch)continue;changed=true;const directive=directiveMatch[1];if(directive===`ifdef`||directive===`ifndef`){const condition=evaluateCondition(directiveSource.slice(directiveMatch[0].length),defines,options.filename,line);frames.push({condition,elseSeen:false,parentActive:active});active=active&&(directive===`ifdef`?condition:!condition)}else{const frame=frames[frames.length-1];if(!frame)throw new Error(`[uni-app] ${options.filename}:${line} 存在未配对的 #${directive}`);if(directive===`else`){if(frame.elseSeen)throw new Error(`[uni-app] ${options.filename}:${line} 同一条件块不能出现多个 #else`);frame.elseSeen=true;active=frame.parentActive&&!frame.condition}else{frames.pop();active=frame.parentActive}}code+=match[0].replace(/[^\r\n]/g,``);line+=match[0].split(`
26
26
  `).length-1;cursor=offset+match[0].length}const trailing=source.slice(cursor);code+=active?trailing:trailing.replace(/[^\r\n]/g,``);if(frames.length)throw new Error(`[uni-app] ${options.filename} 存在未闭合的条件编译块`);return{changed,code}}function normalizeAuxiliaryWxsScripts(source){const wxsBlocks=[];const withoutScripts=source.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(block,attributes,content)=>{const src=attributes.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];const moduleName=attributes.match(/\bmodule\s*=\s*["']([^"']+)["']/i)?.[1];if(!(/\blang\s*=\s*["']wxs["']/i.test(attributes)||src?.endsWith(`.wxs`))||!moduleName)return block;wxsBlocks.push(src?`<wxs module="${moduleName}" src="${src}" />`:`<wxs module="${moduleName}">${content}</wxs>`);return block.replace(/[^\r\n]/g,``)});if(!wxsBlocks.length)return source;return withoutScripts.replace(/<template\b[^>]*>/i,match=>`${match}\n${wxsBlocks.join(`
27
27
  `)}`)}function analyzeScript$1(source,filename){if(!source.trim())return{source,importSources:[],importEnd:0,usesFreeUni:false,virtualHostTrueRanges:[]};const isJsx=/\.[cm]?[jt]sx$/i.test(filename);const ast=parse$3(source,{sourceType:`module`,plugins:[`typescript`,`decorators-legacy`,...isJsx?[`jsx`]:[]]});const importSources=[];let importEnd=0;let usesFreeUni=false;const virtualHostTrueRanges=[];traverse(ast,{ImportDeclaration(path){const sourceNode=path.node.source;if(typeof path.node.end===`number`)importEnd=Math.max(importEnd,path.node.end);const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportAllDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportNamedDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ReferencedIdentifier(path){if(path.node.name===`uni`&&!path.scope.hasBinding(`uni`))usesFreeUni=true},ObjectProperty(path){const key=path.node.key;if(!(!path.node.computed&&(t.isIdentifier(key,{name:`virtualHost`})||t.isStringLiteral(key,{value:`virtualHost`})))||!t.isBooleanLiteral(path.node.value,{value:true})||!path.parentPath?.isObjectExpression())return;const optionsProperty=path.parentPath.parentPath;if(!optionsProperty?.isObjectProperty()||optionsProperty.node.computed||!(t.isIdentifier(optionsProperty.node.key,{name:`options`})||t.isStringLiteral(optionsProperty.node.key,{value:`options`})))return;const{start,end}=path.node.value;if(typeof start===`number`&&typeof end===`number`)virtualHostTrueRanges.push({start,end})}});return{source,importSources,importEnd,usesFreeUni,virtualHostTrueRanges}}function renderScript(analysis,injectUni,disableVirtualHost){const output=new MagicString(analysis.source);for(const source of analysis.importSources)output.overwrite(source.start,source.end,JSON.stringify(source.replacement));if(injectUni){const insertion=analysis.importEnd>0?analysis.importEnd:0;output.prepend(`import { createUniAppHost as __wevuCreateUniAppHost } from 'wevu/internal-runtime'\n`);output.appendLeft(insertion,`${insertion>0?`
28
- `:``}const uni = __wevuCreateUniAppHost(wx)\n`)}if(disableVirtualHost)for(const range of analysis.virtualHostTrueRanges)output.overwrite(range.start,range.end,`false`);return output.toString()}function transformVueSfc(source,filename,target){const normalizedSource=normalizeAuxiliaryWxsScripts(source);const{descriptor,errors}=parse$1(normalizedSource,{filename});if(errors.length){const error=errors[0];throw new Error(`[uni-app] 解析 ${filename} 失败:${error.message}`)}const blocks=[descriptor.script,descriptor.scriptSetup].filter(Boolean);const analyses=blocks.map(block=>{const lang=block.lang??`js`;return analyzeScript$1(block.content,`${filename}.${lang}`)});const injectIndex=analyses.findIndex(analysis=>analysis.usesFreeUni);const output=new MagicString(normalizedSource);for(let index=blocks.length-1;index>=0;index-=1){const block=blocks[index];const analysis=analyses[index];const code=renderScript(analysis,index===injectIndex,target===`mp-weixin`);output.overwrite(block.loc.start.offset,block.loc.end.offset,code)}return output.toString()}function transformUniAppSource(source,options){const conditional=transformUniAppConditionalCode(source,options);const filename=options.filename.split(`?`,1)[0];const blockType=options.blockType??(filename.endsWith(`.vue`)?`sfc`:SCRIPT_EXT_RE.test(filename)?`script`:STYLE_EXT_RE.test(filename)?`style`:void 0);if(blockType===`sfc`){const code=transformVueSfc(conditional.code,filename,options.target);return{changed:conditional.changed||code!==source,code}}if(blockType===`script`){const analysis=analyzeScript$1(conditional.code,filename);const code=renderScript(analysis,analysis.usesFreeUni,options.target===`mp-weixin`&&filename.endsWith(`.vue`));return{changed:conditional.changed||code!==source,code}}if(blockType===`style`||blockType===`template`)return conditional;return{changed:false,code:source}}function isUniAppCompatibilityFile(filename,srcRoot,include){const clean=filename.split(`?`,1)[0];const relative=path.relative(srcRoot,clean);if(relative===``||!relative.startsWith(`..`)&&!path.isAbsolute(relative))return true;const normalized=clean.replace(/\\/g,`/`);return include.some(packageName=>{const packagePath=packageName.replace(/^\/+|\/+$/g,``);return normalized.includes(`/node_modules/${packagePath}/`)})}function transformNestedWxssVars(source){return source}function normalizeStyleError(error){return error instanceof Error?error.message:String(error)}function hasSlottedScopeSelector(source,slottedScopeId){let found=false;const processor=selectorParser(selectors=>{selectors.walkAttributes(attribute=>{if(attribute.attribute===slottedScopeId)found=true})});postcss.parse(source).walkRules(rule=>{if(!found)processor.processSync(rule.selector)});return found}function transformVueDeepSelectors(source){const root=postcss.parse(source);const processor=selectorParser(selectors=>{selectors.walkTags(tag=>{const mapped=DEFAULT_HTML_TO_WXML_TAG_MAP[tag.value.toLowerCase()];if(mapped&&mapped!==tag.value.toLowerCase())tag.replaceWith(selectorParser.className({value:tag.value.toLowerCase()}))});selectors.walkPseudos(pseudo=>{if(![`:deep`,`::v-deep`].includes(pseudo.value))return;const replacement=pseudo.nodes?.[0]?.nodes.map(node=>node.clone())??[];replacement.length?pseudo.replaceWith(...replacement):pseudo.remove()})});root.walkRules(rule=>{rule.selector=processor.processSync(rule.selector).replace(/\s{2,}/g,` `).trim()});return root.toString()}async function compileVueStyleToWxss(styleBlock,options){const filename=options.filename??`style-${options.id}.${styleBlock.lang||`css`}`;const moduleName=typeof styleBlock.module===`string`?styleBlock.module:typeof options.modules===`string`?options.modules:`$style`;const modules=Boolean(options.modules||styleBlock.module);const result=await compileStyleAsync({filename,id:`data-v-${options.id}`,source:styleBlock.content,scoped:options.transformScoped!==false&&Boolean(options.scoped||styleBlock.scoped),modules,modulesOptions:modules?{generateScopedName:name=>`${name}_${options.id}`}:void 0,preprocessLang:styleBlock.lang,preprocessOptions:options.preprocessOptions});if(result.errors.length)throw new Error(`SFC 样式编译失败(${filename}):${result.errors.map(normalizeStyleError).join(`; `)}`);return{code:options.preserveDeepSelectors?result.code:transformVueDeepSelectors(result.code),map:result.map?JSON.stringify(result.map):void 0,scopedId:options.scoped||styleBlock.scoped?`data-v-${options.id}`:void 0,usesSlotted:hasSlottedScopeSelector(result.code,`data-v-${options.id}-s`),modules:result.modules?{[moduleName]:result.modules}:void 0,dependencies:[...result.dependencies]}}const CLASS_LIKE_TEMPLATE_ATTR_RE=/(?:^|[\s<])(?:[\w-]*class[\w-]*|v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[^\s>]+)/g;const VUE_DYNAMIC_CLASS_LIKE_BINDING_RE=/(?:^|[\s<])(?:v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=/;function hashPayload$1(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function collectTemplateTailwindCandidates(content){const candidates=/* @__PURE__ */ new Set;for(const match of content.matchAll(CLASS_LIKE_TEMPLATE_ATTR_RE))candidates.add(match[0].trim());return Array.from(candidates).sort()}function normalizeTailwindContentPayload(payload){const scriptLiterals=VUE_DYNAMIC_CLASS_LIKE_BINDING_RE.test(payload.template)?payload.scriptLiterals:payload.hasScriptTailwindClassHint?payload.scriptCallLiterals:[];return{...payload,template:collectTemplateTailwindCandidates(payload.template),scriptLiterals,scriptCallLiterals:[]}}function buildTailwindContentPayload(template,scriptContent,scriptSetupContent){return{template,scriptLiterals:[...collectScriptStringLiterals(scriptContent),...collectScriptStringLiterals(scriptSetupContent)],scriptCallLiterals:[...collectScriptCallStringLiterals(scriptContent),...collectScriptCallStringLiterals(scriptSetupContent)],hasScriptTailwindClassHint:mayContainScriptCallOrModuleSyntax(`${scriptContent}\n${scriptSetupContent}`)}}function hashTailwindContentPayload(payload){return hashPayload$1(normalizeTailwindContentPayload(payload))}function hashTailwindTemplateContentPayload(payload){return hashPayload$1({template:normalizeTailwindContentPayload(payload).template})}function hashTailwindScriptContentPayload(payload){return hashPayload$1({scriptLiterals:normalizeTailwindContentPayload(payload).scriptLiterals})}const signaturePayloadCache=/* @__PURE__ */ new WeakMap;function serializeAttrs(attrs){return Object.fromEntries(Object.entries(attrs).sort(([a],[b])=>a.localeCompare(b)))}function serializeBlock(block){if(!block)return null;return{type:block.type,attrs:serializeAttrs(block.attrs),content:block.content}}function buildRawVueSfcPayload(descriptor){const configBlocks=[];const templateBlocks=[];for(const block of descriptor.customBlocks){const serialized=serializeBlock(block);if(block.type===`json`||block.type===`config`)configBlocks.push(serialized);else templateBlocks.push(serialized)}return{script:{script:serializeBlock(descriptor.script),scriptSetup:serializeBlock(descriptor.scriptSetup)},template:{template:serializeBlock(descriptor.template),customBlocks:templateBlocks},style:{styles:descriptor.styles.map(style=>serializeBlock(style))},config:{customBlocks:configBlocks},hasTemplate:Boolean(descriptor.template?.content.trim())}}function normalizeScriptBlock(block,filename){if(!block)return{block:null,macroSources:[]};try{const split=splitJsonMacroCallsFromCode(block.content,filename);return{block:{...block,content:split.stripped},macroSources:split.macroSources}}catch{return{block,macroSources:[]}}}function normalizeVueSfcPayload(raw,filename){const script=normalizeScriptBlock(raw.script.script,filename);const scriptSetup=normalizeScriptBlock(raw.script.scriptSetup,filename);const scriptPayload={script:script.block,scriptSetup:scriptSetup.block};return{...raw,script:scriptPayload,config:{...raw.config,macroSources:[...script.macroSources,...scriptSetup.macroSources]},tailwindContent:buildTailwindContentPayload(raw.template.template?.content??``,script.block?.content??``,scriptSetup.block?.content??``)}}function resolveVueSfcSignaturePayload(source,filename){const{descriptor,errors}=parse$1(source,{filename});if(errors.length)return;const cached=signaturePayloadCache.get(descriptor);if(cached)return cached;const payload=normalizeVueSfcPayload(buildRawVueSfcPayload(descriptor),filename);signaturePayloadCache.set(descriptor,payload);return payload}const VUE_SFC_BLOCK_TYPES=[`script`,`template`,`style`,`config`];const hmrSignaturesCache=/* @__PURE__ */ new WeakMap;function hashPayload(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function resolveVueSfcHmrSignatures(source,filename){const payload=resolveVueSfcSignaturePayload(source,filename);if(!payload)return{};const cached=hmrSignaturesCache.get(payload);if(cached)return cached;const cssModules=payload.style.styles.filter(style=>Boolean(style.attrs.module));const blockSignatures={script:hashPayload(cssModules.length?[payload.script,cssModules]:payload.script),template:hashPayload(payload.template),style:hashPayload(payload.style),config:hashPayload(payload.config)};const tailwindContentSignature=hashTailwindContentPayload(payload.tailwindContent);const tailwindTemplateContentSignature=hashTailwindTemplateContentPayload(payload.tailwindContent);const tailwindScriptContentSignature=hashTailwindScriptContentPayload(payload.tailwindContent);const signatures={blockSignatures,contentSignatures:{tailwindcss:tailwindContentSignature},nonJsonSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.style]),scriptSignature:blockSignatures.script,styleIndependentSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.config]),scriptContentSignatures:{tailwindcss:tailwindScriptContentSignature},tailwindContentSignature,tailwindScriptContentSignature,tailwindTemplateContentSignature,templateContentSignatures:{tailwindcss:tailwindTemplateContentSignature},hasTemplate:payload.hasTemplate};hmrSignaturesCache.set(payload,signatures);return signatures}function classifyVueSfcBlockChanges(previous,current){return VUE_SFC_BLOCK_TYPES.filter(type=>previous[type]!==current[type])}function resolveVueSfcNonJsonSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).nonJsonSignature}function resolveVueSfcScriptSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).blockSignatures?.script}function resolveVueSfcStyleIndependentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).styleIndependentSignature}function resolveVueSfcTailwindContentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).tailwindContentSignature}function resolveVueSfcHasTemplate(source,filename){return resolveVueSfcHmrSignatures(source,filename).hasTemplate}const SOURCE_ROOT_RE=/(?:^|\/)src\/(.+)$/;function normalizeScopedIdInput(filename){const normalized=filename.replace(/\\/g,`/`);return normalized.match(SOURCE_ROOT_RE)?.[1]??normalized.replace(/^.*?\/(pages|components|layouts)\//,`$1/`)}function generateScopedId(filename){const input=normalizeScopedIdInput(filename);let hash=2166136261;for(let index=0;index<input.length;index+=1){hash^=input.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function collectNativeComponentRegistrations(analysis,templateNames,templateTags){if(!analysis?.registeredComponents)return;const pending=[];const imports=new Map(analysis.imports.filter(item=>!item.typeOnly&&item.kind!==`namespace`).map(item=>[item.local,item]));for(const registration of analysis.registeredComponents){const imported=imports.get(registration.local);if(!registration.name||!imported||imported.kind===`namespace`||!templateNames.has(registration.name))continue;pending.push({localName:registration.local,importSource:imported.source,importedName:imported.imported,kind:imported.kind,templateTags:[...templateTags?.get(registration.name)??[registration.name]]})}return pending}function normalizeResolvedUsingComponent(result){if(!result)return;if(typeof result===`string`)return{from:result};return result}function isWevuSfcComponent(result){return result?.sourceType?result.sourceType===`wevu-sfc`:Boolean(result?.resolvedId?.endsWith(`.vue`)||result?.from?.endsWith(`.vue`))}function isVueSfcSource(source){return source.endsWith(`.vue`)}function kebabToCamel(name){return name.replace(/-([a-z0-9])/g,(_,character)=>character.toUpperCase())}function capitalize(name){return name?`${name.charAt(0).toUpperCase()}${name.slice(1)}`:name}function extractStringPropertyFromObject(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if(!(t.isIdentifier(key)?key.name===keyName:t.isStringLiteral(key)?key.value===keyName:false)||!t.isStringLiteral(property.value))continue;return property.value.value}}function extractStaticComponentMeta(scriptSetupContent){let ast;try{ast=parse$3(scriptSetupContent,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return{isMiniProgramComponent:false}}let componentName;let isMiniProgramComponent=false;traverse(ast,{CallExpression(path){const callee=path.node.callee;const arg=path.node.arguments[0];if(!t.isObjectExpression(arg))return;if(t.isIdentifier(callee,{name:`defineOptions`})){componentName??=extractStringPropertyFromObject(arg,`name`);return}if(!t.isIdentifier(callee,{name:`defineComponentJson`}))return;for(const property of arg.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if((t.isIdentifier(key)?key.name===`component`:t.isStringLiteral(key)?key.value===`component`:false)&&t.isBooleanLiteral(property.value)&&property.value.value){isMiniProgramComponent=true;return}}}});return{componentName,isMiniProgramComponent}}function readVueSfcScriptSetupContent(source,resolvedId){const{descriptor,errors}=parse$1(source,{filename:resolvedId});if(errors.length>0||!descriptor.scriptSetup?.content)return;return descriptor.scriptSetup.content}async function resolveVueSfcStaticComponentMeta(resolvedId,options){if(!resolvedId?.endsWith(`.vue`))return{isMiniProgramComponent:false};const cached=options?.cache?.get(resolvedId);if(cached)return await cached;const task=(async()=>{try{const scriptSetupContent=readVueSfcScriptSetupContent(await readFile$1(resolvedId,`utf8`),resolvedId);return scriptSetupContent?extractStaticComponentMeta(scriptSetupContent):{isMiniProgramComponent:false}}catch(error){const message=error instanceof Error?error.message:String(error);options?.warn?.(`[Vue 编译] 解析 ${resolvedId} 的静态组件元信息失败:${message}`);return{isMiniProgramComponent:false}}})();options?.cache?.set(resolvedId,task);return await task}function registerResolvedComponentTag(result,tag,registration){const normalizedTag=normalizeTemplateTagName(tag);const{resolvedId,sourceType,componentMeta}=registration;result.resolvedComponentIds.set(tag,resolvedId);result.resolvedComponentIds.set(normalizedTag,resolvedId);if(sourceType===`wevu-sfc`){result.wevuComponentTags.add(tag);result.wevuComponentTags.add(normalizedTag)}if(componentMeta.componentName){result.componentNameMap[tag]=componentMeta.componentName;result.componentNameMap[normalizedTag]=componentMeta.componentName}if(componentMeta.isMiniProgramComponent){result.miniProgramComponentTags.add(tag);result.miniProgramComponentTags.add(normalizedTag)}}function createComponentSourceInfo(){return{autoUsingComponentsMap:{},autoImportTagsMap:{},autoComponentMeta:{},wevuComponentTags:/* @__PURE__ */ new Set,resolvedComponentIds:/* @__PURE__ */ new Map,miniProgramComponentTags:/* @__PURE__ */ new Set,componentNameMap:{}}}function collectTemplateComponentTagInfo(template,filename,warn){const warnHandler=resolveWarnHandler(warn);const analysis=analyzeVueTemplateTags(template);if(analysis.errorMessage!==void 0)for(const warnLabel of[`组件标签`,`脚本导入组件标签`])warnVueTemplateTagAnalysis(analysis.errorMessage,{filename,warnLabel,warn:warnHandler});const autoImportTags=/* @__PURE__ */ new Set;const componentNames=/* @__PURE__ */ new Set;const tagsByComponentName=/* @__PURE__ */ new Map;for(const tag of analysis.tags){if(isAutoImportCandidateTag(tag))autoImportTags.add(tag);const camelName=kebabToCamel(tag);for(const componentName of[tag,camelName,capitalize(camelName)]){componentNames.add(componentName);const matchedTags=tagsByComponentName.get(componentName)??/* @__PURE__ */ new Set;matchedTags.add(tag);tagsByComponentName.set(componentName,matchedTags)}}return{autoImportTags,componentNames,tagsByComponentName}}async function resolveScriptComponentRegistrations(options){const{pending,filename,compileOptions,autoUsingComponents}=options;return await Promise.all(pending.map(async({localName,importSource,importedName,kind,templateTags})=>{let resolved=autoUsingComponents?.resolveUsingComponentPath?normalizeResolvedUsingComponent(await autoUsingComponents.resolveUsingComponentPath(importSource,filename,{localName,importedName,kind})):void 0;if(!resolved?.from&&importSource.startsWith(`/`))resolved={from:removeExtensionDeep(importSource),resolvedId:importSource};if(!resolved?.resolvedId&&isVueSfcSource(importSource)&&importSource.startsWith(`.`))resolved={...resolved??{},resolvedId:path.resolve(path.dirname(filename),importSource)};const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoUsingComponents?.warn??compileOptions?.warn});return{kind:`script`,name:localName,templateTags,from:resolved?.from,resolvedId:resolved?.resolvedId,sourceType:resolved?.sourceType??(isVueSfcSource(importSource)||isWevuSfcComponent(resolved)?`wevu-sfc`:void 0),componentMeta}}))}async function collectScriptSetupUsingComponents(options){const{descriptor,descriptorForCompile,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,nativeScriptAnalysis}=options;if(!descriptor.scriptSetup||!descriptor.template)return[];if(!templateComponentNames?.size)return[];try{const pending=[];const addImport=imported=>{if(imported.typeOnly||imported.kind===`namespace`||!templateComponentNames.has(imported.local))return;const templateTags=[...templateTagsByComponentName?.get(imported.local)??[imported.local]];if(imported.kind==="default"||imported.kind===`named`)pending.push({localName:imported.local,importSource:imported.source,importedName:imported.imported,kind:imported.kind,templateTags})};if(nativeScriptAnalysis)nativeScriptAnalysis.imports.forEach(addImport);else{const setupAst=parse$3(descriptorForCompile.scriptSetup.content,BABEL_TS_MODULE_PARSER_OPTIONS);traverse(setupAst,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;const importSource=path.node.source.value;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!(`local`in specifier)||!t.isIdentifier(specifier.local))continue;const localName=specifier.local.name;if(!templateComponentNames.has(localName))continue;const templateTags=[...templateTagsByComponentName?.get(localName)??[localName]];if(t.isImportDefaultSpecifier(specifier))pending.push({localName,importSource,importedName:`default`,kind:`default`,templateTags});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;pending.push({localName,importSource,importedName,kind:`named`,templateTags})}}}})}return await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 <script setup> 导入失败:${message}`);return[]}}function getExportDefaultExpression(scriptAst,aliases){const declarations=/* @__PURE__ */ new Map;let declaration=null;traverse(scriptAst,{VariableDeclarator(path){const{id,init}=path.node;if(!t.isIdentifier(id)||!init)return;const initializer=unwrapTypeLikeExpression$1(init);const options=t.isObjectExpression(initializer)?initializer:unwrapDefineComponent(initializer,aliases);if(options)declarations.set(id.name,options)},ExportDefaultDeclaration(path){declaration=t.isExpression(path.node.declaration)?unwrapTypeLikeExpression$1(path.node.declaration):path.node.declaration;if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&aliases.has(declaration.callee.name)){const argument=declaration.arguments[0];if(t.isExpression(argument))declaration.arguments[0]=unwrapTypeLikeExpression$1(argument)}}});return resolveComponentExpression(declaration,declarations,aliases)}function getComponentRegistrationName(property){if(t.isIdentifier(property.key))return property.key.name;return t.isStringLiteral(property.key)?property.key.value:void 0}async function collectOptionsApiUsingComponents(options){const{descriptor,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,nativeScriptAnalysis}=options;if(!descriptor.script||!descriptor.template||!templateComponentNames?.size)return[];try{const nativeRegistrations=collectNativeComponentRegistrations(nativeScriptAnalysis,templateComponentNames,templateTagsByComponentName);if(nativeRegistrations)return await resolveScriptComponentRegistrations({pending:nativeRegistrations,filename,compileOptions,autoUsingComponents});const ast=parse$3(descriptor.script.content,BABEL_TS_MODULE_PARSER_OPTIONS);const imports=/* @__PURE__ */ new Map;if(nativeScriptAnalysis)for(const imported of nativeScriptAnalysis.imports){if(imported.typeOnly||imported.kind===`namespace`)continue;imports.set(imported.local,{importSource:imported.source,importedName:imported.imported,kind:imported.kind})}else traverse(ast,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!t.isIdentifier(specifier.local))continue;if(t.isImportDefaultSpecifier(specifier))imports.set(specifier.local.name,{importSource:path.node.source.value,importedName:`default`,kind:`default`});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;imports.set(specifier.local.name,{importSource:path.node.source.value,importedName,kind:`named`})}}}});const aliases=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]);for(const[localName,imported]of imports)if(imported.kind===`named`&&imported.importedName===WE_VU_RUNTIME_APIS.defineComponent&&(imported.importSource===`vue`||isWevuRuntimeModuleId(imported.importSource)))aliases.add(localName);const componentExpression=getExportDefaultExpression(ast,aliases);const componentsProperty=componentExpression&&resolveStaticObjectProperty(componentExpression,`components`,void 0);if(componentsProperty?.kind!==`expression`||!t.isObjectExpression(componentsProperty.node))return[];const pending=[];for(const property of componentsProperty.node.properties){if(!t.isObjectProperty(property)||!t.isIdentifier(property.value))continue;const registrationName=getComponentRegistrationName(property);const imported=imports.get(property.value.name);if(!registrationName||!imported||!templateComponentNames.has(registrationName))continue;pending.push({localName:property.value.name,...imported,templateTags:[...templateTagsByComponentName?.get(registrationName)??[registrationName]]})}return await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 Options API 局部组件失败:${message}`);return[]}}async function collectAutoImportWevuComponents(options){const{descriptor,filename,compileOptions,autoImportTags,templateAutoImportTags,warn}=options;if(!autoImportTags||!descriptor.template)return[];const resolvedTags=await Promise.all([...templateAutoImportTags??[]].map(async tag=>{let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoImportTags.warn??warn});return{tag,resolved,componentMeta}}));const registrations=[];for(const{tag,resolved,componentMeta}of resolvedTags){if(!resolved?.from)continue;registrations.push({kind:`auto`,name:resolved.name||tag,templateTags:[tag],from:resolved.from,resolvedId:resolved.resolvedId,sourceType:resolved.sourceType??(isWevuSfcComponent(resolved)?`wevu-sfc`:void 0),componentMeta})}return registrations}async function collectComponentSourceInfo(options){const result=createComponentSourceInfo();const templateComponentTagInfo=options.descriptor.template?collectTemplateComponentTagInfo(options.descriptor.template.content,options.filename,options.autoUsingComponents?.warn??options.autoImportTags?.warn??options.compileOptions?.warn):void 0;const[setupRegistrations,optionsRegistrations,autoRegistrations]=await Promise.all([collectScriptSetupUsingComponents({descriptor:options.descriptor,descriptorForCompile:options.descriptorForCompile,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,nativeScriptAnalysis:options.nativeScriptAnalysis?.scriptSetup}),collectOptionsApiUsingComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,nativeScriptAnalysis:options.nativeScriptAnalysis?.script&&options.descriptor.script?.content===options.descriptorForCompile.script?.content?options.nativeScriptAnalysis.script:void 0}),collectAutoImportWevuComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoImportTags:options.autoImportTags,templateAutoImportTags:templateComponentTagInfo?.autoImportTags,warn:options.compileOptions?.warn})]);const registrationsByTag=/* @__PURE__ */ new Map;for(const registrations of[autoRegistrations,optionsRegistrations,setupRegistrations])for(const registration of registrations){if(registration.kind===`script`&&registration.from)result.autoComponentMeta[registration.name]=registration.from;for(const tag of registration.templateTags){const normalizedTag=normalizeTemplateTagName(tag);const previous=registrationsByTag.get(normalizedTag);if(previous){if(registration.from&&previous.registration.from&&previous.registration.from!==registration.from)(registration.kind===`script`?options.autoUsingComponents?.warn:options.autoImportTags?.warn)?.(`[Vue 编译] usingComponents 冲突:${options.filename} 中 '${normalizedTag}' 的 '${previous.registration.from}' 将被更高优先级组件注册覆盖为 '${registration.from}'`);previous.registration=registration;previous.tags.add(tag)}else registrationsByTag.set(normalizedTag,{registration,tags:/* @__PURE__ */ new Set([tag])})}}for(const[normalizedTag,{registration,tags}]of registrationsByTag){const{kind,name,from}=registration;if(from){if(kind===`auto`)result.autoImportTagsMap[name]=from;else for(const tag of tags)result.autoUsingComponentsMap[tag]=from}const normalizedName=normalizeTemplateTagName(name);if(normalizedName===normalizedTag||!registrationsByTag.has(normalizedName))registerResolvedComponentTag(result,name,registration);for(const tag of tags)registerResolvedComponentTag(result,tag,registration)}return result}function normalizeConfigLang(lang){if(!lang)return`json`;const lower=lang.toLowerCase();if(lower===`txt`)return`json`;return lower}function isJsonLikeLang(lang){return lang===`json`||lang===`jsonc`||lang===`json5`}function resolveJsLikeLang(lang){if(lang===`ts`||lang===`tsx`||lang===`cts`||lang===`mts`)return`ts`;return`js`}async function evaluateJsLikeConfig(source,filename,lang){const dir=path.dirname(filename);const extension=resolveJsLikeLang(lang)===`ts`?`ts`:`js`;const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.config.${unique}`);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.${unique}.${extension}`);const rewritten=rewriteJsLikeImportsForTempDir(source,dir,tempDir);await writeFile(tempFile,rewritten,`utf8`);try{const{mod}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});let resolved=mod?.default??mod;if(typeof resolved===`function`)resolved=resolved();if(resolved&&typeof resolved.then===`function`)resolved=await resolved;if(resolved&&typeof resolved===`object`)return resolved;throw new Error(`配置块必须导出对象或返回对象的函数。`)}finally{try{await remove(tempDir)}catch{}}})}async function compileConfigBlocks(blocks,filename,options){const jsonBlocks=blocks.filter(block=>block.type===`json`);if(!jsonBlocks.length)return;let accumulator={};for(const block of jsonBlocks){const lang=normalizeConfigLang(block.lang);try{if(isJsonLikeLang(lang)){const parsed=parse$2(block.content,void 0,true);if(options?.merge){const merged=options.merge(accumulator,parsed);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,parsed);continue}const evaluated=await evaluateJsLikeConfig(block.content,filename,lang);if(!evaluated||typeof evaluated!==`object`)continue;if(options?.merge){const merged=options.merge(accumulator,evaluated);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,evaluated)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 <json> 块失败(${lang}):${filename}: ${message}`)}}if(Reflect.has(accumulator,`$schema`))delete accumulator.$schema;return JSON.stringify(accumulator,null,2)}function collectTemplateAutoImportTags(template,filename,warn){const warnHandler=resolveWarnHandler(warn);return collectVueTemplateTags(template,{filename,warnLabel:`自动导入标签`,warn:message=>warnHandler(message),shouldCollect:isAutoImportCandidateTag})}function normalizeUsingComponents(config){const raw=config.usingComponents;if(!raw||typeof raw!==`object`||Array.isArray(raw))return;const usingComponents={};for(const[name,from]of Object.entries(raw))usingComponents[normalizeTemplateTagName(name)]=from;config.usingComponents=usingComponents}async function compileConfigPhase(params){const{descriptor,filename,autoUsingComponentsMap,autoImportTagsMap:precomputedAutoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults,mergeJson,scriptSetupMacroConfig,result,warn}=params;let configObj;if(descriptor.customBlocks.some(b=>b.type===`json`)){const configResult=await compileConfigBlocks(descriptor.customBlocks,filename,{merge:(target,source)=>mergeJson(target,source,`json-block`)});if(configResult)try{configObj=JSON.parse(configResult)}catch{configObj={}}}const autoImportTagsMap=precomputedAutoImportTagsMap?{...precomputedAutoImportTagsMap}:{};if(!precomputedAutoImportTagsMap&&autoImportTags&&descriptor.template){const tags=collectTemplateAutoImportTags(descriptor.template.content,filename,autoImportTags.warn??warn);for(const tag of tags){let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;autoImportTagsMap[resolved.name||tag]=resolved.from}}if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents={};if(existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw))for(const[name,from]of Object.entries(existingRaw))usingComponents[normalizeTemplateTagName(name)]=from;for(const[name,from]of Object.entries(autoImportTagsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoImportTags?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被模板标签自动引入覆盖为 '${from}'`);usingComponents[normalizedName]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoUsingComponents?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被 <script setup> 导入覆盖为 '${from}'`);usingComponents[normalizedName]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(result.componentGenerics&&Object.keys(result.componentGenerics).length>0){const existing=configObj?.componentGenerics;const componentGenerics=existing&&typeof existing===`object`&&!Array.isArray(existing)?existing:{};for(const[key,value]of Object.entries(result.componentGenerics))componentGenerics[key]=value;configObj=mergeJson(configObj??{},{componentGenerics},`component-generics`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptSetupMacroConfig&&Object.keys(scriptSetupMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptSetupMacroConfig,`macro`);if(configObj)normalizeUsingComponents(configObj);if(configObj&&Object.keys(configObj).length>0)result.config=JSON.stringify(configObj,null,2)}function finalizeResult(result,options){if(!result.script||result.script.trim()===``)result.script=`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from '${RUNTIME_IMPORT_PATH}';\n${WE_VU_RUNTIME_APIS.createWevuComponent}({});\n`;if(result.meta&&options.scriptSetupMacroHash)result.meta.jsonMacroHash=options.scriptSetupMacroHash;if(result.meta&&options.defineOptionsHash)result.meta.defineOptionsHash=options.defineOptionsHash}function createModuleValueBoundary(isPrimitive,isRuntimeApi){const opaque={kind:`opaque`};const importedValues=/* @__PURE__ */ new WeakMap;const factoryProofs=/* @__PURE__ */ new WeakMap;const factoryResolvers=/* @__PURE__ */ new WeakMap;function safeFactory(fn){if(!t.isFunction(fn.node)||fn.node.async||fn.node.generator)return false;const cached=factoryProofs.get(fn.node);if(cached!==void 0)return cached;factoryProofs.set(fn.node,false);let safe=true;fn.scope.path.traverse({ReferencedIdentifier(p){const value=fn.resolve(p.node,p.scope);if(value?.kind===`opaque`||!isPrimitive(value)&&(value?.kind===`ref`||value?.kind===`refs`||value?.kind===`local`&&!t.isFunction(value.node))&&value.scope.getFunctionParent()!==fn.scope){safe=false;p.stop()}},AssignmentExpression(p){let target=p.node.left;while(t.isMemberExpression(target)||t.isOptionalMemberExpression(target))target=target.object;const binding=t.isIdentifier(target)?p.scope.getBinding(target.name):void 0;if(!binding||binding.scope.getFunctionParent()!==fn.scope){safe=false;p.stop()}},"CallExpression|OptionalCallExpression":function(p){if(!t.isCallExpression(p.node)&&!t.isOptionalCallExpression(p.node))return;const callee=fn.resolve(p.node.callee,p.scope);if(callee?.kind!==`api`||!isRuntimeApi(callee.name)){safe=false;p.stop()}}});factoryProofs.set(fn.node,safe);return safe}function imported(value){if(!value||isPrimitive(value)||value.kind===`api`)return value;const cached=importedValues.get(value);if(cached)return cached;const result=value.kind===`local`&&t.isFunction(value.node)&&safeFactory(value)?{...value,imported:true}:value.kind===`module`?{...value,exported:name=>imported(value.exported(name))}:opaque;importedValues.set(value,result);return result}function fresh(value,owner){if(!value||isPrimitive(value)||value.kind===`api`)return value;if(value.kind===`local`&&t.isFunction(value.node))return imported(value);if(value.kind!==`local`&&value.kind!==`ref`&&value.kind!==`refs`||value.scope.getFunctionParent()!==owner)return opaque;let resolvers=factoryResolvers.get(owner);if(!resolvers){resolvers=/* @__PURE__ */ new Map;factoryResolvers.set(owner,resolvers)}let resolve=resolvers.get(value.resolve);if(!resolve){const original=value.resolve;resolve=(node,scope)=>fresh(original(node,scope),owner);resolvers.set(original,resolve)}return value.kind===`local`?{...value,resolve}:{...value,resolve,value:fresh(value.value,owner)}}function factoryReturn(fn,value){return fn.imported?fresh(value,fn.scope):value}return{imported,factoryReturn}}const pureRuntimeApis={ref:true,shallowRef:true,reactive:true,shallowReactive:true,readonly:true,shallowReadonly:true,computed:true,isRef:true,unref:true,toRef:true,toRefs:true,toValue:true,isReactive:true,isReadonly:true,isProxy:true,toRaw:true,markRaw:true,triggerRef:true,isShallow:true,defineComponent:true};const compilerMacros={defineProps:true,defineEmits:true,defineExpose:true,defineOptions:true,defineSlots:true,withDefaults:true,definePage:true,definePageMeta:true};const primitive={kind:`primitive`};function isCompilerMacro(name){return compilerMacros[name]===true||JSON_MACROS.has(name)}function isSafeApi(name){return pureRuntimeApis[name]===true||isCompilerMacro(name)}function runtimeModule(source){return source===`vue`||isWevuRuntimeModuleId(source)}function propertyName$1(node,computed){return t.isStringLiteral(node)||t.isNumericLiteral(node)?String(node.value):!computed&&t.isIdentifier(node)?node.name:void 0}function isPrimitive(value){return value?.kind===`primitive`||value?.kind===`local`&&(t.isNullLiteral(value.node)||t.isStringLiteral(value.node)||t.isNumericLiteral(value.node)||t.isBooleanLiteral(value.node)||t.isBigIntLiteral(value.node))}function createValueResolver(scopes,lookup,exported,sharedBindings,moduleScope){const resolving=/* @__PURE__ */ new Set;const boundary=createModuleValueBoundary(isPrimitive,name=>pureRuntimeApis[name]===true);const dataProofs=/* @__PURE__ */ new WeakMap;function imported(source,name){return runtimeModule(source)||(source===`weapp-vite`||source===`wevu/router`||source===`wevu/dev/router`)&&isCompilerMacro(name)?{kind:`api`,name}:boundary.imported(exported(source,name))??{kind:`module`,source,name,exported:name=>boundary.imported(exported(source,name))}}function key(node,computed,scope){const name=propertyName$1(node,computed);if(name!==void 0)return name;const value=resolve(node,scope);return value?.kind===`local`?propertyName$1(value.node,true):void 0}function member(object,name){if(!object||name===void 0)return;if(object.kind===`api`&&object.name===`*`)return{kind:`api`,name};if(object.kind===`module`&&object.name===`*`)return object.exported(name)??{...object,name};if(object.kind===`ref`)return name===`value`?object.value:void 0;if(object.kind===`refs`){const value=member(object.value,name);return value?{...object,kind:`ref`,value}:void 0}if(object.kind===`props`)return{kind:`opaque`};if(object.kind!==`local`)return;if(t.isObjectExpression(object.node))for(let index=object.node.properties.length-1;index>=0;index--){const property=object.node.properties[index];if(t.isSpreadElement(property)||propertyName$1(property.key,property.computed)===void 0)return;if(propertyName$1(property.key,property.computed)===name)return t.isObjectProperty(property)?object.resolve(property.value,object.scope):property.kind===`method`?object.resolve(property,object.scope):void 0}if(t.isArrayExpression(object.node)){if(name===`length`)return primitive;const element=/^(?:0|[1-9]\d*)$/.test(name)?object.node.elements[Number(name)]:void 0;return element?object.resolve(element,object.scope):void 0}}function functionReturn(value){if(value?.kind!==`local`||!t.isFunction(value.node)||value.node.async||value.node.generator)return;const body=value.node.body;if(t.isExpression(body))return boundary.factoryReturn(value,value.resolve(body,value.scope));if(body.body.some(statement=>!t.isVariableDeclaration(statement)&&!t.isFunctionDeclaration(statement)&&!t.isExpressionStatement(statement)&&!t.isReturnStatement(statement)&&!t.isEmptyStatement(statement)))return;const returns=body.body.filter(statement=>t.isReturnStatement(statement));return returns.length===1&&returns[0].argument?boundary.factoryReturn(value,value.resolve(returns[0].argument,value.scope)):void 0}function resolve(input,scope){const node=t.isExpression(input)?unwrapTypeLikeExpression$1(input):input;if(resolving.has(node))return;resolving.add(node);try{if(t.isIdentifier(node)){const binding=scope.getBinding(node.name);if(!binding)return lookup(node.name,scope)??(isCompilerMacro(node.name)?{kind:`api`,name:node.name}:node.name===`undefined`?primitive:void 0);if(!binding.constant)return;const declaration=binding.path.node;if(t.isImportSpecifier(declaration)||t.isImportDefaultSpecifier(declaration)||t.isImportNamespaceSpecifier(declaration)){const parent=binding.path.parent;if(!t.isImportDeclaration(parent)||parent.importKind===`type`||t.isImportSpecifier(declaration)&&declaration.importKind===`type`)return;return imported(parent.source.value,t.isImportSpecifier(declaration)?propertyName$1(declaration.imported,false):t.isImportDefaultSpecifier(declaration)?`default`:`*`)}const shared=sharedBindings.has(binding.identifier)||binding.scope===moduleScope&&scope.getFunctionParent()!==null;if(t.isVariableDeclarator(declaration)&&declaration.init){let value=resolve(declaration.init,binding.path.scope);if(t.isObjectPattern(declaration.id)){const property=declaration.id.properties.find(item=>t.isObjectProperty(item)&&t.isIdentifier(item.value,{name:node.name}));value=t.isObjectProperty(property)?member(value,propertyName$1(property.key,property.computed)):void 0}else if(!t.isIdentifier(declaration.id))value=void 0;return shared?boundary.imported(value):value}if(t.isFunctionDeclaration(declaration)){const value=resolve(declaration,binding.path.scope);return shared?boundary.imported(value):value}if(binding.kind===`param`){const fn=binding.path.getFunctionParent();const owner=fn?.isFunctionDeclaration()&&fn.node.id?fn.parentPath.scope.getBinding(fn.node.id.name):void 0;const index=fn?.node.params.indexOf(declaration)??-1;if(owner?.referencePaths.length&&index>=0&&owner.referencePaths.every(reference=>{const call=reference.parentPath;return call?.isCallExpression()&&call.node.callee===reference.node&&call.node.arguments[index]&&isPrimitive(resolve(call.node.arguments[index],call.scope))}))return primitive}return}if(t.isMemberExpression(node)||t.isOptionalMemberExpression(node))return member(resolve(node.object,scope),key(node.property,node.computed,scope));if(t.isCallExpression(node)||t.isOptionalCallExpression(node)){const callee=resolve(node.callee,scope);if(callee?.kind!==`api`)return functionReturn(callee);const first=node.arguments[0]?resolve(node.arguments[0],scope):primitive;switch(callee.name){case`ref`:case`shallowRef`:return first?.kind===`ref`?first:{kind:`ref`,value:first,node,scope,resolve};case`toRefs`:return{kind:`refs`,value:first,node,scope,resolve};case`reactive`:case`shallowReactive`:case`readonly`:case`shallowReadonly`:case`toRaw`:case`markRaw`:return first;case`computed`:return{kind:`ref`,value:functionReturn(first)??functionReturn(member(first,`get`)),node,scope,resolve};case`unref`:return first?.kind===`ref`?first.value:first;case`toValue`:return first?.kind===`ref`?first.value:first?.kind===`local`&&t.isFunction(first.node)?functionReturn(first):first;case`toRef`:return node.arguments.length>1?{kind:`ref`,value:member(first,key(node.arguments[1],true,scope)),node,scope,resolve}:first?.kind===`ref`?first:{kind:`ref`,value:first?.kind===`local`&&t.isFunction(first.node)?functionReturn(first):first,node,scope,resolve};case`isRef`:case`isReactive`:case`isReadonly`:case`isProxy`:case`isShallow`:return primitive;case`defineComponent`:return first?.kind===`local`&&t.isObjectExpression(first.node)?first:void 0;case`defineProps`:return{kind:`props`};case`withDefaults`:return first;default:return}}if(t.isBinaryExpression(node)||t.isUnaryExpression(node)||t.isUpdateExpression(node)||t.isTemplateLiteral(node))return primitive;return{kind:`local`,node,scope:scopes.get(node)??scope,resolve}}finally{resolving.delete(node)}}function safeData(value){if(!value)return false;if(value.kind===`primitive`||value.kind===`props`)return true;if(value.kind===`ref`||value.kind===`refs`)return safeData(value.value);if(value.kind!==`local`)return value.kind===`api`&&isSafeApi(value.name);if(isPrimitive(value)||t.isFunction(value.node))return true;let scopes=dataProofs.get(value.resolve);if(!scopes){scopes=/* @__PURE__ */ new WeakMap;dataProofs.set(value.resolve,scopes)}let proof=scopes.get(value.scope);if(!proof){proof={complete:/* @__PURE__ */ new WeakMap,visiting:/* @__PURE__ */ new WeakSet};scopes.set(value.scope,proof)}const complete=proof.complete.get(value.node);if(complete!==void 0)return complete;if(proof.visiting.has(value.node))return false;proof.visiting.add(value.node);let safe=false;if(t.isObjectExpression(value.node))safe=value.node.properties.every(property=>!t.isSpreadElement(property)&&propertyName$1(property.key,property.computed)!==void 0&&(t.isObjectProperty(property)?safeData(value.resolve(property.value,value.scope)):property.kind===`method`));else if(t.isArrayExpression(value.node))safe=value.node.elements.every(element=>!element||!t.isSpreadElement(element)&&safeData(value.resolve(element,value.scope)));proof.visiting.delete(value.node);proof.complete.set(value.node,safe);return safe}return{resolve,member,safeData,functionReturn,imported,key,moduleValue:boundary.imported}}function prepareScriptScopes(source,component,setupSource,expressions,exported){const script=typeof source===`string`?parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS):source;const setup=setupSource===void 0?void 0:parse$3(setupSource,BABEL_TS_MODULE_PARSER_OPTIONS);const template=expressions?parse$3(expressions,BABEL_TS_MODULE_PARSER_OPTIONS):void 0;const scopes=/* @__PURE__ */ new WeakMap;const observedFunctions=/* @__PURE__ */ new Set;const templateValues=/* @__PURE__ */ new Map;for(const ast of[script,setup,template])if(ast)traverse(ast,{Program(p){scopes.set(p.node,p.scope)},Function(p){scopes.set(p.node,p.scope)}});const scriptScope=scopes.get(script.program);const setupScope=setup&&scopes.get(setup.program);const templateScope=template&&scopes.get(template.program);const componentExport=script.program.body.find(statement=>t.isExportDefaultDeclaration(statement));const sharedBindings=/* @__PURE__ */ new WeakSet;const visitedDeclarations=/* @__PURE__ */ new WeakSet;for(const root of[scriptScope,setupScope]){if(!root)continue;const pending=Object.values(root.bindings).filter(binding=>t.isExportNamedDeclaration(binding.path.parent)||t.isVariableDeclaration(binding.path.parent)&&t.isExportNamedDeclaration(binding.path.parentPath?.parent)||binding.referencePaths.some(reference=>t.isExportSpecifier(reference.parent)&&t.isExportNamedDeclaration(reference.parentPath?.parent)&&!(t.isIdentifier(reference.parent.exported,{name:`default`})||t.isStringLiteral(reference.parent.exported,{value:`default`}))));for(const binding of pending)sharedBindings.add(binding.identifier);for(const binding of pending)for(let index=-1;index<binding.constantViolations.length;index++){const declaration=index===-1?binding.path:binding.constantViolations[index];if(visitedDeclarations.has(declaration.node))continue;visitedDeclarations.add(declaration.node);declaration.traverse({ReferencedIdentifier(p){if(!p.isIdentifier())return;const dependency=p.scope.getBinding(p.node.name);if(dependency?.scope===root&&!sharedBindings.has(dependency.identifier)){sharedBindings.add(dependency.identifier);pending.push(dependency)}}})}}const values=createValueResolver(scopes,(name,scope)=>{const root=scope.getProgramParent();if(root===setupScope){const binding=scriptScope.getBinding(name);const value=binding?values.moduleValue(values.resolve(binding.identifier,binding.scope)):void 0;if(value?.kind===`local`&&t.isFunction(value.node))observedFunctions.add(value.node);return value}if(root!==templateScope)return;if(templateValues.has(name))return templateValues.get(name);let value;if(setupScope){const binding=setupScope.getBinding(name)??scriptScope.getBinding(name);value=binding?values.resolve(binding.identifier,binding.scope):void 0;if(binding?.scope===scriptScope)value=values.moduleValue(value)}else if(component){const options=componentExport&&values.resolve(componentExport.declaration,scriptScope);const setupFunction=values.member(options,`setup`);value=values.member(values.functionReturn(setupFunction),name)}if(value?.kind===`local`&&t.isFunction(value.node))observedFunctions.add(value.node);const unwrapped=value?.kind===`ref`?value.value:value;templateValues.set(name,unwrapped);return unwrapped},exported,sharedBindings,scriptScope);return{script,setup,template,values,observedFunctions,scriptScope}}function isUnusedAlias(reference){let expression=reference;while(expression.parentPath&&(expression.parentPath.isTSAsExpression()||expression.parentPath.isTSNonNullExpression()||expression.parentPath.isTSTypeAssertion()||expression.parentPath.isTSSatisfiesExpression()))expression=expression.parentPath;const declaration=expression.parentPath;if(!declaration?.isVariableDeclarator()||declaration.node.init!==expression.node||!t.isIdentifier(declaration.node.id)||declaration.parentPath.parentPath?.isExportDeclaration())return false;const binding=declaration.scope.getBinding(declaration.node.id.name);return Boolean(binding&&binding.referencePaths.every(p=>p.findParent(parent=>t.isTSType(parent.node))))}async function analyzeScript(source,component=false,setupSource,expressions,loadModule){const facts={required:false,imports:/* @__PURE__ */ new Set,exports:/* @__PURE__ */ new Map};try{const modules=/* @__PURE__ */ new Map;const{script,setup,template,values,observedFunctions,scriptScope}=prepareScriptScopes(source,component,setupSource,expressions,(source,name)=>modules.get(source)?.exports.get(name));if(loadModule)for(const ast of[script,setup])for(const statement of ast?.program.body??[]){if(t.isImportDeclaration(statement)&&statement.specifiers.length>0&&statement.specifiers.every(specifier=>t.isImportSpecifier(specifier)&&specifier.importKind===`type`)||t.isExportNamedDeclaration(statement)&&statement.specifiers.length>0&&statement.specifiers.every(specifier=>t.isExportSpecifier(specifier)&&specifier.exportKind===`type`))continue;const source=t.isImportDeclaration(statement)&&statement.importKind!==`type`||(t.isExportNamedDeclaration(statement)||t.isExportAllDeclaration(statement))&&statement.exportKind!==`type`?statement.source?.value:void 0;if(source&&!runtimeModule(source)&&!source.endsWith(`.vue`)&&!modules.has(source)){const module=await loadModule(source);if(module){modules.set(source,module);facts.required||=module.required}}}const{resolve:resolveValue,member,safeData}=values;const inspectCallback=value=>{if(value?.kind===`module`)facts.imports.add(value.source);else if(!value||value.kind!==`local`||!t.isFunction(value.node))facts.required=true};const inspectOptions=(node,scope)=>{if(!node)return;let value=resolveValue(node,scope);if(value?.kind===`local`&&t.isFunction(value.node))value=values.functionReturn(value);if(value?.kind!==`local`||!t.isObjectExpression(value.node)){facts.required=true;return}for(const property of value.node.properties){if(t.isSpreadElement(property)||property.computed){facts.required=true;continue}const name=propertyName$1(property.key,false);if(name===`provide`||name===`inject`||name===`mixins`||name===`extends`||name===`render`)facts.required=true;if(name===`components`&&(!t.isObjectProperty(property)||!t.isObjectExpression(property.value)))facts.required=true;if(name===`setup`)inspectCallback(member(value,`setup`))}};const inspectCall=(callee,args,scope)=>{const value=resolveValue(callee,scope);if(value?.kind!==`api`){inspectCallback(value);facts.required||=args.some(argument=>!safeData(resolveValue(argument,scope)));return}facts.required||=!isSafeApi(value.name);if(value.name===`defineOptions`||value.name===`defineComponent`){inspectOptions(args[0],scope);return}if(isCompilerMacro(value.name))return;const first=args[0]&&resolveValue(args[0],scope);facts.required||=args.some(argument=>!safeData(resolveValue(argument,scope)));if(value.name===`computed`){if(first?.kind===`local`&&t.isObjectExpression(first.node)){inspectCallback(member(first,`get`));const setter=member(first,`set`);if(setter)inspectCallback(setter)}else inspectCallback(first)}else if(value.name===`toRef`&&args.length>1)facts.required||=!safeData(member(first,values.key(args[1],true,scope)));else if((value.name===`toValue`||value.name===`toRef`)&&first?.kind===`local`&&t.isFunction(first.node))inspectCallback(first)};const inspectExportValue=(node,scope)=>{const value=resolveValue(node,scope);if(!value||value.kind===`api`&&!isSafeApi(value.name))facts.required=true;else if(value.kind===`local`&&!(t.isFunction(value.node)||t.isLiteral(value.node)||t.isObjectExpression(value.node)||t.isArrayExpression(value.node)))facts.required=true};const inspectPattern=(pattern,value)=>{if(t.isObjectPattern(pattern))for(const property of pattern.properties){if(!t.isObjectProperty(property)){facts.required=true;continue}const field=member(value,propertyName$1(property.key,property.computed));facts.required||=!field;inspectPattern(property.value,field)}else if(t.isArrayPattern(pattern)){facts.required||=value?.kind!==`local`||!t.isArrayExpression(value.node);pattern.elements.forEach((element,index)=>{if(element)inspectPattern(element,member(value,String(index)))})}else if(t.isRestElement(pattern))facts.required=true};for(const ast of[template,setup,script]){if(!ast)continue;traverse(ast,{enter(p){if(t.isTSType(p.node)||t.isTSInterfaceDeclaration(p.node)||t.isTSTypeAliasDeclaration(p.node)||t.isTSDeclareFunction(p.node))p.skip();if(p.isFunctionDeclaration()&&p.node.id&&!observedFunctions.has(p.node)&&!p.parentPath.isExportDeclaration()&&!p.parentPath.scope.getBinding(p.node.id.name)?.referenced)p.skip();if((p.isFunctionExpression()||p.isArrowFunctionExpression())&&!observedFunctions.has(p.node)&&p.parentPath.isVariableDeclarator()){const declarator=p.parentPath;if(t.isIdentifier(declarator.node.id)&&!declarator.scope.getBinding(declarator.node.id.name)?.referenced&&!declarator.parentPath.parentPath?.isExportDeclaration())p.skip()}},ImportDeclaration(p){if(p.node.importKind===`type`||p.node.specifiers.length&&p.node.specifiers.every(s=>t.isImportSpecifier(s)&&s.importKind===`type`)){p.skip();return}const source=p.node.source.value;if(component&&source.endsWith(`.vue`)&&p.node.specifiers.length>0&&p.node.specifiers.every(s=>!p.scope.getBinding(s.local.name)?.referenced))return;const onlyMacros=p.node.specifiers.length>0&&p.node.specifiers.every(s=>t.isImportSpecifier(s)&&isCompilerMacro(propertyName$1(s.imported,false)));if(!runtimeModule(source)&&!((source===`weapp-vite`||source===`wevu/router`||source===`wevu/dev/router`)&&onlyMacros))facts.imports.add(source)},ReferencedIdentifier(p){const value=resolveValue(p.node,p.scope);if(!value&&p.isIdentifier()&&!p.scope.getBinding(p.node.name)||value?.kind===`api`&&value.name!==`*`&&!isSafeApi(value.name)&&!isUnusedAlias(p))facts.required=true},"MemberExpression|OptionalMemberExpression":function(p){const value=resolveValue(p.node,p.scope);if(!value||value.kind===`api`&&!isSafeApi(value.name)&&!isUnusedAlias(p))facts.required=true},Function(p){facts.required||=Boolean(p.node.async||p.node.generator);for(const parameter of p.node.params)inspectPattern(parameter,void 0)},"ObjectProperty|ObjectMethod":function(p){const node=p.node;if((t.isObjectProperty(node)||t.isObjectMethod(node))&&node.computed)facts.required||=!isPrimitive(resolveValue(node.key,p.scope))},VariableDeclarator(p){if(p.node.init&&!t.isIdentifier(p.node.id))inspectPattern(p.node.id,resolveValue(p.node.init,p.scope))},AssignmentExpression(p){facts.required||=!safeData(resolveValue(p.node.right,p.scope));if(t.isPattern(p.node.left))inspectPattern(p.node.left,resolveValue(p.node.right,p.scope));if(p.node.operator!==`=`||t.isMemberExpression(p.node.left))facts.required||=!isPrimitive(resolveValue(p.node.left,p.scope))||!isPrimitive(resolveValue(p.node.right,p.scope))},UpdateExpression(p){facts.required||=!isPrimitive(resolveValue(p.node.argument,p.scope))},UnaryExpression(p){if(p.node.operator===`delete`||[`+`,`-`,`~`].includes(p.node.operator)&&!isPrimitive(resolveValue(p.node.argument,p.scope)))facts.required=true},BinaryExpression(p){if(p.node.operator!==`===`&&p.node.operator!==`!==`)facts.required||=!isPrimitive(resolveValue(p.node.left,p.scope))||!isPrimitive(resolveValue(p.node.right,p.scope))},TemplateLiteral(p){facts.required||=p.node.expressions.some(expression=>!isPrimitive(resolveValue(expression,p.scope)))},CallExpression(p){const{callee,arguments:args}=p.node;if((t.isImport(callee)||t.isIdentifier(callee,{name:`require`})&&!p.scope.hasBinding(`require`))&&t.isStringLiteral(args[0]))facts.imports.add(args[0].value);inspectCall(callee,args,p.scope)},OptionalCallExpression(p){inspectCall(p.node.callee,p.node.arguments,p.scope)},ExportNamedDeclaration(p){if(p.node.exportKind===`type`||p.node.specifiers.length>0&&p.node.specifiers.every(s=>t.isExportSpecifier(s)&&s.exportKind===`type`)){p.skip();return}if(p.node.source){if(runtimeModule(p.node.source.value))facts.required||=p.node.specifiers.some(s=>!t.isExportSpecifier(s)||s.exportKind!==`type`&&!isSafeApi(propertyName$1(s.local,false)));else facts.imports.add(p.node.source.value)}else if(!component){const declaration=p.node.declaration;if(t.isVariableDeclaration(declaration)){for(const item of declaration.declarations)if(item.init)inspectExportValue(item.init,p.scope)}for(const specifier of p.node.specifiers)if(t.isExportSpecifier(specifier)&&specifier.exportKind!==`type`)inspectExportValue(specifier.local,p.scope)}},ExportAllDeclaration(p){if(p.node.exportKind!==`type`){if(runtimeModule(p.node.source.value))facts.required=true;else facts.imports.add(p.node.source.value)}},ExportDefaultDeclaration(p){if(component){if(t.isCallExpression(p.node.declaration)){const factory=resolveValue(p.node.declaration.callee,p.scope);if(factory?.kind!==`api`||factory.name!==`defineComponent`)facts.required=true}else inspectOptions(p.node.declaration,p.scope)}else inspectExportValue(p.node.declaration,p.scope)},"NewExpression|TaggedTemplateExpression|ImportExpression|JSXElement|JSXFragment|Class|Decorator|SpreadElement|TSImportEqualsDeclaration|TSExportAssignment|ForOfStatement|ForInStatement|AwaitExpression|YieldExpression":function(p){facts.required=true;if(p.isImportExpression()&&t.isStringLiteral(p.node.source))facts.imports.add(p.node.source.value)}})}if(!component){for(const statement of script.program.body)if(t.isExportDefaultDeclaration(statement))facts.exports.set(`default`,resolveValue(statement.declaration,scriptScope));else if(t.isExportNamedDeclaration(statement)&&statement.exportKind!==`type`){if(statement.declaration)for(const name of Object.keys(t.getBindingIdentifiers(statement.declaration)))facts.exports.set(name,resolveValue(t.identifier(name),scriptScope));for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&specifier.exportKind!==`type`)facts.exports.set(propertyName$1(specifier.exported,false),statement.source?values.imported(statement.source.value,propertyName$1(specifier.local,false)):resolveValue(specifier.local,scriptScope))}const explicitExports=new Set(facts.exports.keys());for(const statement of script.program.body)if(t.isExportAllDeclaration(statement)&&statement.exportKind!==`type`){for(const[name,value]of modules.get(statement.source.value)?.exports??[])if(name!=="default"&&!explicitExports.has(name))facts.exports.set(name,facts.exports.has(name)?void 0:value)}}}catch{facts.required=true}return facts}function normalizeSourceId(id){return path.normalize(normalizeFsResolvedId(id))}function createSourceReader(options,dependencies){const cache=options?.nativeSlotContextCache??/* @__PURE__ */ new Map;const reader=options?.sfcSrc?.readFile??readFile;const load=input=>{const id=normalizeSourceId(input);dependencies.add(id);const cached=cache.get(id);if(cached)return cached;const task=(async()=>{if(isSkippableResolvedId(id))return;try{const source=await reader(id,{checkMtime:options?.sfcSrc?.checkMtime});if(typeof source!==`string`)return;if(id.endsWith(`.vue`)){const parsed=parse$1(source,{filename:id,sourceMap:false,ignoreEmpty:true});return{source,descriptor:parsed.descriptor,invalid:parsed.errors.length>0}}return{source}}catch{return}})();cache.set(id,task);return task};const resolve=async(source,importer)=>{try{const resolved=await options?.sfcSrc?.resolveId?.(source,importer);if(resolved){const id=normalizeSourceId(resolved);dependencies.add(id);return id}const normalized=normalizeSourceId(source);if(!source.startsWith(`.`)&&!path.isAbsolute(normalized))return;const id=path.isAbsolute(normalized)?normalized:path.resolve(path.dirname(importer),normalized);dependencies.add(id);if(path.extname(id))return id;for(const candidate of[id,`${id}.ts`,`${id}.js`,`${id}.mts`,`${id}.mjs`,`${id}.tsx`,`${id}.jsx`,`${id}/index.ts`,`${id}/index.js`])if(await load(candidate))return candidate;return id}catch{return}};return{load,resolve}}function analyzeTemplate(content,options){const facts={required:false,tags:/* @__PURE__ */ new Set,expressions:``};const tagContext={htmlTagToWxmlMap:resolveHtmlTagToWxmlMap(options?.htmlTagToWxml)};const expression=(source,event=false)=>{if(!source.trim())return``;try{const statement=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];const handler=t.isExpressionStatement(statement)&&(t.isIdentifier(statement.expression)||t.isMemberExpression(statement.expression)||t.isOptionalMemberExpression(statement.expression));return event&&handler?`;(${source})();`:`;(${source});`}catch{if(event)return`;(() => { ${source}\n})();`;facts.required=true;return``}};try{const ast=baseParse(content,{onError:()=>{facts.required=true}});const visit=node=>{if(node.type===NodeTypes.INTERPOLATION&&node.content.type===NodeTypes.SIMPLE_EXPRESSION)return expression(node.content.content);if(node.type!==NodeTypes.ELEMENT)return``;const tag=resolveTemplateTagName(node.tag,tagContext);if(node.tag===`slot`||node.tag===`component`||tag===`slot`||tag===`component`||node.tag===`template`&&node.props.some(prop=>prop.type===NodeTypes.ATTRIBUTE&&(prop.name===`is`||prop.name===`src`)))facts.required=true;else if(!isBuiltinComponent(tag.toLowerCase())&&tag!==`template`&&tag!==`block`)facts.tags.add(node.tag);let code=``;let list=``;let parameters;let bindings=``;for(const prop of node.props){if(prop.type!==NodeTypes.DIRECTIVE)continue;if(prop.name===`slot`||![`bind`,`on`,`if`,`else`,`else-if`,`for`,`show`,`model`,`text`,`once`,`memo`,`cloak`,`pre`].includes(prop.name))facts.required=true;if(prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&!prop.arg.isStatic)code+=expression(prop.arg.content);if(prop.exp?.type!==NodeTypes.SIMPLE_EXPRESSION)continue;if(prop.name===`for`){const loop=parseForExpression(prop.exp.content);if(loop.error||loop.itemPatternError||!loop.listExp)facts.required=true;if(loop.listExp)list+=expression(loop.listExp);parameters=[loop.itemPattern??loop.item,loop.index,loop.key].filter(name=>Boolean(name));if(!loop.itemPattern)for(const[name,value]of Object.entries(loop.itemAliases??{}))bindings+=`const ${name} = (${value});`}else if(prop.name!==`slot`){const body=expression(prop.exp.content,prop.name===`on`);code+=prop.name===`on`?`;(($event) => { ${body} });`:body}}code+=node.children.map(visit).join(`
28
+ `:``}const uni = __wevuCreateUniAppHost(wx)\n`)}if(disableVirtualHost)for(const range of analysis.virtualHostTrueRanges)output.overwrite(range.start,range.end,`false`);return output.toString()}function transformVueSfc(source,filename,target){const normalizedSource=normalizeAuxiliaryWxsScripts(source);const{descriptor,errors}=parse$1(normalizedSource,{filename});if(errors.length){const error=errors[0];throw new Error(`[uni-app] 解析 ${filename} 失败:${error.message}`)}const blocks=[descriptor.script,descriptor.scriptSetup].filter(Boolean);const analyses=blocks.map(block=>{const lang=block.lang??`js`;return analyzeScript$1(block.content,`${filename}.${lang}`)});const injectIndex=analyses.findIndex(analysis=>analysis.usesFreeUni);const output=new MagicString(normalizedSource);for(let index=blocks.length-1;index>=0;index-=1){const block=blocks[index];const analysis=analyses[index];const code=renderScript(analysis,index===injectIndex,target===`mp-weixin`);output.overwrite(block.loc.start.offset,block.loc.end.offset,code)}return output.toString()}function transformUniAppSource(source,options){const conditional=transformUniAppConditionalCode(source,options);const filename=options.filename.split(`?`,1)[0];const blockType=options.blockType??(filename.endsWith(`.vue`)?`sfc`:SCRIPT_EXT_RE.test(filename)?`script`:STYLE_EXT_RE.test(filename)?`style`:void 0);if(blockType===`sfc`){const code=transformVueSfc(conditional.code,filename,options.target);return{changed:conditional.changed||code!==source,code}}if(blockType===`script`){const analysis=analyzeScript$1(conditional.code,filename);const code=renderScript(analysis,analysis.usesFreeUni,options.target===`mp-weixin`&&filename.endsWith(`.vue`));return{changed:conditional.changed||code!==source,code}}if(blockType===`style`||blockType===`template`)return conditional;return{changed:false,code:source}}function isUniAppCompatibilityFile(filename,srcRoot,include){const clean=filename.split(`?`,1)[0];const relative=path.relative(srcRoot,clean);if(relative===``||!relative.startsWith(`..`)&&!path.isAbsolute(relative))return true;const normalized=clean.replace(/\\/g,`/`);return include.some(packageName=>{const packagePath=packageName.replace(/^\/+|\/+$/g,``);return normalized.includes(`/node_modules/${packagePath}/`)})}function transformNestedWxssVars(source){return source}function normalizeStyleError(error){return error instanceof Error?error.message:String(error)}function hasSlottedScopeSelector(source,slottedScopeId){let found=false;const processor=selectorParser(selectors=>{selectors.walkAttributes(attribute=>{if(attribute.attribute===slottedScopeId)found=true})});postcss.parse(source).walkRules(rule=>{if(!found)processor.processSync(rule.selector)});return found}function transformVueDeepSelectors(source){const root=postcss.parse(source);const processor=selectorParser(selectors=>{selectors.walkTags(tag=>{const mapped=DEFAULT_HTML_TO_WXML_TAG_MAP[tag.value.toLowerCase()];if(mapped&&mapped!==tag.value.toLowerCase())tag.replaceWith(selectorParser.className({value:tag.value.toLowerCase()}))});selectors.walkPseudos(pseudo=>{if(![`:deep`,`::v-deep`].includes(pseudo.value))return;const replacement=pseudo.nodes?.[0]?.nodes.map(node=>node.clone())??[];replacement.length?pseudo.replaceWith(...replacement):pseudo.remove()})});root.walkRules(rule=>{rule.selector=processor.processSync(rule.selector).replace(/\s{2,}/g,` `).trim()});return root.toString()}async function compileVueStyleToWxss(styleBlock,options){const filename=options.filename??`style-${options.id}.${styleBlock.lang||`css`}`;const moduleName=typeof styleBlock.module===`string`?styleBlock.module:typeof options.modules===`string`?options.modules:`$style`;const modules=Boolean(options.modules||styleBlock.module);const result=await compileStyleAsync({filename,id:`data-v-${options.id}`,source:styleBlock.content,scoped:options.transformScoped!==false&&Boolean(options.scoped||styleBlock.scoped),modules,modulesOptions:modules?{generateScopedName:name=>`${name}_${options.id}`}:void 0,preprocessLang:styleBlock.lang,preprocessOptions:options.preprocessOptions});if(result.errors.length)throw new Error(`SFC 样式编译失败(${filename}):${result.errors.map(normalizeStyleError).join(`; `)}`);return{code:options.preserveDeepSelectors?result.code:transformVueDeepSelectors(result.code),map:result.map?JSON.stringify(result.map):void 0,scopedId:options.scoped||styleBlock.scoped?`data-v-${options.id}`:void 0,usesSlotted:hasSlottedScopeSelector(result.code,`data-v-${options.id}-s`),modules:result.modules?{[moduleName]:result.modules}:void 0,dependencies:[...result.dependencies]}}const CLASS_LIKE_TEMPLATE_ATTR_RE=/(?:^|[\s<])(?:[\w-]*class[\w-]*|v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[^\s>]+)/g;const VUE_DYNAMIC_CLASS_LIKE_BINDING_RE=/(?:^|[\s<])(?:v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=/;function hashPayload$1(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function collectTemplateTailwindCandidates(content){const candidates=/* @__PURE__ */ new Set;for(const match of content.matchAll(CLASS_LIKE_TEMPLATE_ATTR_RE))candidates.add(match[0].trim());return Array.from(candidates).sort()}function normalizeTailwindContentPayload(payload){const scriptLiterals=VUE_DYNAMIC_CLASS_LIKE_BINDING_RE.test(payload.template)?payload.scriptLiterals:payload.hasScriptTailwindClassHint?payload.scriptCallLiterals:[];return{...payload,template:collectTemplateTailwindCandidates(payload.template),scriptLiterals,scriptCallLiterals:[]}}function buildTailwindContentPayload(template,scriptContent,scriptSetupContent){return{template,scriptLiterals:[...collectScriptStringLiterals(scriptContent),...collectScriptStringLiterals(scriptSetupContent)],scriptCallLiterals:[...collectScriptCallStringLiterals(scriptContent),...collectScriptCallStringLiterals(scriptSetupContent)],hasScriptTailwindClassHint:mayContainScriptCallOrModuleSyntax(`${scriptContent}\n${scriptSetupContent}`)}}function hashTailwindContentPayload(payload){return hashPayload$1(normalizeTailwindContentPayload(payload))}function hashTailwindTemplateContentPayload(payload){return hashPayload$1({template:normalizeTailwindContentPayload(payload).template})}function hashTailwindScriptContentPayload(payload){return hashPayload$1({scriptLiterals:normalizeTailwindContentPayload(payload).scriptLiterals})}const signaturePayloadCache=/* @__PURE__ */ new WeakMap;function serializeAttrs(attrs){return Object.fromEntries(Object.entries(attrs).sort(([a],[b])=>a.localeCompare(b)))}function serializeBlock(block){if(!block)return null;return{type:block.type,attrs:serializeAttrs(block.attrs),content:block.content}}function buildRawVueSfcPayload(descriptor){const configBlocks=[];const templateBlocks=[];for(const block of descriptor.customBlocks){const serialized=serializeBlock(block);if(block.type===`json`||block.type===`config`)configBlocks.push(serialized);else templateBlocks.push(serialized)}return{script:{script:serializeBlock(descriptor.script),scriptSetup:serializeBlock(descriptor.scriptSetup)},template:{template:serializeBlock(descriptor.template),customBlocks:templateBlocks},style:{styles:descriptor.styles.map(style=>serializeBlock(style))},config:{customBlocks:configBlocks},hasTemplate:Boolean(descriptor.template?.content.trim())}}function normalizeScriptBlock(block,filename){if(!block)return{block:null,macroSources:[]};try{const split=splitJsonMacroCallsFromCode(block.content,filename);return{block:{...block,content:split.stripped},macroSources:split.macroSources}}catch{return{block,macroSources:[]}}}function normalizeVueSfcPayload(raw,filename){const script=normalizeScriptBlock(raw.script.script,filename);const scriptSetup=normalizeScriptBlock(raw.script.scriptSetup,filename);const scriptPayload={script:script.block,scriptSetup:scriptSetup.block};return{...raw,script:scriptPayload,config:{...raw.config,macroSources:[...script.macroSources,...scriptSetup.macroSources]},tailwindContent:buildTailwindContentPayload(raw.template.template?.content??``,script.block?.content??``,scriptSetup.block?.content??``)}}function resolveVueSfcSignaturePayload(source,filename){const{descriptor,errors}=parse$1(source,{filename});if(errors.length)return;const cached=signaturePayloadCache.get(descriptor);if(cached)return cached;const payload=normalizeVueSfcPayload(buildRawVueSfcPayload(descriptor),filename);signaturePayloadCache.set(descriptor,payload);return payload}const VUE_SFC_BLOCK_TYPES=[`script`,`template`,`style`,`config`];const hmrSignaturesCache=/* @__PURE__ */ new WeakMap;function hashPayload(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function resolveVueSfcHmrSignatures(source,filename){const payload=resolveVueSfcSignaturePayload(source,filename);if(!payload)return{};const cached=hmrSignaturesCache.get(payload);if(cached)return cached;const cssModules=payload.style.styles.filter(style=>Boolean(style.attrs.module));const blockSignatures={script:hashPayload(cssModules.length?[payload.script,cssModules]:payload.script),template:hashPayload(payload.template),style:hashPayload(payload.style),config:hashPayload(payload.config)};const tailwindContentSignature=hashTailwindContentPayload(payload.tailwindContent);const tailwindTemplateContentSignature=hashTailwindTemplateContentPayload(payload.tailwindContent);const tailwindScriptContentSignature=hashTailwindScriptContentPayload(payload.tailwindContent);const signatures={blockSignatures,contentSignatures:{tailwindcss:tailwindContentSignature},nonJsonSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.style]),scriptSignature:blockSignatures.script,styleIndependentSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.config]),scriptContentSignatures:{tailwindcss:tailwindScriptContentSignature},tailwindContentSignature,tailwindScriptContentSignature,tailwindTemplateContentSignature,templateContentSignatures:{tailwindcss:tailwindTemplateContentSignature},hasTemplate:payload.hasTemplate};hmrSignaturesCache.set(payload,signatures);return signatures}function classifyVueSfcBlockChanges(previous,current){return VUE_SFC_BLOCK_TYPES.filter(type=>previous[type]!==current[type])}function resolveVueSfcNonJsonSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).nonJsonSignature}function resolveVueSfcScriptSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).blockSignatures?.script}function resolveVueSfcStyleIndependentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).styleIndependentSignature}function resolveVueSfcTailwindContentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).tailwindContentSignature}function resolveVueSfcHasTemplate(source,filename){return resolveVueSfcHmrSignatures(source,filename).hasTemplate}const SOURCE_ROOT_RE=/(?:^|\/)src\/(.+)$/;function normalizeScopedIdInput(filename){const normalized=filename.replace(/\\/g,`/`);return normalized.match(SOURCE_ROOT_RE)?.[1]??normalized.replace(/^.*?\/(pages|components|layouts)\//,`$1/`)}function generateScopedId(filename){const input=normalizeScopedIdInput(filename);let hash=2166136261;for(let index=0;index<input.length;index+=1){hash^=input.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function collectNativeComponentRegistrations(analysis,templateNames,templateTags){if(!analysis?.registeredComponents)return;const pending=[];const imports=new Map(analysis.imports.filter(item=>!item.typeOnly&&item.kind!==`namespace`).map(item=>[item.local,item]));for(const registration of analysis.registeredComponents){const imported=imports.get(registration.local);if(!registration.name||!imported||imported.kind===`namespace`||!templateNames.has(registration.name))continue;pending.push({localName:registration.local,importSource:imported.source,importedName:imported.imported,kind:imported.kind,templateTags:[...templateTags?.get(registration.name)??[registration.name]]})}return pending}function normalizeResolvedUsingComponent(result){if(!result)return;if(typeof result===`string`)return{from:result};return result}function isWevuSfcComponent(result){return result?.sourceType?result.sourceType===`wevu-sfc`:Boolean(result?.resolvedId?.endsWith(`.vue`)||result?.from?.endsWith(`.vue`))}function isVueSfcSource(source){return source.endsWith(`.vue`)}function kebabToCamel(name){return name.replace(/-([a-z0-9])/g,(_,character)=>character.toUpperCase())}function capitalize(name){return name?`${name.charAt(0).toUpperCase()}${name.slice(1)}`:name}function extractStringPropertyFromObject(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if(!(t.isIdentifier(key)?key.name===keyName:t.isStringLiteral(key)?key.value===keyName:false)||!t.isStringLiteral(property.value))continue;return property.value.value}}function extractStaticComponentMeta(scriptSetupContent){let ast;try{ast=parse$3(scriptSetupContent,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return{isMiniProgramComponent:false}}let componentName;let isMiniProgramComponent=false;traverse(ast,{CallExpression(path){const callee=path.node.callee;const arg=path.node.arguments[0];if(!t.isObjectExpression(arg))return;if(t.isIdentifier(callee,{name:`defineOptions`})){componentName??=extractStringPropertyFromObject(arg,`name`);return}if(!t.isIdentifier(callee,{name:`defineComponentJson`}))return;for(const property of arg.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if((t.isIdentifier(key)?key.name===`component`:t.isStringLiteral(key)?key.value===`component`:false)&&t.isBooleanLiteral(property.value)&&property.value.value){isMiniProgramComponent=true;return}}}});return{componentName,isMiniProgramComponent}}function readVueSfcScriptSetupContent(source,resolvedId){const{descriptor,errors}=parse$1(source,{filename:resolvedId});if(errors.length>0||!descriptor.scriptSetup?.content)return;return descriptor.scriptSetup.content}async function resolveVueSfcStaticComponentMeta(resolvedId,options){if(!resolvedId?.endsWith(`.vue`))return{isMiniProgramComponent:false};const cached=options?.cache?.get(resolvedId);if(cached)return await cached;const task=(async()=>{try{const scriptSetupContent=readVueSfcScriptSetupContent(await readFile$1(resolvedId,`utf8`),resolvedId);return scriptSetupContent?extractStaticComponentMeta(scriptSetupContent):{isMiniProgramComponent:false}}catch(error){const message=error instanceof Error?error.message:String(error);options?.warn?.(`[Vue 编译] 解析 ${resolvedId} 的静态组件元信息失败:${message}`);return{isMiniProgramComponent:false}}})();options?.cache?.set(resolvedId,task);return await task}function registerResolvedComponentTag(result,tag,registration){const normalizedTag=normalizeTemplateTagName(tag);const{resolvedId,sourceType,componentMeta}=registration;result.resolvedComponentIds.set(tag,resolvedId);result.resolvedComponentIds.set(normalizedTag,resolvedId);if(sourceType===`wevu-sfc`){result.wevuComponentTags.add(tag);result.wevuComponentTags.add(normalizedTag)}if(componentMeta.componentName){result.componentNameMap[tag]=componentMeta.componentName;result.componentNameMap[normalizedTag]=componentMeta.componentName}if(componentMeta.isMiniProgramComponent){result.miniProgramComponentTags.add(tag);result.miniProgramComponentTags.add(normalizedTag)}}function createComponentSourceInfo(){return{autoUsingComponentsMap:{},autoImportTagsMap:{},autoComponentMeta:{},wevuComponentTags:/* @__PURE__ */ new Set,resolvedComponentIds:/* @__PURE__ */ new Map,miniProgramComponentTags:/* @__PURE__ */ new Set,componentNameMap:{}}}function collectTemplateComponentTagInfo(template,filename,warn){const warnHandler=resolveWarnHandler(warn);const analysis=analyzeVueTemplateTags(template);if(analysis.errorMessage!==void 0)for(const warnLabel of[`组件标签`,`脚本导入组件标签`])warnVueTemplateTagAnalysis(analysis.errorMessage,{filename,warnLabel,warn:warnHandler});const autoImportTags=/* @__PURE__ */ new Set;const componentNames=/* @__PURE__ */ new Set;const tagsByComponentName=/* @__PURE__ */ new Map;for(const tag of analysis.tags){if(isAutoImportCandidateTag(tag))autoImportTags.add(tag);const camelName=kebabToCamel(tag);for(const componentName of[tag,camelName,capitalize(camelName)]){componentNames.add(componentName);const matchedTags=tagsByComponentName.get(componentName)??/* @__PURE__ */ new Set;matchedTags.add(tag);tagsByComponentName.set(componentName,matchedTags)}}return{autoImportTags,componentNames,tagsByComponentName}}async function resolveScriptComponentRegistrations(options){const{pending,filename,compileOptions,autoUsingComponents}=options;return await Promise.all(pending.map(async({localName,importSource,importedName,kind,templateTags})=>{let resolved=autoUsingComponents?.resolveUsingComponentPath?normalizeResolvedUsingComponent(await autoUsingComponents.resolveUsingComponentPath(importSource,filename,{localName,importedName,kind})):void 0;if(!resolved?.from&&importSource.startsWith(`/`))resolved={from:removeExtensionDeep(importSource),resolvedId:importSource};if(!resolved?.resolvedId&&isVueSfcSource(importSource)&&importSource.startsWith(`.`))resolved={...resolved??{},resolvedId:path.resolve(path.dirname(filename),importSource)};const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoUsingComponents?.warn??compileOptions?.warn});return{kind:`script`,name:localName,templateTags,from:resolved?.from,resolvedId:resolved?.resolvedId,sourceType:resolved?.sourceType??(isVueSfcSource(importSource)||isWevuSfcComponent(resolved)?`wevu-sfc`:void 0),componentMeta}}))}async function collectScriptSetupUsingComponents(options){const{descriptor,descriptorForCompile,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,nativeScriptAnalysis}=options;if(!descriptor.scriptSetup||!descriptor.template)return[];if(!templateComponentNames?.size)return[];try{const pending=[];const addImport=imported=>{if(imported.typeOnly||imported.kind===`namespace`||!templateComponentNames.has(imported.local))return;const templateTags=[...templateTagsByComponentName?.get(imported.local)??[imported.local]];if(imported.kind==="default"||imported.kind===`named`)pending.push({localName:imported.local,importSource:imported.source,importedName:imported.imported,kind:imported.kind,templateTags})};if(nativeScriptAnalysis)nativeScriptAnalysis.imports.forEach(addImport);else{const setupAst=parse$3(descriptorForCompile.scriptSetup.content,BABEL_TS_MODULE_PARSER_OPTIONS);traverse(setupAst,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;const importSource=path.node.source.value;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!(`local`in specifier)||!t.isIdentifier(specifier.local))continue;const localName=specifier.local.name;if(!templateComponentNames.has(localName))continue;const templateTags=[...templateTagsByComponentName?.get(localName)??[localName]];if(t.isImportDefaultSpecifier(specifier))pending.push({localName,importSource,importedName:`default`,kind:`default`,templateTags});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;pending.push({localName,importSource,importedName,kind:`named`,templateTags})}}}})}return await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 <script setup> 导入失败:${message}`);return[]}}function getExportDefaultExpression(scriptAst,aliases){const declarations=/* @__PURE__ */ new Map;let declaration=null;traverse(scriptAst,{VariableDeclarator(path){const{id,init}=path.node;if(!t.isIdentifier(id)||!init)return;const initializer=unwrapTypeLikeExpression$1(init);const options=t.isObjectExpression(initializer)?initializer:unwrapDefineComponent(initializer,aliases);if(options)declarations.set(id.name,options)},ExportDefaultDeclaration(path){declaration=t.isExpression(path.node.declaration)?unwrapTypeLikeExpression$1(path.node.declaration):path.node.declaration;if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&aliases.has(declaration.callee.name)){const argument=declaration.arguments[0];if(t.isExpression(argument))declaration.arguments[0]=unwrapTypeLikeExpression$1(argument)}}});return resolveComponentExpression(declaration,declarations,aliases)}function getComponentRegistrationName(property){if(t.isIdentifier(property.key))return property.key.name;return t.isStringLiteral(property.key)?property.key.value:void 0}async function collectOptionsApiUsingComponents(options){const{descriptor,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,nativeScriptAnalysis}=options;if(!descriptor.script||!descriptor.template||!templateComponentNames?.size)return[];try{const nativeRegistrations=collectNativeComponentRegistrations(nativeScriptAnalysis,templateComponentNames,templateTagsByComponentName);if(nativeRegistrations)return await resolveScriptComponentRegistrations({pending:nativeRegistrations,filename,compileOptions,autoUsingComponents});const ast=parse$3(descriptor.script.content,BABEL_TS_MODULE_PARSER_OPTIONS);const imports=/* @__PURE__ */ new Map;if(nativeScriptAnalysis)for(const imported of nativeScriptAnalysis.imports){if(imported.typeOnly||imported.kind===`namespace`)continue;imports.set(imported.local,{importSource:imported.source,importedName:imported.imported,kind:imported.kind})}else traverse(ast,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!t.isIdentifier(specifier.local))continue;if(t.isImportDefaultSpecifier(specifier))imports.set(specifier.local.name,{importSource:path.node.source.value,importedName:`default`,kind:`default`});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;imports.set(specifier.local.name,{importSource:path.node.source.value,importedName,kind:`named`})}}}});const aliases=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]);for(const[localName,imported]of imports)if(imported.kind===`named`&&imported.importedName===WE_VU_RUNTIME_APIS.defineComponent&&(imported.importSource===`vue`||isWevuRuntimeModuleId(imported.importSource)))aliases.add(localName);const componentExpression=getExportDefaultExpression(ast,aliases);const componentsProperty=componentExpression&&resolveStaticObjectProperty(componentExpression,`components`,void 0);if(componentsProperty?.kind!==`expression`||!t.isObjectExpression(componentsProperty.node))return[];const pending=[];for(const property of componentsProperty.node.properties){if(!t.isObjectProperty(property)||!t.isIdentifier(property.value))continue;const registrationName=getComponentRegistrationName(property);const imported=imports.get(property.value.name);if(!registrationName||!imported||!templateComponentNames.has(registrationName))continue;pending.push({localName:property.value.name,...imported,templateTags:[...templateTagsByComponentName?.get(registrationName)??[registrationName]]})}return await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 Options API 局部组件失败:${message}`);return[]}}async function collectAutoImportWevuComponents(options){const{descriptor,filename,compileOptions,autoImportTags,templateAutoImportTags,warn}=options;if(!autoImportTags||!descriptor.template)return[];const resolvedTags=await Promise.all([...templateAutoImportTags??[]].map(async tag=>{let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoImportTags.warn??warn});return{tag,resolved,componentMeta}}));const registrations=[];for(const{tag,resolved,componentMeta}of resolvedTags){if(!resolved?.from)continue;registrations.push({kind:`auto`,name:resolved.name||tag,templateTags:[tag],from:resolved.from,resolvedId:resolved.resolvedId,sourceType:resolved.sourceType??(isWevuSfcComponent(resolved)?`wevu-sfc`:void 0),componentMeta})}return registrations}async function collectComponentSourceInfo(options){const result=createComponentSourceInfo();const templateComponentTagInfo=options.descriptor.template?collectTemplateComponentTagInfo(options.descriptor.template.content,options.filename,options.autoUsingComponents?.warn??options.autoImportTags?.warn??options.compileOptions?.warn):void 0;const[setupRegistrations,optionsRegistrations,autoRegistrations]=await Promise.all([collectScriptSetupUsingComponents({descriptor:options.descriptor,descriptorForCompile:options.descriptorForCompile,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,nativeScriptAnalysis:options.nativeScriptAnalysis?.scriptSetup}),collectOptionsApiUsingComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,nativeScriptAnalysis:options.nativeScriptAnalysis?.script&&options.descriptor.script?.content===options.descriptorForCompile.script?.content?options.nativeScriptAnalysis.script:void 0}),collectAutoImportWevuComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoImportTags:options.autoImportTags,templateAutoImportTags:templateComponentTagInfo?.autoImportTags,warn:options.compileOptions?.warn})]);const registrationsByTag=/* @__PURE__ */ new Map;for(const registrations of[autoRegistrations,optionsRegistrations,setupRegistrations])for(const registration of registrations){if(registration.kind===`script`&&registration.from)result.autoComponentMeta[registration.name]=registration.from;for(const tag of registration.templateTags){const normalizedTag=normalizeTemplateTagName(tag);const previous=registrationsByTag.get(normalizedTag);if(previous){if(registration.from&&previous.registration.from&&previous.registration.from!==registration.from)(registration.kind===`script`?options.autoUsingComponents?.warn:options.autoImportTags?.warn)?.(`[Vue 编译] usingComponents 冲突:${options.filename} 中 '${normalizedTag}' 的 '${previous.registration.from}' 将被更高优先级组件注册覆盖为 '${registration.from}'`);previous.registration=registration;previous.tags.add(tag)}else registrationsByTag.set(normalizedTag,{registration,tags:/* @__PURE__ */ new Set([tag])})}}for(const[normalizedTag,{registration,tags}]of registrationsByTag){const{kind,name,from}=registration;if(from){if(kind===`auto`)result.autoImportTagsMap[name]=from;else for(const tag of tags)result.autoUsingComponentsMap[tag]=from}const normalizedName=normalizeTemplateTagName(name);if(normalizedName===normalizedTag||!registrationsByTag.has(normalizedName))registerResolvedComponentTag(result,name,registration);for(const tag of tags)registerResolvedComponentTag(result,tag,registration)}return result}function normalizeConfigLang(lang){if(!lang)return`json`;const lower=lang.toLowerCase();if(lower===`txt`)return`json`;return lower}function isJsonLikeLang(lang){return lang===`json`||lang===`jsonc`||lang===`json5`}function resolveJsLikeLang(lang){if(lang===`ts`||lang===`tsx`||lang===`cts`||lang===`mts`)return`ts`;return`js`}async function evaluateJsLikeConfig(source,filename,lang){const dir=path.dirname(filename);const extension=resolveJsLikeLang(lang)===`ts`?`ts`:`js`;const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.config.${unique}`);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.${unique}.${extension}`);const rewritten=rewriteJsLikeImportsForTempDir(source,dir,tempDir);await writeFile(tempFile,rewritten,`utf8`);try{const{mod}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});let resolved=mod?.default??mod;if(typeof resolved===`function`)resolved=resolved();if(resolved&&typeof resolved.then===`function`)resolved=await resolved;if(resolved&&typeof resolved===`object`)return resolved;throw new Error(`配置块必须导出对象或返回对象的函数。`)}finally{try{await remove(tempDir)}catch{}}})}async function compileConfigBlocks(blocks,filename,options){const jsonBlocks=blocks.filter(block=>block.type===`json`);if(!jsonBlocks.length)return;let accumulator={};for(const block of jsonBlocks){const lang=normalizeConfigLang(block.lang);try{if(isJsonLikeLang(lang)){const parsed=parse$2(block.content,void 0,true);if(options?.merge){const merged=options.merge(accumulator,parsed);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,parsed);continue}const evaluated=await evaluateJsLikeConfig(block.content,filename,lang);if(!evaluated||typeof evaluated!==`object`)continue;if(options?.merge){const merged=options.merge(accumulator,evaluated);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,evaluated)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 <json> 块失败(${lang}):${filename}: ${message}`)}}if(Reflect.has(accumulator,`$schema`))delete accumulator.$schema;return JSON.stringify(accumulator,null,2)}function collectTemplateAutoImportTags(template,filename,warn){const warnHandler=resolveWarnHandler(warn);return collectVueTemplateTags(template,{filename,warnLabel:`自动导入标签`,warn:message=>warnHandler(message),shouldCollect:isAutoImportCandidateTag})}function normalizeUsingComponents(config){const raw=config.usingComponents;if(!raw||typeof raw!==`object`||Array.isArray(raw))return;const usingComponents={};for(const[name,from]of Object.entries(raw))usingComponents[normalizeTemplateTagName(name)]=from;config.usingComponents=usingComponents}async function compileConfigPhase(params){const{descriptor,filename,autoUsingComponentsMap,autoImportTagsMap:precomputedAutoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults,mergeJson,scriptSetupMacroConfig,result,warn}=params;let configObj;if(descriptor.customBlocks.some(b=>b.type===`json`)){const configResult=await compileConfigBlocks(descriptor.customBlocks,filename,{merge:(target,source)=>mergeJson(target,source,`json-block`)});if(configResult)try{configObj=JSON.parse(configResult)}catch{configObj={}}}const autoImportTagsMap=precomputedAutoImportTagsMap?{...precomputedAutoImportTagsMap}:{};if(!precomputedAutoImportTagsMap&&autoImportTags&&descriptor.template){const tags=collectTemplateAutoImportTags(descriptor.template.content,filename,autoImportTags.warn??warn);for(const tag of tags){let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;autoImportTagsMap[resolved.name||tag]=resolved.from}}if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents={};if(existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw))for(const[name,from]of Object.entries(existingRaw))usingComponents[normalizeTemplateTagName(name)]=from;for(const[name,from]of Object.entries(autoImportTagsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoImportTags?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被模板标签自动引入覆盖为 '${from}'`);usingComponents[normalizedName]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoUsingComponents?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被 <script setup> 导入覆盖为 '${from}'`);usingComponents[normalizedName]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(result.componentGenerics&&Object.keys(result.componentGenerics).length>0){const existing=configObj?.componentGenerics;const componentGenerics=existing&&typeof existing===`object`&&!Array.isArray(existing)?existing:{};for(const[key,value]of Object.entries(result.componentGenerics))componentGenerics[key]=value;configObj=mergeJson(configObj??{},{componentGenerics},`component-generics`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptSetupMacroConfig&&Object.keys(scriptSetupMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptSetupMacroConfig,`macro`);if(configObj)normalizeUsingComponents(configObj);if(configObj&&Object.keys(configObj).length>0)result.config=JSON.stringify(configObj,null,2)}function finalizeResult(result,options){if(!result.script||result.script.trim()===``)result.script=`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from '${RUNTIME_IMPORT_PATH}';\n${WE_VU_RUNTIME_APIS.createWevuComponent}({});\n`;if(result.meta&&options.scriptSetupMacroHash)result.meta.jsonMacroHash=options.scriptSetupMacroHash;if(result.meta&&options.defineOptionsHash)result.meta.defineOptionsHash=options.defineOptionsHash}function createModuleValueBoundary(isPrimitive,isRuntimeApi){const opaque={kind:`opaque`};const importedValues=/* @__PURE__ */ new WeakMap;const factoryProofs=/* @__PURE__ */ new WeakMap;const factoryResolvers=/* @__PURE__ */ new WeakMap;function safeFactory(fn){if(!t.isFunction(fn.node)||fn.node.async||fn.node.generator)return false;const cached=factoryProofs.get(fn.node);if(cached!==void 0)return cached;factoryProofs.set(fn.node,false);let safe=true;fn.scope.path.traverse({ReferencedIdentifier(p){const value=fn.resolve(p.node,p.scope);if(value?.kind===`opaque`||!isPrimitive(value)&&(value?.kind===`ref`||value?.kind===`refs`||value?.kind===`local`&&!t.isFunction(value.node))&&value.scope.getFunctionParent()!==fn.scope){safe=false;p.stop()}},AssignmentExpression(p){let target=p.node.left;while(t.isMemberExpression(target)||t.isOptionalMemberExpression(target))target=target.object;const binding=t.isIdentifier(target)?p.scope.getBinding(target.name):void 0;if(!binding||binding.scope.getFunctionParent()!==fn.scope){safe=false;p.stop()}},"CallExpression|OptionalCallExpression":function(p){if(!t.isCallExpression(p.node)&&!t.isOptionalCallExpression(p.node))return;const callee=fn.resolve(p.node.callee,p.scope);if(callee?.kind!==`api`||!isRuntimeApi(callee.name)){safe=false;p.stop()}}});factoryProofs.set(fn.node,safe);return safe}function imported(value){if(!value||isPrimitive(value)||value.kind===`api`)return value;const cached=importedValues.get(value);if(cached)return cached;const result=value.kind===`local`&&t.isFunction(value.node)&&safeFactory(value)?{...value,imported:true}:value.kind===`module`?{...value,exported:name=>imported(value.exported(name))}:opaque;importedValues.set(value,result);return result}function fresh(value,owner){if(!value||isPrimitive(value)||value.kind===`api`)return value;if(value.kind===`local`&&t.isFunction(value.node))return imported(value);if(value.kind!==`local`&&value.kind!==`ref`&&value.kind!==`refs`||value.scope.getFunctionParent()!==owner)return opaque;let resolvers=factoryResolvers.get(owner);if(!resolvers){resolvers=/* @__PURE__ */ new Map;factoryResolvers.set(owner,resolvers)}let resolve=resolvers.get(value.resolve);if(!resolve){const original=value.resolve;resolve=(node,scope)=>fresh(original(node,scope),owner);resolvers.set(original,resolve)}return value.kind===`local`?{...value,resolve}:{...value,resolve,value:fresh(value.value,owner)}}function factoryReturn(fn,value){return fn.imported?fresh(value,fn.scope):value}return{imported,factoryReturn}}const pureRuntimeApis={ref:true,shallowRef:true,reactive:true,shallowReactive:true,readonly:true,shallowReadonly:true,computed:true,isRef:true,unref:true,toRef:true,toRefs:true,toValue:true,isReactive:true,isReadonly:true,isProxy:true,toRaw:true,markRaw:true,triggerRef:true,isShallow:true,defineComponent:true};const compilerMacros={defineProps:true,defineEmits:true,defineExpose:true,defineOptions:true,defineSlots:true,withDefaults:true,definePage:true,definePageMeta:true};const primitive={kind:`primitive`};function isCompilerMacro(name){return compilerMacros[name]===true||JSON_MACROS.has(name)}function isSafeApi(name){return pureRuntimeApis[name]===true||isCompilerMacro(name)}function runtimeModule(source){return source===`vue`||isWevuRuntimeModuleId(source)}function propertyName(node,computed){return t.isStringLiteral(node)||t.isNumericLiteral(node)?String(node.value):!computed&&t.isIdentifier(node)?node.name:void 0}function isPrimitive(value){return value?.kind===`primitive`||value?.kind===`local`&&(t.isNullLiteral(value.node)||t.isStringLiteral(value.node)||t.isNumericLiteral(value.node)||t.isBooleanLiteral(value.node)||t.isBigIntLiteral(value.node))}function createValueResolver(scopes,lookup,exported,sharedBindings,moduleScope){const resolving=/* @__PURE__ */ new Set;const boundary=createModuleValueBoundary(isPrimitive,name=>pureRuntimeApis[name]===true);const dataProofs=/* @__PURE__ */ new WeakMap;function imported(source,name){return runtimeModule(source)||(source===`weapp-vite`||source===`wevu/router`||source===`wevu/dev/router`)&&isCompilerMacro(name)?{kind:`api`,name}:boundary.imported(exported(source,name))??{kind:`module`,source,name,exported:name=>boundary.imported(exported(source,name))}}function key(node,computed,scope){const name=propertyName(node,computed);if(name!==void 0)return name;const value=resolve(node,scope);return value?.kind===`local`?propertyName(value.node,true):void 0}function member(object,name){if(!object||name===void 0)return;if(object.kind===`api`&&object.name===`*`)return{kind:`api`,name};if(object.kind===`module`&&object.name===`*`)return object.exported(name)??{...object,name};if(object.kind===`ref`)return name===`value`?object.value:void 0;if(object.kind===`refs`){const value=member(object.value,name);return value?{...object,kind:`ref`,value}:void 0}if(object.kind===`props`)return{kind:`opaque`};if(object.kind!==`local`)return;if(t.isObjectExpression(object.node))for(let index=object.node.properties.length-1;index>=0;index--){const property=object.node.properties[index];if(t.isSpreadElement(property)||propertyName(property.key,property.computed)===void 0)return;if(propertyName(property.key,property.computed)===name)return t.isObjectProperty(property)?object.resolve(property.value,object.scope):property.kind===`method`?object.resolve(property,object.scope):void 0}if(t.isArrayExpression(object.node)){if(name===`length`)return primitive;const element=/^(?:0|[1-9]\d*)$/.test(name)?object.node.elements[Number(name)]:void 0;return element?object.resolve(element,object.scope):void 0}}function functionReturn(value){if(value?.kind!==`local`||!t.isFunction(value.node)||value.node.async||value.node.generator)return;const body=value.node.body;if(t.isExpression(body))return boundary.factoryReturn(value,value.resolve(body,value.scope));if(body.body.some(statement=>!t.isVariableDeclaration(statement)&&!t.isFunctionDeclaration(statement)&&!t.isExpressionStatement(statement)&&!t.isReturnStatement(statement)&&!t.isEmptyStatement(statement)))return;const returns=body.body.filter(statement=>t.isReturnStatement(statement));return returns.length===1&&returns[0].argument?boundary.factoryReturn(value,value.resolve(returns[0].argument,value.scope)):void 0}function resolve(input,scope){const node=t.isExpression(input)?unwrapTypeLikeExpression$1(input):input;if(resolving.has(node))return;resolving.add(node);try{if(t.isIdentifier(node)){const binding=scope.getBinding(node.name);if(!binding)return lookup(node.name,scope)??(isCompilerMacro(node.name)?{kind:`api`,name:node.name}:node.name===`undefined`?primitive:void 0);if(!binding.constant)return;const declaration=binding.path.node;if(t.isImportSpecifier(declaration)||t.isImportDefaultSpecifier(declaration)||t.isImportNamespaceSpecifier(declaration)){const parent=binding.path.parent;if(!t.isImportDeclaration(parent)||parent.importKind===`type`||t.isImportSpecifier(declaration)&&declaration.importKind===`type`)return;return imported(parent.source.value,t.isImportSpecifier(declaration)?propertyName(declaration.imported,false):t.isImportDefaultSpecifier(declaration)?`default`:`*`)}const shared=sharedBindings.has(binding.identifier)||binding.scope===moduleScope&&scope.getFunctionParent()!==null;if(t.isVariableDeclarator(declaration)&&declaration.init){let value=resolve(declaration.init,binding.path.scope);if(t.isObjectPattern(declaration.id)){const property=declaration.id.properties.find(item=>t.isObjectProperty(item)&&t.isIdentifier(item.value,{name:node.name}));value=t.isObjectProperty(property)?member(value,propertyName(property.key,property.computed)):void 0}else if(!t.isIdentifier(declaration.id))value=void 0;return shared?boundary.imported(value):value}if(t.isFunctionDeclaration(declaration)){const value=resolve(declaration,binding.path.scope);return shared?boundary.imported(value):value}if(binding.kind===`param`){const fn=binding.path.getFunctionParent();const owner=fn?.isFunctionDeclaration()&&fn.node.id?fn.parentPath.scope.getBinding(fn.node.id.name):void 0;const index=fn?.node.params.indexOf(declaration)??-1;if(owner?.referencePaths.length&&index>=0&&owner.referencePaths.every(reference=>{const call=reference.parentPath;return call?.isCallExpression()&&call.node.callee===reference.node&&call.node.arguments[index]&&isPrimitive(resolve(call.node.arguments[index],call.scope))}))return primitive}return}if(t.isMemberExpression(node)||t.isOptionalMemberExpression(node))return member(resolve(node.object,scope),key(node.property,node.computed,scope));if(t.isCallExpression(node)||t.isOptionalCallExpression(node)){const callee=resolve(node.callee,scope);if(callee?.kind!==`api`)return functionReturn(callee);const first=node.arguments[0]?resolve(node.arguments[0],scope):primitive;switch(callee.name){case`ref`:case`shallowRef`:return first?.kind===`ref`?first:{kind:`ref`,value:first,node,scope,resolve};case`toRefs`:return{kind:`refs`,value:first,node,scope,resolve};case`reactive`:case`shallowReactive`:case`readonly`:case`shallowReadonly`:case`toRaw`:case`markRaw`:return first;case`computed`:return{kind:`ref`,value:functionReturn(first)??functionReturn(member(first,`get`)),node,scope,resolve};case`unref`:return first?.kind===`ref`?first.value:first;case`toValue`:return first?.kind===`ref`?first.value:first?.kind===`local`&&t.isFunction(first.node)?functionReturn(first):first;case`toRef`:return node.arguments.length>1?{kind:`ref`,value:member(first,key(node.arguments[1],true,scope)),node,scope,resolve}:first?.kind===`ref`?first:{kind:`ref`,value:first?.kind===`local`&&t.isFunction(first.node)?functionReturn(first):first,node,scope,resolve};case`isRef`:case`isReactive`:case`isReadonly`:case`isProxy`:case`isShallow`:return primitive;case`defineComponent`:return first?.kind===`local`&&t.isObjectExpression(first.node)?first:void 0;case`defineProps`:return{kind:`props`};case`withDefaults`:return first;default:return}}if(t.isBinaryExpression(node)||t.isUnaryExpression(node)||t.isUpdateExpression(node)||t.isTemplateLiteral(node))return primitive;return{kind:`local`,node,scope:scopes.get(node)??scope,resolve}}finally{resolving.delete(node)}}function safeData(value){if(!value)return false;if(value.kind===`primitive`||value.kind===`props`)return true;if(value.kind===`ref`||value.kind===`refs`)return safeData(value.value);if(value.kind!==`local`)return value.kind===`api`&&isSafeApi(value.name);if(isPrimitive(value)||t.isFunction(value.node))return true;let scopes=dataProofs.get(value.resolve);if(!scopes){scopes=/* @__PURE__ */ new WeakMap;dataProofs.set(value.resolve,scopes)}let proof=scopes.get(value.scope);if(!proof){proof={complete:/* @__PURE__ */ new WeakMap,visiting:/* @__PURE__ */ new WeakSet};scopes.set(value.scope,proof)}const complete=proof.complete.get(value.node);if(complete!==void 0)return complete;if(proof.visiting.has(value.node))return false;proof.visiting.add(value.node);let safe=false;if(t.isObjectExpression(value.node))safe=value.node.properties.every(property=>!t.isSpreadElement(property)&&propertyName(property.key,property.computed)!==void 0&&(t.isObjectProperty(property)?safeData(value.resolve(property.value,value.scope)):property.kind===`method`));else if(t.isArrayExpression(value.node))safe=value.node.elements.every(element=>!element||!t.isSpreadElement(element)&&safeData(value.resolve(element,value.scope)));proof.visiting.delete(value.node);proof.complete.set(value.node,safe);return safe}return{resolve,member,safeData,functionReturn,imported,key,moduleValue:boundary.imported}}function prepareScriptScopes(source,component,setupSource,expressions,exported){const script=typeof source===`string`?parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS):source;const setup=setupSource===void 0?void 0:parse$3(setupSource,BABEL_TS_MODULE_PARSER_OPTIONS);const template=expressions?parse$3(expressions,BABEL_TS_MODULE_PARSER_OPTIONS):void 0;const scopes=/* @__PURE__ */ new WeakMap;const observedFunctions=/* @__PURE__ */ new Set;const templateValues=/* @__PURE__ */ new Map;for(const ast of[script,setup,template])if(ast)traverse(ast,{Program(p){scopes.set(p.node,p.scope)},Function(p){scopes.set(p.node,p.scope)}});const scriptScope=scopes.get(script.program);const setupScope=setup&&scopes.get(setup.program);const templateScope=template&&scopes.get(template.program);const componentExport=script.program.body.find(statement=>t.isExportDefaultDeclaration(statement));const sharedBindings=/* @__PURE__ */ new WeakSet;const visitedDeclarations=/* @__PURE__ */ new WeakSet;for(const root of[scriptScope,setupScope]){if(!root)continue;const pending=Object.values(root.bindings).filter(binding=>t.isExportNamedDeclaration(binding.path.parent)||t.isVariableDeclaration(binding.path.parent)&&t.isExportNamedDeclaration(binding.path.parentPath?.parent)||binding.referencePaths.some(reference=>t.isExportSpecifier(reference.parent)&&t.isExportNamedDeclaration(reference.parentPath?.parent)&&!(t.isIdentifier(reference.parent.exported,{name:`default`})||t.isStringLiteral(reference.parent.exported,{value:`default`}))));for(const binding of pending)sharedBindings.add(binding.identifier);for(const binding of pending)for(let index=-1;index<binding.constantViolations.length;index++){const declaration=index===-1?binding.path:binding.constantViolations[index];if(visitedDeclarations.has(declaration.node))continue;visitedDeclarations.add(declaration.node);declaration.traverse({ReferencedIdentifier(p){if(!p.isIdentifier())return;const dependency=p.scope.getBinding(p.node.name);if(dependency?.scope===root&&!sharedBindings.has(dependency.identifier)){sharedBindings.add(dependency.identifier);pending.push(dependency)}}})}}const values=createValueResolver(scopes,(name,scope)=>{const root=scope.getProgramParent();if(root===setupScope){const binding=scriptScope.getBinding(name);const value=binding?values.moduleValue(values.resolve(binding.identifier,binding.scope)):void 0;if(value?.kind===`local`&&t.isFunction(value.node))observedFunctions.add(value.node);return value}if(root!==templateScope)return;if(templateValues.has(name))return templateValues.get(name);let value;if(setupScope){const binding=setupScope.getBinding(name)??scriptScope.getBinding(name);value=binding?values.resolve(binding.identifier,binding.scope):void 0;if(binding?.scope===scriptScope)value=values.moduleValue(value)}else if(component){const options=componentExport&&values.resolve(componentExport.declaration,scriptScope);const setupFunction=values.member(options,`setup`);value=values.member(values.functionReturn(setupFunction),name)}if(value?.kind===`local`&&t.isFunction(value.node))observedFunctions.add(value.node);const unwrapped=value?.kind===`ref`?value.value:value;templateValues.set(name,unwrapped);return unwrapped},exported,sharedBindings,scriptScope);return{script,setup,template,values,observedFunctions,scriptScope}}function isUnusedAlias(reference){let expression=reference;while(expression.parentPath&&(expression.parentPath.isTSAsExpression()||expression.parentPath.isTSNonNullExpression()||expression.parentPath.isTSTypeAssertion()||expression.parentPath.isTSSatisfiesExpression()))expression=expression.parentPath;const declaration=expression.parentPath;if(!declaration?.isVariableDeclarator()||declaration.node.init!==expression.node||!t.isIdentifier(declaration.node.id)||declaration.parentPath.parentPath?.isExportDeclaration())return false;const binding=declaration.scope.getBinding(declaration.node.id.name);return Boolean(binding&&binding.referencePaths.every(p=>p.findParent(parent=>t.isTSType(parent.node))))}async function analyzeScript(source,component=false,setupSource,expressions,loadModule){const facts={required:false,imports:/* @__PURE__ */ new Set,exports:/* @__PURE__ */ new Map};try{const modules=/* @__PURE__ */ new Map;const{script,setup,template,values,observedFunctions,scriptScope}=prepareScriptScopes(source,component,setupSource,expressions,(source,name)=>modules.get(source)?.exports.get(name));if(loadModule)for(const ast of[script,setup])for(const statement of ast?.program.body??[]){if(t.isImportDeclaration(statement)&&statement.specifiers.length>0&&statement.specifiers.every(specifier=>t.isImportSpecifier(specifier)&&specifier.importKind===`type`)||t.isExportNamedDeclaration(statement)&&statement.specifiers.length>0&&statement.specifiers.every(specifier=>t.isExportSpecifier(specifier)&&specifier.exportKind===`type`))continue;const source=t.isImportDeclaration(statement)&&statement.importKind!==`type`||(t.isExportNamedDeclaration(statement)||t.isExportAllDeclaration(statement))&&statement.exportKind!==`type`?statement.source?.value:void 0;if(source&&!runtimeModule(source)&&!source.endsWith(`.vue`)&&!modules.has(source)){const module=await loadModule(source);if(module){modules.set(source,module);facts.required||=module.required}}}const{resolve:resolveValue,member,safeData}=values;const inspectCallback=value=>{if(value?.kind===`module`)facts.imports.add(value.source);else if(!value||value.kind!==`local`||!t.isFunction(value.node))facts.required=true};const inspectOptions=(node,scope)=>{if(!node)return;let value=resolveValue(node,scope);if(value?.kind===`local`&&t.isFunction(value.node))value=values.functionReturn(value);if(value?.kind!==`local`||!t.isObjectExpression(value.node)){facts.required=true;return}for(const property of value.node.properties){if(t.isSpreadElement(property)||property.computed){facts.required=true;continue}const name=propertyName(property.key,false);if(name===`provide`||name===`inject`||name===`mixins`||name===`extends`||name===`render`)facts.required=true;if(name===`components`&&(!t.isObjectProperty(property)||!t.isObjectExpression(property.value)))facts.required=true;if(name===`setup`)inspectCallback(member(value,`setup`))}};const inspectCall=(callee,args,scope)=>{const value=resolveValue(callee,scope);if(value?.kind!==`api`){inspectCallback(value);facts.required||=args.some(argument=>!safeData(resolveValue(argument,scope)));return}facts.required||=!isSafeApi(value.name);if(value.name===`defineOptions`||value.name===`defineComponent`){inspectOptions(args[0],scope);return}if(isCompilerMacro(value.name))return;const first=args[0]&&resolveValue(args[0],scope);facts.required||=args.some(argument=>!safeData(resolveValue(argument,scope)));if(value.name===`computed`){if(first?.kind===`local`&&t.isObjectExpression(first.node)){inspectCallback(member(first,`get`));const setter=member(first,`set`);if(setter)inspectCallback(setter)}else inspectCallback(first)}else if(value.name===`toRef`&&args.length>1)facts.required||=!safeData(member(first,values.key(args[1],true,scope)));else if((value.name===`toValue`||value.name===`toRef`)&&first?.kind===`local`&&t.isFunction(first.node))inspectCallback(first)};const inspectExportValue=(node,scope)=>{const value=resolveValue(node,scope);if(!value||value.kind===`api`&&!isSafeApi(value.name))facts.required=true;else if(value.kind===`local`&&!(t.isFunction(value.node)||t.isLiteral(value.node)||t.isObjectExpression(value.node)||t.isArrayExpression(value.node)))facts.required=true};const inspectPattern=(pattern,value)=>{if(t.isObjectPattern(pattern))for(const property of pattern.properties){if(!t.isObjectProperty(property)){facts.required=true;continue}const field=member(value,propertyName(property.key,property.computed));facts.required||=!field;inspectPattern(property.value,field)}else if(t.isArrayPattern(pattern)){facts.required||=value?.kind!==`local`||!t.isArrayExpression(value.node);pattern.elements.forEach((element,index)=>{if(element)inspectPattern(element,member(value,String(index)))})}else if(t.isRestElement(pattern))facts.required=true};for(const ast of[template,setup,script]){if(!ast)continue;traverse(ast,{enter(p){if(t.isTSType(p.node)||t.isTSInterfaceDeclaration(p.node)||t.isTSTypeAliasDeclaration(p.node)||t.isTSDeclareFunction(p.node))p.skip();if(p.isFunctionDeclaration()&&p.node.id&&!observedFunctions.has(p.node)&&!p.parentPath.isExportDeclaration()&&!p.parentPath.scope.getBinding(p.node.id.name)?.referenced)p.skip();if((p.isFunctionExpression()||p.isArrowFunctionExpression())&&!observedFunctions.has(p.node)&&p.parentPath.isVariableDeclarator()){const declarator=p.parentPath;if(t.isIdentifier(declarator.node.id)&&!declarator.scope.getBinding(declarator.node.id.name)?.referenced&&!declarator.parentPath.parentPath?.isExportDeclaration())p.skip()}},ImportDeclaration(p){if(p.node.importKind===`type`||p.node.specifiers.length&&p.node.specifiers.every(s=>t.isImportSpecifier(s)&&s.importKind===`type`)){p.skip();return}const source=p.node.source.value;if(component&&source.endsWith(`.vue`)&&p.node.specifiers.length>0&&p.node.specifiers.every(s=>!p.scope.getBinding(s.local.name)?.referenced))return;const onlyMacros=p.node.specifiers.length>0&&p.node.specifiers.every(s=>t.isImportSpecifier(s)&&isCompilerMacro(propertyName(s.imported,false)));if(!runtimeModule(source)&&!((source===`weapp-vite`||source===`wevu/router`||source===`wevu/dev/router`)&&onlyMacros))facts.imports.add(source)},ReferencedIdentifier(p){const value=resolveValue(p.node,p.scope);if(!value&&p.isIdentifier()&&!p.scope.getBinding(p.node.name)||value?.kind===`api`&&value.name!==`*`&&!isSafeApi(value.name)&&!isUnusedAlias(p))facts.required=true},"MemberExpression|OptionalMemberExpression":function(p){const value=resolveValue(p.node,p.scope);if(!value||value.kind===`api`&&!isSafeApi(value.name)&&!isUnusedAlias(p))facts.required=true},Function(p){facts.required||=Boolean(p.node.async||p.node.generator);for(const parameter of p.node.params)inspectPattern(parameter,void 0)},"ObjectProperty|ObjectMethod":function(p){const node=p.node;if((t.isObjectProperty(node)||t.isObjectMethod(node))&&node.computed)facts.required||=!isPrimitive(resolveValue(node.key,p.scope))},VariableDeclarator(p){if(p.node.init&&!t.isIdentifier(p.node.id))inspectPattern(p.node.id,resolveValue(p.node.init,p.scope))},AssignmentExpression(p){facts.required||=!safeData(resolveValue(p.node.right,p.scope));if(t.isPattern(p.node.left))inspectPattern(p.node.left,resolveValue(p.node.right,p.scope));if(p.node.operator!==`=`||t.isMemberExpression(p.node.left))facts.required||=!isPrimitive(resolveValue(p.node.left,p.scope))||!isPrimitive(resolveValue(p.node.right,p.scope))},UpdateExpression(p){facts.required||=!isPrimitive(resolveValue(p.node.argument,p.scope))},UnaryExpression(p){if(p.node.operator===`delete`||[`+`,`-`,`~`].includes(p.node.operator)&&!isPrimitive(resolveValue(p.node.argument,p.scope)))facts.required=true},BinaryExpression(p){if(p.node.operator!==`===`&&p.node.operator!==`!==`)facts.required||=!isPrimitive(resolveValue(p.node.left,p.scope))||!isPrimitive(resolveValue(p.node.right,p.scope))},TemplateLiteral(p){facts.required||=p.node.expressions.some(expression=>!isPrimitive(resolveValue(expression,p.scope)))},CallExpression(p){const{callee,arguments:args}=p.node;if((t.isImport(callee)||t.isIdentifier(callee,{name:`require`})&&!p.scope.hasBinding(`require`))&&t.isStringLiteral(args[0]))facts.imports.add(args[0].value);inspectCall(callee,args,p.scope)},OptionalCallExpression(p){inspectCall(p.node.callee,p.node.arguments,p.scope)},ExportNamedDeclaration(p){if(p.node.exportKind===`type`||p.node.specifiers.length>0&&p.node.specifiers.every(s=>t.isExportSpecifier(s)&&s.exportKind===`type`)){p.skip();return}if(p.node.source){if(runtimeModule(p.node.source.value))facts.required||=p.node.specifiers.some(s=>!t.isExportSpecifier(s)||s.exportKind!==`type`&&!isSafeApi(propertyName(s.local,false)));else facts.imports.add(p.node.source.value)}else if(!component){const declaration=p.node.declaration;if(t.isVariableDeclaration(declaration)){for(const item of declaration.declarations)if(item.init)inspectExportValue(item.init,p.scope)}for(const specifier of p.node.specifiers)if(t.isExportSpecifier(specifier)&&specifier.exportKind!==`type`)inspectExportValue(specifier.local,p.scope)}},ExportAllDeclaration(p){if(p.node.exportKind!==`type`){if(runtimeModule(p.node.source.value))facts.required=true;else facts.imports.add(p.node.source.value)}},ExportDefaultDeclaration(p){if(component){if(t.isCallExpression(p.node.declaration)){const factory=resolveValue(p.node.declaration.callee,p.scope);if(factory?.kind!==`api`||factory.name!==`defineComponent`)facts.required=true}else inspectOptions(p.node.declaration,p.scope)}else inspectExportValue(p.node.declaration,p.scope)},"NewExpression|TaggedTemplateExpression|ImportExpression|JSXElement|JSXFragment|Class|Decorator|SpreadElement|TSImportEqualsDeclaration|TSExportAssignment|ForOfStatement|ForInStatement|AwaitExpression|YieldExpression":function(p){facts.required=true;if(p.isImportExpression()&&t.isStringLiteral(p.node.source))facts.imports.add(p.node.source.value)}})}if(!component){for(const statement of script.program.body)if(t.isExportDefaultDeclaration(statement))facts.exports.set(`default`,resolveValue(statement.declaration,scriptScope));else if(t.isExportNamedDeclaration(statement)&&statement.exportKind!==`type`){if(statement.declaration)for(const name of Object.keys(t.getBindingIdentifiers(statement.declaration)))facts.exports.set(name,resolveValue(t.identifier(name),scriptScope));for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&specifier.exportKind!==`type`)facts.exports.set(propertyName(specifier.exported,false),statement.source?values.imported(statement.source.value,propertyName(specifier.local,false)):resolveValue(specifier.local,scriptScope))}const explicitExports=new Set(facts.exports.keys());for(const statement of script.program.body)if(t.isExportAllDeclaration(statement)&&statement.exportKind!==`type`){for(const[name,value]of modules.get(statement.source.value)?.exports??[])if(name!=="default"&&!explicitExports.has(name))facts.exports.set(name,facts.exports.has(name)?void 0:value)}}}catch{facts.required=true}return facts}function normalizeSourceId(id){return path.normalize(normalizeFsResolvedId(id))}function isMissingSource(error){return Boolean(error&&typeof error===`object`&&`code`in error&&[`ENOENT`,`ENOTDIR`,`EISDIR`].includes(String(error.code)))}function sourceCandidates(id){return path.extname(id)?[id]:[id,`${id}.ts`,`${id}.js`,`${id}.mts`,`${id}.mjs`,`${id}.tsx`,`${id}.jsx`,`${id}/index.ts`,`${id}/index.js`]}function createAnalysisSourceReader(options,dependencies){const cache=options.cache??/* @__PURE__ */ new Map;const reader=options.source?.readFile??readFile;const load=input=>{const id=normalizeSourceId(input);dependencies.add(id);const cached=cache.get(id);if(cached)return cached;const task=(async()=>{if(isSkippableResolvedId(id))return;try{const source=await reader(id,{checkMtime:options.source?.checkMtime});if(typeof source!==`string`)return;if(id.endsWith(`.vue`)){const parsed=parse$1(source,{filename:id,sourceMap:false,ignoreEmpty:true});return{source,descriptor:parsed.descriptor,invalid:parsed.errors.length>0}}return{source}}catch(error){if(options.tolerateErrors||!options.source?.readFile&&isMissingSource(error))return;throw error}})();cache.set(id,task);return task};const resolve=async(source,importer)=>{try{const normalized=normalizeSourceId(source);const logicalId=source.startsWith(`.`)||path.isAbsolute(normalized)?path.isAbsolute(normalized)?normalized:path.resolve(path.dirname(importer),normalized):void 0;if(logicalId&&options.trackLogicalPaths)sourceCandidates(logicalId).forEach(id=>dependencies.add(id));const resolved=await options.source?.resolveId?.(source,importer);if(resolved){const id=normalizeSourceId(resolved);dependencies.add(id);return id}if(!logicalId)return;const id=logicalId;dependencies.add(id);if(path.extname(id))return id;for(const candidate of sourceCandidates(id))if(await load(candidate))return candidate;return id}catch(error){if(options.tolerateErrors)return;throw error}};return{load,resolve}}function createSourceReader(options,dependencies){return createAnalysisSourceReader({source:options?.sfcSrc,cache:options?.nativeSlotContextCache,tolerateErrors:true},dependencies)}function analyzeTemplate(content,options){const facts={required:false,tags:/* @__PURE__ */ new Set,expressions:``};const tagContext={htmlTagToWxmlMap:resolveHtmlTagToWxmlMap(options?.htmlTagToWxml)};const expression=(source,event=false)=>{if(!source.trim())return``;try{const statement=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];const handler=t.isExpressionStatement(statement)&&(t.isIdentifier(statement.expression)||t.isMemberExpression(statement.expression)||t.isOptionalMemberExpression(statement.expression));return event&&handler?`;(${source})();`:`;(${source});`}catch{if(event)return`;(() => { ${source}\n})();`;facts.required=true;return``}};try{const ast=baseParse(content,{onError:()=>{facts.required=true}});const visit=node=>{if(node.type===NodeTypes.INTERPOLATION&&node.content.type===NodeTypes.SIMPLE_EXPRESSION)return expression(node.content.content);if(node.type!==NodeTypes.ELEMENT)return``;const tag=resolveTemplateTagName(node.tag,tagContext);if(node.tag===`slot`||node.tag===`component`||tag===`slot`||tag===`component`||node.tag===`template`&&node.props.some(prop=>prop.type===NodeTypes.ATTRIBUTE&&(prop.name===`is`||prop.name===`src`)))facts.required=true;else if(!isBuiltinComponent(tag.toLowerCase())&&tag!==`template`&&tag!==`block`)facts.tags.add(node.tag);let code=``;let list=``;let parameters;let bindings=``;for(const prop of node.props){if(prop.type!==NodeTypes.DIRECTIVE)continue;if(prop.name===`slot`||![`bind`,`on`,`if`,`else`,`else-if`,`for`,`show`,`model`,`text`,`once`,`memo`,`cloak`,`pre`].includes(prop.name))facts.required=true;if(prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&!prop.arg.isStatic)code+=expression(prop.arg.content);if(prop.exp?.type!==NodeTypes.SIMPLE_EXPRESSION)continue;if(prop.name===`for`){const loop=parseForExpression(prop.exp.content);if(loop.error||loop.itemPatternError||!loop.listExp)facts.required=true;if(loop.listExp)list+=expression(loop.listExp);parameters=[loop.itemPattern??loop.item,loop.index,loop.key].filter(name=>Boolean(name));if(!loop.itemPattern)for(const[name,value]of Object.entries(loop.itemAliases??{}))bindings+=`const ${name} = (${value});`}else if(prop.name!==`slot`){const body=expression(prop.exp.content,prop.name===`on`);code+=prop.name===`on`?`;(($event) => { ${body} });`:body}}code+=node.children.map(visit).join(`
29
29
  `);return parameters?`${list};((${parameters.join(`,`)}) => { ${bindings}${code}\n});`:code};facts.expressions=ast.children.map(visit).join(`
30
30
  `)}catch{facts.required=true}return facts}async function analyzeNativeSlotContext({descriptor,filename,options,components}){const rootId=normalizeSourceId(filename);const rootTemplate=analyzeTemplate(descriptor.template?.content??``,options?.template);const dependencies=/* @__PURE__ */ new Set;const sources=createSourceReader(options,dependencies);const graph=/* @__PURE__ */ new Map;const modules=/* @__PURE__ */ new Map;const analyzingModules=/* @__PURE__ */ new Set;const loadModule=async(source,importer)=>{const id=await sources.resolve(source,importer);if(!id||id.endsWith(`.vue`))return;const cached=modules.get(id);if(cached)return cached;if(analyzingModules.has(id))return{required:true,imports:/* @__PURE__ */ new Set,exports:/* @__PURE__ */ new Map};const input=await sources.load(id);if(!input)return;try{input.ast??=parse$3(input.source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{const result={required:true,imports:/* @__PURE__ */ new Set,exports:/* @__PURE__ */ new Map};modules.set(id,result);return result}analyzingModules.add(id);const result=await analyzeScript(input.ast,false,void 0,void 0,source=>loadModule(source,id));analyzingModules.delete(id);modules.set(id,result);return result};const pending=[];const enqueue=input=>{const id=normalizeSourceId(input);dependencies.add(id);if(!graph.has(id)){graph.set(id,{required:false,edges:/* @__PURE__ */ new Set});pending.push(id)}return id};const addImports=async(node,imports,importer)=>{for(const source of imports){const id=await sources.resolve(source,importer);if(id)node.edges.add(enqueue(id));else node.required=true}};const addComponent=async(node,current,id,info)=>{const template=id===rootId?rootTemplate:analyzeTemplate(current.template?.content??``,options?.template);node.required||=template.required||Boolean(current.template?.lang&&current.template.lang!==`html`);for(const tag of template.tags){if(!info.wevuComponentTags.has(tag))node.required=true;const source=info.resolvedComponentIds.get(tag);if(source)node.edges.add(enqueue(source));else node.required=true}const script=await analyzeScript(current.script?.content??``,true,current.scriptSetup?.content,template.expressions,source=>loadModule(source,id));node.required||=script.required;await addImports(node,script.imports,id)};enqueue(rootId);for(const id of pending){const node=graph.get(id);if(id===rootId){node.required||=Boolean(options?.pageLayout||options?.appShell);for(const block of[descriptor.template,descriptor.script,descriptor.scriptSetup]){if(!block?.src)continue;const sourceId=await sources.resolve(block.src,id);if(sourceId)dependencies.add(sourceId);else node.required=true;if(!options?.sfcSrc)node.required=true}await addComponent(node,descriptor,id,components);continue}const facts=await sources.load(id);if(!facts||facts.invalid){node.required=true;continue}if(!facts.descriptor){const script=modules.get(id)??await loadModule(id,id);node.required||=!script||script.required;if(script)await addImports(node,script.imports,id);continue}let current=facts.descriptor;try{const resolved=await resolveSfcBlockSrc({...current,styles:[]},id,{...options?.sfcSrc,resolveId:(source,importer)=>sources.resolve(source,importer??id),readFile:async sourceId=>{const source=await sources.load(sourceId);if(!source)throw new Error(`Unavailable source: ${sourceId}`);return source.source}});current=resolved.descriptor;for(const dependency of resolved.deps)dependencies.add(normalizeSourceId(dependency));if(resolved.scriptResolvedId||resolved.scriptSetupResolvedId)current=prepareSfcScriptCompile(facts.source,id,current,false,resolved,false)?.descriptor??current}catch{node.required=true;for(const block of[current.template,current.script,current.scriptSetup])if(block?.src)await sources.resolve(block.src,id)}try{const info=await collectComponentSourceInfo({descriptor:current,descriptorForCompile:current,filename:id,compileOptions:options,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags});await addComponent(node,current,id,info)}catch{node.required=true}}const classifications=/* @__PURE__ */ new Map;const visiting=/* @__PURE__ */ new Set;const required=id=>{if(visiting.has(id))return true;const cached=classifications.get(id);if(cached!==void 0)return cached;const node=graph.get(id);if(!node)return true;visiting.add(id);let result=node.required;for(const dependency of node.edges)result=required(dependency)||result;visiting.delete(id);classifications.set(id,result);return result};const rootRequired=required(rootId);const tags=/* @__PURE__ */ new Set;for(const tag of rootTemplate.tags){if(!components.wevuComponentTags.has(tag))continue;const source=components.resolvedComponentIds.get(tag);if(!source||required(normalizeSourceId(source)))tags.add(tag)}dependencies.delete(rootId);return{required:rootRequired,tags,dependencies:[...dependencies]}}function getErrorMessage(error){if(error instanceof Error)return error.message;return typeof error===`string`?error:``}const BEHAVIOR_NOT_DEFINED_RE=/\bBehavior is not defined\b/;function shouldFallbackToRawDefineOptions(error){const message=getErrorMessage(error);return BEHAVIOR_NOT_DEFINED_RE.test(message)}function normalizeScriptSetupLang(lang){if(!lang)return`ts`;const lower=lang.toLowerCase();if(lower===`txt`)return`ts`;return lower}function resolveScriptSetupExtension(lang){const normalized=normalizeScriptSetupLang(lang);if(normalized===`ts`||normalized===`tsx`||normalized===`cts`||normalized===`mts`)return`ts`;return`js`}const IDENTIFIER_LIKE_KEY_RE=/^[A-Z_$][\w$]*$/i;const OBJECT_TO_STRING=Object.prototype.toString;function isIdentifierLikeKey(key){return IDENTIFIER_LIKE_KEY_RE.test(key)}function resolveRuntimeMarkerReference(value,scopeValues){if(value[WEAPP_I18N_RUNTIME_MARKER]!==true)return;const pending=Object.entries(scopeValues).filter(([name])=>isIdentifierLikeKey(name));const visited=/* @__PURE__ */ new WeakSet;for(let index=0;index<pending.length;index+=1){const[reference,candidate]=pending[index];if(candidate===value)return reference;if(!candidate||typeof candidate!==`object`||visited.has(candidate))continue;visited.add(candidate);for(const[key,member]of Object.entries(candidate))if(member&&typeof member===`object`){const accessor=isIdentifierLikeKey(key)?`.${key}`:`[${JSON.stringify(key)}]`;pending.push([`${reference}${accessor}`,member])}}}function getObjectTag(value){return OBJECT_TO_STRING.call(value)}const SERIALIZABLE_NATIVE_FUNCTIONS=/* @__PURE__ */ new Map([[String,`String`],[Number,`Number`],[Boolean,`Boolean`],[Object,`Object`],[Array,`Array`],[Function,`Function`],[Date,`Date`],[RegExp,`RegExp`],[Map,`Map`],[Set,`Set`],[WeakMap,`WeakMap`],[WeakSet,`WeakSet`],[Promise,`Promise`]]);function isParsableFunctionExpressionSource(source){try{parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);return true}catch{return false}}function tryConvertObjectMethodSourceToFunctionExpression(source){try{const statement=parse$3(`({ ${source} })`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement)||!t.isObjectExpression(statement.expression))return null;const firstProperty=statement.expression.properties[0];if(!firstProperty)return null;if(t.isObjectMethod(firstProperty)){const functionName=t.isIdentifier(firstProperty.key)?t.identifier(firstProperty.key.name):null;const functionExpression=t.functionExpression(functionName,firstProperty.params,firstProperty.body,firstProperty.generator,firstProperty.async);return generate(functionExpression).code}if(t.isObjectProperty(firstProperty)&&(t.isFunctionExpression(firstProperty.value)||t.isArrowFunctionExpression(firstProperty.value)))return generate(firstProperty.value).code}catch{}return null}function normalizeFunctionSourceToExpression(source){if(isParsableFunctionExpressionSource(source))return source;const converted=tryConvertObjectMethodSourceToFunctionExpression(source);if(converted&&isParsableFunctionExpressionSource(converted))return converted;throw new Error(`defineOptions 的参数中包含无法序列化的函数值。`)}function parseExpressionFromSource(source){const statement=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);return statement.expression}function rewriteFunctionSourceWithScopeValues(source,scopeValues){if(!Object.keys(scopeValues).length)return source;const wrappedAst=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);traverse(wrappedAst,{Identifier(path){if(!path.isReferencedIdentifier())return;if(path.scope.hasBinding(path.node.name))return;if(!hasOwn(scopeValues,path.node.name))return;try{const replacement=serializeStaticValueToExpression(scopeValues[path.node.name],/* @__PURE__ */ new WeakSet,{});path.replaceWith(parseExpressionFromSource(replacement))}catch{}}});const statement=wrappedAst.program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);const expression=statement.expression;return generate(expression).code}function serializeStaticValueToExpression(value,seen=/* @__PURE__ */ new WeakSet,scopeValues={}){if(value===null)return`null`;if(value===void 0)return`undefined`;const valueType=typeof value;if(valueType===`string`)return JSON.stringify(value);if(valueType===`boolean`)return value?`true`:`false`;if(valueType===`number`){if(Number.isNaN(value))return`Number.NaN`;if(value===Number.POSITIVE_INFINITY)return`Number.POSITIVE_INFINITY`;if(value===Number.NEGATIVE_INFINITY)return`Number.NEGATIVE_INFINITY`;if(Object.is(value,-0))return`-0`;return String(value)}if(valueType===`bigint`)return`${String(value)}n`;if(valueType===`symbol`)throw new Error(`defineOptions 的参数中不支持 Symbol 值。`);if(valueType===`function`){const source=Function.prototype.toString.call(value);if(source.includes(`[native code]`)){const nativeLiteral=SERIALIZABLE_NATIVE_FUNCTIONS.get(value);if(nativeLiteral)return nativeLiteral;throw new Error(`defineOptions 的参数中不支持原生函数值。`)}return`(${normalizeFunctionSourceToExpression(rewriteFunctionSourceWithScopeValues(normalizeFunctionSourceToExpression(source),scopeValues))})`}if(getObjectTag(value)===`[object Date]`)return`new Date(${JSON.stringify(value.toISOString())})`;if(getObjectTag(value)===`[object RegExp]`)return value.toString();if(Array.isArray(value))return`[${value.map(item=>serializeStaticValueToExpression(item,seen,scopeValues)).join(`, `)}]`;if(value&&typeof value===`object`){const runtimeReference=resolveRuntimeMarkerReference(value,scopeValues);if(runtimeReference)return runtimeReference;if(seen.has(value))throw new Error(`defineOptions 的参数中不支持循环引用。`);seen.add(value);const proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new Error(`defineOptions 的参数仅支持普通对象。`);const objectValue=value;return`{ ${Object.keys(objectValue).map(key=>{return`${isIdentifierLikeKey(key)?key:JSON.stringify(key)}: ${serializeStaticValueToExpression(objectValue[key],seen,scopeValues)}`}).join(`, `)} }`}throw new Error(`defineOptions 的参数中包含不支持的值类型:${valueType}`)}function resolveStaticDefineOptionsValues(statements){const values=[];for(const statement of statements){const arg=statement.argPath?.node;if(!arg||!t.isExpression(arg))return;let value;try{value=resolveStaticLiteralValue(arg)}catch{return}if(!value||typeof value!==`object`||Array.isArray(value))return;values.push(value)}return values}function collectDefineOptionsStatements(content,filename){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const statements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;if(path.node.arguments.length!==1)throw new Error(`defineOptions() 在 ${filename} 中必须且只能传 1 个参数。`);statements.push({statementPath:path.parentPath,callPath:path,argPath:path.get(`arguments.0`)})}});return{statements}}function evaluateStaticExpression(source){return vm.runInNewContext(`(${source})`,{})}function collectStaticTopLevelScopeValues(content){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const scopeValues={};for(const statement of ast.program.body){if(!t.isVariableDeclaration(statement)||statement.kind!==`const`)continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init)continue;try{scopeValues[declarator.id.name]=evaluateStaticExpression(declarator.init.end!=null&&declarator.init.start!=null?content.slice(declarator.init.start,declarator.init.end):``)}catch{}}}return scopeValues}function collectKeptBindingNames(keptStatementPaths){const names=/* @__PURE__ */ new Set;for(const statementPath of keptStatementPaths){if(statementPath.isImportDeclaration()){if(statementPath.node.importKind===`type`)continue;for(const specifier of statementPath.get(`specifiers`))if(specifier.isImportSpecifier()||specifier.isImportDefaultSpecifier()||specifier.isImportNamespaceSpecifier()){if(specifier.isImportSpecifier()&&specifier.node.importKind===`type`)continue;const local=specifier.node.local;if(t.isIdentifier(local))names.add(local.name)}continue}if(statementPath.isVariableDeclaration()){for(const declarator of statementPath.get(`declarations`)){const id=declarator.get(`id`);if(id.isIdentifier())names.add(id.node.name)}continue}if(statementPath.isFunctionDeclaration()||statementPath.isClassDeclaration()){const id=statementPath.node.id;if(t.isIdentifier(id))names.add(id.name)}}return[...names]}async function evaluateDefineOptionsValues(params){const{content,filename,lang,statements}=params;const ms=new MagicString(content);const dir=path.dirname(filename);const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.define-options.${unique}`);const programPath=statements[0]?.statementPath.parentPath;if(!programPath)return{values:[],dependencies:[],scopeValues:{}};const bodyPaths=programPath?.get(`body`)??[];const macroStatementPaths=statements.map(item=>item.statementPath);const{keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatementPaths);const keptBindingNames=collectKeptBindingNames(keptStatementPaths);for(const statementPath of keptStatementPaths){if(!statementPath.isImportDeclaration())continue;const sourceNode=statementPath.node.source;if(!sourceNode||!t.isStringLiteral(sourceNode))continue;const originalSource=sourceNode.value;if(!originalSource.startsWith(`.`))continue;const next=rewriteRelativeImportSource(originalSource,dir,tempDir);if(typeof sourceNode.start===`number`&&typeof sourceNode.end===`number`)ms.overwrite(sourceNode.start,sourceNode.end,JSON.stringify(next))}for(const statementPath of macroStatementPaths){const calleePath=statementPath.get(`expression`).get(`callee`);if(calleePath?.isIdentifier()&&typeof calleePath.node.start===`number`&&typeof calleePath.node.end===`number`)ms.overwrite(calleePath.node.start,calleePath.node.end,`__weapp_defineOptions`)}for(const statementPath of bodyPaths){if(keptStatementPaths.has(statementPath))continue;const start=statementPath.node.start;const end=statementPath.node.end;if(typeof start===`number`&&typeof end===`number`)ms.remove(start,end)}const extension=resolveScriptSetupExtension(lang);const header=`
31
31
  const __weapp_define_options_values = []
@@ -36,7 +36,7 @@ const __weapp_defineOptions = (value) => (__weapp_define_options_values.push(val
36
36
  `)}export const __weapp_define_scope = __weapp_define_scope_values\n
37
37
  export const __weapp_define_options = __weapp_define_options_values
38
38
  `;return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.define-options.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const exported=mod?.__weapp_define_options??mod;return{values:Array.isArray(exported)?exported:[exported],dependencies,scopeValues:mod?.__weapp_define_scope??{}}}finally{try{await remove(tempDir)}catch{}}})}async function resolveDefineOptionsValue(raw){let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`defineOptions 的参数最终必须解析为对象。`);return next}async function inlineScriptSetupDefineOptionsArgs(content,filename,lang,sourceMap){const{statements}=collectDefineOptionsStatements(content,filename);if(!statements.length)return{code:content,dependencies:[]};let values=[];let dependencies=[];let scopeValues={};const staticValues=resolveStaticDefineOptionsValues(statements);if(staticValues)values=staticValues;else{scopeValues=collectStaticTopLevelScopeValues(content);try{const evaluated=await evaluateDefineOptionsValues({content,filename,lang,statements});values=evaluated.values;dependencies=evaluated.dependencies;scopeValues={...scopeValues,...evaluated.scopeValues}}catch(error){if(shouldFallbackToRawDefineOptions(error))return{code:content,dependencies:[]};throw error}}const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);for(let index=0;index<statements.length;index+=1){const argNode=statements[index].argPath?.node;if(!argNode||typeof argNode.start!==`number`||typeof argNode.end!==`number`)continue;const value=await resolveDefineOptionsValue(values[index]);const literal=serializeStaticValueToExpression(value,/* @__PURE__ */ new WeakSet,scopeValues);ms.overwrite(argNode.start,argNode.end,literal)}const code=sourceMap?ms.slice(0,content.length):ms.toString();const result={code,dependencies:dependencies.filter(Boolean)};if(!sourceMap||code===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}const EXPORT_DEFAULT_RE=/\bexport\s+default\b/;function mayHaveDefaultExport(scriptCode){return EXPORT_DEFAULT_RE.test(scriptCode)}function hasDefaultExport(scriptCode,nativeAnalysis){if(!mayHaveDefaultExport(scriptCode))return false;if(nativeAnalysis?.hasDefaultExport!==void 0)return nativeAnalysis.hasDefaultExport;try{const ast=parseJsLike(scriptCode);let found=false;traverse(ast,{ExportDefaultDeclaration(path){found=true;path.stop()}});return found}catch{return mayHaveDefaultExport(scriptCode)}}function mayShareNativeOptionsAnalysis(scriptCode,template){if(!template?.ast||template.src||!mayHaveDefaultExport(scriptCode))return false;const hasComponentTag=node=>{if(node.type!==NodeTypes.ELEMENT)return false;if(!RESERVED_VUE_COMPONENT_TAGS.has(node.tag)&&!isBuiltinComponent(node.tag))return true;return node.children.some(hasComponentTag)};return template.ast.children.some(hasComponentTag)}function resolveScriptFilename(filename,lang){return`${filename}.${lang===`tsx`||lang===`jsx`||lang===`js`?lang:`ts`}`}function analyzeNativeScriptBlocks(descriptor,filename,defineOptionsSource){const blocks=[[`script`,descriptor.script],[`scriptSetup`,descriptor.scriptSetup],[`defineOptions`,defineOptionsSource]].filter(entry=>Boolean(entry[1]));if(!blocks.length)return;try{const results=analyzeCompilerScriptsWithNative(blocks.map(([,block])=>({code:block.content,filename:resolveScriptFilename(filename,block.lang)})));if(!results||results.length!==blocks.length)return;const scripts={};let defineOptions;for(const[index,[key]]of blocks.entries()){const result=results[index];if(!result)continue;if(key===`defineOptions`)defineOptions=result;else scripts[key]=result}return{scripts,defineOptions}}catch{return}}const SETUP_CALL_RE=/\bsetup\s*\(/;const DEFINE_OPTIONS_CALL_RE=/\bdefineOptions\s*\(/;const APP_VUE_FILE_RE=/[\\/]app\.vue$/;const TEMPLATE_BLOCK_RE=/<template\b[\s\S]*?<\/template>/g;const TEMPLATE_IMPORT_META_RE=/\bimport\.meta\b/g;const TEMPLATE_IMPORT_META_PLACEHOLDER=`__im_meta__`;function createIdentitySourceMap(source,originalSource,filename){const sourceMap=new MagicString(source).generateMap({hires:true,includeContent:false,source:filename});sourceMap.sourcesContent=[originalSource];return sourceMap}function resolveSfcScriptLangLabel(lang){return typeof lang===`string`&&lang.length>0?lang:`(default)`}function assertMatchingSfcScriptLang(descriptor,filename){const scriptLang=descriptor.script?.lang;const scriptSetupLang=descriptor.scriptSetup?.lang;if(!descriptor.script||!descriptor.scriptSetup||scriptLang===scriptSetupLang)return;throw new Error(`解析 ${filename} 失败:同一个 SFC 中 <script> 与 <script setup> 的 lang 必须一致,当前分别为 ${resolveSfcScriptLangLabel(scriptLang)} 与 ${resolveSfcScriptLangLabel(scriptSetupLang)}`)}function resolveSourcePosition(source,offset){let line=1;let lineStart=0;for(let index=0;index<offset;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{column:offset-lineStart+1,line,offset}}function replaceScriptSetupContent(descriptor,content){const scriptSetup=descriptor.scriptSetup;const startOffset=scriptSetup.loc.start.offset;const endOffset=scriptSetup.loc.end.offset;const nextSource=descriptor.source.slice(0,startOffset)+content+descriptor.source.slice(endOffset);const delta=content.length-(endOffset-startOffset);const updateBlock=block=>{if(!block)return null;const isSetup=block===scriptSetup;const nextStart=isSetup?startOffset:block.loc.start.offset>=endOffset?block.loc.start.offset+delta:block.loc.start.offset;const nextEnd=isSetup?startOffset+content.length:block.loc.end.offset>=endOffset?block.loc.end.offset+delta:block.loc.end.offset;return{...block,content:isSetup?content:block.content,loc:{source:isSetup?content:block.loc.source,start:resolveSourcePosition(nextSource,nextStart),end:resolveSourcePosition(nextSource,nextEnd)}}};return{...descriptor,source:nextSource,script:updateBlock(descriptor.script),scriptSetup:updateBlock(descriptor.scriptSetup)}}function hashDefineOptionsSources(sources){if(!sources.length)return;return createHash(`sha256`).update(sources.join(`
39
- `)).digest(`hex`).slice(0,12)}function extractDefineOptionsHash(content,analysis){if(analysis)return hashDefineOptionsSources(analysis.defineOptionsStatements.map(({start,end})=>content.slice(start,end)));let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});return hashDefineOptionsSources(macroSources)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}function hasSharedNativeAnalysis(descriptor,defineOptionsSource,isAppFile){return[descriptor.script,descriptor.scriptSetup,defineOptionsSource].filter(Boolean).length>1||process.env.WEAPP_VITE_NATIVE===`1`&&Boolean(process.env.WEAPP_VITE_NATIVE_AST_PATH?.trim())&&!isAppFile&&!descriptor.scriptSetup&&Boolean(descriptor.script&&mayShareNativeOptionsAnalysis(descriptor.script.content,descriptor.template))}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let routeConfig;let pageMeta;let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(scriptResolvedId||scriptSetupResolvedId||options?.isPage===true&&(mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=prepareSfcScriptCompile(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId},options?.isPage===true);if(stripped){routeConfig=stripped.routeConfig;pageMeta=stripped.pageMeta;const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={routeConfig,pageMeta,hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps,sfcSrcCompilationDeps:[templateResolvedId,scriptResolvedId,scriptSetupResolvedId].filter(id=>Boolean(id))};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsSource;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind,routeConfig,pageMeta});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsSource=scriptSetup}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);const nativeAnalysis=hasSharedNativeAnalysis(descriptorForCompile,defineOptionsSource,isAppFile)?analyzeNativeScriptBlocks(descriptorForCompile,filename,defineOptionsSource):void 0;const defineOptionsHash=defineOptionsSource?extractDefineOptionsHash(defineOptionsSource.content,nativeAnalysis?.defineOptions):void 0;return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile,nativeScriptAnalysis:nativeAnalysis?.scripts}}function propertyName(node){return t.isIdentifier(node)?node.name:t.isStringLiteral(node)?node.value:void 0}function resolveSetupPropConflicts(script,bindings,getScriptAst=()=>parseJsLike(script)){if(!/\bprops\s*:/.test(script))return;let setupKeys=Object.entries(bindings??{}).filter(([,kind])=>typeof kind===`string`&&(kind.startsWith(`setup-`)||kind===`literal-const`)).map(([key])=>key);if(!setupKeys.length)return;const ast=getScriptAst();const declarations=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(!t.isVariableDeclaration(statement))continue;for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init)declarations.set(declaration.id.name,declaration.init)}const findOption=(node,name,visited=/* @__PURE__ */ new Set)=>{if(t.isIdentifier(node)&&!visited.has(node.name)){visited.add(node.name);const declaration=declarations.get(node.name);return declaration?findOption(declaration,name,visited):void 0}if(t.isObjectExpression(node))for(const property of[...node.properties].reverse()){if((t.isObjectProperty(property)||t.isObjectMethod(property))&&!property.computed&&propertyName(property.key)===name)return t.isObjectProperty(property)?property.value:property;if(t.isSpreadElement(property)){const inherited=findOption(property.argument,name,visited);if(inherited)return inherited}}if(t.isCallExpression(node))for(const argument of[...node.arguments].reverse()){const props=findOption(argument,name,visited);if(props)return props}if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node))return findOption(node.expression,name,visited)};const exported=ast.program.body.find(statement=>t.isExportDefaultDeclaration(statement));const props=exported&&t.isExportDefaultDeclaration(exported)?findOption(exported.declaration,`props`):void 0;if(!props)return;const setup=exported&&t.isExportDefaultDeclaration(exported)?findOption(exported.declaration,`setup`):void 0;if(setup&&(t.isObjectMethod(setup)||t.isFunctionExpression(setup)||t.isArrowFunctionExpression(setup))&&t.isIdentifier(setup.params[0])&&t.isBlockStatement(setup.body)){const propsBindings=/* @__PURE__ */ new Set;for(const statement of setup.body.body){if(!t.isVariableDeclaration(statement))continue;for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&t.isIdentifier(declaration.init,{name:setup.params[0].name}))propsBindings.add(declaration.id.name)}setupKeys=setupKeys.filter(key=>!propsBindings.has(key))}const names=/* @__PURE__ */ new Set;if(t.isObjectExpression(props))for(const property of props.properties){if(!t.isObjectProperty(property)||property.computed)return setupKeys;const name=propertyName(property.key);if(name===void 0)return setupKeys;names.add(name)}else if(t.isArrayExpression(props)&&props.elements.every(element=>t.isStringLiteral(element)))for(const element of props.elements)names.add(element.value);else return setupKeys;return setupKeys.filter(key=>names.has(key))}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile){if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearBindingManifestLocations(manifest);return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearBindingManifestLocations(manifest);return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={},diagnostic){if(!scriptSetupCode)return;const offset=diagnostic?.warningOffset;const lines=offset===void 0?void 0:scriptSetupCode.slice(0,offset).split(/\r\n|[\r\n\u2028\u2029]/);const result=diagnostic?lines&&{location:{line:lines.length,column:lines.at(-1).length}}:detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(getScriptAst){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=getScriptAst();traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode,getScriptAst=()=>parseJsLike(scriptCode)){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(getScriptAst);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap,nativeScriptAnalysis){const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start},nativeScriptAnalysis?.scriptSetup?.reservedPropsDiagnostic);if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);const defaultExportAnalysis=scriptCode===descriptorForCompile.script?.content?nativeScriptAnalysis?.script:void 0;if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode,defaultExportAnalysis))scriptCode+=`
39
+ `)).digest(`hex`).slice(0,12)}function extractDefineOptionsHash(content,analysis){if(analysis)return hashDefineOptionsSources(analysis.defineOptionsStatements.map(({start,end})=>content.slice(start,end)));let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});return hashDefineOptionsSources(macroSources)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}function hasSharedNativeAnalysis(descriptor,defineOptionsSource,isAppFile){return[descriptor.script,descriptor.scriptSetup,defineOptionsSource].filter(Boolean).length>1||process.env.WEAPP_VITE_NATIVE===`1`&&Boolean(process.env.WEAPP_VITE_NATIVE_AST_PATH?.trim())&&!isAppFile&&!descriptor.scriptSetup&&Boolean(descriptor.script&&mayShareNativeOptionsAnalysis(descriptor.script.content,descriptor.template))}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let routeConfig;let pageMeta;let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(scriptResolvedId||scriptSetupResolvedId||options?.isPage===true&&(mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=prepareSfcScriptCompile(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId},options?.isPage===true);if(stripped){routeConfig=stripped.routeConfig;pageMeta=stripped.pageMeta;const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={routeConfig,pageMeta,hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps,sfcSrcCompilationDeps:[templateResolvedId,scriptResolvedId,scriptSetupResolvedId].filter(id=>Boolean(id))};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsSource;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind,routeConfig,pageMeta});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsSource=scriptSetup}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);const nativeAnalysis=hasSharedNativeAnalysis(descriptorForCompile,defineOptionsSource,isAppFile)?analyzeNativeScriptBlocks(descriptorForCompile,filename,defineOptionsSource):void 0;const defineOptionsHash=defineOptionsSource?extractDefineOptionsHash(defineOptionsSource.content,nativeAnalysis?.defineOptions):void 0;return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile,nativeScriptAnalysis:nativeAnalysis?.scripts}}function createModuleFacts(id,ast){let scope;traverse(ast,{Program(path){scope=path.scope;path.stop()}});return{id,ast,scope}}function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function staticName(node,computed=false){node=unwrap(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return String(node.value);if(!computed&&t.isIdentifier(node))return node.name;if(t.isTemplateLiteral(node)&&!node.expressions.length)return node.quasis[0]?.value.cooked??node.quasis[0]?.value.raw}function createPropsModuleResolver(reader,root){const modules=/* @__PURE__ */ new Map([[root.id,Promise.resolve(root)]]);const load=id=>{let task=modules.get(id);if(!task){task=(async()=>{const source=await reader.load(id);if(!source||source.descriptor||source.invalid)return;try{source.ast??=parseJsLike(source.source);return createModuleFacts(id,source.ast)}catch{return}})();modules.set(id,task)}return task};const resolveExport=async(source,importer,name,visiting=/* @__PURE__ */ new Set)=>{const id=await reader.resolve(source,importer);if(!id)return;const key=`${id}\0${name}`;if(visiting.has(key))return;const next=new Set(visiting).add(key);const module=await load(id);if(!module)return;for(const statement of module.ast.program.body){if(name==="default"&&t.isExportDefaultDeclaration(statement))return{node:statement.declaration,module};if(!t.isExportNamedDeclaration(statement)||statement.exportKind===`type`)continue;if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id,{name}))return{node:declaration.id,module}}for(const specifier of statement.specifiers){if(!t.isExportSpecifier(specifier)||specifier.exportKind===`type`||staticName(specifier.exported)!==name)continue;const local=staticName(specifier.local);if(statement.source)return local?resolveExport(statement.source.value,module.id,local,next):void 0;return{node:specifier.local,module}}}};const resolveImport=async(node,module)=>{node=unwrap(node);let local;let member;if(t.isIdentifier(node))local=node.name;else if(t.isMemberExpression(node)&&t.isIdentifier(node.object)){local=node.object.name;member=staticName(node.property,node.computed);if(!member)return}const binding=local&&module.scope.getBinding(local);if(!binding||!binding.path.parentPath?.isImportDeclaration()||binding.path.parentPath.node.importKind===`type`)return;const declaration=binding.path.parentPath.node;const specifier=binding.path.node;const name=t.isImportDefaultSpecifier(specifier)&&member===void 0?`default`:t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&member===void 0?staticName(specifier.imported):t.isImportNamespaceSpecifier(specifier)?member:void 0;return name?resolveExport(declaration.source.value,module.id,name):void 0};return{resolveImport}}function isObjectCall(node,scope,name){return t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&!scope.getBinding(`Object`)&&t.isIdentifier(node.callee.property,{name})}function isGeneratedSetupReturn(reference,setup){const property=reference.parentPath;const object=property?.parentPath;const declaration=object?.parentPath;return Boolean(setup&&property?.isObjectProperty()&&property.node.value===reference.node&&object?.isObjectExpression()&&declaration?.isVariableDeclarator()&&t.isIdentifier(declaration.node.id,{name:`__returned__`})&&declaration.findParent(parent=>parent.node===setup))}function isSafeReference(reference,ownership,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(ownership.props&&unwrap(current.node)===unwrap(ownership.props)||isGeneratedSetupReturn(current,ownership.setup))return true;if(current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isSpreadElement()&&(parent.parentPath.isObjectExpression()||parent.parentPath.isArrayExpression()))return true;if(parent?.isCallExpression())return isObjectCall(parent.node,parent.scope,`freeze`)&&parent.node.arguments.length===1||isObjectCall(parent.node,parent.scope,`assign`)&&parent.node.arguments.indexOf(current.node)>0;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafePropsBinding(parent.scope.getBinding(parent.node.id.name),ownership,visiting);return false}function isSafePropsBinding(binding,ownership,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,ownership,next))}const absent={kind:`absent`};const unknown={kind:`unknown`};function isSafeOptionReference(reference,allowed,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(allowed.has(unwrap(current.node))||current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafeOptionBinding(parent.scope.getBinding(parent.node.id.name),allowed,visiting);return false}function isSafeOptionBinding(binding,allowed,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeOptionReference(reference,allowed,next))}function isComponentFactory(node,module){if(!t.isIdentifier(node.callee))return false;const binding=module.scope.getBinding(node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeMergeOperand(input,module,visiting){const node=unwrap(input);if(visiting.has(node))return false;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&Boolean(binding?.path.isVariableDeclarator()&&binding.path.node.init&&isSafeMergeOperand(binding.path.node.init,module,next))}if(t.isObjectExpression(node))return node.properties.every(property=>{if(t.isSpreadElement(property))return isSafeMergeOperand(property.argument,module,next);const key=staticName(property.key,property.computed);return key!==void 0&&key!==`__proto__`&&(t.isObjectProperty(property)||property.kind===`method`)});if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return isSafeMergeOperand(node.arguments[0],module,next);if(isObjectCall(node,module.scope,`assign`))return node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next))}return false}function findCompiledOption(input,name,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return unknown;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&binding?.path.isVariableDeclarator()&&binding.path.node.init?findCompiledOption(binding.path.node.init,name,module,next):unknown}if(t.isObjectExpression(node)){for(const property of[...node.properties].reverse()){if(t.isSpreadElement(property)){const inherited=findCompiledOption(property.argument,name,module,next);if(inherited.kind!==`absent`)return inherited;continue}const key=staticName(property.key,property.computed);if(key===void 0||key===`__proto__`)return unknown;if(key===name)return t.isObjectProperty(property)||property.kind===`method`?{kind:`value`,node:t.isObjectProperty(property)?property.value:property}:unknown}return absent}if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return findCompiledOption(node.arguments[0],name,module,next);if(isObjectCall(node,module.scope,`assign`)){if(!node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next)))return unknown;for(const argument of[...node.arguments].reverse()){const option=t.isExpression(argument)?findCompiledOption(argument,name,module,next):unknown;if(option.kind!==`absent`)return option}return absent}}return unknown}function excludePropsObjectAliases(keys,setup){if(!setup||!(t.isObjectMethod(setup)||t.isFunctionExpression(setup)||t.isArrowFunctionExpression(setup))||!t.isIdentifier(setup.params[0])||!t.isBlockStatement(setup.body))return keys;const aliases=/* @__PURE__ */ new Set;for(const statement of setup.body.body)if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&t.isIdentifier(declaration.init,{name:setup.params[0].name}))aliases.add(declaration.id.name)}return keys.filter(key=>!aliases.has(key))}function constantInitializer(node,module){if(!t.isIdentifier(node))return;const binding=module.scope.getBinding(node.name);if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||!binding.path.node.init)return;return{binding,node:binding.path.node.init}}function createPropsShapeAnalyzer(modules,ownership){async function primitive(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return node.value;if(t.isTemplateLiteral(node)&&!node.expressions.length)return staticName(node,true);const local=constantInitializer(node,module);if(local)return primitive(local.node,module,next);const imported=await modules.resolveImport(node,module);return imported?primitive(imported.node,imported.module,next):void 0}async function analyze(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);const local=constantInitializer(node,module);if(local){const value=await analyze(local.node,module,next);return value&&(value.frozen||isSafePropsBinding(local.binding,ownership))?value:void 0}if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=await modules.resolveImport(node,module);const value=imported&&await analyze(imported.node,imported.module,next);return value?.frozen?value:void 0}if(isObjectCall(node,module.scope,`freeze`)&&node.arguments.length===1&&t.isExpression(node.arguments[0])){const value=await analyze(node.arguments[0],module,next);return value&&{...value,frozen:true}}if(isObjectCall(node,module.scope,`assign`)){const first=node.arguments[0]&&unwrap(node.arguments[0]);if(!t.isObjectExpression(first)||first.properties.length)return;const names=/* @__PURE__ */ new Set;for(const argument of node.arguments.slice(1)){if(!t.isExpression(argument))return;const value=await analyze(argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name))}return{kind:`object`,names,frozen:false}}if(t.isObjectExpression(node)){const names=/* @__PURE__ */ new Set;for(const property of node.properties){if(t.isSpreadElement(property)){const value=await analyze(property.argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name));continue}if(!t.isObjectProperty(property))return;const key=property.computed?await primitive(property.key,module,next):staticName(property.key);if(key===void 0||key===`__proto__`)return;names.add(String(key))}return{kind:`object`,names,frozen:false}}if(t.isArrayExpression(node)){const names=/* @__PURE__ */ new Set;for(const element of node.elements){if(!element)return;if(t.isSpreadElement(element)){const value=await analyze(element.argument,module,next);if(!value||value.kind!==`array`)return;value.names.forEach(name=>names.add(name))}else{const value=await primitive(element,module,next);if(typeof value!==`string`)return;names.add(value)}}return{kind:`array`,names,frozen:false}}}return{analyze}}async function resolveSetupPropConflicts(options){const dependencies=/* @__PURE__ */ new Set;if(!/\bprops\b/.test(options.script))return{dependencies:[]};let setupKeys=Object.entries(options.bindings??{}).filter(([,kind])=>typeof kind===`string`&&(kind.startsWith(`setup-`)||kind===`literal-const`)).map(([key])=>key);if(!setupKeys.length)return{dependencies:[]};const root=createModuleFacts(normalizeSourceId(options.filename),options.getScriptAst());const exported=root.ast.program.body.find(statement=>t.isExportDefaultDeclaration(statement));if(!exported||!t.isExportDefaultDeclaration(exported))return{conflicts:setupKeys,dependencies:[]};const props=findCompiledOption(exported.declaration,`props`,root);const setup=findCompiledOption(exported.declaration,`setup`,root);const setupNode=setup.kind===`value`?setup.node:void 0;setupKeys=excludePropsObjectAliases(setupKeys,setupNode);if(props.kind!==`value`)return{conflicts:props.kind===`unknown`?setupKeys:void 0,dependencies:[]};const reader=createAnalysisSourceReader({source:options.source,trackLogicalPaths:true},dependencies);const modules=createPropsModuleResolver(reader,root);const shape=await createPropsShapeAnalyzer(modules,{props:props.node,setup:setupNode}).analyze(props.node,root);dependencies.delete(root.id);return{conflicts:shape?setupKeys.filter(key=>shape.names.has(key)):setupKeys,dependencies:[...dependencies]}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile){if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearBindingManifestLocations(manifest);return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearBindingManifestLocations(manifest);return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={},diagnostic){if(!scriptSetupCode)return;const offset=diagnostic?.warningOffset;const lines=offset===void 0?void 0:scriptSetupCode.slice(0,offset).split(/\r\n|[\r\n\u2028\u2029]/);const result=diagnostic?lines&&{location:{line:lines.length,column:lines.at(-1).length}}:detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(getScriptAst){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=getScriptAst();traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode,getScriptAst=()=>parseJsLike(scriptCode)){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(getScriptAst);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap,nativeScriptAnalysis){const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start},nativeScriptAnalysis?.scriptSetup?.reservedPropsDiagnostic);if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);const defaultExportAnalysis=scriptCode===descriptorForCompile.script?.content?nativeScriptAnalysis?.script:void 0;if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode,defaultExportAnalysis))scriptCode+=`
40
40
  export default {}`}else scriptCode=`export default {}`;if(scriptCode){const scriptLang=descriptor.script?.lang??descriptor.scriptSetup?.lang;const isJsxScript=scriptLang===`jsx`||scriptLang===`tsx`;let jsxTemplate;if(isJsxScript){jsxTemplate=compileJsxTemplateAndCollectComponents(scriptCode,filename,options);const externalScriptBlock=descriptor.script?.src?descriptor.script:descriptor.scriptSetup?.src?descriptor.scriptSetup:void 0;remapJsxBindingManifestLocations(jsxTemplate.bindingManifest,scriptMap,externalScriptBlock?.content??originalSource,externalScriptBlock?.src);if(jsxTemplate.template&&(options?.pageLayout||options?.appShell))jsxTemplate.template=applyCompilerTemplateWrappers({template:jsxTemplate.template,manifest:jsxTemplate.bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const reportJsxWarnings=!descriptor.template||Boolean(jsxTemplate.template);scriptCode=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptCode,filename,reportJsxWarnings?jsxTemplate.warnings:void 0),jsxTemplate.dynamicIslands);if(reportJsxWarnings&&jsxTemplate.warnings.length){jsxDiagnostics=createJsxDiagnostics(jsxTemplate.warnings,filename);if(options?.warn)jsxDiagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message))}}const jsxTransformed=isJsxScript?(await import(`./vueJsxTransform-C4lhnLbg.mjs`)).transformVueJsxScript(scriptCode,filename,options?.sourceMap!==false):{code:scriptCode,map:null};const bindingManifest=jsxTemplate?.template?jsxTemplate.bindingManifest:templateCompiled?.bindingManifest;const effectiveInlineExpressions=jsxTemplate?.template?jsxTemplate.inlineExpressions:templateCompiled?.inlineExpressions;const runtimeCapabilities=bindingManifest?createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest):templateCompiled?.runtimeCapabilities;const transformed=transformScript(jsxTransformed.code,{isTypeScript:descriptor.script?.lang===`ts`||descriptor.script?.lang===`tsx`||descriptor.scriptSetup?.lang===`ts`||descriptor.scriptSetup?.lang===`tsx`,skipComponentTransform:options?.skipComponentTransform??isAppFile,isApp:isAppFile,isPage:options?.isPage===true,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,templateComponentMeta:Object.keys(autoComponentMeta).length?autoComponentMeta:void 0,wevuDefaults:options?.wevuDefaults,classStyleRuntime:templateCompiled?.classStyleRuntime,classStyleBindings:templateCompiled?.classStyleBindings,templateRefs:templateCompiled?.templateRefs,layoutHosts:templateCompiled?.layoutHosts,inlineExpressions:effectiveInlineExpressions,bindingManifest:isAppFile?void 0:bindingManifest,autoSetDataPick:!isAppFile&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:isAppFile?void 0:options?.pageLayout,runtimeCapabilities,functionPropPaths:templateCompiled?.functionPropPaths,propsAliases,propsDerivedKeys,cssModules:precomputedScriptPhaseInfo?.cssModules,stabilizeCssVarsRuntime:options?.stabilizeCssVarsRuntime,relaxStructuredTypeOnlyProps,nativeSlotContext:!isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true}),scopedSlotHostProperties:!isAppFile&&options?.isPage!==true&&Boolean(templateCompiled?.hasSlotOutlet||templateCompiled?.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length>0)});return{script:transformed.code,scriptMap:composeSourceMaps(transformed.map??jsxTransformed.map,scriptMap),template:jsxTemplate?.template,diagnostics:jsxDiagnostics,bindingManifest,inlineExpressions:jsxTemplate?.inlineExpressions,runtimeCapabilities:transformed.runtimeCapabilities,componentStyleOptions:transformed.componentStyleOptions,autoUsingComponentsMap,autoComponentMeta}}return{script:scriptCode,scriptMap:null,autoUsingComponentsMap,autoComponentMeta}}async function compileStylePhase(descriptor,filename,result,options){if(descriptor.styles.length===0)return{usesSlotted:false};const scopedId=generateScopedId(filename);const compiledStyles=await Promise.all(descriptor.styles.map(async styleBlock=>{return await compileVueStyleToWxss(styleBlock,{id:scopedId,filename,scoped:styleBlock.scoped,modules:styleBlock.module,preprocessOptions:options?.preprocessOptions?.[styleBlock.lang||`css`],preserveDeepSelectors:options?.preserveDeepSelectors,transformScoped:options?.transformScoped})}));result.style=compiledStyles.map(s=>s.code.trim()).filter(Boolean).join(`
41
41
 
42
- `);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;if(templateCompiled.diagnostics.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(templateCompiled.diagnostics,templateResolvedId,descriptor.template.content);else for(const diagnostic of templateCompiled.diagnostics)diagnostic.loc=void 0}else remapTemplateDiagnostics(templateCompiled.diagnostics,descriptor.template.loc.start,source);result.diagnostics=templateCompiled.diagnostics}if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis});if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo});options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const scriptSetupPropConflicts=scriptCompiled?resolveSetupPropConflicts(scriptCompiled.content,scriptCompiled.bindings,getCompiledScriptAst):void 0;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};
42
+ `);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;if(templateCompiled.diagnostics.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(templateCompiled.diagnostics,templateResolvedId,descriptor.template.content);else for(const diagnostic of templateCompiled.diagnostics)diagnostic.loc=void 0}else remapTemplateDiagnostics(templateCompiled.diagnostics,descriptor.template.loc.start,source);result.diagnostics=templateCompiled.diagnostics}if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis});if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo});options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const propsAnalysis=scriptCompiled?await resolveSetupPropConflicts({script:scriptCompiled.content,bindings:scriptCompiled.bindings,getScriptAst:getCompiledScriptAst,filename,source:options?.sfcSrc}):void 0;const scriptSetupPropConflicts=propsAnalysis?.conflicts;if(propsAnalysis?.dependencies.length)result.meta.propsAnalysisDeps=propsAnalysis.dependencies;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};