@wevu/compiler 7.11.0-dev.20261114.1 → 7.11.0-dev.20261115.1
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 +1 -1
- package/package.json +9 -9
package/dist/index.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import{ROOT_PORTAL_ENABLE_MIN_SDK_VERSION,ROOT_PORTAL_MIN_SDK_VERSION,ROOT_PORTA
|
|
|
3
3
|
`);const parsed=parse$1(`<template></template>\n${styleSource}`,{filename,sourceMap:false});if(parsed.errors.length){const error=parsed.errors[0];const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:无法重建外部样式 CSS 变量元数据:${message}`)}const cssVars=[];for(const expression of parsed.descriptor.cssVars){let restored=expression;for(const[token,source]of closeTagRestorations)restored=restored.replaceAll(token,source);if(!cssVars.includes(restored))cssVars.push(restored)}return cssVars}function inferLangFromSrc(src,kind){const ext=path.extname(src).toLowerCase();if(!ext)return;if(kind===`style`)return STYLE_LANG_EXT.get(ext);if(kind===`template`)return TEMPLATE_LANG_EXT.get(ext);return SCRIPT_LANG_EXT.get(ext)}function getBlockLabel(kind){if(kind===`script setup`)return`script setup`;return kind}async function resolveBlockSrcPath(src,filename,options){const normalizedSrc=normalizeFsResolvedId(src);if(normalizedSrc&&isSkippableResolvedId(normalizedSrc))throw new Error(`解析 ${filename} 失败:不支持 <src> 引用虚拟模块 ${src}`);let resolvedId;if(options?.resolveId){const resolved=await options.resolveId(src,filename);if(resolved){const normalized=normalizeFsResolvedId(resolved);if(normalized&&isSkippableResolvedId(normalized))throw new Error(`解析 ${filename} 失败:不支持 <src> 引用虚拟模块 ${src}`);resolvedId=normalized||resolved}}if(resolvedId){if(!path.isAbsolute(resolvedId))resolvedId=path.resolve(path.dirname(filename),resolvedId);return resolvedId}if(normalizedSrc&&path.isAbsolute(normalizedSrc))return normalizedSrc;return path.resolve(path.dirname(filename),normalizedSrc||src)}async function readBlockContent(resolvedId,filename,kind,options){const reader=options?.readFile;const checkMtime=options?.checkMtime;if(reader)return await reader(resolvedId,{checkMtime,blockType:kind===`script setup`?`script`:kind});try{return await readFile(resolvedId,{checkMtime})}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:读取 ${resolvedId} 失败:${message}`,{cause:error})}}async function resolveSfcBlockSrc(descriptor,filename,options){if(!options)return{descriptor,deps:[]};const deps=/* @__PURE__ */ new Set;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;let hasResolvedStyleSrc=false;const nextDescriptor={...descriptor,styles:descriptor.styles.slice()};const resolveBlock=async(block,kind)=>{if(!block||!block.src)return block;if(block.content.trim().length>0)throw new Error(`解析 ${filename} 失败:<${getBlockLabel(kind)}> 同时存在 src 与内联内容`);const resolvedId=await resolveBlockSrcPath(block.src,filename,options);if(kind===`template`)templateResolvedId=resolvedId;else if(kind===`script`)scriptResolvedId=resolvedId;else if(kind===`script setup`)scriptSetupResolvedId=resolvedId;const content=await readBlockContent(resolvedId,filename,kind,options);if(kind===`style`)hasResolvedStyleSrc=true;deps.add(resolvedId);const inferredLang=block.lang??inferLangFromSrc(resolvedId,kind);return{...block,content,lang:inferredLang??block.lang}};nextDescriptor.template=await resolveBlock(descriptor.template,`template`);nextDescriptor.script=await resolveBlock(descriptor.script,`script`);nextDescriptor.scriptSetup=await resolveBlock(descriptor.scriptSetup,`script setup`);if(nextDescriptor.styles.length)nextDescriptor.styles=await Promise.all(nextDescriptor.styles.map(style=>resolveBlock(style,`style`)));if(hasResolvedStyleSrc)nextDescriptor.cssVars=resolveDescriptorCssVars(nextDescriptor.styles,filename);return{descriptor:nextDescriptor,deps:[...deps],scriptResolvedId,scriptSetupResolvedId,templateResolvedId}}const sfcParseCache=new LRUCache({max:512});const SCRIPT_SETUP_SRC_ATTR=`data-weapp-vite-src`;const SCRIPT_SRC_ATTR=`data-weapp-vite-script-src`;const INTERNAL_SCRIPT_SRC_ATTR=`\0wevu-script-src`;const EXTERNAL_SCRIPT_CONTENT_SENTINEL=`\0wevu-external-script`;function createSourceLineStarts$1(source){const starts=[0];for(const match of source.matchAll(/\r\n?|\n/g))starts.push(match.index+match[0].length);return starts}function resolvePosition(source,lineStarts,line,column){const safeLine=Math.min(Math.max(line,1),lineStarts.length);const lineStart=lineStarts[safeLine-1]??0;const offset=Math.min(source.length,lineStart+Math.max(column-1,0));return{offset,line:safeLine,column:offset-lineStart+1}}function readSfcParseErrorPosition(value){if(!value||typeof value!==`object`)return;if(!(`line`in value)||typeof value.line!==`number`||!(`column`in value)||typeof value.column!==`number`)return;return{line:value.line,column:value.column}}function readSfcParseErrorLocation(error){if(!error||typeof error!==`object`||!(`loc`in error)||!error.loc||typeof error.loc!==`object`)return;const start=`start`in error.loc?readSfcParseErrorPosition(error.loc.start):void 0;const end=`end`in error.loc?readSfcParseErrorPosition(error.loc.end):void 0;return start?{start,end:end??start}:void 0}function createSfcParseError(error,options){const originalLocation=readSfcParseErrorLocation(error);const sourceLineStarts=originalLocation?createSourceLineStarts$1(options.source):[];let traceMap;if(originalLocation&&isEncodedSourceMapLike(options.sourceMap))try{traceMap=new TraceMap(options.sourceMap)}catch{traceMap=void 0}const remap=position=>{if(traceMap)try{const mapped=originalPositionFor(traceMap,{line:position.line,column:Math.max(position.column-1,0)});if(mapped.line!=null&&mapped.column!=null)return resolvePosition(options.source,sourceLineStarts,mapped.line,mapped.column+1)}catch{}return resolvePosition(options.source,sourceLineStarts,position.line,position.column)};const location=originalLocation?{start:remap(originalLocation.start),end:remap(originalLocation.end)}:void 0;const causeMessage=error instanceof Error?error.message:String(error);const diagnostic={code:`WV2003`,severity:`error`,message:options.formatMessage?.(causeMessage,location)??`解析 ${options.filename} 失败:${causeMessage}`,filename:options.filename,source:`sfc`,loc:location};return new CompilerDiagnosticError(diagnostic,{cause:error})}function parseSfcAst(source,options,onScriptSrc){const{ast}=parseTemplateWithScriptModules(source,options);for(const child of ast.children){if(child.type!==NodeTypes.ELEMENT||child.tag!==`script`)continue;let src;let setup=false;for(const attribute of child.props){if(attribute.type!==NodeTypes.ATTRIBUTE)continue;if(attribute.name===`src`)src=attribute;else if(attribute.name===`setup`)setup=true}if(src)onScriptSrc({attribute:src,node:child,setup})}return ast}function collectSfcScriptSrcAttributes(source){const attributes=[];try{parseSfcAst(source,{parseMode:`sfc`,onError(){}},owned=>attributes.push(owned))}catch{}return attributes}const sfcSrcCompiler={compile:compilerDom.compile,parse(source,options){return parseSfcAst(source,options,({attribute,node})=>{attribute.name=INTERNAL_SCRIPT_SRC_ATTR;if(node.children.every(child=>child.type===NodeTypes.TEXT&&child.content.trim()===``))node.children.push({type:NodeTypes.TEXT,content:EXTERNAL_SCRIPT_CONTENT_SENTINEL,loc:node.innerLoc??node.loc})})}};function restoreScriptBlockSrc(block,marker){if(!block||!(marker in block.attrs))return;const raw=block.attrs[marker];delete block.attrs[marker];block.attrs.src=raw;block.src=typeof raw===`string`?raw:void 0}function parseVueSfc(source,options={}){const parsed=parse$1(source,{...options,compiler:sfcSrcCompiler});restoreScriptBlockSrc(parsed.descriptor.script,INTERNAL_SCRIPT_SRC_ATTR);restoreScriptBlockSrc(parsed.descriptor.scriptSetup,INTERNAL_SCRIPT_SRC_ATTR);return parsed}function preprocessScriptSource(source,setup){if(!source.includes(`<script`)||!source.includes(`src`))return source;let transformed;const marker=setup?SCRIPT_SETUP_SRC_ATTR:SCRIPT_SRC_ATTR;for(const owned of collectSfcScriptSrcAttributes(source)){if(owned.setup!==setup)continue;transformed??=new MagicString(source);transformed.overwrite(owned.attribute.nameLoc.start.offset,owned.attribute.nameLoc.end.offset,marker)}return transformed?.toString()??source}function preprocessScriptSetupSrc(source){return preprocessScriptSource(source,true)}function preprocessScriptSrc(source){return preprocessScriptSource(source,false)}function restoreScriptSetupSrc(descriptor){restoreScriptBlockSrc(descriptor.scriptSetup,SCRIPT_SETUP_SRC_ATTR)}function restoreScriptSrc(descriptor){restoreScriptBlockSrc(descriptor.script,SCRIPT_SRC_ATTR)}async function readAndParseSfc(filename,options){const checkMtime=options?.checkMtime??true;const source=normalizeLineEndings(options?.source??await readFile(filename,{checkMtime}));const parserSource=options?.preprocessedSource??source;const ignoreEmpty=options?.ignoreEmpty??true;const cached=sfcParseCache.get(filename);if(cached){if(cached.parserSource===parserSource&&cached.ignoreEmpty===ignoreEmpty){if(options?.resolveSrc)return{source,descriptor:(await resolveSfcBlockSrc(cached.descriptor,filename,options.resolveSrc)).descriptor,errors:cached.errors};return{source,descriptor:cached.descriptor,errors:cached.errors}}}const parsed=parseVueSfc(parserSource,{filename,ignoreEmpty});sfcParseCache.set(filename,{parserSource,ignoreEmpty,descriptor:parsed.descriptor,errors:parsed.errors});if(options?.resolveSrc)return{source,descriptor:(await resolveSfcBlockSrc(parsed.descriptor,filename,options.resolveSrc)).descriptor,errors:parsed.errors};return{source,descriptor:parsed.descriptor,errors:parsed.errors}}function getSfcCheckMtime(config){return getReadFileCheckMtime(config)}function resolveSourceLocation$1(source,offset){let line=1;let lineStart=0;const end=Math.min(Math.max(offset,0),source.length);for(let index=0;index<end;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{line,column:end-lineStart+1}}function getAbsoluteOffset(block,node){return block.offset+(typeof node?.start===`number`?node.start:0)}function createPageDeclarationError(block,node,message){const location=resolveSourceLocation$1(block.source,getAbsoluteOffset(block,node));return/* @__PURE__ */ new Error(`${block.filename}:${location.line}:${location.column} ${message}`)}function createPageDeclarationParseError(block,error){const parseError=error instanceof Error?error:new Error(String(error));const offset=`pos`in parseError&&typeof parseError.pos===`number`?parseError.pos:0;const location=resolveSourceLocation$1(block.source,block.offset+offset);return/* @__PURE__ */ new Error(`${block.filename}:${location.line}:${location.column} 解析页面声明失败:${parseError.message}`)}const BACKSLASH_RE$3=/\\/g;const LEADING_SLASH_RE=/^[\\/]+/;const DUPLICATE_SLASH_RE=/\/{2,}/g;const TRIM_SLASH_RE=/^\/+|\/+$/g;function toPosixPath(value){return value.replace(BACKSLASH_RE$3,`/`)}function stripLeadingSlashes(value){return value.replace(LEADING_SLASH_RE,``)}function normalizeRoot(root){return toPosixPath(root).replace(DUPLICATE_SLASH_RE,`/`).replace(TRIM_SLASH_RE,``)}function rewriteRelativeImportSource(source,fromDir,tempDir){if(!source.startsWith(`.`))return source;const abs=path.resolve(fromDir,source);let next=toPosixPath(path.relative(tempDir,abs));if(!next.startsWith(`.`))next=`./${next}`;return next}function rewriteJsLikeImportsForTempDir(source,fromDir,tempDir){const ast=parseJsLike(source);const ms=new MagicString(source);let mutated=false;const rewriteLiteral=(node,originalSource)=>{if(!originalSource||!originalSource.startsWith(`.`))return;const next=rewriteRelativeImportSource(originalSource,fromDir,tempDir);const start=node?.start;const end=node?.end;if(typeof start===`number`&&typeof end===`number`){ms.overwrite(start,end,JSON.stringify(next));mutated=true}};traverse(ast,{ImportDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ExportNamedDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ExportAllDeclaration(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},ImportExpression(p){const sourceNode=p.node?.source;if(sourceNode&&t.isStringLiteral(sourceNode))rewriteLiteral(sourceNode,sourceNode.value)},CallExpression(p){const callee=p.node?.callee;if(!callee)return;const arg0=p.node?.arguments?.[0];if(!arg0||!t.isStringLiteral(arg0))return;if(t.isImport(callee)){rewriteLiteral(arg0,arg0.value);return}if(t.isIdentifier(callee,{name:`require`}))rewriteLiteral(arg0,arg0.value)}});return mutated?ms.toString():source}function nodeStart(node){return node.start??0}function nodeEnd(node){return node.end??nodeStart(node)}function isValueBindingPath(bindingPath){const declarationPath=bindingPath.parentPath;if(`declare`in bindingPath.node&&bindingPath.node.declare===true||declarationPath?.isVariableDeclaration()&&declarationPath.node.declare===true)return false;if(!declarationPath?.isImportDeclaration())return true;if(declarationPath.node.importKind===`type`)return false;return!bindingPath.isImportSpecifier()||bindingPath.node.importKind!==`type`}function hasTypeScriptValueBinding(parsed,reference,name){for(let current=reference;current;current=current.parentPath)if(parsed.typeScriptValueBindings.get(current.node)?.has(name))return true;return false}function hasValueBinding(parsed,reference,name){const binding=reference.scope.getBinding(name);return Boolean(binding&&isValueBindingPath(binding.path))||hasTypeScriptValueBinding(parsed,reference,name)}function hasModuleVisibleValueBinding(parsedBlocks,name){return parsedBlocks.some(parsed=>{if(parsed.block.kind===`script`&&parsed.typeScriptValueBindings.get(parsed.ast.program)?.has(name))return true;const binding=parsed.programPath.scope.getBinding(name);if(!binding||!isValueBindingPath(binding.path))return false;return parsed.block.kind===`script`||binding.path.parentPath?.isImportDeclaration()===true})}function getImportRemovalEdits(macroImports){const byDeclaration=/* @__PURE__ */ new Map;for(const macroImport of macroImports){const entries=byDeclaration.get(macroImport.declaration)??[];entries.push(macroImport);byDeclaration.set(macroImport.declaration,entries)}const edits=[];for(const[declaration,entries]of byDeclaration){const block=entries[0].block;const removed=new Set(entries.map(entry=>entry.specifier));if(!declaration.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||!removed.has(specifier)}).length){edits.push({block,start:nodeStart(declaration),end:nodeEnd(declaration)});continue}const namedSpecifiers=declaration.specifiers.filter(t.isImportSpecifier);if(!namedSpecifiers.filter(specifier=>!removed.has(specifier)).length){edits.push({block,start:nodeStart(namedSpecifiers[0]),end:nodeEnd(namedSpecifiers[namedSpecifiers.length-1])});continue}for(let index=0;index<namedSpecifiers.length;){if(!removed.has(namedSpecifiers[index])){index+=1;continue}const firstRemoved=index;while(index<namedSpecifiers.length&&removed.has(namedSpecifiers[index]))index+=1;const lastRemoved=index-1;const nextKept=namedSpecifiers[index];const previousKept=namedSpecifiers[firstRemoved-1];edits.push(nextKept?{block,start:nodeStart(namedSpecifiers[firstRemoved]),end:nodeStart(nextKept)}:{block,start:nodeEnd(previousKept),end:nodeEnd(namedSpecifiers[lastRemoved])})}}return edits}function rebaseExternalScriptImports(parsed,targetFilename,code,parsedBlocks){const sourceDir=path.dirname(parsed.block.filename);const targetDir=path.dirname(targetFilename);if(sourceDir===targetDir)return;const rewriteSource=node=>{if(!t.isStringLiteral(node)||!node.value.startsWith(`.`))return;code.overwrite(parsed.block.offset+nodeStart(node),parsed.block.offset+nodeEnd(node),JSON.stringify(rewriteRelativeImportSource(node.value,sourceDir,targetDir)))};const hasModuleRequireBinding=hasModuleVisibleValueBinding(parsedBlocks,`require`);parsed.programPath.traverse({ImportDeclaration(path){rewriteSource(path.node.source)},ExportNamedDeclaration(path){rewriteSource(path.node.source)},ExportAllDeclaration(path){rewriteSource(path.node.source)},ImportExpression(path){rewriteSource(path.node.source)},CallExpression(path){const{callee,arguments:args}=path.node;if(t.isImport(callee)){rewriteSource(args[0]);return}if(!t.isIdentifier(callee,{name:`require`}))return;if(!hasModuleRequireBinding&&!hasValueBinding(parsed,path,`require`))rewriteSource(args[0])}})}function isRuntimeReference(path){const parent=path.parentPath;if(parent&&(parent.isTSEnumDeclaration()||parent.isTSEnumMember()||parent.isTSModuleDeclaration()||parent.isTSImportEqualsDeclaration())&&parent.node.id===path.node)return false;if(parent?.isTSQualifiedName()&&parent.node.right===path.node)return false;return!path.findParent(parent=>parent.isTSType()||parent.isTSInterfaceDeclaration()||parent.isTSTypeAliasDeclaration()||parent.isTSDeclareFunction()||(parent.isExportNamedDeclaration()||parent.isExportSpecifier())&&parent.node.exportKind===`type`)}function importedName$1(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function collectMacroImports(parsed,macro){const imports=[];for(const statement of parsed.ast.program.body){if(!t.isImportDeclaration(statement)||statement.source.value!==macro.moduleId)continue;for(const specifier of statement.specifiers){if(!t.isImportSpecifier(specifier)||importedName$1(specifier)!==macro.name)continue;imports.push({binding:parsed.programPath.scope.getBinding(specifier.local.name),block:parsed.block,declaration:statement,localName:specifier.local.name,specifier,typeOnly:statement.importKind===`type`||specifier.importKind===`type`,parsed})}}return imports}function isCanonicalMacroImportBinding(bindingPath,macro){if(!bindingPath?.isImportSpecifier())return false;const declaration=bindingPath.parentPath;return declaration?.isImportDeclaration()===true&&declaration.node.source.value===macro.moduleId&&declaration.node.importKind!==`type`&&bindingPath.node.importKind!==`type`&&importedName$1(bindingPath.node)===macro.name}function resolveDirectCall(referencePath,topLevelOnly=true){const callPath=referencePath.parentPath;if(!callPath?.isCallExpression()||callPath.node.callee!==referencePath.node)return;const statementPath=callPath.parentPath;if(!statementPath?.isExpressionStatement()||topLevelOnly&&!statementPath.parentPath?.isProgram())return;return{callPath,statementPath}}function collectDirectMacroCalls(parsed,macro,options={}){const calls=[];const isGlobalMacro=(path,name)=>name===macro.name&&!hasValueBinding(parsed,path,name)&&options.hasModuleShadow?.(name)!==true;const rejectGlobalWrite=path=>{if(!options.rejectInvalidReferences)return;const identifier=t.getAssignmentIdentifiers(path.node)[macro.name];if(identifier&&isGlobalMacro(path,macro.name))throw createPageDeclarationError(parsed.block,identifier,`${macro.name} 全局宏不能被重新赋值。`)};traverse(parsed.ast,{"AssignmentExpression|UpdateExpression|ForInStatement|ForOfStatement":rejectGlobalWrite,ReferencedIdentifier(path){const canonicalImport=isCanonicalMacroImportBinding(path.scope.getBinding(path.node.name)?.path,macro);if(canonicalImport&&options.includeCanonicalImports===false)return;if(!canonicalImport&&!isGlobalMacro(path,path.node.name))return;if(!isRuntimeReference(path))return;const directCall=resolveDirectCall(path,options.topLevelOnly!==false);if(!directCall){if(options.rejectInvalidReferences)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 全局宏只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);return}calls.push({block:parsed.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}});return calls}function collectBoundCalls(macroImport,macro){if(!macroImport.binding)return[];const write=macroImport.binding.constantViolations.find(path=>!hasTypeScriptValueBinding(macroImport.parsed,path,macroImport.localName));if(write)throw createPageDeclarationError(macroImport.block,write.node,`${macro.name} 导入绑定不能被重新赋值。`);const calls=[];for(const referencePath of macroImport.binding.referencePaths){if(!isRuntimeReference(referencePath)||hasTypeScriptValueBinding(macroImport.parsed,referencePath,macroImport.localName))continue;const directCall=resolveDirectCall(referencePath);if(!directCall||macroImport.typeOnly)throw createPageDeclarationError(macroImport.block,referencePath.node,`${macro.name} 导入绑定只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);calls.push({block:macroImport.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}return calls}function getCrossBlockCandidates(path,importedFromOtherBlock,name,parsed){const candidates=importedFromOtherBlock.get(name);if(!candidates?.length)return;return hasValueBinding(parsed,path,name)?void 0:candidates}function collectCrossBlockCalls(parsedBlocks,macroImports,macro){const calls=[];for(const parsed of parsedBlocks){const importedFromOtherBlock=/* @__PURE__ */ new Map;for(const macroImport of macroImports){if(macroImport.block===parsed.block)continue;const entries=importedFromOtherBlock.get(macroImport.localName)??[];entries.push(macroImport);importedFromOtherBlock.set(macroImport.localName,entries)}if(!importedFromOtherBlock.size)continue;const rejectCrossBlockWrite=path=>{for(const[name,identifier]of Object.entries(t.getAssignmentIdentifiers(path.node))){if(!getCrossBlockCandidates(path,importedFromOtherBlock,name,parsed))continue;throw createPageDeclarationError(parsed.block,identifier,`${macro.name} 导入绑定不能被重新赋值。`)}};traverse(parsed.ast,{"AssignmentExpression|UpdateExpression|ForInStatement|ForOfStatement":rejectCrossBlockWrite,ReferencedIdentifier(path){const candidates=getCrossBlockCandidates(path,importedFromOtherBlock,path.node.name,parsed);if(!candidates||!isRuntimeReference(path))return;const directCall=resolveDirectCall(path);const runtimeCandidates=candidates.filter(candidate=>!candidate.typeOnly);if(!directCall||!runtimeCandidates.length)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 导入绑定只能用于顶层直接调用,不能被引用、传递或嵌套调用。`);if(runtimeCandidates.length>1)throw createPageDeclarationError(parsed.block,path.node,`${macro.name} 调用对应了多个导入绑定。`);calls.push({block:parsed.block,call:directCall.callPath.node,statement:directCall.statementPath.node})}})}return calls}function collectMacroCallsFromPrograms(parsedBlocks,macro){const macroImports=parsedBlocks.flatMap(parsed=>collectMacroImports(parsed,macro));return{calls:[...macroImports.flatMap(macroImport=>collectBoundCalls(macroImport,macro)),...collectCrossBlockCalls(parsedBlocks,macroImports,macro),...parsedBlocks.flatMap(parsed=>collectDirectMacroCalls(parsed,macro,{hasModuleShadow:name=>hasModuleVisibleValueBinding(parsedBlocks,name),includeCanonicalImports:false,rejectInvalidReferences:true}))],runtimeImports:macroImports.filter(macroImport=>!macroImport.typeOnly)}}function collectDirectMacroCallsForTransform(parsed,macro){return collectDirectMacroCalls(parsed,macro,{topLevelOnly:false})}function hasRuntimeCode(node){if(`declare`in node&&node.declare===true||t.isTSInterfaceDeclaration(node)||t.isTSTypeAliasDeclaration(node)||t.isTSDeclareFunction(node)||t.isEmptyStatement(node))return false;if(t.isImportDeclaration(node)||t.isTSImportEqualsDeclaration(node))return node.importKind!==`type`;if(t.isExportNamedDeclaration(node))return node.exportKind!==`type`&&(node.declaration?hasRuntimeCode(node.declaration):node.specifiers.some(specifier=>!t.isExportSpecifier(specifier)||specifier.exportKind!==`type`));if(t.isTSModuleDeclaration(node))return Boolean(node.body&&hasRuntimeCode(node.body));if(t.isTSModuleBlock(node))return node.body.some(hasRuntimeCode);return true}function createParsedBlock(ast,block){let programPath;const typeScriptValueBindings=/* @__PURE__ */ new Map;const registerTypeScriptValue=path=>{if(!t.isIdentifier(path.node.id)||!hasRuntimeCode(path.node)||path.findParent(parent=>`declare`in parent.node&&parent.node.declare===true))return;let owner=path.scope.block;for(let parent=path.parentPath;parent&&parent.node!==owner;parent=parent.parentPath)if(parent.isTSModuleBlock()||parent.isTSModuleDeclaration()){owner=parent.node;break}const names=typeScriptValueBindings.get(owner)??/* @__PURE__ */ new Set;names.add(path.node.id.name);typeScriptValueBindings.set(owner,names)};traverse(ast,{Program(path){programPath=path},TSEnumDeclaration:registerTypeScriptValue,TSModuleDeclaration:registerTypeScriptValue,TSImportEqualsDeclaration:registerTypeScriptValue});if(!programPath)throw new Error(`${block.filename}:1:1 无法读取页面声明模块。`);return{ast,block,programPath,typeScriptValueBindings}}function parsePageDeclarationBlock(block){let ast;try{ast=parse$3(block.content,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:block.filename})}catch(error){throw createPageDeclarationParseError(block,error)}return createParsedBlock(ast,block)}function createProgramBlock(ast,kind){return createParsedBlock(ast,{content:``,filename:``,kind,offset:0,order:0,source:``})}function unwrapStaticExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapStaticExpression(node.expression);return node}function resolveStaticString(node){const value=unwrapStaticExpression(node);if(t.isStringLiteral(value))return value.value;if(t.isTemplateLiteral(value)&&value.expressions.length===0)return value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``}function resolveObjectKey(property){if(property.computed)return;if(t.isIdentifier(property.key))return property.key.name;if(t.isStringLiteral(property.key)||t.isNumericLiteral(property.key))return String(property.key.value)}function defineSafeProperty(target,key,value){Object.defineProperty(target,key,{configurable:true,enumerable:true,value,writable:true})}function resolveStaticRouteValue(pageCall,node){const value=unwrapStaticExpression(node);if(t.isStringLiteral(value)||t.isBooleanLiteral(value))return value.value;if(t.isNullLiteral(value))return null;if(t.isNumericLiteral(value)&&Number.isFinite(value.value))return value.value;if(t.isUnaryExpression(value)&&(value.operator===`-`||value.operator===`+`)&&t.isNumericLiteral(value.argument)){const numberValue=value.operator===`-`?-value.argument.value:value.argument.value;if(Number.isFinite(numberValue))return numberValue}if(t.isTemplateLiteral(value)&&value.expressions.length===0)return value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``;if(t.isArrayExpression(value))return value.elements.map(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))throw createPageDeclarationError(pageCall.block,element??value,`${WEVU_DEFINE_PAGE_MACRO}().meta 只能包含无空项、无展开的有限 JSON 值。`);return resolveStaticRouteValue(pageCall,element)});if(t.isObjectExpression(value)){const result={};for(const property of value.properties){if(!t.isObjectProperty(property)||!t.isExpression(property.value))throw createPageDeclarationError(pageCall.block,property,`${WEVU_DEFINE_PAGE_MACRO}().meta 不支持展开、方法或访问器。`);const key=resolveObjectKey(property);if(key==null)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}().meta 不支持计算或动态属性名。`);defineSafeProperty(result,key,resolveStaticRouteValue(pageCall,property.value))}return result}throw createPageDeclarationError(pageCall.block,value,`${WEVU_DEFINE_PAGE_MACRO}().meta 只能包含静态有限 JSON 值。`)}function resolvePageDeclaration(pageCall){const call=pageCall.call;if(call.arguments.length!==1||!t.isExpression(call.arguments[0]))throw createPageDeclarationError(pageCall.block,call,`${WEVU_DEFINE_PAGE_MACRO}() 必须且只能接收一个静态对象参数。`);const declaration=unwrapStaticExpression(call.arguments[0]);if(!t.isObjectExpression(declaration))throw createPageDeclarationError(pageCall.block,call.arguments[0],`${WEVU_DEFINE_PAGE_MACRO}() 必须且只能接收一个静态对象参数。`);let name;let meta;const seen=/* @__PURE__ */ new Set;for(const property of declaration.properties){if(!t.isObjectProperty(property)||!t.isExpression(property.value))throw createPageDeclarationError(pageCall.block,property,`${WEVU_DEFINE_PAGE_MACRO}() 不支持展开、方法或访问器。`);const key=resolveObjectKey(property);if(key==null)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 不支持计算或动态属性名。`);if(key!==`name`&&key!==`meta`)throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 不支持属性 "${key}";path 由页面注册位置生成。`);if(seen.has(key))throw createPageDeclarationError(pageCall.block,property.key,`${WEVU_DEFINE_PAGE_MACRO}() 的属性 "${key}" 不能重复。`);seen.add(key);if(key===`name`){const staticName=resolveStaticString(property.value);if(staticName==null||staticName.trim().length===0)throw createPageDeclarationError(pageCall.block,property.value,`${WEVU_DEFINE_PAGE_MACRO}().name 必须是非空静态字符串。`);name=staticName}else{const value=unwrapStaticExpression(property.value);if(!t.isObjectExpression(value))throw createPageDeclarationError(pageCall.block,property.value,`${WEVU_DEFINE_PAGE_MACRO}().meta 必须是静态对象。`);meta=resolveStaticRouteValue(pageCall,value)}}if(name==null)throw createPageDeclarationError(pageCall.block,declaration,`${WEVU_DEFINE_PAGE_MACRO}() 必须声明非空静态 name。`);return meta===void 0?{name}:{name,meta}}function tryResolveStaticPageMeta(pageCall){const argument=pageCall.call.arguments[0];if(pageCall.call.arguments.length!==1||!t.isExpression(argument))return;const value=unwrapStaticExpression(argument);if(!t.isObjectExpression(value))return;try{return resolveStaticRouteValue(pageCall,value)}catch{return}}const PAGE_META_MACRO={moduleId:WE_VU_MODULE_ID,name:WEVU_DEFINE_PAGE_META_MACRO};const PAGE_ROUTE_MACRO={moduleId:WEVU_ROUTER_MODULE_ID,name:WEVU_DEFINE_PAGE_MACRO};function collectPageMetaCallsForTransform(ast){return collectDirectMacroCallsForTransform(createProgramBlock(ast,`script`),PAGE_META_MACRO).map(call=>call.call)}function collectPageMetaCallsFromPrograms(programs){const parsedBlocks=[];for(const kind of[`script`,`scriptSetup`]){const ast=programs[kind];if(ast)parsedBlocks.push(createProgramBlock(ast,kind))}return collectMacroCallsFromPrograms(parsedBlocks,PAGE_META_MACRO).calls.map(call=>call.call)}function analyzePageRouteBlocks(blocks,parsedBlocks){const{calls:unsortedCalls,runtimeImports}=collectMacroCallsFromPrograms(parsedBlocks,PAGE_ROUTE_MACRO);const blockOrder=new Map(blocks.map((block,index)=>[block,index]));const calls=unsortedCalls.sort((left,right)=>{return(blockOrder.get(left.block)??0)-(blockOrder.get(right.block)??0)||getAbsoluteOffset(left.block,left.call)-getAbsoluteOffset(right.block,right.call)});const importEdits=getImportRemovalEdits(runtimeImports);if(!calls.length)return{edits:importEdits,parsedBlocks};if(calls.length>1)throw createPageDeclarationError(calls[1].block,calls[1].call,`同一个页面只能声明一次 ${WEVU_DEFINE_PAGE_MACRO}()。`);const pageCall=calls[0];return{declaration:resolvePageDeclaration(pageCall),declarationSourceFile:pageCall.block.filename,parsedBlocks,edits:[...importEdits,{block:pageCall.block,start:pageCall.statement.start??0,end:pageCall.statement.end??0}]}}function analyzePageDeclarationBlocks(blocks){return analyzePageRouteBlocks(blocks,blocks.map(parsePageDeclarationBlock))}function analyzePageCompileTimeMacroBlocks(blocks){const parsedBlocks=blocks.map(parsePageDeclarationBlock);const routeAnalysis=analyzePageRouteBlocks(blocks,parsedBlocks);const{calls,runtimeImports}=collectMacroCallsFromPrograms(parsedBlocks,PAGE_META_MACRO);return{...routeAnalysis,pageMeta:calls.length===1?tryResolveStaticPageMeta(calls[0]):void 0,edits:[...routeAnalysis.edits,...getImportRemovalEdits(runtimeImports),...calls.map(call=>({block:call.block,start:call.statement.start??0,end:call.statement.end??0}))]}}function collectSfcScriptBlocks(source,filename,descriptor,resolvedIds={}){const blocks=[];const appendBlock=(block,kind,resolvedId)=>{if(!block)return;const external=Boolean(block.src&&resolvedId);blocks.push({content:block.content,filename:external?resolvedId:filename,kind,offset:external?0:block.loc.start.offset,order:block.loc.start.offset,source:external?block.content:source})};appendBlock(descriptor.script,`script`,resolvedIds.scriptResolvedId);appendBlock(descriptor.scriptSetup,`scriptSetup`,resolvedIds.scriptSetupResolvedId);blocks.sort((left,right)=>left.order-right.order);return blocks}function createSourceTransforms(filename,source,blocks,analysis){const transforms=/* @__PURE__ */ new Map;for(const block of blocks){const current=transforms.get(block.filename);if(current&¤t.source!==block.source)throw new Error(`${block.filename}:1:1 页面声明源文件内容不一致。`);if(!current)transforms.set(block.filename,{code:new MagicString(block.source),source:block.source})}for(const[sourceFile,transform]of transforms){const edits=analysis.edits.filter(edit=>edit.block.filename===sourceFile).map(edit=>({end:edit.block.offset+edit.end,start:edit.block.offset+edit.start})).sort((left,right)=>left.start-right.start);for(let index=0;index<edits.length;index+=1){const edit=edits[index];if(edit.start<0||edit.end>transform.source.length||edit.start>edit.end)throw new Error(`${sourceFile}:1:1 页面声明擦除范围无效。`);if(index>0&&edit.start<edits[index-1].end)throw new Error(`${sourceFile}:1:1 页面声明擦除范围发生重叠。`);const replacement=transform.source.slice(edit.start,edit.end).replace(/[^\r\n\u2028\u2029]/g,` `);transform.code.overwrite(edit.start,edit.end,replacement)}}if(!transforms.has(filename))transforms.set(filename,{code:new MagicString(source),source});return transforms}function updateScriptBlockSource(block,info,transform,sourceMap){if(!block||!info||!transform)return block;const content=transform.code.slice(info.offset,info.offset+info.content.length);return{...block,content,map:block.src&&sourceMap?transform.code.generateMap({hires:true,includeContent:true,source:info.filename}):block.map}}function resolveSourcePosition$1(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 createDescriptorForExternalScriptCompile(descriptor,blocks,transforms,sourceMap){if(!descriptor.scriptSetup||!blocks.some(block=>block.filename!==descriptor.filename))return;const bundle=new Bundle({separator:``});let source=``;let script=null;let scriptSetup=null;for(const block of blocks){const original=block.kind===`script`?descriptor.script:descriptor.scriptSetup;const chunk=transforms.get(block.filename).code.clone().snip(block.offset,block.offset+block.content.length);const content=chunk.toString();const openingTag=`<script${block.kind===`scriptSetup`?` setup`:``}${original?.lang?` lang=${JSON.stringify(original.lang)}`:``}>\n`;bundle.append(openingTag);bundle.addSource({content:chunk,filename:block.filename});bundle.append(`<\/script>
|
|
4
4
|
`);source+=openingTag;const startOffset=source.length;source+=`${content}<\/script>\n`;const attrs={...original.attrs};delete attrs.src;const nextBlock={...original,attrs,src:void 0,content,loc:{source:content,start:resolveSourcePosition$1(source,startOffset),end:resolveSourcePosition$1(source,startOffset+content.length)}};if(block.kind===`script`)script=nextBlock;else scriptSetup=nextBlock}return{descriptor:{...descriptor,source,script,scriptSetup},map:sourceMap?bundle.generateMap({hires:true,includeContent:true}):void 0}}const PAGE_DECLARATION_MACRO_HINT_RE=new RegExp(`(?:^|[^\\p{ID_Continue}$\\u200C\\u200D])${WEVU_DEFINE_PAGE_MACRO}(?![\\p{ID_Continue}$\\u200C\\u200D])`,`u`);function isOriginalVueSfc(filename){return!filename.includes(`?`)&&!filename.includes(`#`)&&/\.vue$/i.test(filename)}function parsePageDeclarationSfc(source,filename,ignoreEmpty=true){const parsed=parseVueSfc(source,{filename,ignoreEmpty,templateParseOptions:{prefixIdentifiers:false}});if(parsed.errors.length)throw createSfcParseError(parsed.errors[0],{filename,source,formatMessage:(message,location)=>`${filename}:${location?.start.line??1}:${location?.start.column??1} 解析页面声明 SFC 失败:${message}`});return parsed.descriptor}function mayContainPageDeclaration(source){return source.includes(`\\`)||PAGE_DECLARATION_MACRO_HINT_RE.test(source)}function mayContainPageMeta(source){return source.includes(`\\`)||source.includes(WEVU_DEFINE_PAGE_META_MACRO)}function stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analysis){if(!analysis.edits.length&&!blocks.some(block=>block.filename!==filename))return;const transforms=createSourceTransforms(filename,source,blocks,analysis);for(const parsed of analysis.parsedBlocks)if(parsed.block.filename!==filename)rebaseExternalScriptImports(parsed,filename,transforms.get(parsed.block.filename).code,analysis.parsedBlocks);const scriptBlock=blocks.find(block=>block.kind===`script`);const scriptSetupBlock=blocks.find(block=>block.kind===`scriptSetup`);const descriptorWithStrippedScripts={...descriptor,source:transforms.get(filename).code.toString(),script:updateScriptBlockSource(descriptor.script,scriptBlock,scriptBlock?transforms.get(scriptBlock.filename):void 0,sourceMap),scriptSetup:updateScriptBlockSource(descriptor.scriptSetup,scriptSetupBlock,scriptSetupBlock?transforms.get(scriptSetupBlock.filename):void 0,sourceMap)};const externalCompile=createDescriptorForExternalScriptCompile(descriptorWithStrippedScripts,blocks,transforms,sourceMap);const mainTransform=transforms.get(filename);const hasMainEdits=analysis.edits.some(edit=>edit.block.filename===filename);return{code:mainTransform.code.toString(),descriptor:descriptorWithStrippedScripts,routeConfig:analysis.declaration,pageMeta:analysis.pageMeta,descriptorForCompile:externalCompile?.descriptor,map:sourceMap&&hasMainEdits?mainTransform.code.generateMap({hires:true,includeContent:true,source:filename}):void 0,scriptMap:externalCompile?.map}}function stripPageDeclarationFromSfcDescriptor(source,filename,descriptor,sourceMap=true,resolvedIds={}){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analyzePageDeclarationBlocks(blocks))}function prepareSfcScriptCompile(source,filename,descriptor,sourceMap=true,resolvedIds={},isPage=true){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,isPage?analyzePageCompileTimeMacroBlocks(blocks):{edits:[],parsedBlocks:blocks.map(parsePageDeclarationBlock)})}async function extractPageDeclarationWithDependencies(source,filename,options){if(!isOriginalVueSfc(filename)){if(!mayContainPageDeclaration(source))return{dependencies:[]};const analysis=analyzePageDeclarationBlocks([{content:source,filename,kind:`script`,offset:0,order:0,source}]);return{declaration:analysis.declaration,declarationSourceFile:analysis.declarationSourceFile,dependencies:[]}}if(!mayContainPageDeclaration(source)&&(!source.includes(`<script`)||!source.includes(`src`)))return{dependencies:[]};const descriptor=parsePageDeclarationSfc(source,filename);const inlineBlocks=collectSfcScriptBlocks(source,filename,descriptor);if(!Boolean(descriptor.script?.src||descriptor.scriptSetup?.src)&&!inlineBlocks.some(block=>mayContainPageDeclaration(block.content)))return{dependencies:[]};const resolved=await resolveSfcBlockSrc(descriptor,filename,options??{});const resolvedIds={scriptResolvedId:resolved.scriptResolvedId,scriptSetupResolvedId:resolved.scriptSetupResolvedId};const dependencies=[...new Set([resolved.scriptResolvedId,resolved.scriptSetupResolvedId].filter(dependency=>Boolean(dependency)))];const blocks=collectSfcScriptBlocks(source,filename,resolved.descriptor,resolvedIds);if(!blocks.some(block=>mayContainPageDeclaration(block.content)))return{dependencies};const analysis=analyzePageDeclarationBlocks(blocks);return{declaration:analysis.declaration,declarationSourceFile:analysis.declarationSourceFile,dependencies}}function extractPageDeclaration(source,filename){if(isOriginalVueSfc(filename)){const descriptor=parsePageDeclarationSfc(source,filename);return analyzePageDeclarationBlocks(collectSfcScriptBlocks(source,filename,descriptor)).declaration}return analyzePageDeclarationBlocks([{content:source,filename,kind:`script`,offset:0,order:0,source}]).declaration}function stripPageDeclaration(source,filename){if(isOriginalVueSfc(filename)){const result=stripPageDeclarationFromSfcDescriptor(source,filename,parsePageDeclarationSfc(source,filename));return result?{code:result.code,map:result.map}:void 0}const block={content:source,filename,kind:`script`,offset:0,order:0,source};const analysis=analyzePageDeclarationBlocks([block]);if(!analysis.edits.length)return;const transform=createSourceTransforms(filename,source,[block],analysis).get(filename);return{code:transform.code.toString(),map:transform.code.generateMap({hires:true,includeContent:true,source:filename})}}const WE_VU_RUNTIME_CAPABILITY_ORDER=[`patchStrategy`,`templateRefs`,`inlineEvents`,`setDataHighFrequencyWarning`,`scopedSlots`,`layout`,`jsxIslands`];const WE_VU_RUNTIME_CAPABILITY_INSTALLERS={patchStrategy:`installPatchStrategy`,templateRefs:`installTemplateRefs`,inlineEvents:`installInlineEvents`,setDataHighFrequencyWarning:`installSetDataHighFrequencyWarning`,scopedSlots:`installScopedSlots`,layout:`installLayout`,jsxIslands:`installJsxIslands`};function createWevuRuntimeCapabilityMetadata(required,conservative=[]){const requiredSet=new Set(required);if(requiredSet.has(`layout`))requiredSet.add(`templateRefs`);const sortedRequired=WE_VU_RUNTIME_CAPABILITY_ORDER.filter(name=>requiredSet.has(name));if(!sortedRequired.length)return;const conservativeSet=new Set(conservative);const sortedConservative=sortedRequired.filter(name=>conservativeSet.has(name));return{required:sortedRequired,...sortedConservative.length?{conservative:sortedConservative}:{}}}function createWevuRuntimeCapabilityMetadataFromBindingManifest(manifest){const required=[];const features=manifest.features;if(features.templateRefs)required.push(`templateRefs`);if(features.inlineEvents)required.push(`inlineEvents`);if(features.scopedSlots)required.push(`scopedSlots`);if(features.layout)required.push(`layout`);if(features.jsxIslands)required.push(`jsxIslands`);return createWevuRuntimeCapabilityMetadata(required)}function mergeWevuRuntimeCapabilityMetadata(...metadata){const required=/* @__PURE__ */ new Set;const conservative=/* @__PURE__ */ new Set;for(const item of metadata){item?.required.forEach(name=>required.add(name));item?.conservative?.forEach(name=>conservative.add(name))}return createWevuRuntimeCapabilityMetadata(required,conservative)}const RESERVED_VUE_COMPONENT_TAGS=/* @__PURE__ */ new Set([`template`,`slot`,`component`,`transition`,`keep-alive`,`teleport`,`suspense`]);const VUE_COMPONENT_TAG_RE=/^[A-Z_$][\w$]*$/i;const PASCAL_CASE_TAG_RE=/^[A-Z][\w$]*$/;function isAutoImportCandidateTag(tag){return tag.includes(`-`)||PASCAL_CASE_TAG_RE.test(tag)}function analyzeVueTemplateTags(template,options){const tags=/* @__PURE__ */ new Set;try{const{ast,scripts}=parseTemplateWithScriptModules(template,{onError:()=>{}},void 0,baseParse);const visit=node=>{if(node.type===NodeTypes.ELEMENT){if(scripts.byStart.has(node.loc.start.offset))return;const tag=node.tag;const normalizedTag=tag.toLowerCase();if((!options||options.shouldCollect(tag))&&!RESERVED_VUE_COMPONENT_TAGS.has(normalizedTag)&&!isBuiltinComponent(tag))tags.add(tag);node.children.forEach(visit)}};ast.children.forEach(visit);return{tags}}catch(error){return{tags,errorMessage:error instanceof Error?error.message:String(error)}}}function warnVueTemplateTagAnalysis(errorMessage,options){if(errorMessage!==void 0){const warn=options.warn;const warnLabel=options.warnLabel||`模板标签收集`;const filename=options.filename||`<未知文件>`;warn?.(`[Vue 模板] 解析失败:${warnLabel}(${filename}):${errorMessage}`)}}function collectVueTemplateTags(template,options){const{warn,warnLabel,filename}=options;const analysis=analyzeVueTemplateTags(template,options);if(analysis.errorMessage!==void 0)warnVueTemplateTagAnalysis(analysis.errorMessage,{warn,warnLabel,filename});return analysis.tags}const IDENTIFIER_RE$5=/^[A-Z_$][\w$]*$/i;const INLINE_GLOBALS=/* @__PURE__ */ new Set([`Math`,`Number`,`Date`,`Array`,`Object`,`Boolean`,`String`,`RegExp`,`Map`,`Set`,`JSON`,`Intl`,`Promise`,`console`,`Infinity`,`undefined`,`NaN`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`require`,`arguments`,WEVU_CLASS_STYLE_RUNTIME_MODULE,`__wevuUnref`,`globalThis`,`setTimeout`,`clearTimeout`,`setInterval`,`clearInterval`,`Page`,`App`,`Component`,`requirePlugin`,`getApp`,`getCurrentPages`,...getMiniProgramRuntimeGlobalKeys()]);function createInlineExpressionParameterIdentifiers(scope,usedNames){const generatedNames=/* @__PURE__ */ new Set;const createIdentifier=name=>{let identifier=scope.generateUidIdentifier(name);while(usedNames.has(identifier.name)||generatedNames.has(identifier.name))identifier=scope.generateUidIdentifier(name);generatedNames.add(identifier.name);return identifier};return{context:createIdentifier(`ctx`),scope:createIdentifier(`scope`),event:createIdentifier(`event`)}}function createMemberAccess$2(target,prop){if(IDENTIFIER_RE$5.test(prop))return t.memberExpression(t.identifier(target),t.identifier(prop));return t.memberExpression(t.identifier(target),t.stringLiteral(prop),true)}function isTemplateContextThis(path){let childPath=path;let parentPath=path.parentPath;while(parentPath){if((parentPath.isObjectMethod()||parentPath.isClassMethod())&&(childPath.key===`key`||childPath.listKey===`decorators`)){childPath=parentPath;parentPath=parentPath.parentPath;continue}if(parentPath.isFunction()&&!parentPath.isArrowFunctionExpression())return false;if((parentPath.isClassProperty()||parentPath.isClassPrivateProperty()||parentPath.isClassAccessorProperty())&&childPath.key===`value`)return false;if(parentPath.isStaticBlock())return false;childPath=parentPath;parentPath=parentPath.parentPath}return true}function replaceIdentifierWithExpression$1(path,replacement){const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}const babelExpressionCache=new LRUCache({max:1024});const inlineHandlerCache=new LRUCache({max:1024});const BABEL_GENERATE_MINI_PROGRAM_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};function stripPatternTypes(node){if(!node||typeof node!==`object`)return;if(`typeAnnotation`in node)node.typeAnnotation=null;if(`optional`in node)node.optional=false;if(node.type===`AssignmentPattern`)stripPatternTypes(node.left);else if(node.type===`RestElement`)stripPatternTypes(node.argument);else if(node.type===`ObjectPattern`)for(const property of node.properties)stripPatternTypes(property.type===`RestElement`?property.argument:property.value);else if(node.type===`ArrayPattern`)for(const element of node.elements)stripPatternTypes(element)}function stripTypeScriptExpression(ast){traverse(ast,{TSAsExpression(path){path.replaceWith(path.node.expression)},TSNonNullExpression(path){path.replaceWith(path.node.expression)},TSTypeAssertion(path){path.replaceWith(path.node.expression)},Function(path){path.node.typeParameters=null;path.node.returnType=null;for(const param of path.node.params)stripPatternTypes(param)}});return ast}function parseTypeScriptExpression(exp){return stripTypeScriptExpression(parse$3(`(${exp})`,{sourceType:`module`,plugins:[`typescript`]}))}function generateExpression(node){const{code}=generate(node,BABEL_GENERATE_MINI_PROGRAM_OPTIONS);return code}function parseBabelExpression(exp){const cached=babelExpressionCache.get(exp);if(cached!==void 0)return cached===false?null:cached;try{const stmt=parseTypeScriptExpression(exp).program.body[0];if(!stmt||!(`expression`in stmt)){babelExpressionCache.set(exp,false);return null}const expression=stmt.expression;babelExpressionCache.set(exp,expression);return expression}catch{babelExpressionCache.set(exp,false);return null}}function parseBabelExpressionFile(exp){try{const ast=parseTypeScriptExpression(exp);const stmt=ast.program.body[0];if(!stmt||!(`expression`in stmt))return null;return{ast,expression:stmt.expression}}catch{return null}}function hasOwn(source,key){return Object.prototype.hasOwnProperty.call(source,key)}function getForItemAccess(context,name){for(let index=context.forStack.length-1;index>=0;index-=1){const forInfo=context.forStack[index];if(forInfo?.item===name&&forInfo.itemAccess)return forInfo.itemAccess}return name}function rewriteForItemAccess(ast,context){const itemAccesses=/* @__PURE__ */ new Map;for(const forInfo of context.forStack)if(forInfo.item&&forInfo.itemAccess)itemAccesses.set(forInfo.item,forInfo.itemAccess);if(!itemAccesses.size)return;traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier()||path.scope.hasBinding(path.node.name))return;const replacement=itemAccesses.get(path.node.name);if(!replacement)return;const parsed=replacement.split(`.`).slice(1).reduce((target,property)=>t.memberExpression(target,t.identifier(property)),t.identifier(path.node.name));replaceIdentifierWithExpression$1(path,parsed);path.skip()}})}const DIGIT_NUMERIC_SEPARATOR_RE=/\d_\d/;const NON_DECIMAL_NUMERIC_LITERAL_RE=/\b0[bxo][\da-f_]/i;const DECIMAL_BIGINT_LITERAL_RE=/\b\d[\d_]*n\b/;const NON_DECIMAL_NUMERIC_RAW_RE=/^0[bxo]/i;function hasExtendedNumericLiteralSyntax(exp){return DIGIT_NUMERIC_SEPARATOR_RE.test(exp)||NON_DECIMAL_NUMERIC_LITERAL_RE.test(exp)||DECIMAL_BIGINT_LITERAL_RE.test(exp)}function serializeBigIntForWxml(value){const asNumber=Number(value);if(!Number.isSafeInteger(asNumber))return t.stringLiteral(value.toString());return asNumber<0?t.unaryExpression(`-`,t.numericLiteral(Math.abs(asNumber))):t.numericLiteral(asNumber)}function normalizeTopLevelBigInt(expression){if(t.isBigIntLiteral(expression))return serializeBigIntForWxml(BigInt(expression.value));if(t.isUnaryExpression(expression,{operator:`-`})&&t.isBigIntLiteral(expression.argument))return serializeBigIntForWxml(-BigInt(expression.argument.value));return expression}function canonicalizeNumericLiteral(node){const raw=node.extra?.raw;if(typeof raw!==`string`||!raw.includes(`_`)&&!NON_DECIMAL_NUMERIC_RAW_RE.test(raw))return;delete node.extra?.raw;delete node.extra?.rawValue}function templateLiteralToConcat(node){const segments=[];node.quasis.forEach((quasi,index)=>{const cooked=quasi.value.cooked??quasi.value.raw??``;if(cooked)segments.push(t.stringLiteral(cooked));if(index<node.expressions.length){let inner=node.expressions[index];if(t.isTemplateLiteral(inner))inner=templateLiteralToConcat(inner);segments.push(inner)}});if(segments.length===0)return t.stringLiteral(``);if(segments.length===1)return segments[0];return segments.reduce((acc,cur)=>t.binaryExpression(`+`,acc,cur))}function isOptionalChainNode(node){return Boolean(node&&(t.isOptionalMemberExpression(node)||t.isOptionalCallExpression(node)))}function collectOptionalChain(node){const operations=[];let current=node;while(isOptionalChainNode(current)){if(t.isOptionalMemberExpression(current)){operations.push({type:`member`,optional:current.optional===true,computed:current.computed,property:t.cloneNode(current.property)});current=current.object;continue}operations.push({type:`call`,optional:current.optional===true,args:current.arguments.map(arg=>t.cloneNode(arg))});current=current.callee}if(!t.isExpression(current))return null;return{base:t.cloneNode(current),operations:operations.reverse()}}function applyOptionalChainOperation(base,operation){if(operation.type===`member`)return t.memberExpression(base,t.cloneNode(operation.property),operation.computed);return t.callExpression(base,operation.args.map(arg=>t.cloneNode(arg)))}function lowerOptionalChain(node){const chain=collectOptionalChain(node);if(!chain)return t.cloneNode(node);const segments=[chain.base];for(const operation of chain.operations){const currentBase=t.cloneNode(segments[segments.length-1]);segments.push(applyOptionalChainOperation(currentBase,operation))}let lowered=t.cloneNode(segments[segments.length-1]);for(let index=chain.operations.length-1;index>=0;index--){if(!chain.operations[index].optional)continue;lowered=t.conditionalExpression(t.binaryExpression(`==`,t.cloneNode(segments[index]),t.nullLiteral()),t.identifier(`undefined`),lowered)}return lowered}const TEMPLATE_INTERPOLATION_RE=/\$\{([^}]+)\}/g;const EMPTY_STRING_CONCAT_LEFT_RE=/'\s*\+\s*''/g;const EMPTY_STRING_CONCAT_RIGHT_RE=/''\s*\+\s*'/g;const LEADING_EMPTY_CONCAT_RE=/^\s*''\s*\+\s*/g;const TRAILING_EMPTY_CONCAT_RE=/\s*\+\s*''\s*$/g;function rewriteVueSlotsExpression(ast){traverse(ast,{MemberExpression:{exit(path){const node=path.node;if(!t.isIdentifier(node.object,{name:`$slots`}))return;const access=t.memberExpression(t.identifier(`vueSlots`),t.cloneNode(node.property),node.computed);path.replaceWith(t.logicalExpression(`&&`,t.identifier(`vueSlots`),access));path.skip()}},OptionalMemberExpression:{exit(path){const node=path.node;if(!t.isIdentifier(node.object,{name:`$slots`}))return;const access=t.memberExpression(t.identifier(`vueSlots`),t.cloneNode(node.property),node.computed);path.replaceWith(t.logicalExpression(`&&`,t.identifier(`vueSlots`),access));path.skip()}},Identifier:{exit(path){if(!path.isReferencedIdentifier()||path.node.name!==`$slots`)return;const parent=path.parentPath.node;if((t.isMemberExpression(parent)||t.isOptionalMemberExpression(parent))&&parent.object===path.node)return;path.replaceWith(t.identifier(`vueSlots`));path.skip()}}})}function normalizeWxmlExpression(exp){const hasTypeScriptSyntax=/\s(?:as|satisfies)\s/.test(exp)||/[\w$)\]]!(?=[.[\s,);:?]|$)/.test(exp)||/^\s*<[^>]+>/.test(exp);const needsVueSlotsRewrite=exp.includes(`$slots`);const needsThisRewrite=/\bthis\./.test(exp);const needsNumericLiteralRewrite=hasExtendedNumericLiteralSyntax(exp);if(!exp.includes("`")&&!exp.includes(`??`)&&!exp.includes(`?.`)&&!hasTypeScriptSyntax&&!needsVueSlotsRewrite&&!needsThisRewrite&&!needsNumericLiteralRewrite)return exp;try{const ast=parse$3(`(${exp})`,{sourceType:`module`,plugins:[`typescript`]});const stmt=ast.program.body[0];if(!stmt||!(`expression`in stmt))return exp;if(needsVueSlotsRewrite)rewriteVueSlotsExpression(ast);const expressionStatement=stmt;expressionStatement.expression=normalizeTopLevelBigInt(expressionStatement.expression);traverse(ast,{MemberExpression:{exit(path){const node=path.node;if(!t.isThisExpression(node.object)||node.computed||!t.isIdentifier(node.property))return;path.replaceWith(t.identifier(node.property.name));path.skip()}},TSAsExpression(path){path.replaceWith(path.node.expression)},TSNonNullExpression(path){path.replaceWith(path.node.expression)},TSTypeAssertion(path){path.replaceWith(path.node.expression)},NumericLiteral(path){canonicalizeNumericLiteral(path.node)},OptionalMemberExpression:{exit(path){if(isOptionalChainNode(path.parentPath.node))return;path.replaceWith(lowerOptionalChain(path.node));path.skip()}},OptionalCallExpression:{exit(path){if(isOptionalChainNode(path.parentPath.node))return;path.replaceWith(lowerOptionalChain(path.node));path.skip()}},LogicalExpression:{exit(path){if(path.node.operator!==`??`)return;const left=path.node.left;const right=path.node.right;const test=t.binaryExpression(`!=`,t.cloneNode(left),t.nullLiteral());path.replaceWith(t.conditionalExpression(test,t.cloneNode(left),t.cloneNode(right)));path.skip()}},TemplateLiteral(path){if(t.isTaggedTemplateExpression(path.parent))return;path.replaceWith(templateLiteralToConcat(path.node))}});const normalized=stmt.expression;return generateExpression(normalized)}catch{if(exp.startsWith("`")&&exp.endsWith("`")){let rewritten=`'${exp.slice(1,-1).replace(TEMPLATE_INTERPOLATION_RE,`' + ($1) + '`)}'`;rewritten=rewritten.replace(EMPTY_STRING_CONCAT_LEFT_RE,`'`).replace(EMPTY_STRING_CONCAT_RIGHT_RE,`'`);rewritten=rewritten.replace(LEADING_EMPTY_CONCAT_RE,``).replace(TRAILING_EMPTY_CONCAT_RE,``);return rewritten}return exp}}const SCOPED_SLOT_GLOBALS=/* @__PURE__ */ new Set([`Math`,`Number`,`Date`,`Array`,`Object`,`Boolean`,`String`,`RegExp`,`Map`,`Set`,`JSON`,`Intl`,`console`,`Infinity`,`undefined`,`NaN`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`require`,`arguments`,`vueSlots`,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_PROPS_DATA_KEY,WEVU_CLASS_STYLE_RUNTIME_MODULE]);function collectScopedSlotLocals(context){const locals=/* @__PURE__ */ new Set;for(const scope of context.scopeStack)for(const name of scope)locals.add(name);return locals}function collectSlotPropMapping(context){const mapping={};for(const entry of context.slotPropStack)Object.assign(mapping,entry);return mapping}function collectForAliasMapping$2(context){const mapping={};for(const forInfo of context.forStack){if(!forInfo.itemAliases)continue;Object.assign(mapping,forInfo.itemAliases)}return mapping}function replaceIdentifierWithExpression(path,replacement){const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}const IDENTIFIER_RE$4=/^[A-Z_$][\w$]*$/i;function rewriteScopedSlotExpression(exp,context){const normalized=normalizeWxmlExpression(exp);const parsed=parseBabelExpressionFile(normalized);if(!parsed)return normalized;const{ast}=parsed;const locals=collectScopedSlotLocals(context);const slotProps=collectSlotPropMapping(context);const forAliases=collectForAliasMapping$2(context);const createMemberAccess=(target,prop)=>{if(!prop)return t.identifier(target);if(IDENTIFIER_RE$4.test(prop))return t.memberExpression(t.identifier(target),t.identifier(prop));return t.memberExpression(t.identifier(target),t.stringLiteral(prop),true)};traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(path.scope.getBinding(name))return;if(hasOwn(forAliases,name)){const aliasExp=parseBabelExpression(forAliases[name]);if(aliasExp){replaceIdentifierWithExpression(path,t.cloneNode(aliasExp,true));return}}if(locals.has(name))return;if(SCOPED_SLOT_GLOBALS.has(name))return;if(hasOwn(slotProps,name)){replaceIdentifierWithExpression(path,createMemberAccess(WEVU_SLOT_PROPS_DATA_KEY,slotProps[name]));return}replaceIdentifierWithExpression(path,createMemberAccess(WEVU_SLOT_OWNER_KEY,name))}});rewriteForItemAccess(ast,context);const stmt=ast.program.body[0];const updatedExpression=stmt&&`expression`in stmt?stmt.expression:null;return updatedExpression?generateExpression(updatedExpression):normalized}function rewriteForAliasExpression(exp,context){const normalized=normalizeWxmlExpression(exp);const forAliases=collectForAliasMapping$2(context);if(!Object.keys(forAliases).length&&!context.forStack.some(forInfo=>forInfo.itemAccess))return normalized;const parsed=parseBabelExpressionFile(normalized);if(!parsed)return normalized;const{ast}=parsed;traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(path.scope.getBinding(name))return;if(hasOwn(forAliases,name)){const aliasExp=parseBabelExpression(forAliases[name]);if(aliasExp)replaceIdentifierWithExpression(path,t.cloneNode(aliasExp,true))}}});rewriteForItemAccess(ast,context);const stmt=ast.program.body[0];const updatedExpression=stmt&&`expression`in stmt?stmt.expression:null;return updatedExpression?generateExpression(updatedExpression):normalized}function normalizeWxmlExpressionWithContext(exp,context){if(!context)return normalizeWxmlExpression(exp);if(!context.rewriteScopedSlot)return rewriteForAliasExpression(exp,context);return rewriteScopedSlotExpression(exp,context)}const INTERNAL_GLOBALS={undefined:true,Infinity:true,NaN:true,arguments:true};const completeBindingManifests=/* @__PURE__ */ new WeakSet;function cloneSourceSpan(location){if(!location)return;return{start:{...location.start},end:{...location.end}}}function getStaticPropertyName(node){if(!node.computed&&t.isIdentifier(node.property))return node.property.name;if(node.computed&&(t.isStringLiteral(node.property)||t.isNumericLiteral(node.property)))return String(node.property.value);return null}function resolveMemberDependency(node){const segments=[];let current=node;let dynamic=false;while(t.isMemberExpression(current)||t.isOptionalMemberExpression(current)){const property=getStaticPropertyName(current);if(property===null)dynamic=true;else segments.unshift(property);if(!t.isExpression(current.object))return null;current=current.object}if(!t.isIdentifier(current)||INLINE_GLOBALS.has(current.name)||INTERNAL_GLOBALS[current.name])return null;if(dynamic)return{root:current.name,mode:`top-level`};const path=[current.name,...segments].join(`.`);return{root:current.name,path,mode:`exact-path`}}function collectDependencies(expression,context,additionalLocals){const normalized=context?normalizeWxmlExpressionWithContext(expression,context):expression;const parsed=parseBabelExpressionFile(normalized);if(!parsed)return null;const localNames=/* @__PURE__ */ new Set;for(const scope of context?.scopeStack??[])for(const name of scope)localNames.add(name);for(const name of additionalLocals??[])localNames.add(name);const dependencies=/* @__PURE__ */ new Map;let snapshotFallback=false;const addDependency=dependency=>{if(localNames.has(dependency.root)||INLINE_GLOBALS.has(dependency.root)||INTERNAL_GLOBALS[dependency.root])return;const key=`${dependency.root}:${dependency.path??``}:${dependency.mode}`;dependencies.set(key,dependency)};traverse(parsed.ast,{Identifier(path){if(!path.isReferencedIdentifier()||path.scope.hasBinding(path.node.name))return;const parent=path.parentPath;if((parent.isMemberExpression()||parent.isOptionalMemberExpression())&&parent.node.object===path.node){let outer=parent;while((outer.parentPath.isMemberExpression()||outer.parentPath.isOptionalMemberExpression())&&outer.parentPath.node.object===outer.node)outer=outer.parentPath;const dependency=resolveMemberDependency(outer.node);if(dependency)addDependency(dependency);return}if((parent.isMemberExpression()||parent.isOptionalMemberExpression())&&parent.node.property===path.node&&!parent.node.computed)return;addDependency({root:path.node.name,path:path.node.name,mode:`exact-path`})},CallExpression(path){if(t.isIdentifier(path.node.callee)&&context?.templateSafeCallNames.has(path.node.callee.name))return;snapshotFallback=true},OptionalCallExpression(){snapshotFallback=true},NewExpression(){snapshotFallback=true},Function(){snapshotFallback=true},SpreadElement(){snapshotFallback=true}});if(localNames.size&&context)for(const forInfo of context.forStack){const listExpression=forInfo.rawListExp??forInfo.listExp;if(!listExpression)continue;const outerAnalysis=collectDependencies(listExpression,{...context,scopeStack:[],forStack:[]});for(const dependency of outerAnalysis?.dependencies??[])addDependency(dependency);snapshotFallback||=outerAnalysis?.snapshotFallback??false}return{dependencies:[...dependencies.values()],snapshotFallback}}function resolveBindingDependencies(dependencies,snapshotFallback){return dependencies.map(dependency=>({root:dependency.root,...dependency.path?{path:dependency.path}:{},updateMode:snapshotFallback?`snapshot-fallback`:dependency.mode}))}function resolveBindingUpdateMode(dependencies){if(dependencies.some(dependency=>dependency.updateMode===`snapshot-fallback`))return`snapshot-fallback`;if(dependencies.some(dependency=>dependency.updateMode===`top-level`))return`top-level`;return`exact-path`}function resolveBindingScopes(context,dependencies,explicitScopes){if(explicitScopes)return explicitScopes.map(scope=>({...scope,...scope.locals?{locals:[...scope.locals]}:{}}));const scopes=[{kind:`root`,depth:0}];let forDepth=1;if(context?.rewriteScopedSlot){const roots=new Set(dependencies.map(dependency=>dependency.root));if(roots.has(WEVU_SLOT_OWNER_KEY)||roots.has(WEVU_SLOT_OWNER_PROXY_KEY)||roots.has(WEVU_SLOT_OWNER_ID_KEY)||roots.has(WEVU_SLOT_OWNER_ID_PROP)||roots.has(WEVU_SLOT_SCOPE_KEY)){scopes.push({kind:`slot-owner`,depth:1});forDepth=2}if(roots.has(WEVU_SLOT_PROPS_DATA_KEY)){scopes.push({kind:`slot-props`,depth:1});forDepth=2}}for(const[index,forInfo]of(context?.forStack??[]).entries()){const locals=[forInfo.item,forInfo.index,forInfo.key,...Object.keys(forInfo.itemAliases??{})].filter(Boolean);scopes.push({kind:`for`,depth:forDepth+index,...locals.length?{locals:[...new Set(locals)]}:{}})}return scopes}function mergeBindingScopeDependencies(analysis,scopeDependencies){const dependencies=/* @__PURE__ */ new Map;const addDependency=dependency=>{const key=`${dependency.root}:${dependency.path??``}:${dependency.mode}`;dependencies.set(key,dependency)};analysis.dependencies.forEach(addDependency);let snapshotFallback=analysis.snapshotFallback;for(const scope of scopeDependencies){const scopeAnalysis=collectDependencies(scope.expression,void 0,scope.locals);if(!scopeAnalysis){snapshotFallback=true;continue}scopeAnalysis.dependencies.forEach(addDependency);snapshotFallback||=scopeAnalysis.snapshotFallback}return{dependencies:[...dependencies.values()],snapshotFallback}}function recordBindingManifestExpression(manifest,options,context,additionalLocals){const initialAnalysis=collectDependencies(options.expression,context,additionalLocals);const analysis=initialAnalysis&&options.scopeDependencies?.length?mergeBindingScopeDependencies(initialAnalysis,options.scopeDependencies):initialAnalysis;const sourceLocation=cloneSourceSpan(options.sourceLocation);if(!analysis){manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:options.outputPath??`*`,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots:[],dependencies:[],scopes:resolveBindingScopes(context,[],options.scopes),updateMode:`snapshot-fallback`,sourceLocation});return}const{dependencies,snapshotFallback}=analysis;if(options.outputPath){const sourceRoots=[...new Set(dependencies.map(dependency=>dependency.root))];const sourcePaths=dependencies.flatMap(dependency=>dependency.path?[dependency.path]:[]);const bindingDependencies=resolveBindingDependencies(dependencies,snapshotFallback);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:options.outputPath,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots,sourcePaths:sourcePaths.length?[...new Set(sourcePaths)]:void 0,dependencies:bindingDependencies,scopes:resolveBindingScopes(context,dependencies,options.scopes),updateMode:resolveBindingUpdateMode(bindingDependencies),sourceLocation});return}for(const dependency of dependencies){const[bindingDependency]=resolveBindingDependencies([dependency],snapshotFallback);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:options.kind,outputPath:dependency.mode===`exact-path`?dependency.path:dependency.root,...options.sourceFile&&options.sourceFile!==manifest.sourceFile?{sourceFile:options.sourceFile}:{},sourceRoots:[dependency.root],sourcePaths:dependency.path?[dependency.path]:void 0,dependencies:[bindingDependency],scopes:resolveBindingScopes(context,[dependency],options.scopes),updateMode:bindingDependency.updateMode,sourceLocation})}}function createBindingManifest(sourceFile){const manifest={version:1,sourceFile,bindings:[],features:{}};completeBindingManifests.add(manifest);return manifest}function isBindingManifestComplete(manifest){return completeBindingManifests.has(manifest)}function markBindingManifestIncomplete(manifest){completeBindingManifests.delete(manifest)}function recordBindingExpression(context,options){recordBindingManifestExpression(context.bindingManifest,options,context)}function recordSyntheticBindingExpression(manifest,options,localNames){recordBindingManifestExpression(manifest,options,void 0,localNames)}const CLASS_STYLE_WXS_MODULE=WEVU_CLASS_STYLE_RUNTIME_MODULE;const CLASS_STYLE_WXS_FILE=WEVU_CLASS_STYLE_RUNTIME_FILE;function resolveScriptModuleTag(extension){return(extension.startsWith(`.`)?extension.slice(1):extension)===`sjs`?`sjs`:`wxs`}function buildClassStyleWxsTag(extension,src,platform){const normalized=extension.startsWith(`.`)?extension.slice(1):extension;const resolvedSrc=src??`./${CLASS_STYLE_WXS_FILE}.${normalized}`;const options=getMiniProgramScriptModuleOptions(resolveMiniProgramPlatform(platform),normalized);return`<${platform?options.tag:resolveScriptModuleTag(normalized)} ${options.moduleAttribute}="${CLASS_STYLE_WXS_MODULE}" ${options.sourceAttribute}="${resolvedSrc}"/>`}function resolveClassStyleWxsLocation(options){const normalizedExt=options.extension.startsWith(`.`)?options.extension.slice(1):options.extension;const normalizedRoot=normalizeRoot(options.packageRoot??``);const fileName=normalizedRoot?`${normalizedRoot}/${CLASS_STYLE_WXS_FILE}.${normalizedExt}`:`${CLASS_STYLE_WXS_FILE}.${normalizedExt}`;const baseDir=path.posix.dirname(toPosixPath(options.relativeBase));const fromDir=baseDir===`.`?`.`:baseDir;let src=path.posix.relative(fromDir,fileName);if(!src||src===`.`)src=path.posix.basename(fileName);if(!src.startsWith(`.`)&&!src.startsWith(`/`))src=`./${src}`;return{fileName,src}}function getClassStyleWxsSource(options={}){const isSjs=(options.extension?.startsWith(`.`)?options.extension.slice(1):options.extension)===`sjs`;const isArrayFunctionLines=isSjs?[`function isArray(value) {`,` if (!toString) {`,` return false`,` }`,` return toString.call(value) === '[object Array]'`,`}`]:[`function isArray(value) {`,` if (!value) {`,` return false`,` }`,` if (typeof Array !== 'undefined' && Array.isArray && Array.isArray(value)) {`,` return true`,` }`,` if (toString && toString.call(value) === '[object Array]') {`,` return true`,` }`,` return typeof value.length === 'number' && typeof value.join === 'function'`,`}`];const hyphenateUpperCaseLine=isSjs?` res += str.charAt(i).toLowerCase()`:` res += String.fromCharCode(code + 32)`;const bodyLines=[`var objectCtor = ({}).constructor`,`var objectProto = objectCtor ? objectCtor.prototype : null`,`var hasOwn = objectProto ? objectProto.hasOwnProperty : null`,`var toString = objectProto ? objectProto.toString : null`,``,...isArrayFunctionLines,``,`function getObjectKeys(obj) {`,` if (objectCtor && objectCtor.keys) {`,` return objectCtor.keys(obj)`,` }`,` if (objectCtor && objectCtor.getOwnPropertyNames) {`,` return objectCtor.getOwnPropertyNames(obj)`,` }`,` return null`,`}`,``,`function isWordCharCode(code) {`,` return (code >= 48 && code <= 57)`,` || (code >= 65 && code <= 90)`,` || (code >= 97 && code <= 122)`,` || code === 95`,`}`,``,`function isUpperCaseCode(code) {`,` return code >= 65 && code <= 90`,`}`,``,`function hyphenate(str) {`,` if (!str) {`,` return ''`,` }`,` if (str.indexOf('--') === 0) {`,` return str`,` }`,` var res = ''`,` for (var i = 0; i < str.length; i++) {`,` var code = str.charCodeAt(i)`,` if (isUpperCaseCode(code)) {`,` if (i > 0 && isWordCharCode(str.charCodeAt(i - 1))) {`,` res += '-'`,` }`,hyphenateUpperCaseLine,` continue`,` }`,` res += str.charAt(i)`,` }`,` return res`,`}`,``,`function appendStyle(base, part) {`,` if (!part) {`,` return base || ''`,` }`,` if (!base) {`,` return part`,` }`,` if (base.charAt(base.length - 1) !== ';') {`,` base += ';'`,` }`,` if (part.charAt(0) === ';') {`,` part = part.slice(1)`,` }`,` return base + part`,`}`,``,`function stylePair(key, value) {`,` if (value == null) {`,` return ''`,` }`,` if (isArray(value)) {`,` var res = ''`,` for (var i = 0; i < value.length; i++) {`,` var item = value[i]`,` if (item == null) {`,` continue`,` }`,` res = appendStyle(res, key + ':' + item)`,` }`,` return res`,` }`,` return key + ':' + value`,`}`,``,`function normalizeClass(value) {`,` var res = ''`,` if (!value) {`,` return res`,` }`,` if (typeof value === 'string') {`,` return value`,` }`,` if (isArray(value)) {`,` for (var i = 0; i < value.length; i++) {`,` var normalized = normalizeClass(value[i])`,` if (normalized) {`,` res += normalized + ' '`,` }`,` }`,` return res.trim()`,` }`,` if (typeof value === 'object') {`,` var keys = getObjectKeys(value)`,` if (!keys) {`,` return res`,` }`,` for (var i = 0; i < keys.length; i++) {`,` var key = keys[i]`,` if ((!hasOwn || hasOwn.call(value, key)) && value[key]) {`,` res += key + ' '`,` }`,` }`,` return res.trim()`,` }`,` return res`,`}`,``,`function stringifyStyle(obj) {`,` var res = ''`,` var keys = getObjectKeys(obj)`,` if (!keys) {`,` return res`,` }`,` for (var i = 0; i < keys.length; i++) {`,` var key = keys[i]`,` if (hasOwn && !hasOwn.call(obj, key)) {`,` continue`,` }`,` var val = obj[key]`,` if (val == null) {`,` continue`,` }`,` var name = hyphenate(key)`,` if (isArray(val)) {`,` for (var j = 0; j < val.length; j++) {`,` var item = val[j]`,` if (item == null) {`,` continue`,` }`,` res = appendStyle(res, name + ':' + item)`,` }`,` }`,` else {`,` res = appendStyle(res, name + ':' + val)`,` }`,` }`,` return res`,`}`,``,`function normalizeStyle(value) {`,` if (value == null) {`,` return ''`,` }`,` if (typeof value === 'string') {`,` return value`,` }`,` if (isArray(value)) {`,` var res = ''`,` for (var i = 0; i < value.length; i++) {`,` var normalized = normalizeStyle(value[i])`,` if (normalized) {`,` res = appendStyle(res, normalized)`,` }`,` }`,` return res`,` }`,` if (typeof value === 'object') {`,` return stringifyStyle(value)`,` }`,` return ''`,`}`,``];const exportLines=(options.moduleFormat??(isSjs?`esm`:`commonjs`))===`esm`?[`export default {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`]:[`module.exports = {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`];return[...bodyLines,...exportLines,``].join(`
|
|
5
5
|
`)}function warn(context,message,location,source=`template`,options){const normalized=typeof options===`string`?{code:options,severity:`error`}:options;context.diagnostics.push({code:normalized?.code??(source===`expression`?`WV1002`:`WV1001`),severity:normalized?.severity??`warning`,message,filename:context.filename,source,loc:location?{start:location.start,end:location.end}:void 0})}function normalizeClassBindingExpression(exp,context){const ast=parseBabelExpression(exp);if(!ast)return[normalizeWxmlExpressionWithContext(exp,context)];const out=[];const pushExpr=node=>{out.push(normalizeWxmlExpressionWithContext(generateExpression(node),context))};const visit=node=>{if(!node)return;if(t.isArrayExpression(node)){for(const el of node.elements){if(!el)continue;if(t.isSpreadElement(el)){warn(context,`小程序不支持 :class 的展开语法,已忽略。`);continue}if(t.isExpression(el))visit(el)}return}if(t.isObjectExpression(node)){for(const prop of node.properties){if(t.isSpreadElement(prop)){warn(context,`小程序不支持 :class 对象的展开语法,已忽略。`);continue}if(!t.isObjectProperty(prop))continue;const value=prop.value;if(!t.isExpression(value))continue;const test=value;if(prop.computed){const keyExpr=prop.key;if(!t.isExpression(keyExpr))continue;pushExpr(t.conditionalExpression(test,keyExpr,t.stringLiteral(``)))}else if(t.isIdentifier(prop.key))pushExpr(t.conditionalExpression(test,t.stringLiteral(prop.key.name),t.stringLiteral(``)));else if(t.isStringLiteral(prop.key))pushExpr(t.conditionalExpression(test,t.stringLiteral(prop.key.value),t.stringLiteral(``)))}return}pushExpr(node)};visit(ast);if(!out.length)return[normalizeWxmlExpressionWithContext(exp,context)];return out}function normalizeStyleBindingExpression(exp,context){const ast=parseBabelExpression(exp);if(!ast)return[normalizeWxmlExpressionWithContext(exp,context)];const out=[];const pushExpr=node=>{out.push(normalizeWxmlExpressionWithContext(generateExpression(node),context))};const buildKeyExpression=(key,computed)=>{if(computed)return t.isExpression(key)?key:null;if(t.isIdentifier(key))return t.stringLiteral(key.name);if(t.isStringLiteral(key))return t.stringLiteral(key.value);if(t.isNumericLiteral(key))return t.stringLiteral(String(key.value));if(t.isBooleanLiteral(key))return t.stringLiteral(String(key.value));return null};const buildStylePair=(keyExpr,valueExpr)=>{return t.callExpression(t.memberExpression(t.identifier(WEVU_CLASS_STYLE_RUNTIME_MODULE),t.identifier(`stylePair`)),[keyExpr,valueExpr])};const visit=node=>{if(!node)return;if(t.isArrayExpression(node)){for(const el of node.elements){if(!el)continue;if(t.isSpreadElement(el)){warn(context,`小程序不支持 :style 的展开语法,已忽略。`);continue}if(t.isExpression(el))visit(el)}return}if(t.isObjectExpression(node)){for(const prop of node.properties){if(t.isSpreadElement(prop)){warn(context,`小程序不支持 :style 对象的展开语法,已忽略。`);continue}if(!t.isObjectProperty(prop))continue;const value=prop.value;if(!t.isExpression(value))continue;const keyExpr=buildKeyExpression(prop.key,prop.computed);if(!keyExpr)continue;pushExpr(buildStylePair(keyExpr,value))}return}pushExpr(node)};visit(ast);if(!out.length)return[normalizeWxmlExpressionWithContext(exp,context)];return out}const NON_ALNUM_RE=/[^a-z0-9]+/gi;const LEADING_TRAILING_DASH_RE=/^-+|-+$/g;function normalizeMiniProgramEventName(eventName){return eventName.includes(`:`)?eventName.replaceAll(`:`,`-`).toLowerCase():hyphenate(eventName)}function normalizeEventDatasetSuffix(eventName){return normalizeMiniProgramEventName(eventName.trim()).replace(NON_ALNUM_RE,`-`).replace(LEADING_TRAILING_DASH_RE,``)||`event`}function createInlineExpressionId(seed){return`i${seed.toString(36)}`}const SIMPLE_PATH_RE=/^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;function rewriteForItemResolverExpression(expression,resolvedLocals,resolvedIndexes,parameterIdentifiers){const ast=t.file(t.program([t.expressionStatement(t.cloneNode(expression,true))]));traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier()||path.scope.getBinding(path.node.name))return;const name=path.node.name;if(name===parameterIdentifiers.context.name||name===parameterIdentifiers.scope.name)return;const localExpression=resolvedLocals.get(name)??resolvedIndexes.get(name);if(localExpression){replaceIdentifierWithExpression$1(path,t.cloneNode(localExpression,true));path.skip();return}if(INLINE_GLOBALS.has(name))return;replaceIdentifierWithExpression$1(path,createMemberAccess$2(parameterIdentifiers.context.name,name));path.skip()},ThisExpression(path){if(isTemplateContextThis(path))path.replaceWith(t.cloneNode(parameterIdentifiers.context))}});const statement=ast.program.body[0];return statement&&t.isExpressionStatement(statement)?statement.expression:null}function getParsedResolverExpression(source,cache){if(cache.has(source))return cache.get(source)??null;const expression=parseBabelExpressionFile(source);cache.set(source,expression);return expression}function getForResolverListExpression(info){return(info?.itemPatternRequiresProjection?info.listExp:info?.rawListExp??info?.listExp)?.trim()??``}function buildNestedForItemResolverExpression(targetKey,targetLevel,context,slotProps,indexBindings){const expressionCache=/* @__PURE__ */ new Map;for(let level=0;level<=targetLevel;level+=1){const forInfo=context.forStack[level];const listExp=getForResolverListExpression(forInfo);if(!listExp||!getParsedResolverExpression(listExp,expressionCache))return null;for(const aliasExp of Object.values(forInfo.itemAliases??{}))getParsedResolverExpression(aliasExp,expressionCache)}const usedIdentifierNames=/* @__PURE__ */ new Set;let programScope;for(const parsed of expressionCache.values()){if(!parsed)continue;traverse(parsed.ast,{Program(path){programScope??=path.scope},Identifier(path){usedIdentifierNames.add(path.node.name)}})}if(!programScope)return null;const parameterIdentifiers=createInlineExpressionParameterIdentifiers(programScope,usedIdentifierNames);const resolvedLocals=/* @__PURE__ */ new Map;const resolvedIndexes=/* @__PURE__ */ new Map;for(let level=0;level<=targetLevel;level+=1){const forInfo=context.forStack[level];const listExp=getForResolverListExpression(forInfo);const indexBinding=indexBindings[level];const parsedList=getParsedResolverExpression(listExp,expressionCache);if(!forInfo||!parsedList||!indexBinding)return null;const root=SIMPLE_PATH_RE.test(listExp)?listExp.split(`.`)[0]:``;if(root&&hasOwn(slotProps,root)&&!resolvedLocals.has(root))return null;const listExpression=rewriteForItemResolverExpression(parsedList.expression,resolvedLocals,resolvedIndexes,parameterIdentifiers);if(!listExpression)return null;const indexExpression=createMemberAccess$2(parameterIdentifiers.scope.name,indexBinding.key);const itemExpression=t.memberExpression(listExpression,t.cloneNode(indexExpression),true);if(forInfo.item)resolvedLocals.set(forInfo.item,itemExpression);resolvedIndexes.set(forInfo.index?.trim()||`index`,indexExpression);if(forInfo.key)resolvedIndexes.set(forInfo.key,indexExpression);for(const[alias,aliasExp]of Object.entries(forInfo.itemAliases??{})){const parsedAlias=getParsedResolverExpression(aliasExp,expressionCache);if(!parsedAlias)continue;const resolvedAlias=rewriteForItemResolverExpression(parsedAlias.expression,resolvedLocals,resolvedIndexes,parameterIdentifiers);if(resolvedAlias)resolvedLocals.set(alias,resolvedAlias)}const targetExpression=resolvedLocals.get(targetKey);if(level===targetLevel&&targetExpression)return generateExpression(t.arrowFunctionExpression([t.cloneNode(parameterIdentifiers.context),t.cloneNode(parameterIdentifiers.scope)],t.cloneNode(targetExpression,true)))}return null}function buildForItemResolverExpression(targetKey,context,slotProps,indexBindings){let targetLevel=-1;for(let level=context.forStack.length-1;level>=0;level-=1){const forInfo=context.forStack[level];if(forInfo?.item===targetKey||hasOwn(forInfo?.itemAliases??{},targetKey)){targetLevel=level;break}}if(targetLevel<0)return null;const forInfo=context.forStack[targetLevel];const listExp=getForResolverListExpression(forInfo);const indexBinding=indexBindings[targetLevel];if(!listExp||!indexBinding)return null;if(forInfo?.item===targetKey&&SIMPLE_PATH_RE.test(listExp)){const root=listExp.split(`.`)[0];const localRoots=new Set(Object.keys(slotProps));for(let level=0;level<=targetLevel;level+=1){const item=context.forStack[level]?.item?.trim();const index=context.forStack[level]?.index?.trim();if(item)localRoots.add(item);if(index)localRoots.add(index);localRoots.add(`index`);for(const alias of Object.keys(context.forStack[level]?.itemAliases??{}))localRoots.add(alias)}if(!localRoots.has(root))return`({type:'for-item',path:${JSON.stringify(listExp)},indexKey:${JSON.stringify(indexBinding.key)}})`}return buildNestedForItemResolverExpression(targetKey,targetLevel,context,slotProps,indexBindings)}const SCRIPT_SETUP_REF_BINDINGS=/* @__PURE__ */ new Set([`setup-ref`,`setup-maybe-ref`]);function getScriptSetupBindingType(context,name){const binding=context.scriptSetupBindings?.[name];return typeof binding===`string`?binding:void 0}function isScriptSetupBinding(context,name){return Boolean(getScriptSetupBindingType(context,name))}function isScriptSetupRefLikeBinding(context,name){const bindingType=getScriptSetupBindingType(context,name);return bindingType?SCRIPT_SETUP_REF_BINDINGS.has(bindingType):false}function isRefLikeCtxMember(node,context,contextIdentifierName){return t.isMemberExpression(node)&&t.isIdentifier(node.object,{name:contextIdentifierName})&&t.isIdentifier(node.property)&&!node.computed&&isScriptSetupRefLikeBinding(context,node.property.name)}function buildCtxValueAccess(member){return t.memberExpression(t.cloneNode(member),t.identifier(`value`))}function rewriteAssignmentPatternTarget(target,scope,context,parameterIdentifiers,locals,markLocal){if(t.isIdentifier(target)){const name=target.name;if(INLINE_GLOBALS.has(name)||scope.getBinding(name))return target;if(name===`$event`)return t.cloneNode(parameterIdentifiers.event);if(locals.has(name)){markLocal?.(name);return createMemberAccess$2(parameterIdentifiers.scope.name,name)}const member=createMemberAccess$2(parameterIdentifiers.context.name,name);return isScriptSetupRefLikeBinding(context,name)?buildCtxValueAccess(member):member}if(t.isAssignmentPattern(target)){target.left=rewriteAssignmentPatternTarget(target.left,scope,context,parameterIdentifiers,locals,markLocal);return target}if(t.isRestElement(target)){target.argument=rewriteAssignmentPatternTarget(target.argument,scope,context,parameterIdentifiers,locals,markLocal);return target}if(t.isArrayPattern(target)){for(let index=0;index<target.elements.length;index+=1){const element=target.elements[index];if(element)target.elements[index]=rewriteAssignmentPatternTarget(element,scope,context,parameterIdentifiers,locals,markLocal)}return target}if(t.isObjectPattern(target))for(const property of target.properties){if(t.isRestElement(property)){property.argument=rewriteAssignmentPatternTarget(property.argument,scope,context,parameterIdentifiers,locals,markLocal);continue}const value=property.value;if(!t.isPatternLike(value))continue;property.value=rewriteAssignmentPatternTarget(value,scope,context,parameterIdentifiers,locals,markLocal);if(property.shorthand&&!(t.isIdentifier(property.key)&&(t.isIdentifier(property.value,{name:property.key.name})||t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left,{name:property.key.name}))))property.shorthand=false}return target}function isValueMemberObject(node,parent){return t.isMemberExpression(parent)&&parent.object===node&&t.isIdentifier(parent.property,{name:`value`})&&!parent.computed}function isCallTarget(node,parent){return(t.isCallExpression(parent)||t.isOptionalCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node}function rewriteTopLevelRefLikeAccess(ast,context,parameterIdentifiers,locals,createHelperIdentifier,markLocal){let unrefIdentifier;const getUnrefIdentifier=()=>{if(!unrefIdentifier)unrefIdentifier=createHelperIdentifier(`unref`);return t.cloneNode(unrefIdentifier)};const contextIdentifier=parameterIdentifiers.context;traverse(ast,{AssignmentExpression(path){const left=path.node.left;if(t.isIdentifier(left)&&path.scope.getBinding(left.name))return;if(t.isIdentifier(left)&&left.name===`$event`){path.node.left=t.cloneNode(parameterIdentifiers.event);return}if(t.isObjectPattern(left)||t.isArrayPattern(left)){rewriteAssignmentPatternTarget(left,path.scope,context,parameterIdentifiers,locals,markLocal);return}if(t.isIdentifier(left)&&isScriptSetupRefLikeBinding(context,left.name))path.node.left=buildCtxValueAccess(t.memberExpression(t.cloneNode(contextIdentifier),t.identifier(left.name)));else if(t.isIdentifier(left)&&isScriptSetupBinding(context,left.name))path.node.left=t.memberExpression(t.cloneNode(contextIdentifier),t.identifier(left.name));else if(isRefLikeCtxMember(left,context,contextIdentifier.name))path.node.left=buildCtxValueAccess(left)},UpdateExpression(path){const arg=path.node.argument;if(t.isIdentifier(arg)&&path.scope.getBinding(arg.name))return;if(t.isIdentifier(arg)&&isScriptSetupRefLikeBinding(context,arg.name))path.node.argument=buildCtxValueAccess(t.memberExpression(t.cloneNode(contextIdentifier),t.identifier(arg.name)));else if(t.isIdentifier(arg)&&isScriptSetupBinding(context,arg.name))path.node.argument=t.memberExpression(t.cloneNode(contextIdentifier),t.identifier(arg.name));else if(isRefLikeCtxMember(arg,context,contextIdentifier.name))path.node.argument=buildCtxValueAccess(arg)}});traverse(ast,{MemberExpression(path){if(!isRefLikeCtxMember(path.node,context,contextIdentifier.name))return;if(isValueMemberObject(path.node,path.parentPath?.node))return;if(isCallTarget(path.node,path.parentPath?.node))return;const bindingType=getScriptSetupBindingType(context,path.node.property.name);path.replaceWith(bindingType===`setup-maybe-ref`?t.callExpression(getUnrefIdentifier(),[t.cloneNode(path.node)]):buildCtxValueAccess(path.node));path.skip()}});return unrefIdentifier?{unref:unrefIdentifier.name}:void 0}function resolveSlotPropBinding(slotProps,name){if(!hasOwn(slotProps,name))return null;const prop=slotProps[name];if(!prop)return WEVU_SLOT_PROPS_DATA_KEY;return generateExpression(createMemberAccess$2(WEVU_SLOT_PROPS_DATA_KEY,prop))}function rewriteExpressionAst(ast,locals,parameterIdentifiers,options){traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(name===parameterIdentifiers.context.name||name===parameterIdentifiers.scope.name||name===parameterIdentifiers.event.name)return;if(path.scope.getBinding(name))return;if(name===`$event`){path.replaceWith(t.cloneNode(parameterIdentifiers.event));return}if(locals.has(name)){options?.markLocal?.(name);replaceIdentifierWithExpression$1(path,createMemberAccess$2(parameterIdentifiers.scope.name,name));return}if(INLINE_GLOBALS.has(name))return;replaceIdentifierWithExpression$1(path,createMemberAccess$2(parameterIdentifiers.context.name,name))},ThisExpression(path){if(isTemplateContextThis(path))path.replaceWith(t.cloneNode(parameterIdentifiers.context))}})}function buildInlineIndexBindings(context){if(!context.forStack.length)return[];return context.forStack.map((forInfo,level)=>({key:`__wv_i${level}`,binding:forInfo.index?.trim()||`index`}))}function buildScopeResolvers(usedLocals,context,slotProps,indexBindings){const resolvers=[];for(const key of usedLocals){const expression=buildForItemResolverExpression(key,context,slotProps,indexBindings);if(!expression)continue;resolvers.push({key,expression})}return resolvers}function collectForAliasMapping$1(context){const mapping={};for(const forInfo of context.forStack){if(!forInfo.itemAliases)continue;Object.assign(mapping,forInfo.itemAliases)}return mapping}function registerInlineExpression$1(exp,context){const parsed=parseBabelExpressionFile(exp);if(!parsed)return null;const{ast}=parsed;const usedIdentifierNames=/* @__PURE__ */ new Set;let programScope;traverse(ast,{Program(path){programScope=path.scope},Identifier(path){usedIdentifierNames.add(path.node.name)}});if(!programScope)throw new Error(`无法为内联表达式创建程序作用域。`);const parameterIdentifiers=createInlineExpressionParameterIdentifiers(programScope,usedIdentifierNames);const locals=collectScopedSlotLocals(context);const slotProps=collectSlotPropMapping(context);for(const name of Object.keys(slotProps))locals.add(name);const usedLocals=[];const usedLocalSet=/* @__PURE__ */ new Set;const markLocal=name=>{if(usedLocalSet.has(name))return;usedLocalSet.add(name);usedLocals.push(name)};rewriteExpressionAst(ast,locals,parameterIdentifiers,{markLocal});const createHelperIdentifier=name=>{let identifier=programScope.generateUidIdentifier(name);while(usedIdentifierNames.has(identifier.name))identifier=programScope.generateUidIdentifier(name);return identifier};const runtimeHelpers=rewriteTopLevelRefLikeAccess(ast,context,parameterIdentifiers,locals,createHelperIdentifier,markLocal);const forAliases=collectForAliasMapping$1(context);const updatedStmt=ast.program.body[0];const updatedExpressionNode=updatedStmt&&`expression`in updatedStmt?updatedStmt.expression:null;const updatedExpression=updatedExpressionNode?generateExpression(updatedExpressionNode):exp;const scopeBindings=usedLocals.map(name=>{const forAlias=forAliases[name];if(forAlias)return forAlias;return resolveSlotPropBinding(slotProps,name)??name});const indexBindings=buildInlineIndexBindings(context);const scopeResolvers=buildScopeResolvers(usedLocals,context,slotProps,indexBindings);const asset={id:createInlineExpressionId(context.inlineExpressionSeed++),expression:updatedExpression,scopeKeys:usedLocals,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}};if(runtimeHelpers)asset.runtimeHelpers=runtimeHelpers;if(scopeResolvers.length){asset.indexBindings=indexBindings;asset.scopeResolvers=scopeResolvers}context.inlineExpressions.push(asset);return{id:asset.id,scopeBindings,indexBindings:scopeResolvers.length?indexBindings.map(binding=>binding.binding):[]}}const JS_RUNTIME_GLOBALS=/* @__PURE__ */ new Set([`Math`,`Number`,`Date`,`Array`,`Object`,`Boolean`,`String`,`RegExp`,`Map`,`Set`,`WeakMap`,`WeakSet`,`Promise`,`Symbol`,`BigInt`,`JSON`,`Intl`,`console`,`Infinity`,`undefined`,`NaN`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`require`,`arguments`,`globalThis`,`__wevuUnref`,`__wevuResolvePropValue`,`getApp`,`getCurrentPages`,...getMiniProgramRuntimeGlobalKeys()]);function createMemberAccess$1(target,prop){if(!prop)return target;if(t.isValidIdentifier(prop))return t.memberExpression(target,t.identifier(prop));return t.memberExpression(target,t.stringLiteral(prop),true)}function createThisMemberAccess(prop){return createMemberAccess$1(t.thisExpression(),prop)}function createUnrefCall(exp){return t.callExpression(t.identifier(`__wevuUnref`),[exp])}function createHasOwnPropertyCall$1(target,key){return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`prototype`)),t.identifier(`hasOwnProperty`)),t.identifier(`call`)),[target,t.stringLiteral(key)])}function createResolvePropValueCall(name,fallback,preferProps=false){const args=[t.thisExpression(),t.stringLiteral(name),fallback];if(preferProps)args.push(t.booleanLiteral(true));return t.callExpression(t.identifier(`__wevuResolvePropValue`),args)}function createPropsKeyAccessFallback(name,fallback){const propsObject=createThisMemberAccess(WEVU_PROPS_KEY);const propsAccess=createMemberAccess$1(propsObject,name);const hasPropsObject=t.binaryExpression(`!=`,propsObject,t.nullLiteral());const hasPropsValue=t.logicalExpression(`&&`,hasPropsObject,t.logicalExpression(`||`,t.binaryExpression(`!==`,propsAccess,t.identifier(`undefined`)),createHasOwnPropertyCall$1(propsObject,name)));return t.conditionalExpression(hasPropsValue,propsAccess,fallback)}function createIdentifierAccessWithPropsFallback(name,context,useRuntimePropHelper=false){if(useRuntimePropHelper){if(name===`props`){const propsObject=createThisMemberAccess(WEVU_PROPS_KEY);return t.conditionalExpression(t.binaryExpression(`!=`,propsObject,t.nullLiteral()),propsObject,createThisMemberAccess(`props`))}return createResolvePropValueCall(name,createThisMemberAccess(name))}if(name===`props`){const propsObject=createThisMemberAccess(WEVU_PROPS_KEY);return t.conditionalExpression(t.binaryExpression(`!=`,propsObject,t.nullLiteral()),propsObject,createThisMemberAccess(`props`))}if(name===`data`)return createPropsKeyAccessFallback(name,createThisMemberAccess(name));const thisAccess=createThisMemberAccess(name);const propsAccess=createMemberAccess$1(createThisMemberAccess(WEVU_PROPS_KEY),name);const propsObject=createThisMemberAccess(WEVU_PROPS_KEY);const stateObject=createThisMemberAccess(`$state`);const hasPropsObject=t.binaryExpression(`!=`,propsObject,t.nullLiteral());const hasDefinedPropsValue=t.binaryExpression(`!==`,propsAccess,t.identifier(`undefined`));const hasPropsKey=createHasOwnPropertyCall$1(propsObject,name);const hasUsablePropsValue=t.logicalExpression(`&&`,hasPropsObject,t.logicalExpression(`||`,hasDefinedPropsValue,hasPropsKey));const hasStateObject=t.binaryExpression(`!=`,stateObject,t.nullLiteral());const hasStateKey=createHasOwnPropertyCall$1(stateObject,name);const shouldUseStateAccess=Boolean(context.propsDerivedKeys?.includes(name))?t.booleanLiteral(false):t.logicalExpression(`&&`,hasStateObject,hasStateKey);return t.conditionalExpression(shouldUseStateAccess,thisAccess,t.conditionalExpression(hasUsablePropsValue,propsAccess,thisAccess))}function createAliasedPropsAccess(name,propName){return createResolvePropValueCall(propName,createThisMemberAccess(name),true)}function collectForAliasMapping(context){const mapping={};for(const forInfo of context.forStack){if(!forInfo.itemAliases)continue;Object.assign(mapping,forInfo.itemAliases)}return mapping}function isThisMemberChain(node){if(!node)return false;if(t.isThisExpression(node))return true;if(t.isMemberExpression(node))return isThisMemberChain(node.object);return false}function isUnrefCallArgument(node,parent){return t.isCallExpression(parent)&&t.isIdentifier(parent.callee,{name:`__wevuUnref`})&&parent.arguments.includes(node)}function isMemberCallTarget(node,parent){return(t.isCallExpression(parent)||t.isOptionalCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node}function shouldUnrefMemberAccess(node,parent){if(isThisMemberChain(node)||isUnrefCallArgument(node,parent)||isMemberCallTarget(node,parent))return false;return true}function normalizeJsExpressionWithContext(exp,context,options){const trimmed=exp.trim();if(!trimmed)return null;const normalized=normalizeWxmlExpression(trimmed);const parsed=parseBabelExpressionFile(normalized);if(!parsed){const hint=options?.hint?`${options.hint} `:``;warn(context,`${hint}模板表达式解析失败,已忽略:${exp}`,void 0,`expression`);return null}const{ast}=parsed;const locals=collectScopedSlotLocals(context);const slotProps=context.rewriteScopedSlot?collectSlotPropMapping(context):{};const forAliases=collectForAliasMapping(context);traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;if(path.scope.getBinding(name))return;if(hasOwn(forAliases,name)){const aliasExp=parseBabelExpression(forAliases[name]);if(aliasExp){const replacement=t.cloneNode(aliasExp,true);const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement);return}}if(locals.has(name))return;if(JS_RUNTIME_GLOBALS.has(name))return;if(options?.preserveForItems&&context.forStack.some(forInfo=>{return forInfo.item===name||forInfo.index===name||forInfo.key===name}))return;let replacement;if(context.classStyleBindings?.some(binding=>binding.name===name))replacement=createUnrefCall(createThisMemberAccess(name));else if(context.rewriteScopedSlot){if(hasOwn(slotProps,name)){const prop=slotProps[name];const base=createThisMemberAccess(WEVU_SLOT_PROPS_DATA_KEY);replacement=createUnrefCall(prop?createMemberAccess$1(base,prop):base)}else if(name===WEVU_SLOT_OWNER_KEY||name===WEVU_SLOT_PROPS_DATA_KEY||name===WEVU_SLOT_PROPS_KEY||name===WEVU_SLOT_SCOPE_KEY)replacement=createUnrefCall(createThisMemberAccess(name));else replacement=createUnrefCall(createMemberAccess$1(createThisMemberAccess(WEVU_SLOT_OWNER_PROXY_KEY),name))}else{const propsAlias=context.propsAliases?.[name];replacement=createUnrefCall(propsAlias?createAliasedPropsAccess(name,propsAlias):createIdentifierAccessWithPropsFallback(name,context,options?.runtimePropAccess===`helper`))}const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;path.skip();return}path.replaceWith(replacement);path.skip()}});rewriteForItemAccess(ast,context);if(options?.unrefMemberAccess)traverse(ast,{MemberExpression:{exit(path){if(!shouldUnrefMemberAccess(path.node,path.parentPath?.node))return;path.replaceWith(createUnrefCall(t.cloneNode(path.node,true)));path.skip()}}});const stmt=ast.program.body[0];return(stmt&&`expression`in stmt?stmt.expression:null)||null}const WXML_PARENTHESIZED_MEMBER_RE=/\)\s*(?:\.|\[)/;function buildForIndexAccess$1(context){if(!context.forStack.length)return``;return context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}function hasWxmlParenthesizedMemberAccess(exp){const trimmed=exp.trim();if(!trimmed)return false;return WXML_PARENTHESIZED_MEMBER_RE.test(normalizeWxmlExpression(trimmed))}function shouldFallbackToRuntimeBinding(exp,templateSafeCallNames=/* @__PURE__ */ new Set,context){const trimmed=exp.trim();if(!trimmed)return false;if(hasWxmlParenthesizedMemberAccess(trimmed))return true;const normalized=normalizeWxmlExpression(trimmed);const parsed=parseBabelExpressionFile(normalized);if(!parsed)return false;let shouldFallback=false;const visitor={CallExpression(path){if(path.node.callee.type===`Identifier`&&templateSafeCallNames.has(path.node.callee.name))return;shouldFallback=true;path.stop()},OptionalCallExpression(path){shouldFallback=true;path.stop()},UnaryExpression(path){if(path.node.operator!==`typeof`)return;shouldFallback=true;path.stop()},BigIntLiteral(path){shouldFallback=true;path.stop()}};if(context?.scriptSetupPropConflicts?.length)visitor.Identifier=path=>{const name=path.node.name;if(context.scriptSetupPropConflicts.includes(name)&&path.isReferencedIdentifier()&&!context.scopeStack.some(scope=>scope.has(name))&&!context.slotPropStack.some(scope=>Object.hasOwn(scope,name))&&!path.scope.hasBinding(name)){shouldFallback=true;path.stop()}};traverse(parsed.ast,visitor);return shouldFallback}function normalizeRuntimeBindingReference(exp,context){return normalizeJsExpressionWithContext(exp,{...context,forStack:context.forStack.map(info=>({...info,itemAccess:void 0,itemAliases:info.index&&info.key?{[info.index]:info.key}:void 0}))},{hint:`内部循环绑定`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true})}function registerRuntimeBindingAst(exp,expAst,context){const binding={name:`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`,type:`bind`,exp,expAst,forStack:context.forStack.map(info=>({...info})),conditions:context.bindingConditions?.slice()};context.classStyleBindings.push(binding);return`${binding.name}${buildForIndexAccess$1(context)}`}function registerRuntimeBindingExpression(exp,context,options){const expAst=normalizeJsExpressionWithContext(exp,context,{...options,runtimePropAccess:`helper`,unrefMemberAccess:true});if(!expAst)return null;return registerRuntimeBindingAst(exp,expAst,context)}const predecessors=/* @__PURE__ */ new WeakMap;const resolvedConditions=/* @__PURE__ */ new WeakMap;function collectConditionalBranches(children){let branches=[];for(const child of children){if(child.type===NodeTypes.COMMENT||child.type===NodeTypes.TEXT&&!child.content.trim())continue;if(child.type!==NodeTypes.ELEMENT){branches=[];continue}const directive=child.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&[`if`,`else-if`,`else`].includes(prop.name));if(directive?.name===`if`)branches=[directive];else if(directive){predecessors.set(directive,[...branches]);branches=directive.name===`else`?[]:[...branches,directive]}else branches=[];collectConditionalBranches(child.children)}}function rememberCondition(directive,expression){resolvedConditions.set(directive,expression)}function precedingBranchCondition(directive){const previous=(predecessors.get(directive)??[]).map(branch=>{return resolvedConditions.get(branch)??(branch.exp?.type===NodeTypes.SIMPLE_EXPRESSION?branch.exp.content:`false`)});return previous.length?`!(${previous.map(expression=>`(${expression})`).join(` || `)})`:void 0}function withBindingCondition(context,expression,render){if(!expression)return render();const expAst=normalizeJsExpressionWithContext(expression,context,{hint:`条件分支`,runtimePropAccess:`helper`,unrefMemberAccess:true});if(!expAst)return render();const rawExpAst=context.forStack.some(info=>info.itemAccess)?normalizeJsExpressionWithContext(expression,{...context,forStack:context.forStack.map(info=>({...info,itemAccess:void 0}))},{hint:`条件分支原始项`,runtimePropAccess:`helper`,unrefMemberAccess:true}):void 0;const previous=context.bindingConditions;context.bindingConditions=[...previous??[],{expAst,rawExpAst:rawExpAst??void 0,forDepth:context.forStack.length}];try{return render()}finally{context.bindingConditions=previous}}function resolveConditionalBranch(directive,context){const preceding=precedingBranchCondition(directive);const conditionKind=directive.name;if(conditionKind===`else`)return{conditionKind,condition:void 0,bindingCondition:preceding};const rawExpression=directive.exp?.type===NodeTypes.SIMPLE_EXPRESSION?directive.exp.content:``;const runtimeExpression=withBindingCondition(context,preceding,()=>{return context.rewriteScopedSlot||shouldFallbackToRuntimeBinding(rawExpression,context.templateSafeCallNames,context)?registerRuntimeBindingExpression(rawExpression,context,{hint:`v-${conditionKind}`}):null});const condition=runtimeExpression??normalizeWxmlExpressionWithContext(rawExpression,context);const bindingExpression=runtimeExpression??rawExpression;if(condition){rememberCondition(directive,bindingExpression);recordBindingExpression(context,{kind:`if`,expression:rawExpression,outputPath:runtimeExpression?.split(`[`)[0],sourceLocation:directive.exp?.loc})}return{conditionKind,condition,bindingCondition:preceding?`(${preceding}) && (${bindingExpression})`:bindingExpression}}function tokenizeWxml(source){const tokens=[];let index=0;while(index<source.length){const start=source.indexOf(`<`,index);if(start<0){tokens.push({type:`text`,value:source.slice(index)});break}if(start>index)tokens.push({type:`text`,value:source.slice(index,start)});if(source.startsWith(`<!--`,start)){const commentEnd=source.indexOf(`-->`,start+4);const end=commentEnd<0?source.length:commentEnd+3;tokens.push({type:`comment`,value:source.slice(start,end)});index=end;continue}let quote;let end=start+1;for(;end<source.length;end++){const char=source[end];if(quote){if(char===quote)quote=void 0;continue}if(char===`"`||char===`'`){quote=char;continue}if(char===`>`)break}if(end>=source.length){tokens.push({type:`text`,value:source.slice(start)});break}tokens.push({type:`tag`,value:source.slice(start,end+1)});index=end+1}return tokens.filter(token=>token.value.length>0)}function isClosingTag(value){return/^<\//.test(value)}function isSelfClosingTag(value){return/\/>$/.test(value)||/^<(?:import|include|wxs|sjs)\b/i.test(value)}function isOpeningTag(value){return/^<[^/!][\s\S]*>$/.test(value)&&!isSelfClosingTag(value)}function isWhitespaceText(token){return token.type===`text`&&token.value.trim().length===0}function shouldKeepInline(tokens,openIndex,closeIndex){if(/^<text(?:\s|>)/i.test(tokens[openIndex].value))return true;let depth=0;for(let index=openIndex+1;index<closeIndex;index++){const token=tokens[index];if(token.type===`tag`){if(isClosingTag(token.value))depth-=1;else if(isOpeningTag(token.value))depth+=1}else if(token.type===`text`&&depth===0&&(token.value.trim()||!/[\r\n]/.test(token.value)))return true}return false}function findMatchingClosingTag(tokens,openIndex){const openTag=tokens[openIndex]?.value;const match=/^<([^\s>/]+)/.exec(openTag??``);if(!match)return-1;const tagName=match[1];let depth=0;for(let index=openIndex;index<tokens.length;index++){const token=tokens[index];if(token?.type!==`tag`)continue;if(new RegExp(`^<${tagName}(?:\\s|>|/)`).test(token.value)&&!isSelfClosingTag(token.value)){depth+=1;continue}if(new RegExp(`^</${tagName}>`).test(token.value)){depth-=1;if(depth===0)return index}}return-1}function appendLine(lines,level,value,indent){lines.push(`${indent.repeat(Math.max(level,0))}${value}`)}function formatWxml(source,options={}){const tokens=tokenizeWxml(source);const indent=options.indent??` `;const lines=[];let level=0;let index=0;while(index<tokens.length){const token=tokens[index];if(!token){index+=1;continue}if(token.type===`text`){if(!isWhitespaceText(token))appendLine(lines,level,token.value,indent);index+=1;continue}if(isClosingTag(token.value)){level-=1;appendLine(lines,level,token.value,indent);index+=1;continue}if(isOpeningTag(token.value)){const closeIndex=findMatchingClosingTag(tokens,index);if(closeIndex>index&&shouldKeepInline(tokens,index,closeIndex)){const inline=tokens.slice(index,closeIndex+1).map(item=>item.value).join(``);appendLine(lines,level,inline,indent);index=closeIndex+1;continue}appendLine(lines,level,token.value,indent);level+=1;index+=1;continue}appendLine(lines,level,token.value,indent);index+=1}return`${lines.join(`
|
|
6
|
-
`)}\n`}const DEFAULT_HTML_TO_WXML_TAG_MAP={a:`navigator`,article:`view`,aside:`view`,b:`text`,blockquote:`view`,br:`view`,button:`button`,code:`text`,dd:`view`,div:`view`,dl:`view`,dt:`view`,em:`text`,figcaption:`view`,figure:`view`,footer:`view`,form:`form`,h1:`view`,h2:`view`,h3:`view`,h4:`view`,h5:`view`,h6:`view`,header:`view`,hr:`view`,i:`text`,img:`image`,input:`input`,label:`label`,li:`view`,main:`view`,nav:`view`,ol:`view`,p:`view`,pre:`view`,section:`view`,small:`text`,span:`text`,strong:`text`,table:`view`,tbody:`view`,td:`view`,textarea:`textarea`,tfoot:`view`,th:`view`,thead:`view`,tr:`view`,u:`text`,ul:`view`};function resolveHtmlTagToWxmlMap(value){if(value===false)return;if(value===true||value===void 0)return{...DEFAULT_HTML_TO_WXML_TAG_MAP};return{...DEFAULT_HTML_TO_WXML_TAG_MAP,...Object.fromEntries(Object.entries(value).map(([key,mapped])=>[key.toLowerCase(),mapped]))}}function normalizeTemplateTagName(tag){return tag.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function resolveTemplateTagName(tag,context){if(!tag)return tag;const lowerTag=tag.toLowerCase();if(tag!==lowerTag)return normalizeTemplateTagName(tag);return context.htmlTagToWxmlMap?.[lowerTag]??tag}function resolveMappedHtmlTagClassName(tag,context,resolvedTag){if(!context.htmlTagToWxmlTagClass||!tag)return;const lowerTag=tag.toLowerCase();if(tag!==lowerTag)return;const mappedTag=context.htmlTagToWxmlMap?.[lowerTag];if(!mappedTag||(resolvedTag??mappedTag??tag)===lowerTag)return;return lowerTag}const IDENTIFIER_RE$3=/^[A-Z_$][\w$]*$/i;const WHITESPACE_RE$1=/\s/;const FOR_ITEM_ALIAS_PLACEHOLDER=`__wv_for_item__`;function isIdentifier(value){return IDENTIFIER_RE$3.test(value)}function splitTopLevelByComma(input){const out=[];let start=0;let parenDepth=0;let bracketDepth=0;let braceDepth=0;let quote=``;let escaped=false;for(let i=0;i<input.length;i+=1){const ch=input[i];if(quote){if(escaped){escaped=false;continue}if(ch===`\\`){escaped=true;continue}if(ch===quote)quote=``;continue}if(ch===`'`||ch===`"`||ch==="`"){quote=ch;continue}if(ch===`(`){parenDepth+=1;continue}if(ch===`)`){parenDepth=Math.max(0,parenDepth-1);continue}if(ch===`[`){bracketDepth+=1;continue}if(ch===`]`){bracketDepth=Math.max(0,bracketDepth-1);continue}if(ch===`{`){braceDepth+=1;continue}if(ch===`}`){braceDepth=Math.max(0,braceDepth-1);continue}if(ch===`,`&&parenDepth===0&&bracketDepth===0&&braceDepth===0){out.push(input.slice(start,i).trim());start=i+1}}out.push(input.slice(start).trim());return out}function splitForExpression(exp){let parenDepth=0;let bracketDepth=0;let braceDepth=0;let quote=``;let escaped=false;let emptyAliasSplit=null;for(let i=0;i<exp.length;i+=1){const ch=exp[i];if(quote){if(escaped){escaped=false;continue}if(ch===`\\`){escaped=true;continue}if(ch===quote)quote=``;continue}if(ch===`'`||ch===`"`||ch==="`"){quote=ch;continue}if(ch===`(`){parenDepth+=1;continue}if(ch===`)`){parenDepth=Math.max(0,parenDepth-1);continue}if(ch===`[`){bracketDepth+=1;continue}if(ch===`]`){bracketDepth=Math.max(0,bracketDepth-1);continue}if(ch===`{`){braceDepth+=1;continue}if(ch===`}`){braceDepth=Math.max(0,braceDepth-1);continue}if(parenDepth!==0||bracketDepth!==0||braceDepth!==0)continue;const keyword=exp.startsWith(`in`,i)?`in`:exp.startsWith(`of`,i)?`of`:void 0;if(keyword&&(i===0||WHITESPACE_RE$1.test(exp[i-1]))&&(i+keyword.length===exp.length||WHITESPACE_RE$1.test(exp[i+keyword.length]))){const split={source:exp.slice(0,i).trim(),list:exp.slice(i+keyword.length).trim()};if(split.source)return split;emptyAliasSplit=split}}return emptyAliasSplit}function stripOuterParentheses(value){const trimmed=value.trim();if(!trimmed.startsWith(`(`)||!trimmed.endsWith(`)`))return trimmed;let depth=0;for(let i=0;i<trimmed.length;i+=1){const ch=trimmed[i];if(ch===`(`)depth+=1;else if(ch===`)`){depth-=1;if(depth===0&&i!==trimmed.length-1)return trimmed}}return trimmed.slice(1,-1).trim()}function toMemberAccess(base,property,computed){if(!computed){if(t.isIdentifier(property)&&isIdentifier(property.name))return`${base}.${property.name}`;if(t.isStringLiteral(property))return`${base}[${JSON.stringify(property.value)}]`}if(t.isExpression(property))return`${base}[${generateExpression(property)}]`;return base}function collectPatternAliases(node,base,result){if(t.isIdentifier(node)){result.aliases[node.name]=base;return}if(t.isAssignmentPattern(node)){result.requiresProjection=true;collectPatternAliases(node.left,base,result);return}if(t.isRestElement(node)){if(t.isIdentifier(node.argument))result.aliases[node.argument.name]=base;return}if(t.isArrayPattern(node)){node.elements.forEach((element,index)=>{if(!element)return;if(t.isRestElement(element)){result.requiresProjection=true;collectPatternAliases(element,base,result);return}collectPatternAliases(element,`${base}[${index}]`,result)});return}if(!t.isObjectPattern(node))return;node.properties.forEach(property=>{if(t.isRestElement(property)){result.requiresProjection=true;collectPatternAliases(property,base,result);return}const nextBase=toMemberAccess(base,property.key,property.computed);collectPatternAliases(property.value,nextBase,result)})}function parseItemAliases(pattern){const result={aliases:{},requiresProjection:false};try{const stmt=parseJsLike(`(${pattern}) => {}`).program.body[0];if(!stmt||stmt.type!==`ExpressionStatement`)return{...result,error:`v-for 别名模式无法解析。`};const exp=stmt.expression;if(!t.isArrowFunctionExpression(exp)||exp.params.length!==1)return{...result,error:`v-for 别名模式无法解析。`};const patternNode=exp.params[0];if(t.isRestElement(patternNode))return{...result,error:`v-for 不支持顶层剩余参数;请在数组或对象解构中使用剩余元素。`};collectPatternAliases(patternNode,FOR_ITEM_ALIAS_PLACEHOLDER,result);if(result.requiresProjection)result.aliases=Object.fromEntries(Object.keys(result.aliases).map(name=>[name,`${FOR_ITEM_ALIAS_PLACEHOLDER}.${name}`]));return result}catch{return{...result,error:`v-for 别名模式无法解析。`}}}function parseForExpression(exp){const split=splitForExpression(exp.trim());if(!split)return{error:`v-for 表达式必须使用 in 或 of 分隔别名与列表。`};if(!split.source)return{error:`v-for 表达式缺少循环项别名。`};if(!split.list)return{error:`v-for 表达式缺少列表。`};const segments=splitTopLevelByComma(stripOuterParentheses(split.source)).filter(Boolean);if(segments.length>3)return{listExp:split.list,itemPatternError:`v-for 最多支持 item、key 与 index 三个别名;额外别名无法等价映射到小程序循环作用域。`};const result={listExp:split.list};const rawItem=segments[0]?.trim();if(rawItem){if(isIdentifier(rawItem)&&t.isValidIdentifier(rawItem))result.item=rawItem;else{const parsed=parseItemAliases(rawItem);if(parsed.error)result.itemPatternError=parsed.error;if(Object.keys(parsed.aliases).length){result.item=FOR_ITEM_ALIAS_PLACEHOLDER;result.itemAliases=parsed.aliases;if(parsed.requiresProjection){result.itemPattern=rawItem;result.itemPatternRequiresProjection=true}}}}if(segments.length===2){const rawIndex=segments[1]?.trim();if(rawIndex&&isIdentifier(rawIndex)&&t.isValidIdentifier(rawIndex))result.index=rawIndex;else result.itemPatternError=`v-for 第二个别名必须是标识符;解构形式无法等价映射到小程序循环索引。`}else if(segments.length===3){const rawKey=segments[1]?.trim();const rawIndex=segments[2]?.trim();if(rawKey&&isIdentifier(rawKey)&&t.isValidIdentifier(rawKey)&&rawIndex&&isIdentifier(rawIndex)&&t.isValidIdentifier(rawIndex)){result.key=rawKey;result.index=rawIndex}else result.itemPatternError=`v-for 的 key 与 index 别名必须是标识符;解构形式无法等价映射到小程序循环作用域。`}if(result.itemPatternRequiresProjection&&segments.length===3)result.itemPatternError=`v-for 需要逻辑层投影的解构暂不支持同时声明 key 与 index;无法保证不同列表类型上的等价语义。`;return result}function isStructuralDirective(node){for(const prop of node.props)if(prop.type===NodeTypes.DIRECTIVE){if(prop.name===`if`||prop.name===`else-if`||prop.name===`else`)return{type:`if`,directive:prop};if(prop.name===`for`)return{type:`for`,directive:prop}}return{type:null,directive:void 0}}function pushScope$1(context,names){if(!names.length)return;context.scopeStack.push(new Set(names))}function popScope$1(context){if(context.scopeStack.length)context.scopeStack.pop()}function pushForScope(context,info){if(!info.listExp)return;context.forStack.push({...info})}function popForScope(context){if(context.forStack.length)context.forStack.pop()}function withForScope(context,info,fn){pushForScope(context,info);try{return fn()}finally{popForScope(context)}}function pushSlotProps(context,mapping){if(!Object.keys(mapping).length)return;context.slotPropStack.push(mapping)}function popSlotProps(context){if(context.slotPropStack.length)context.slotPropStack.pop()}function withScope(context,names,fn){pushScope$1(context,names);try{return fn()}finally{popScope$1(context)}}function withSlotProps(context,mapping,fn){pushSlotProps(context,mapping);try{return fn()}finally{popSlotProps(context)}}const IDENTIFIER_RE$2=/^[A-Z_$][\w$]*$/i;const BIND_SHORTHAND_ARG_RE=/^[A-Z_$][\w$]*(?:-[A-Z_$][\w$]*)*$/i;const BACKSLASH_RE$2=/\\/g;const SINGLE_QUOTE_RE$2=/'/g;const CR_RE$1=/\r/g;const LF_RE$1=/\n/g;function camelizeBindShorthandArg(value){return value.replace(/-([\w$])/g,(_,char)=>char.toUpperCase())}function getBindDirectiveExpression(node){const rawExp=node.exp?.type===NodeTypes.SIMPLE_EXPRESSION?node.exp.content:``;if(rawExp)return rawExp;if(node.name!==`bind`||node.arg?.type!==NodeTypes.SIMPLE_EXPRESSION||!node.arg.isStatic)return``;const rawArg=node.arg.content.trim();if(!rawArg||!BIND_SHORTHAND_ARG_RE.test(rawArg))return``;return camelizeBindShorthandArg(rawArg)}function collectScopePropMapping(context){const mapping={};if(!context.slotMultipleInstance)return mapping;const nativeAliases=new Set(context.forStack.flatMap(info=>Object.values(info.nativeAliases??{})));for(const scope of context.scopeStack)for(const name of scope){if(!IDENTIFIER_RE$2.test(name)||nativeAliases.has(name))continue;if(!hasOwn(mapping,name))mapping[name]=name}return mapping}function toWxmlStringLiteral$1(value){return`'${value.replace(BACKSLASH_RE$2,`\\\\`).replace(SINGLE_QUOTE_RE$2,`\\'`).replace(CR_RE$1,`\\r`).replace(LF_RE$1,`\\n`)}'`}function buildScopePropsExpression(context){const mapping=collectScopePropMapping(context);const keys=Object.keys(mapping);if(!keys.length)return null;const renamed=context.forStack.some(info=>info.nativeAliases);return`[${keys.map(key=>{const access=renamed?normalizeWxmlExpressionWithContext(key,context):getForItemAccess(context,key);return`${toWxmlStringLiteral$1(key)},${access}`}).join(`,`)}]`}function hashString(input){let hash=0;for(let i=0;i<input.length;i++){hash=(hash<<5)-hash+input.charCodeAt(i);hash|=0}return Math.abs(hash).toString(36)}function isScopedSlotsDisabled(context){return context.scopedSlotsCompiler===`off`}function findSlotDirective(node){return node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`slot`)}function renderMustache$1(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function createConsoleErrorGuard(message,errorId){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`error`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`error`)),[t.stringLiteral(message),t.cloneNode(errorId)]))]))}function createConsoleWarnGuard(message,item){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`warn`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`warn`)),[t.stringLiteral(message),t.cloneNode(item)]))]))}function createHasOwnPropertyCall(item,field){return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`prototype`)),t.identifier(`hasOwnProperty`)),t.identifier(`call`)),[t.cloneNode(item),t.stringLiteral(field)])}function createSafeKeyExpression(exp,rawExp,seed,item){const errorId=t.identifier(`__wv_for_key_error_${seed}`);const shouldReportError=item?t.binaryExpression(`!=`,t.cloneNode(item),t.nullLiteral()):t.booleanLiteral(true);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(exp,true))]),t.catchClause(errorId,t.blockStatement([t.ifStatement(shouldReportError,t.blockStatement([createConsoleErrorGuard(`[wevu] v-for :key 表达式执行失败: ${rawExp}`,errorId)])),t.returnStatement(t.identifier(`undefined`))])),null)])),[])}function createProjectedItemExpression(item,keyExp,rawKeyExp,keyField,valueField,seed){const isObject=t.logicalExpression(`&&`,t.binaryExpression(`!=`,t.cloneNode(item),t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.cloneNode(item)),t.stringLiteral(`object`)));const projected=t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.ifStatement(t.logicalExpression(`||`,createHasOwnPropertyCall(item,keyField),createHasOwnPropertyCall(item,valueField)),t.blockStatement([createConsoleWarnGuard(`[wevu] v-for :key 内部字段冲突,投影将使用保留字段 ${keyField} / ${valueField}`,item)])),t.returnStatement(t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),t.cloneNode(item),t.objectExpression([t.objectProperty(t.stringLiteral(valueField),t.cloneNode(item)),t.objectProperty(t.stringLiteral(keyField),createSafeKeyExpression(keyExp,rawKeyExp,seed,item))])]))])),[]);const primitiveProjected=t.objectExpression([t.objectProperty(t.stringLiteral(valueField),t.cloneNode(item)),t.objectProperty(t.stringLiteral(keyField),createSafeKeyExpression(keyExp,rawKeyExp,seed,item))]);return t.conditionalExpression(isObject,projected,primitiveProjected)}function createArrayProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const itemId=forInfo.item&&t.isValidIdentifier(forInfo.item)?t.identifier(forInfo.item):t.identifier(`__wv_for_key_item_${seed}`);const indexId=forInfo.index&&t.isValidIdentifier(forInfo.index)?t.identifier(forInfo.index):t.identifier(`__wv_for_key_index_${seed}`);const body=[];if(forInfo.key&&t.isValidIdentifier(forInfo.key)&&forInfo.key!==indexId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.key),t.cloneNode(indexId))]));body.push(t.returnStatement(createProjectedItemExpression(itemId,keyExp,rawKeyExp,keyField,valueField,seed)));return t.callExpression(t.memberExpression(t.cloneNode(sourceId),t.identifier(`map`)),[t.arrowFunctionExpression([itemId,indexId],t.blockStatement(body))])}function createObjectProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const resultId=t.identifier(`__wv_for_key_result_${seed}`);const keysId=t.identifier(`__wv_for_key_keys_${seed}`);const loopIndexId=t.identifier(`__wv_for_key_loop_index_${seed}`);const sourceKeyId=t.identifier(`__wv_for_key_source_key_${seed}`);const sourceItemId=t.identifier(`__wv_for_key_source_item_${seed}`);const body=[t.variableDeclaration(`const`,[t.variableDeclarator(sourceKeyId,t.memberExpression(keysId,loopIndexId,true))]),t.variableDeclaration(`const`,[t.variableDeclarator(sourceItemId,t.memberExpression(sourceId,sourceKeyId,true))])];if(forInfo.item&&t.isValidIdentifier(forInfo.item)&&forInfo.item!==sourceItemId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.item),t.cloneNode(sourceItemId))]));if(forInfo.key&&t.isValidIdentifier(forInfo.key)&&forInfo.key!==sourceKeyId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.key),t.cloneNode(sourceKeyId))]));if(forInfo.index&&t.isValidIdentifier(forInfo.index)){const source=forInfo.key?loopIndexId:sourceKeyId;if(forInfo.index!==source.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.index),t.cloneNode(source))]))}body.push(t.expressionStatement(t.assignmentExpression(`=`,t.memberExpression(resultId,sourceKeyId,true),createProjectedItemExpression(sourceItemId,keyExp,rawKeyExp,keyField,valueField,seed))));return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(resultId,t.objectExpression([]))]),t.variableDeclaration(`const`,[t.variableDeclarator(keysId,t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`keys`)),[t.cloneNode(sourceId)]))]),t.forStatement(t.variableDeclaration(`let`,[t.variableDeclarator(loopIndexId,t.numericLiteral(0))]),t.binaryExpression(`<`,loopIndexId,t.memberExpression(keysId,t.identifier(`length`))),t.updateExpression(`++`,loopIndexId),t.blockStatement(body)),t.returnStatement(resultId)])),[])}function createForKeyProjectionExpression(sourceExp,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const sourceId=t.identifier(`__wv_for_key_source_${seed}`);const objectCheck=t.logicalExpression(`&&`,t.binaryExpression(`!=`,t.cloneNode(sourceId),t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.cloneNode(sourceId)),t.stringLiteral(`object`)));return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(sourceId,t.cloneNode(sourceExp,true))]),t.ifStatement(t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`isArray`)),[t.cloneNode(sourceId)]),t.blockStatement([t.returnStatement(createArrayProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed))])),t.ifStatement(objectCheck,t.blockStatement([t.returnStatement(createObjectProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed))])),t.returnStatement(t.cloneNode(sourceId))])),[])}const SIMPLE_IDENTIFIER_RE$1=/^[A-Z_$][\w$]*$/i;const SIMPLE_MEMBER_PATH_RE=/^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;const RUNTIME_BINDING_REF_RE$1=/^__wv_bind_\d+(?:\[[A-Z_$][\w$]*\])*$/i;function createSourceContext(context){return{...context,forStack:context.forStack.map(forInfo=>({...forInfo,itemAccess:void 0}))}}function hasKnownPrimitiveItems(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp)||t.isBooleanLiteral(exp)||t.isNullLiteral(exp))return true;if(!t.isArrayExpression(exp))return false;return exp.elements.every(element=>{return element==null||t.isStringLiteral(element)||t.isNumericLiteral(element)||t.isBooleanLiteral(element)||t.isNullLiteral(element)})}function resolveItemAliasKeyField(trimmed,forInfo){const aliasExp=forInfo.itemAliases?.[trimmed]?.trim();if(!aliasExp||!forInfo.item||!aliasExp.startsWith(`${forInfo.item}.`))return null;const remainder=aliasExp.slice(forInfo.item.length+1);return SIMPLE_MEMBER_PATH_RE.test(remainder)&&!remainder.includes(`.`)?remainder:null}function resolveNativeForKeyValue(exp,forInfo,keyThisValue){const trimmed=exp.trim();if(!forInfo)return null;if(forInfo.item&&trimmed===forInfo.item||forInfo.key&&trimmed===forInfo.key)return keyThisValue;if(forInfo.item&&trimmed.startsWith(`${forInfo.item}.`)){const remainder=trimmed.slice(forInfo.item.length+1);if(SIMPLE_MEMBER_PATH_RE.test(remainder)&&!remainder.includes(`.`))return remainder;return null}if(SIMPLE_IDENTIFIER_RE$1.test(trimmed)){if(forInfo.index===trimmed)return trimmed;return resolveItemAliasKeyField(trimmed,forInfo)}return null}function createForKeyProjection(node,forInfo,context,nativeKeyValue=resolveNativeForKeyValue(getBindDirectiveExpression(node),forInfo,context.platform.keyThisValue)){const rawKeyExp=getBindDirectiveExpression(node).trim();if(!rawKeyExp||!forInfo.listExp||nativeKeyValue)return null;const listExp=forInfo.listExp?.trim()??``;const projectionContext={...context,forStack:context.forStack.slice(0,-1),scopeStack:context.scopeStack.slice(0,-1)};const sourceContext=createSourceContext(context);const projectionSourceAst=RUNTIME_BINDING_REF_RE$1.test(listExp)?normalizeRuntimeBindingReference(listExp,projectionContext):forInfo.rawListExpAst??forInfo.listExpAst;if(!projectionSourceAst)return null;if(hasKnownPrimitiveItems(projectionSourceAst))return null;const keyExpAst=normalizeJsExpressionWithContext(rawKeyExp,sourceContext,{hint:`v-for :key`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});if(!keyExpAst)return null;const bindingSeed=context.classStyleBindings.filter(binding=>binding.type===`bind`).length;const bindingName=`__wv_bind_${bindingSeed}`;const keyField=`__wv_key_${bindingSeed}`;const valueField=`__wv_value_${bindingSeed}`;const outerForStack=context.forStack.slice(0,-1).map(info=>({...info}));context.classStyleBindings.push({name:bindingName,type:`bind`,exp:`v-for :key ${rawKeyExp}`,expAst:createForKeyProjectionExpression(projectionSourceAst,keyExpAst,rawKeyExp,keyField,valueField,forInfo,bindingSeed),forStack:outerForStack,conditions:context.bindingConditions?.slice()});const indexAccess=outerForStack.map(info=>`[${info.index??`index`}]`).join(``);return{keyAttr:context.platform.keyAttr(keyField),keyField,listExp:`${bindingName}${indexAccess}`,itemAccess:`${forInfo.item}.${valueField}`}}function unwrapTsExpression$3(node){if(node.type===`TSAsExpression`||node.type===`TSNonNullExpression`||node.type===`TSTypeAssertion`)return unwrapTsExpression$3(node.expression);return node}function isTopLevelObjectLiteral(exp){const parsed=parseBabelExpression(exp);if(!parsed)return false;return unwrapTsExpression$3(parsed).type===`ObjectExpression`}function isStaticLiteralNode(node){const normalized=unwrapTsExpression$3(node);if(normalized.type===`StringLiteral`||normalized.type===`NumericLiteral`||normalized.type===`BooleanLiteral`||normalized.type===`NullLiteral`)return true;if(normalized.type===`UnaryExpression`)return(normalized.operator===`-`||normalized.operator===`+`)&&normalized.argument.type===`NumericLiteral`;if(normalized.type===`ArrayExpression`){for(const element of normalized.elements)if(!element||element.type===`SpreadElement`||!isStaticLiteralNode(element))return false;return true}if(normalized.type===`ObjectExpression`){for(const property of normalized.properties){if(property.type!==`ObjectProperty`||property.computed)return false;const value=property.value;if(!t.isExpression(value)||!isStaticLiteralNode(value))return false}return true}return false}function isStaticObjectLiteral(exp){const parsed=parseBabelExpression(exp);if(!parsed)return false;const normalized=unwrapTsExpression$3(parsed);return normalized.type===`ObjectExpression`&&isStaticLiteralNode(normalized)}function createBindRuntimeAttr(argValue,rawExpValue,context){const bindingRef=registerRuntimeBindingExpression(rawExpValue,context,{hint:`:${argValue} 绑定`});if(!bindingRef)return null;return`${argValue}="${renderMustache$1(bindingRef,context)}"`}function createInlineObjectLiteralAttr(argValue,rawExpValue,context){const normalized=normalizeWxmlExpressionWithContext(rawExpValue,context).trim();const parsed=parseBabelExpression(normalized);const expValue=parsed?generateExpression(parsed):normalized;if(context.mustacheInterpolation===`spaced`)return`${argValue}="${renderMustache$1(expValue,context)}"`;return`${argValue}="{{ ${expValue} }}"`}const COMPONENT_NON_PROP_BINDINGS=/* @__PURE__ */ new Set([`class`,`style`,`id`,`key`,`ref`,`is`,`slot`,`layout-host`]);function collectFunctionPropPath(rawExpValue){const parsed=parseBabelExpression(rawExpValue);if(!parsed)return null;const normalized=unwrapTsExpression$3(parsed);if(normalized.type===`Identifier`)return normalized.name;if(normalized.type!==`MemberExpression`||normalized.computed)return null;const parts=[];let current=normalized;while(current.type===`MemberExpression`&&!current.computed){if(current.property.type!==`Identifier`)return null;parts.unshift(current.property.name);current=unwrapTsExpression$3(current.object)}if(current.type!==`Identifier`)return null;parts.unshift(current.name);return parts.join(`.`)}function isComputedMemberExpression(rawExpValue){const parsed=parseBabelExpression(rawExpValue);if(!parsed)return false;const normalized=unwrapTsExpression$3(parsed);return normalized.type===`MemberExpression`&&normalized.computed}function shouldUseRuntimeFunctionPropBinding(argValue,context){return context.functionPropNames.some(matcher=>{if(typeof matcher===`string`)return matcher===argValue;matcher.lastIndex=0;return matcher.test(argValue)})}function shouldWrapStaticMemberFunctionProp(argValue,path,context){return path.includes(`.`)&&shouldUseRuntimeFunctionPropBinding(argValue,context)}function createFunctionPropRuntimeAttr(argValue,rawExpValue,context){const bindingRef=registerRuntimeBindingExpression(rawExpValue,context,{hint:`:${argValue} 函数 prop 绑定`});if(!bindingRef)return null;const bindingName=bindingRef.split(`[`)[0]||bindingRef;context.functionPropPaths.add(bindingName);return`${argValue}="${renderMustache$1(bindingRef,context)}"`}function rejectUnsupportedDynamicBindName(node,context){const{arg}=node;if(arg?.type!==NodeTypes.SIMPLE_EXPRESSION||arg.isStatic)return false;warn(context,`小程序模板暂不支持动态 v-bind 参数名,已忽略该绑定。`,node.loc);return true}function transformBindDirective(node,context,forInfo,options){const{arg,exp}=node;if(!arg){if(exp?.type===NodeTypes.SIMPLE_EXPRESSION&&exp.content.trim())warn(context,`小程序暂不支持对象形式 v-bind,已忽略该对象绑定;请改用显式属性绑定。`,node.loc);else warn(context,`v-bind 缺少对象绑定表达式。`,node.loc,`template`,`WV2001`);return null}if(rejectUnsupportedDynamicBindName(node,context))return null;const argValue=arg.type===NodeTypes.SIMPLE_EXPRESSION?arg.content:``;const outputArgValue=options?.isComponent?normalizeComponentHostName(argValue):argValue;const rawExpValue=getBindDirectiveExpression(node);if(!rawExpValue)return null;if(options?.isComponent&&!COMPONENT_NON_PROP_BINDINGS.has(argValue)){const path=collectFunctionPropPath(rawExpValue);if(path){if(shouldWrapStaticMemberFunctionProp(argValue,path,context)){const runtimeAttr=createFunctionPropRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}else context.functionPropPaths.add(path)}else if(shouldUseRuntimeFunctionPropBinding(argValue,context)&&isComputedMemberExpression(rawExpValue)){const runtimeAttr=createFunctionPropRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}}if(argValue===`key`){const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);const trimmed=expValue.trim();const nativeKeyValue=resolveNativeForKeyValue(trimmed,forInfo,context.platform.keyThisValue);if(nativeKeyValue)return context.platform.keyAttr(nativeKeyValue);if(forInfo){warn(context,`v-for :key "${trimmed}" 无法生成运行时 key 投影,已降级为 ${context.platform.keyAttr(context.platform.keyThisValue)}。建议使用稳定的基础类型 key。`,node.loc);return context.platform.keyAttr(context.platform.keyThisValue)}return context.platform.keyAttr(expValue)}if(isTopLevelObjectLiteral(rawExpValue)){if(context.objectLiteralBindMode===`inline`||isStaticObjectLiteral(rawExpValue))return createInlineObjectLiteralAttr(outputArgValue,rawExpValue,context);return createBindRuntimeAttr(outputArgValue,rawExpValue,context)}if(shouldFallbackToRuntimeBinding(rawExpValue,context.templateSafeCallNames,context)){const runtimeAttr=createBindRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);return`${outputArgValue}="${renderMustache$1(expValue,context)}"`}const IDENTIFIER_RE$1=/^[a-z_$][\w$]*$/i;function transformCustomDirective(name,exp,arg,context,location){if((/* @__PURE__ */ new Set([`bind`,`on`,`model`,`show`,`html`,`text`,`if`,`else-if`,`else`,`for`,`slot`,`cloak`,`once`])).has(name))return null;const dataAttrName=`data-v-${name}`;if(exp&&exp.type===NodeTypes.SIMPLE_EXPRESSION){recordBindingExpression(context,{kind:`attribute`,expression:exp.content,sourceLocation:exp.loc});const expValue=normalizeWxmlExpressionWithContext(exp.content,context);if(IDENTIFIER_RE$1.test(expValue))return`${dataAttrName}="${renderMustache$1(expValue,context)}"`;return`${dataAttrName}="${renderMustache$1(expValue,context)}"`}if(arg&&arg.type===NodeTypes.SIMPLE_EXPRESSION)return`${dataAttrName}="${arg.content}"`;warn(context,`自定义指令 v-${name} 可能需要运行时支持。已生成 data 属性:${dataAttrName}`,location);return dataAttrName}function getElementType(element){if(!element)return``;for(const prop of element.props)if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`type`){if(prop.value&&prop.value.type===NodeTypes.TEXT)return prop.value.content}return``}const CAMELIZE_RE=/-([a-z0-9])/gi;const IDENTIFIER_RE=/^[A-Z_$][\w$]*$/i;const NATIVE_MODEL_TAGS=/* @__PURE__ */ new Set([`input`,`textarea`,`select`,`switch`,`checkbox`,`slider`,`picker`]);function camelize(value){return value.replace(CAMELIZE_RE,(_,char)=>char.toUpperCase())}function isNativeModelElement(element){if(!element||element.tag!==element.tag.toLowerCase())return false;return NATIVE_MODEL_TAGS.has(element.tag)}function transformVModel(element,expValue,context,location){const escapedModel=escapeWxmlAttribute(expValue);const bindModel=event=>{return`${context.platform.eventBindingAttr(event)}="${WEVU_MODEL_HANDLER}" data-wv-model="${escapedModel}"`};if(!element)return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`;const tag=element.tag;const typeAttr=getElementType(element);switch(tag){case`input`:switch(typeAttr){case`checkbox`:return`checked="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`radio`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;default:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`}case`textarea`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`;case`select`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`switch`:case`checkbox`:return`checked="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`slider`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`picker`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;default:warn(context,`在 <${tag}> 上使用 v-model 可能无法按预期工作,已使用默认绑定。`,location);return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`}}function transformComponentModelDirective(node,context){const rawExpValue=getBindDirectiveExpression(node).trim();if(!rawExpValue)return null;const rawModelName=node.arg?.type===NodeTypes.SIMPLE_EXPRESSION?node.arg.content.trim():``;if(node.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&!node.arg.isStatic){warn(context,`暂不支持动态 v-model 参数,已忽略该 v-model。`,node.loc);return null}const modelProp=rawModelName||`modelValue`;if(!modelProp)return null;const updateEvent=`update:${camelize(modelProp)}`;const eventSuffix=normalizeEventDatasetSuffix(updateEvent);const bindAttr=context.platform.eventBindingAttr(updateEvent);const updateExpression=IDENTIFIER_RE.test(rawExpValue)?`this.${rawExpValue} = $event`:`${rawExpValue} = $event`;const inlineExpression=registerInlineExpression$1(updateExpression,context);if(!inlineExpression){warn(context,`v-model="${rawExpValue}" 需要是可赋值的成员表达式。`,node.loc,`expression`);return null}const modelAttr=modelProp===`modelValue`?`model-value="${renderMustache$1(normalizeWxmlExpressionWithContext(rawExpValue,context),context)}"`:transformBindDirective(node,context,void 0,{isComponent:true});const updateAttr=[`data-${`wd`}-${eventSuffix}="1"`,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `);const modifierNames=node.modifiers.map(modifier=>modifier.content.trim()).filter(Boolean);const modifierProperties=modifierNames.map(name=>`${JSON.stringify(name)}:true`).join(`,`);const modifiersProp=normalizeComponentHostName(modelProp===`modelValue`?`modelModifiers`:`${modelProp}Modifiers`);const modifiersRef=modifierNames.length?registerRuntimeBindingExpression(`{${modifierProperties}}`,context,{hint:`v-model modifiers`}):null;if(modifiersRef)recordBindingExpression(context,{kind:`component-prop`,expression:`{${modifierProperties}}`,outputPath:modifiersRef.split(`[`)[0],sourceLocation:node.loc});return[modelAttr,updateAttr,modifiersRef?`${modifiersProp}="${renderMustache$1(modifiersRef,context)}"`:null].filter(Boolean).join(` `)}function transformModelDirective(node,context,elementNode,options){const{exp}=node;if(!exp)return null;if(options?.isComponent===true&&!isNativeModelElement(elementNode))return transformComponentModelDirective(node,context);if(node.arg){warn(context,`原生小程序元素不支持 v-model 参数,已忽略该 v-model。`,node.loc);return null}const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content:``;return transformVModel(elementNode,normalizeWxmlExpressionWithContext(rawExpValue,context),context,node.loc)}const SIMPLE_IDENTIFIER_RE=/^[A-Z_$][\w$]*$/i;const isSimpleHandler=value=>SIMPLE_IDENTIFIER_RE.test(value);function isScriptSetupHandlerBinding(value,context){return isSimpleHandler(value)&&Boolean(context.scriptSetupBindings?.[value])}function shouldUseDetailPayload(options){return options?.isComponent===true}function buildInlineScopeAttrs(scopeBindings,context){return scopeBindings.map((binding,index)=>{const escaped=escapeWxmlAttribute(binding);return`data-wv-s${index}="${renderMustache$1(escaped,context)}"`})}function buildInlineIndexAttrs(indexBindings,context){return indexBindings.map((binding,index)=>{const escaped=escapeWxmlAttribute(binding);return`data-wv-i${index}="${renderMustache$1(escaped,context)}"`})}function resolveEventPrefix(modifiers){const hasCatch=modifiers.some(modifier=>modifier.content===`catch`);const hasStop=modifiers.some(modifier=>modifier.content===`stop`);const hasCapture=modifiers.some(modifier=>modifier.content===`capture`);const hasMut=modifiers.some(modifier=>modifier.content===`mut`);if((hasCatch||hasStop)&&hasCapture)return`capture-catch`;if(hasCatch||hasStop)return`catch`;if(hasMut)return`mut-bind`;if(hasCapture)return`capture-bind`;return`bind`}function rejectUnsupportedDynamicOnName(node,context){const{arg}=node;if(arg?.type!==NodeTypes.SIMPLE_EXPRESSION||arg.isStatic)return false;warn(context,`小程序模板暂不支持动态 v-on 参数名,已忽略该事件绑定。`,node.loc);return true}function transformOnDirective(node,context,options){const{exp,arg}=node;if(!arg){if(exp?.type===NodeTypes.SIMPLE_EXPRESSION&&exp.content.trim())warn(context,`小程序暂不支持对象形式 v-on,已忽略该对象监听;请改用显式事件绑定。`,node.loc);else warn(context,`v-on 缺少对象监听表达式。`,node.loc,`template`,`WV2001`);return null}if(rejectUnsupportedDynamicOnName(node,context))return null;const argValue=arg.type===NodeTypes.SIMPLE_EXPRESSION?arg.content:``;if(!exp)return null;const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content.trim():``;const useDetailPayload=shouldUseDetailPayload(options);const inlineSource=(useDetailPayload||isScriptSetupHandlerBinding(rawExpValue,context))&&isSimpleHandler(rawExpValue)?`${rawExpValue}($event)`:rawExpValue;const isInlineExpression=inlineSource&&!isSimpleHandler(inlineSource);const inlineExpression=isInlineExpression?registerInlineExpression$1(inlineSource,context):null;const mappedEvent=options?.isComponent===true?argValue:context.platform.mapEventName(argValue);const eventSuffix=normalizeEventDatasetSuffix(mappedEvent);const eventPrefix=resolveEventPrefix(node.modifiers);const bindAttr=eventPrefix===`bind`&&options?.isComponent!==true?context.platform.eventBindingAlias?.(argValue,options?.tagName)??context.platform.eventBindingAttr(`${eventPrefix}:${mappedEvent}`):context.platform.eventBindingAttr(`${eventPrefix}:${mappedEvent}`);const detailAttr=useDetailPayload?`data-${`wd`}-${eventSuffix}="1"`:``;if(context.rewriteScopedSlot){if(inlineExpression){const scopeAttrs=buildInlineScopeAttrs(inlineExpression.scopeBindings,context);const indexAttrs=buildInlineIndexAttrs(inlineExpression.indexBindings,context);return[detailAttr,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,...scopeAttrs,...indexAttrs,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `)}if(!isInlineExpression&&rawExpValue)return[detailAttr,`data-${`wh`}-${eventSuffix}="${rawExpValue}"`,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `);if(isInlineExpression){warn(context,`作用域插槽的事件处理解析失败,请使用简单的方法引用。`,node.loc,`expression`);return[detailAttr,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `)}}const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);if(inlineExpression){const scopeAttrs=buildInlineScopeAttrs(inlineExpression.scopeBindings,context);const indexAttrs=buildInlineIndexAttrs(inlineExpression.indexBindings,context);return[detailAttr,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,...scopeAttrs,...indexAttrs,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `)}if(isInlineExpression)return[detailAttr,`data-wv-inline-${eventSuffix}="${escapeWxmlAttribute(inlineSource)}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `);return[detailAttr,`${bindAttr}="${expValue}"`].filter(Boolean).join(` `)}function transformShowDirective(node,context){const{exp}=node;if(!exp)return null;const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content:``;const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);return`style="${renderMustache$1(`${expValue} ? '' : 'display: none'`,context)}"`}function omitUnsupportedDynamicDirectiveNames(node,context){let compatibleProps;for(let index=0;index<node.props.length;index++){const prop=node.props[index];if(prop.type===NodeTypes.DIRECTIVE&&(prop.name===`bind`&&rejectUnsupportedDynamicBindName(prop,context)||prop.name===`on`&&rejectUnsupportedDynamicOnName(prop,context))){compatibleProps??=node.props.slice(0,index);continue}compatibleProps?.push(prop)}return compatibleProps?{...node,props:compatibleProps}:node}function transformDirective(node,context,elementNode,forInfo,options){const{name,exp,arg}=node;if(name===`bind`)return transformBindDirective(node,context,forInfo,options);if(name===`on`)return transformOnDirective(node,context,{...options,tagName:elementNode?.tag});if(name===`model`)return transformModelDirective(node,context,elementNode,options);if(name===`show`)return transformShowDirective(node,context);if(name===`html`){warn(context,`小程序不支持 v-html,请使用 rich-text 组件替代。`,node.loc);return null}if(name===`cloak`)return null;if(name===`once`){warn(context,`小程序对 v-once 支持不完整,元素将按普通方式渲染。`,node.loc);return null}return transformCustomDirective(name,exp,arg,context,node.loc)}function usesNativeDeclarationContext(context){return context.nativeSlotContext===true&&context.platform.name===`wechat`&&context.platform.nativeSlotContext!==false&&context.scopedSlotsRequireProps}function normalizeNativeForAliases(info,context){if(!usesNativeDeclarationContext(context)||!(context.nativeSlotContextTags??context.wevuComponentTags)?.size)return;const outerNames=new Set(context.forStack.flatMap(scope=>[scope.item,scope.index,scope.key,...Object.keys(scope.itemAliases??{})]));const aliases={};for(const key of[`item`,`index`,`key`]){const name=info[key];if(!name||!outerNames.has(name)&&!INLINE_GLOBALS.has(name))continue;let replacement;do replacement=`__wv_native_${key}_${context.forIndexSeed++}`;while(context.source.includes(replacement));aliases[name]=replacement;info[key]=replacement}if(!Object.keys(aliases).length)return;const itemAliases={};for(const[name,expression]of Object.entries(info.itemAliases??{})){const parsed=parseBabelExpressionFile(expression);if(!parsed)continue;traverse(parsed.ast,{Identifier(path){const replacement=aliases[path.node.name];if(replacement&&path.isReferencedIdentifier()&&!path.scope.getBinding(path.node.name)){path.replaceWith(t.identifier(replacement));path.skip()}}});const statement=parsed.ast.program.body[0];if(t.isExpressionStatement(statement))itemAliases[name]=generateExpression(statement.expression)}info.nativeAliases=aliases;info.itemAliases={...itemAliases,...aliases}}function createLoopIdentity(info){const key=info.effectiveNativeKey;if(!key||key.kind===`position`)return t.identifier(info.key??info.index??`index`);const item=t.identifier(info.item??`item`);const value=key.kind===`self`?item:t.memberExpression(item,t.stringLiteral(key.field),true);return t.callExpression(t.identifier(`String`),[t.logicalExpression(`??`,value,t.stringLiteral(``))])}function createNativeDeclaration(node,context){if(!usesNativeDeclarationContext(context)||!(context.nativeSlotContextTags??context.wevuComponentTags)?.has(node.tag))return;const site=`s${node.loc.start.offset}`;let keyExpression=`'${site}'`;if(context.forStack.length){const expression=t.callExpression(t.memberExpression(t.identifier(`JSON`),t.identifier(`stringify`)),[t.arrayExpression([t.stringLiteral(site),...context.forStack.map(createLoopIdentity)])]);keyExpression=registerRuntimeBindingAst(`native declaration ${site}`,expression,context);const outputPath=keyExpression.split(`[`)[0];recordBindingExpression({...context,rewriteScopedSlot:false},{kind:`component-prop`,expression:outputPath,outputPath,sourceLocation:node.loc})}return{site,loopDepth:context.forStack.length,keyExpression}}function appendNativeDeclarationAttributes(attrs,declaration,context){const parent=context.nativeDeclarationStack.at(-1)?.keyExpression??`''`;attrs.push(`${WEVU_NATIVE_DECLARATION_ADDRESS_PROP}="${renderMustache$1(`[${declaration.keyExpression},${parent}]`,context)}"`);attrs.push(`bind:${WEVU_NATIVE_DECLARATION_EVENT}="${WEVU_NATIVE_DECLARATION_METHOD}"`)}function nativeSlotParentAttribute(context){const parent=context.nativeDeclarationStack.at(-1)?.keyExpression;return`${WEVU_NATIVE_SLOT_PARENT_DATASET_ATTR}="${parent?renderMustache$1(parent,context):``}"`}function withNativeDeclarationScope(context,declaration,render){if(!declaration)return render();context.nativeDeclarationStack.push(declaration);try{return render()}finally{context.nativeDeclarationStack.pop()}}const BACKSLASH_RE$1=/\\/g;const SINGLE_QUOTE_RE$1=/'/g;const CR_RE=/\r/g;const LF_RE=/\n/g;function toWxmlStringLiteral(value){return`'${value.replace(BACKSLASH_RE$1,`\\\\`).replace(SINGLE_QUOTE_RE$1,`\\'`).replace(CR_RE,`\\r`).replace(LF_RE,`\\n`)}'`}function cloneForStack(context){return context.forStack.map(info=>({...info}))}function buildForIndexAccess(context){if(!context.forStack.length)return``;return context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}function generateExpressionCode(exp){const{code}=generate(exp,{compact:true});return code}const TRAILING_SEMICOLONS_RE=/;+\s*$/;function normalizeStyleFallbackValue(value){return value.trim().replace(TRAILING_SEMICOLONS_RE,``)}function buildStyleErrorFallback(staticValue,shouldHideByDefault){const segments=[];if(staticValue?.trim())segments.push(normalizeStyleFallbackValue(staticValue));if(shouldHideByDefault)segments.push(`display: none`);return segments.join(`;`)}function mergeJsExpressionParts(parts){if(!parts.length)return t.stringLiteral(``);if(parts.length===1)return parts[0];return t.arrayExpression(parts)}function unwrapTsExpression$2(node){if(t.isTSAsExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node))return unwrapTsExpression$2(node.expression);return node}function shouldPreferJsClassStyleRuntime(exp){const ast=parseBabelExpression(exp);if(!ast)return true;const visit=node=>{const current=unwrapTsExpression$2(node);if(t.isIdentifier(current)||t.isMemberExpression(current)||t.isOptionalMemberExpression(current)||t.isCallExpression(current)||t.isOptionalCallExpression(current)||t.isThisExpression(current)||t.isSuper(current)||t.isAwaitExpression(current)||t.isYieldExpression(current)||t.isNewExpression(current))return true;if(t.isStringLiteral(current)||t.isNumericLiteral(current)||t.isBooleanLiteral(current)||t.isNullLiteral(current)||t.isBigIntLiteral(current)||t.isRegExpLiteral(current))return false;if(t.isTemplateLiteral(current))return current.expressions.some(exp=>visit(exp));if(t.isArrayExpression(current)){for(const element of current.elements){if(!element||t.isSpreadElement(element))return true;if(visit(element))return true}return false}if(t.isObjectExpression(current)){for(const property of current.properties)if(t.isSpreadElement(property)||!t.isObjectProperty(property))return true;return false}if(t.isConditionalExpression(current))return visit(current.test)||visit(current.consequent)||visit(current.alternate);if(t.isLogicalExpression(current)||t.isBinaryExpression(current)){if(t.isPrivateName(current.left)||t.isPrivateName(current.right))return true;return visit(current.left)||visit(current.right)}if(t.isUnaryExpression(current))return visit(current.argument);return true};return visit(ast)}function createClassStyleBinding(context,type,exp,expAst,errorFallback){const sameTypeCount=context.classStyleBindings.filter(binding=>binding.type===type).length;const binding={name:type===`class`?`__wv_cls_${sameTypeCount}`:type===`style`?`__wv_style_${sameTypeCount}`:`__wv_bind_${sameTypeCount}`,type,exp,expAst,forStack:cloneForStack(context),conditions:context.bindingConditions?.slice()};if(errorFallback!==void 0)binding.errorFallback=errorFallback;return binding}function renderClassAttribute(staticClass,dynamicClassExp,context){const staticValue=staticClass?.trim();if(!dynamicClassExp)return staticValue?`class="${staticValue}"`:void 0;const parts=[];if(staticValue)parts.push(toWxmlStringLiteral(staticValue));if(context.classStyleRuntime===`wxs`&&!shouldPreferJsClassStyleRuntime(dynamicClassExp)){const normalizedParts=normalizeClassBindingExpression(dynamicClassExp,context);for(const part of normalizedParts)parts.push(`(${part})`);const mergedExp=parts.length>1?`[${parts.join(`,`)}]`:parts[0];context.classStyleWxs=true;return`class="${renderMustache$1(`${WEVU_CLASS_STYLE_RUNTIME_MODULE}.cls(${mergedExp})`,context)}"`}const jsParts=[];if(staticValue)jsParts.push(t.stringLiteral(staticValue));const dynamicAst=normalizeJsExpressionWithContext(dynamicClassExp,context,{hint:`class 绑定`,runtimePropAccess:`helper`});if(dynamicAst)jsParts.push(dynamicAst);const expAst=mergeJsExpressionParts(jsParts);const binding=createClassStyleBinding(context,`class`,generateExpressionCode(expAst),expAst,staticValue??``);context.classStyleBindings.push(binding);const indexAccess=buildForIndexAccess(context);return`class="${renderMustache$1(`${binding.name}${indexAccess}`,context)}"`}function renderStyleAttribute(staticStyle,dynamicStyleExp,vShowExp,context){const staticValue=staticStyle?.trim();if(!Boolean(dynamicStyleExp||vShowExp))return staticValue?`style="${staticValue}"`:void 0;const parts=[];if(staticValue)parts.push(toWxmlStringLiteral(staticValue));if(context.classStyleRuntime===`wxs`&&(!dynamicStyleExp||!shouldPreferJsClassStyleRuntime(dynamicStyleExp))){if(dynamicStyleExp){const normalizedParts=normalizeStyleBindingExpression(dynamicStyleExp,context);for(const part of normalizedParts)parts.push(`(${part})`)}if(vShowExp){const normalizedShow=normalizeWxmlExpressionWithContext(vShowExp,context);parts.push(`(${normalizedShow}) ? '' : 'display: none'`)}const mergedExp=parts.length>1?`[${parts.join(`,`)}]`:parts[0]||`''`;context.classStyleWxs=true;return`style="${renderMustache$1(`${WEVU_CLASS_STYLE_RUNTIME_MODULE}.style(${mergedExp})`,context)}"`}const jsParts=[];if(staticValue)jsParts.push(t.stringLiteral(staticValue));if(dynamicStyleExp){const dynamicAst=normalizeJsExpressionWithContext(dynamicStyleExp,context,{hint:`style 绑定`,runtimePropAccess:`helper`});if(dynamicAst)jsParts.push(dynamicAst)}if(vShowExp){const showAst=normalizeJsExpressionWithContext(vShowExp,context,{hint:`v-show`,runtimePropAccess:`helper`});if(showAst)jsParts.push(t.conditionalExpression(showAst,t.stringLiteral(``),t.stringLiteral(`display: none`)))}const expAst=mergeJsExpressionParts(jsParts);const binding=createClassStyleBinding(context,`style`,generateExpressionCode(expAst),expAst,buildStyleErrorFallback(staticValue,Boolean(vShowExp)));context.classStyleBindings.push(binding);const indexAccess=buildForIndexAccess(context);return`style="${renderMustache$1(`${binding.name}${indexAccess}`,context)}"`}function normalizeNativeAttributeValue(value,context){if(!usesNativeDeclarationContext(context)||!value.includes(`{{`)||!context.forStack.some(info=>info.itemAliases||info.itemAccess))return value;return value.replace(/\{\{([\s\S]+?)\}\}/g,(_match,expression)=>{return renderMustache$1(normalizeWxmlExpressionWithContext(expression,context),context)})}function transformAttribute(node,context,nameOverride){const{value}=node;const name=nameOverride??node.name;if(!value)return name;if(value.type===NodeTypes.TEXT){const content=node.name===context.platform.directives.forAttr?value.content:normalizeNativeAttributeValue(value.content,context);return`${name}="${escapeWxmlAttribute(content)}"`}return`${name}=""`}const builtinTagSet=new Set(components.map(tag=>tag.toLowerCase()));const MUSTACHE_EXPRESSION_RE$1=/\{\{([\s\S]*?)\}\}/g;function recordStaticAttributeBindings(prop,context,isComponentElement){const value=prop.value?.content;if(!value?.includes(`{{`))return;if(prop.name===WEVU_SLOT_OWNER_ID_ATTR)context.bindingManifest.features.scopedSlots=true;let kind=isComponentElement?`component-prop`:`attribute`;if(prop.name===context.platform.directives.forAttr)kind=`for`;else if(prop.name===context.platform.directives.ifAttr||prop.name===context.platform.directives.elifAttr)kind=`if`;else if(prop.name===`class`)kind=`class`;else if(prop.name===`style`)kind=`style`;for(const match of value.matchAll(MUSTACHE_EXPRESSION_RE$1)){const expression=match[1]?.trim();if(!expression)continue;recordBindingExpression(context,{kind,expression,sourceLocation:prop.value?.loc})}}function isBuiltinTag(tag){return builtinTagSet.has(tag.toLowerCase())}function prependStaticClass(staticClass,className){const tokens=staticClass?.split(/\s+/).filter(Boolean)??[];if(!tokens.includes(className))tokens.unshift(className);return tokens.join(` `)}function collectElementAttributes(node,context,options){const{props}=node;const resolvedTag=options?.resolvedTag??resolveTemplateTagName(node.tag,context);const isComponentElement=options?.isComponent??!isBuiltinTag(resolvedTag);const attrs=options?.extraAttrs?[...options.extraAttrs]:[];const declaration=isComponentElement?createNativeDeclaration(node,context):void 0;if(declaration){appendNativeDeclarationAttributes(attrs,declaration,context);attrs.push(`bind:${WEVU_NATIVE_SLOT_PARENT_EVENT}="${WEVU_NATIVE_SLOT_PARENT_METHOD}"`)}if(context.scopeId)attrs.push(`${context.scopeId}=""`);const mappedTagClass=resolveMappedHtmlTagClassName(node.tag,context,resolvedTag);let staticClass;let staticId;let dynamicClassExp;let dynamicClassLocation;let staticStyle;let dynamicStyleExp;let dynamicStyleLocation;let vShowExp;let vShowLocation;let vTextExp;let templateRef;let layoutHostKey;let hasDynamicIdBinding=false;const inFor=Boolean(options?.forInfo||context.forStack.length);for(const prop of props){if(prop.type===NodeTypes.ATTRIBUTE){recordStaticAttributeBindings(prop,context,isComponentElement);if(prop.name===`layout-host`){const rawKey=prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():``;if(!isComponentElement)warn(context,`layout-host 仅支持声明在组件节点上,当前节点已忽略。`,prop.loc);else if(!rawKey)warn(context,`layout-host 需要提供非空字符串 key。`,prop.loc);else layoutHostKey=rawKey;continue}if(prop.name===`slot-wrapper`||prop.name.startsWith(`slot-wrapper-`)||prop.name.startsWith(`slot-wrapper:`)||prop.name===`slot-single-root-no-wrapper`||prop.name.startsWith(`slot-single-root-no-wrapper-`)||prop.name.startsWith(`slot-single-root-no-wrapper:`))continue;if(prop.name===`ref`){if(prop.value?.type===NodeTypes.TEXT){const name=prop.value.content.trim();if(name)templateRef={name}}continue}if(prop.name===`class`&&prop.value?.type===NodeTypes.TEXT){staticClass=normalizeNativeAttributeValue(prop.value.content,context);continue}if(prop.name===`id`&&prop.value?.type===NodeTypes.TEXT){staticId=normalizeNativeAttributeValue(prop.value.content.trim(),context);continue}if(prop.name===`style`&&prop.value?.type===NodeTypes.TEXT){staticStyle=normalizeNativeAttributeValue(prop.value.content,context);continue}const attr=transformAttribute(prop,context,isComponentElement?normalizeComponentHostName(prop.name):void 0);if(attr)attrs.push(attr);continue}if(prop.type===NodeTypes.DIRECTIVE){if(options?.skipSlotDirective&&prop.name===`slot`)continue;if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`ref`){const rawExp=getBindDirectiveExpression(prop);if(rawExp){const expAst=normalizeJsExpressionWithContext(rawExp,context,{hint:`ref 绑定`});if(expAst)templateRef={expAst}}continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`id`)hasDynamicIdBinding=true;if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`layout-host`){warn(context,`暂不支持动态 layout-host,已忽略该绑定。`,prop.loc);continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&(prop.arg.content===`slot-wrapper`||prop.arg.content.startsWith(`slot-wrapper-`)||prop.arg.content.startsWith(`slot-wrapper:`)||prop.arg.content===`slot-single-root-no-wrapper`||prop.arg.content.startsWith(`slot-single-root-no-wrapper-`)||prop.arg.content.startsWith(`slot-single-root-no-wrapper:`))){if(prop.arg.content.endsWith(`-class`)||prop.arg.content.endsWith(`:class`)||prop.arg.content.endsWith(`-style`)||prop.arg.content.endsWith(`:style`))continue;warn(context,`暂不支持动态 ${prop.arg.content},已忽略该绑定。`,prop.loc);continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`class`){dynamicClassExp=getBindDirectiveExpression(prop)||void 0;dynamicClassLocation=prop.exp?.loc??prop.loc;continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`style`){dynamicStyleExp=getBindDirectiveExpression(prop)||void 0;dynamicStyleLocation=prop.exp?.loc??prop.loc;continue}if(prop.name===`show`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){vShowExp=prop.exp.content;vShowLocation=prop.exp.loc;continue}if(prop.name===`text`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){const rawExp=prop.exp.content;const runtimeExp=shouldFallbackToRuntimeBinding(rawExp,context.templateSafeCallNames,context)?registerRuntimeBindingExpression(rawExp,context,{hint:`v-text`}):null;vTextExp=runtimeExp??normalizeWxmlExpressionWithContext(rawExp,context);recordBindingExpression(context,{kind:`text`,expression:rawExp,outputPath:runtimeExp?.split(`[`)[0],sourceLocation:prop.exp.loc});continue}const bindingCount=context.classStyleBindings.length;const functionPropCount=context.functionPropPaths.size;const inlineExpressionCount=context.inlineExpressions.length;const dir=transformDirective(prop,context,node,options?.forInfo,{isComponent:isComponentElement});if(prop.name===`bind`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){const arg=prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION?prop.arg.content:``;if(arg&&arg!==`ref`&&arg!==`class`&&arg!==`style`&&arg!==`key`&&arg!==`layout-host`){const generatedBinding=context.classStyleBindings.slice(bindingCount).find(binding=>binding.type===`bind`);recordBindingExpression(context,{kind:isComponentElement?`component-prop`:`attribute`,expression:getBindDirectiveExpression(prop),outputPath:generatedBinding?.name,sourceLocation:prop.exp.loc})}}else if(prop.name===`model`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){context.bindingManifest.features.model=true;recordBindingExpression(context,{kind:isComponentElement?`component-prop`:`attribute`,expression:prop.exp.content,sourceLocation:prop.exp.loc})}if(context.functionPropPaths.size>functionPropCount)context.bindingManifest.features.functionProps=true;if(context.inlineExpressions.length>inlineExpressionCount)context.bindingManifest.features.inlineEvents=true;if(dir)attrs.push(dir)}}if(mappedTagClass)staticClass=prependStaticClass(staticClass,mappedTagClass);if(templateRef){const refIndex=context.templateRefIndexSeed++;const className=`${WEVU_TEMPLATE_REF_CLASS_PREFIX}${refIndex}`;staticClass=staticClass?`${staticClass} ${className}`:className;context.templateRefs.push({selector:`.${className}`,inFor,name:templateRef.name,expAst:templateRef.expAst,kind:isComponentElement?`component`:`element`});context.bindingManifest.features.templateRefs=true}if(layoutHostKey){if(!staticId&&hasDynamicIdBinding)warn(context,`layout-host 暂不支持与动态 id 同时使用,当前节点已忽略。`,node.loc);else{const hostIndex=context.layoutHostIndexSeed++;const hostId=staticId||`${WEVU_LAYOUT_HOST_ID_PREFIX}${hostIndex}`;const hostRefName=`${WEVU_LAYOUT_HOST_REF_PREFIX}${hostIndex}`;staticId=hostId;context.templateRefs.push({selector:`#${hostId}`,inFor:false,name:hostRefName,kind:`component`});context.bindingManifest.features.templateRefs=true;context.layoutHosts.push({key:layoutHostKey,refName:hostRefName,selector:`#${hostId}`,kind:`component`});context.bindingManifest.features.layout=true}}if(staticId)attrs.unshift(`id="${staticId}"`);const classBindingCount=context.classStyleBindings.length;const classAttr=renderClassAttribute(staticClass,dynamicClassExp,context);if(dynamicClassExp){const generatedBinding=context.classStyleBindings.slice(classBindingCount).find(binding=>binding.type===`class`);recordBindingExpression(context,{kind:`class`,expression:dynamicClassExp,outputPath:generatedBinding?.name,sourceLocation:dynamicClassLocation})}if(classAttr)attrs.unshift(classAttr);const styleBindingCount=context.classStyleBindings.length;const styleAttr=renderStyleAttribute(staticStyle,context.cssVars?dynamicStyleExp?`[${dynamicStyleExp}, ${WEVU_CSS_VARS_STYLE_KEY}]`:WEVU_CSS_VARS_STYLE_KEY:dynamicStyleExp,vShowExp,context);const generatedStyleBinding=context.classStyleBindings.slice(styleBindingCount).find(binding=>binding.type===`style`);if(dynamicStyleExp)recordBindingExpression(context,{kind:`style`,expression:dynamicStyleExp,outputPath:generatedStyleBinding?.name,sourceLocation:dynamicStyleLocation});if(vShowExp)recordBindingExpression(context,{kind:`style`,expression:vShowExp,outputPath:generatedStyleBinding?.name,sourceLocation:vShowLocation});if(context.cssVars)recordBindingExpression(context,{kind:`style`,expression:WEVU_CSS_VARS_STYLE_KEY,outputPath:generatedStyleBinding?.name});if(styleAttr)attrs.unshift(styleAttr);return{attrs,vTextExp,declaration}}function createStaticObjectKey$1(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function createValidIdentifier(name,fallback){if(name&&t.isValidIdentifier(name))return t.identifier(name);return t.identifier(fallback)}function buildConsoleErrorGuard(message,errorId){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`error`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`error`)),[t.stringLiteral(message),t.cloneNode(errorId)]))]))}function buildRuntimeExpressionErrorGuard(binding,errorId){return buildConsoleErrorGuard(`[wevu] 模板运行时表达式执行失败: ${binding.name} = ${binding.exp}`,errorId)}function isScopedSlotOwnerBinding(exp){if(!exp)return false;const seen=/* @__PURE__ */ new WeakSet;const visit=node=>{if(!node||typeof node!==`object`)return false;if(seen.has(node))return false;seen.add(node);if(node.type===`MemberExpression`){const member=node;const property=member.property;if(!member.computed&&member.object?.type===`ThisExpression`&&property?.type===`Identifier`&&(property.name===WEVU_SLOT_OWNER_PROXY_KEY||property.name===WEVU_SLOT_OWNER_KEY))return true}for(const value of Object.values(node))if(Array.isArray(value)){if(value.some(item=>visit(item)))return true}else if(visit(value))return true;return false};return visit(exp)}function shouldReportRuntimeExpressionError(binding){return binding.type===`bind`&&!isScopedSlotOwnerBinding(binding.expAst)}function shouldReportForSourceError(info){const listExp=info.listExp?.trim()??``;return!listExp.startsWith(`${WEVU_SLOT_PROPS_DATA_KEY}.`)&&!listExp.startsWith(`${WEVU_SLOT_OWNER_KEY}.`)&&!isScopedSlotOwnerBinding(info.listExpAst)}function createDataPropsFallbackExpression(fallback){const propsObject=t.memberExpression(t.thisExpression(),t.identifier(WEVU_PROPS_KEY));const propsAccess=t.memberExpression(propsObject,t.identifier(`data`));const hasPropsObject=t.binaryExpression(`!=`,propsObject,t.nullLiteral());const hasPropsValue=t.logicalExpression(`&&`,hasPropsObject,t.logicalExpression(`||`,t.binaryExpression(`!==`,propsAccess,t.identifier(`undefined`)),t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`prototype`)),t.identifier(`hasOwnProperty`)),t.identifier(`call`)),[propsObject,t.stringLiteral(`data`)])));return t.conditionalExpression(hasPropsValue,propsAccess,fallback)}function createDataRuntimeAccess(helpers){const unrefHelper=helpers.unref?t.cloneNode(helpers.unref):t.identifier(`unref`);return t.callExpression(unrefHelper,[createDataPropsFallbackExpression(t.memberExpression(t.thisExpression(),t.identifier(`data`)))])}function rewriteDataAccessExpression(exp,helpers){if(t.isIdentifier(exp)&&exp.name===`data`)return createDataRuntimeAccess(helpers);if(t.isMemberExpression(exp))return t.memberExpression(rewriteDataAccessExpression(exp.object,helpers),t.cloneNode(exp.property),exp.computed);if(t.isObjectExpression(exp))return t.objectExpression(exp.properties.map(property=>{if(!t.isObjectProperty(property)||!t.isExpression(property.value))return t.cloneNode(property,true);return t.objectProperty(t.cloneNode(property.key),rewriteDataAccessExpression(property.value,helpers),property.computed,property.shorthand)}));if(t.isArrayExpression(exp))return t.arrayExpression(exp.elements.map(element=>{if(!element||t.isSpreadElement(element))return element?t.cloneNode(element,true):null;return rewriteDataAccessExpression(element,helpers)}));if(t.isBinaryExpression(exp))return t.isPrivateName(exp.left)||t.isPrivateName(exp.right)?t.cloneNode(exp,true):t.binaryExpression(exp.operator,rewriteDataAccessExpression(exp.left,helpers),rewriteDataAccessExpression(exp.right,helpers));if(t.isLogicalExpression(exp))return t.logicalExpression(exp.operator,rewriteDataAccessExpression(exp.left,helpers),rewriteDataAccessExpression(exp.right,helpers));if(t.isConditionalExpression(exp))return t.conditionalExpression(rewriteDataAccessExpression(exp.test,helpers),rewriteDataAccessExpression(exp.consequent,helpers),rewriteDataAccessExpression(exp.alternate,helpers));if(t.isUnaryExpression(exp))return t.unaryExpression(exp.operator,rewriteDataAccessExpression(exp.argument,helpers),exp.prefix);if(t.isCallExpression(exp))return t.callExpression(rewriteDataAccessExpression(exp.callee,helpers),exp.arguments.map(arg=>{if(t.isSpreadElement(arg))return t.cloneNode(arg,true);return rewriteDataAccessExpression(arg,helpers)}));return t.cloneNode(exp,true)}function buildNormalizedExpression(binding,helpers){const errorId=t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER);if(binding.type===`bind`){const exp=binding.expAst?t.cloneNode(binding.expAst,true):t.identifier(`undefined`);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(exp)]),t.catchClause(t.cloneNode(errorId),t.blockStatement([...shouldReportRuntimeExpressionError(binding)?[buildRuntimeExpressionErrorGuard(binding,errorId)]:[],t.returnStatement(t.identifier(`undefined`))])),null)])),[])}const normalizeHelper=binding.type===`class`?helpers.normalizeClass:helpers.normalizeStyle;const errorFallback=binding.errorFallback??``;const exp=binding.expAst?rewriteDataAccessExpression(binding.expAst,helpers):t.stringLiteral(``);const normalizedCall=t.callExpression(t.cloneNode(normalizeHelper),[exp]);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(normalizedCall)]),t.catchClause(t.cloneNode(errorId),t.blockStatement([...shouldReportRuntimeExpressionError(binding)?[buildRuntimeExpressionErrorGuard(binding,errorId)]:[],t.returnStatement(t.stringLiteral(errorFallback))])),null)])),[])}function buildArrayMapExpression(binding,forStack,level,listId,helpers){const itemParam=createValidIdentifier(forStack[level].item,`__wv_item_${level}`);const indexParam=createValidIdentifier(forStack[level].index,`__wv_index_${level}`);const body=[];const keyName=forStack[level].key;if(keyName&&t.isValidIdentifier(keyName)&&keyName!==indexParam.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(keyName),indexParam)]));const inner=buildForExpression(binding,forStack,level+1,helpers);body.push(t.returnStatement(inner));const callback=t.arrowFunctionExpression([itemParam,indexParam],t.blockStatement(body));return t.callExpression(t.memberExpression(listId,t.identifier(`map`)),[callback])}function buildObjectMapExpression(binding,forStack,level,listId,helpers){const resId=t.identifier(`__wv_res_${level}`);const keysId=t.identifier(`__wv_keys_${level}`);const loopIndexId=t.identifier(`__wv_i_${level}`);const keyId=t.identifier(`__wv_key_${level}`);const itemId=t.identifier(`__wv_item_${level}`);const itemAlias=forStack[level].item;const indexAlias=forStack[level].index;const keyAlias=forStack[level].key;const hasKeyAlias=Boolean(keyAlias&&t.isValidIdentifier(keyAlias));const loopBody=[t.variableDeclaration(`const`,[t.variableDeclarator(keyId,t.memberExpression(keysId,loopIndexId,true))]),t.variableDeclaration(`const`,[t.variableDeclarator(itemId,t.memberExpression(listId,keyId,true))])];if(itemAlias&&t.isValidIdentifier(itemAlias)&&itemAlias!==itemId.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(itemAlias),itemId)]));if(hasKeyAlias&&keyAlias&&keyAlias!==keyId.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(keyAlias),keyId)]));if(indexAlias&&t.isValidIdentifier(indexAlias)){const source=hasKeyAlias?loopIndexId:keyId;if(indexAlias!==source.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(indexAlias),source)]))}const inner=buildForExpression(binding,forStack,level+1,helpers);loopBody.push(t.expressionStatement(t.assignmentExpression(`=`,t.memberExpression(resId,keyId,true),inner)));const loop=t.forStatement(t.variableDeclaration(`let`,[t.variableDeclarator(loopIndexId,t.numericLiteral(0))]),t.binaryExpression(`<`,loopIndexId,t.memberExpression(keysId,t.identifier(`length`))),t.updateExpression(`++`,loopIndexId),t.blockStatement(loopBody));return t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(resId,t.objectExpression([]))]),t.variableDeclaration(`const`,[t.variableDeclarator(keysId,t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`keys`)),[listId]))]),loop,t.returnStatement(resId)])}function buildNumericListNormalization(level,listId){const indexId=t.identifier(`__wv_numeric_index_${level}`);const numberCheck=t.logicalExpression(`&&`,t.binaryExpression(`===`,t.unaryExpression(`typeof`,listId),t.stringLiteral(`number`)),t.callExpression(t.memberExpression(t.identifier(`Number`),t.identifier(`isFinite`)),[listId]));const length=t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`max`)),[t.numericLiteral(0),t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`floor`)),[listId])]);const normalized=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`from`)),[t.objectExpression([t.objectProperty(t.identifier(`length`),length)]),t.arrowFunctionExpression([t.identifier(`_`),indexId],indexId)]);return t.ifStatement(numberCheck,t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,listId,normalized))]))}function buildForExpression(binding,forStack,level,helpers){const expression=buildForExpressionBody(binding,forStack,level,helpers);const conditions=binding.conditions?.filter(condition=>condition.forDepth===level)??[];if(!conditions.length)return expression;const isProjectionBinding=binding.exp.startsWith(`v-for :key `);const condition=conditions.map(item=>t.cloneNode(isProjectionBinding?item.rawExpAst??item.expAst:item.expAst,true)).reduce((left,right)=>t.logicalExpression(`&&`,left,right));const fallback=level<forStack.length?t.arrayExpression([]):binding.type===`bind`?t.identifier(`undefined`):t.stringLiteral(``);return t.conditionalExpression(condition,expression,fallback)}function buildForExpressionBody(binding,forStack,level,helpers){if(level>=forStack.length)return buildNormalizedExpression(binding,helpers);const info=forStack[level];const listId=t.identifier(`__wv_list_${level}`);const listExpAst=binding.exp.startsWith(`v-for :key `)?info.rawListExpAst??info.listExpAst:info.projectedListExpAst??info.listExpAst;const listExp=listExpAst?t.cloneNode(listExpAst,true):t.arrayExpression([]);const unrefHelper=helpers.unref?t.cloneNode(helpers.unref):t.identifier(`unref`);const listUnrefExp=t.callExpression(unrefHelper,[listExp]);const listDecl=t.variableDeclaration(`let`,[t.variableDeclarator(listId,t.arrayExpression([]))]);const listSafeAssign=t.tryStatement(t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,listId,listUnrefExp))]),t.catchClause(t.identifier(`__wv_err_${level}`),t.blockStatement([...shouldReportForSourceError(info)?[buildConsoleErrorGuard(`[wevu] 模板 v-for 数据源表达式执行失败: ${info.listExp}`,t.identifier(`__wv_err_${level}`))]:[],t.expressionStatement(t.assignmentExpression(`=`,listId,t.arrayExpression([])))])),null);const arrayCheck=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`isArray`)),[listId]);const arrayMap=buildArrayMapExpression(binding,forStack,level,listId,helpers);const objectCheck=t.logicalExpression(`&&`,t.binaryExpression(`!=`,listId,t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,listId),t.stringLiteral(`object`)));const objectBlock=buildObjectMapExpression(binding,forStack,level,listId,helpers);const fallbackReturn=t.returnStatement(t.arrayExpression([]));const body=t.blockStatement([listDecl,listSafeAssign,buildNumericListNormalization(level,listId),t.ifStatement(arrayCheck,t.blockStatement([t.returnStatement(arrayMap)]),t.ifStatement(objectCheck,objectBlock,t.blockStatement([fallbackReturn])))]);return t.callExpression(t.arrowFunctionExpression([],body),[])}function buildComputedFunctionBody(binding,helpers){const expr=buildForExpression(binding,binding.forStack??[],0,helpers);return t.blockStatement([t.returnStatement(expr)])}function createMemberAccess(target,prop){if(t.isValidIdentifier(prop))return t.memberExpression(target,t.identifier(prop));return t.memberExpression(target,t.stringLiteral(prop),true)}function applyPropsAliasesToExpression(expression,propsAliases,forStack){if(!propsAliases||!Object.keys(propsAliases).length)return expression;const ast=t.file(t.program([t.expressionStatement(expression)]));traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;const propName=propsAliases[name];if(!propName||path.scope.hasBinding(name)||forStack.some(scope=>scope.item===name||scope.index===name||scope.key===name))return;const replacement=createMemberAccess(t.memberExpression(t.thisExpression(),t.identifier(`__wevuProps`)),propName);const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}});const statement=ast.program.body[0];return t.isExpressionStatement(statement)?statement.expression:expression}function buildClassStyleComputedEntries(bindings,helpers,propsAliases){const entries=[];for(const binding of bindings){const key=createStaticObjectKey$1(binding.name);const body=buildComputedFunctionBody({...binding,expAst:binding.expAst?applyPropsAliasesToExpression(t.cloneNode(binding.expAst,true),propsAliases,binding.forStack):binding.expAst},helpers);const fn=t.functionExpression(null,[],body);entries.push(t.objectProperty(key,fn))}return entries}function buildClassStyleComputedObject(bindings,helpers){if(!bindings.length)return null;const entries=buildClassStyleComputedEntries(bindings,helpers);if(!entries.length)return null;return t.objectExpression(entries)}function buildClassStyleComputedCode(bindings,helpers){if(!bindings.length)return null;const obj=buildClassStyleComputedObject(bindings,{normalizeClass:t.identifier(helpers.normalizeClassName),normalizeStyle:t.identifier(helpers.normalizeStyleName),unref:t.identifier(helpers.unrefName??`unref`)});if(!obj)return null;const{code}=generate(obj,{compact:true});return code}function buildInlineExpressionMap(inlineExpressions,unrefImport){return t.objectExpression(inlineExpressions.map(entry=>{const{parameterNames}=entry;let fn=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],parseBabelExpression(entry.expression)??t.identifier(`undefined`));if(entry.runtimeHelpers?.unref){if(!unrefImport)throw new Error(`生成 maybe-ref 内联表达式需要 unref 运行时导入。`);fn=t.callExpression(t.arrowFunctionExpression([t.identifier(entry.runtimeHelpers.unref)],fn),[t.cloneNode(unrefImport)])}const properties=[t.objectProperty(t.identifier(`keys`),t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)))),t.objectProperty(t.identifier(`fn`),fn)];if(entry.indexBindings?.length)properties.push(t.objectProperty(t.identifier(`indexKeys`),t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)))));if(entry.scopeResolvers?.length){const resolvers=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));properties.push(t.objectProperty(t.identifier(`scopeResolvers`),t.arrayExpression(entry.scopeKeys.map(key=>parseBabelExpression(resolvers.get(key)??``)??t.identifier(`undefined`)))))}return t.objectProperty(t.stringLiteral(entry.id),t.objectExpression(properties))}))}function buildInlineExpressionMapCode(inlineExpressions){if(!inlineExpressions.length)return null;return generate(buildInlineExpressionMap(inlineExpressions,t.identifier(`__wevuUnref`)),{compact:true}).code}function buildTemplateRefsCode(templateRefs){if(!templateRefs.length)return null;return`[${templateRefs.map(binding=>{const fields=[`selector:${JSON.stringify(binding.selector)}`,`inFor:${binding.inFor}`];if(binding.name)fields.push(`name:${JSON.stringify(binding.name)}`);if(binding.expAst)fields.push(`get:function(){return ${generate(binding.expAst,{compact:true}).code}}`);if(binding.kind)fields.push(`kind:${JSON.stringify(binding.kind)}`);return`{${fields.join(`,`)}}`}).join(`,`)}]`}function buildScopedSlotComponentScript(options){const computedCode=options.classStyleBindings.length?buildClassStyleComputedCode(options.classStyleBindings,{normalizeClassName:`__wevuNormalizeClass`,normalizeStyleName:`__wevuNormalizeStyle`,unrefName:`__wevuUnref`}):null;const inlineMapCode=buildInlineExpressionMapCode(options.inlineExpressions);const templateRefsCode=buildTemplateRefsCode(options.templateRefs);const layoutHostsCode=options.layoutHosts.length?JSON.stringify(options.layoutHosts):null;const requiredCapabilitySet=new Set(options.runtimeCapabilities?.required);const installerNames=WE_VU_RUNTIME_CAPABILITY_ORDER.filter(capability=>requiredCapabilitySet.has(capability)).map(capability=>WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability]);const lines=[`import { ${[`${WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent} as _createWevuScopedSlotComponent`,...installerNames.map(installerName=>`${installerName} as _${installerName}`)].join(`, `)} } from '${WE_VU_COMPILER_RUNTIME_MODULE_ID}';`];if(computedCode)lines.push(`import { normalizeClass as __wevuNormalizeClass, normalizeStyle as __wevuNormalizeStyle } from '${WE_VU_COMPILER_TEMPLATE_MODULE_ID}';`);if(computedCode||templateRefsCode||options.inlineExpressions.some(entry=>entry.runtimeHelpers?.unref))lines.push(`import { unref as __wevuUnref } from '${WE_VU_COMPILER_REACTIVITY_MODULE_ID}';`);lines.push(...installerNames.map(installerName=>`_${installerName}();`));lines.push(`const globalObject = typeof globalThis !== 'undefined' ? globalThis : undefined;`,`const createWevuScopedSlotComponent = globalObject?.${WEVU_SCOPED_SLOT_CREATOR_KEY}`,` ?? _createWevuScopedSlotComponent;`);if(computedCode)lines.push(`const __wevuComputed = ${computedCode};`);if(inlineMapCode)lines.push(`const __wevuInlineMap = ${inlineMapCode};`);if(templateRefsCode)lines.push(`const __wevuTemplateRefs = ${templateRefsCode};`);if(layoutHostsCode)lines.push(`const __wevuLayoutHosts = ${layoutHostsCode};`);const overrideParts=[`${JSON.stringify(WEVU_BINDING_MANIFEST_KEY)}:Object.freeze(${JSON.stringify(createRuntimeBindingManifest(options.bindingManifest,options.runtimeBindingManifest))})`];if(options.nativeSlotContext)overrideParts.push(`${JSON.stringify(WEVU_NATIVE_SLOT_CONTEXT_KEY)}:true`);if(computedCode)overrideParts.push(`computed:__wevuComputed`);if(layoutHostsCode)overrideParts.push(`layoutHosts:__wevuLayoutHosts`);if(inlineMapCode)overrideParts.push(`inlineMap:__wevuInlineMap`);if(templateRefsCode)overrideParts.push(`templateRefs:__wevuTemplateRefs`);lines.push(`if (typeof createWevuScopedSlotComponent === 'function') {`,` createWevuScopedSlotComponent({${overrideParts.join(`,`)}});`,`}`,``);return lines.join(`
|
|
6
|
+
`)}\n`}const DEFAULT_HTML_TO_WXML_TAG_MAP={a:`navigator`,article:`view`,aside:`view`,b:`text`,blockquote:`view`,br:`view`,button:`button`,code:`text`,dd:`view`,div:`view`,dl:`view`,dt:`view`,em:`text`,figcaption:`view`,figure:`view`,footer:`view`,form:`form`,h1:`view`,h2:`view`,h3:`view`,h4:`view`,h5:`view`,h6:`view`,header:`view`,hr:`view`,i:`text`,img:`image`,input:`input`,label:`label`,li:`view`,main:`view`,nav:`view`,ol:`view`,p:`view`,pre:`view`,section:`view`,small:`text`,span:`text`,strong:`text`,table:`view`,tbody:`view`,td:`view`,textarea:`textarea`,tfoot:`view`,th:`view`,thead:`view`,tr:`view`,u:`text`,ul:`view`};function resolveHtmlTagToWxmlMap(value){if(value===false)return;if(value===true||value===void 0)return{...DEFAULT_HTML_TO_WXML_TAG_MAP};return{...DEFAULT_HTML_TO_WXML_TAG_MAP,...Object.fromEntries(Object.entries(value).map(([key,mapped])=>[key.toLowerCase(),mapped]))}}function normalizeTemplateTagName(tag){return tag.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}function resolveTemplateTagName(tag,context){if(!tag)return tag;const lowerTag=tag.toLowerCase();if(tag!==lowerTag)return normalizeTemplateTagName(tag);return context.htmlTagToWxmlMap?.[lowerTag]??tag}function resolveMappedHtmlTagClassName(tag,context,resolvedTag){if(!context.htmlTagToWxmlTagClass||!tag)return;const lowerTag=tag.toLowerCase();if(tag!==lowerTag)return;const mappedTag=context.htmlTagToWxmlMap?.[lowerTag];if(!mappedTag||(resolvedTag??mappedTag??tag)===lowerTag)return;return lowerTag}const IDENTIFIER_RE$3=/^[A-Z_$][\w$]*$/i;const WHITESPACE_RE$1=/\s/;const FOR_ITEM_ALIAS_PLACEHOLDER=`__wv_for_item__`;function isIdentifier(value){return IDENTIFIER_RE$3.test(value)}function splitTopLevelByComma(input){const out=[];let start=0;let parenDepth=0;let bracketDepth=0;let braceDepth=0;let quote=``;let escaped=false;for(let i=0;i<input.length;i+=1){const ch=input[i];if(quote){if(escaped){escaped=false;continue}if(ch===`\\`){escaped=true;continue}if(ch===quote)quote=``;continue}if(ch===`'`||ch===`"`||ch==="`"){quote=ch;continue}if(ch===`(`){parenDepth+=1;continue}if(ch===`)`){parenDepth=Math.max(0,parenDepth-1);continue}if(ch===`[`){bracketDepth+=1;continue}if(ch===`]`){bracketDepth=Math.max(0,bracketDepth-1);continue}if(ch===`{`){braceDepth+=1;continue}if(ch===`}`){braceDepth=Math.max(0,braceDepth-1);continue}if(ch===`,`&&parenDepth===0&&bracketDepth===0&&braceDepth===0){out.push(input.slice(start,i).trim());start=i+1}}out.push(input.slice(start).trim());return out}function splitForExpression(exp){let parenDepth=0;let bracketDepth=0;let braceDepth=0;let quote=``;let escaped=false;let emptyAliasSplit=null;for(let i=0;i<exp.length;i+=1){const ch=exp[i];if(quote){if(escaped){escaped=false;continue}if(ch===`\\`){escaped=true;continue}if(ch===quote)quote=``;continue}if(ch===`'`||ch===`"`||ch==="`"){quote=ch;continue}if(ch===`(`){parenDepth+=1;continue}if(ch===`)`){parenDepth=Math.max(0,parenDepth-1);continue}if(ch===`[`){bracketDepth+=1;continue}if(ch===`]`){bracketDepth=Math.max(0,bracketDepth-1);continue}if(ch===`{`){braceDepth+=1;continue}if(ch===`}`){braceDepth=Math.max(0,braceDepth-1);continue}if(parenDepth!==0||bracketDepth!==0||braceDepth!==0)continue;const keyword=exp.startsWith(`in`,i)?`in`:exp.startsWith(`of`,i)?`of`:void 0;if(keyword&&(i===0||WHITESPACE_RE$1.test(exp[i-1]))&&(i+keyword.length===exp.length||WHITESPACE_RE$1.test(exp[i+keyword.length]))){const split={source:exp.slice(0,i).trim(),list:exp.slice(i+keyword.length).trim()};if(split.source)return split;emptyAliasSplit=split}}return emptyAliasSplit}function stripOuterParentheses(value){const trimmed=value.trim();if(!trimmed.startsWith(`(`)||!trimmed.endsWith(`)`))return trimmed;let depth=0;for(let i=0;i<trimmed.length;i+=1){const ch=trimmed[i];if(ch===`(`)depth+=1;else if(ch===`)`){depth-=1;if(depth===0&&i!==trimmed.length-1)return trimmed}}return trimmed.slice(1,-1).trim()}function toMemberAccess(base,property,computed){if(!computed){if(t.isIdentifier(property)&&isIdentifier(property.name))return`${base}.${property.name}`;if(t.isStringLiteral(property))return`${base}[${JSON.stringify(property.value)}]`}if(t.isExpression(property))return`${base}[${generateExpression(property)}]`;return base}function collectPatternAliases(node,base,result){if(t.isIdentifier(node)){result.aliases[node.name]=base;return}if(t.isAssignmentPattern(node)){result.requiresProjection=true;collectPatternAliases(node.left,base,result);return}if(t.isRestElement(node)){if(t.isIdentifier(node.argument))result.aliases[node.argument.name]=base;return}if(t.isArrayPattern(node)){node.elements.forEach((element,index)=>{if(!element)return;if(t.isRestElement(element)){result.requiresProjection=true;collectPatternAliases(element,base,result);return}collectPatternAliases(element,`${base}[${index}]`,result)});return}if(!t.isObjectPattern(node))return;node.properties.forEach(property=>{if(t.isRestElement(property)){result.requiresProjection=true;collectPatternAliases(property,base,result);return}const nextBase=toMemberAccess(base,property.key,property.computed);collectPatternAliases(property.value,nextBase,result)})}function parseItemAliases(pattern){const result={aliases:{},requiresProjection:false};try{const stmt=parseJsLike(`(${pattern}) => {}`).program.body[0];if(!stmt||stmt.type!==`ExpressionStatement`)return{...result,error:`v-for 别名模式无法解析。`};const exp=stmt.expression;if(!t.isArrowFunctionExpression(exp)||exp.params.length!==1)return{...result,error:`v-for 别名模式无法解析。`};const patternNode=exp.params[0];if(t.isRestElement(patternNode))return{...result,error:`v-for 不支持顶层剩余参数;请在数组或对象解构中使用剩余元素。`};collectPatternAliases(patternNode,FOR_ITEM_ALIAS_PLACEHOLDER,result);if(result.requiresProjection)result.aliases=Object.fromEntries(Object.keys(result.aliases).map(name=>[name,`${FOR_ITEM_ALIAS_PLACEHOLDER}.${name}`]));return result}catch{return{...result,error:`v-for 别名模式无法解析。`}}}function parseForExpression(exp){const split=splitForExpression(exp.trim());if(!split)return{error:`v-for 表达式必须使用 in 或 of 分隔别名与列表。`};if(!split.source)return{error:`v-for 表达式缺少循环项别名。`};if(!split.list)return{error:`v-for 表达式缺少列表。`};const segments=splitTopLevelByComma(stripOuterParentheses(split.source)).filter(Boolean);if(segments.length>3)return{listExp:split.list,itemPatternError:`v-for 最多支持 item、key 与 index 三个别名;额外别名无法等价映射到小程序循环作用域。`};const result={listExp:split.list};const rawItem=segments[0]?.trim();if(rawItem){if(isIdentifier(rawItem)&&t.isValidIdentifier(rawItem))result.item=rawItem;else{const parsed=parseItemAliases(rawItem);if(parsed.error)result.itemPatternError=parsed.error;if(Object.keys(parsed.aliases).length){result.item=FOR_ITEM_ALIAS_PLACEHOLDER;result.itemAliases=parsed.aliases;if(parsed.requiresProjection){result.itemPattern=rawItem;result.itemPatternRequiresProjection=true}}}}if(segments.length===2){const rawIndex=segments[1]?.trim();if(rawIndex&&isIdentifier(rawIndex)&&t.isValidIdentifier(rawIndex))result.index=rawIndex;else result.itemPatternError=`v-for 第二个别名必须是标识符;解构形式无法等价映射到小程序循环索引。`}else if(segments.length===3){const rawKey=segments[1]?.trim();const rawIndex=segments[2]?.trim();if(rawKey&&isIdentifier(rawKey)&&t.isValidIdentifier(rawKey)&&rawIndex&&isIdentifier(rawIndex)&&t.isValidIdentifier(rawIndex)){result.key=rawKey;result.index=rawIndex}else result.itemPatternError=`v-for 的 key 与 index 别名必须是标识符;解构形式无法等价映射到小程序循环作用域。`}if(result.itemPatternRequiresProjection&&segments.length===3)result.itemPatternError=`v-for 需要逻辑层投影的解构暂不支持同时声明 key 与 index;无法保证不同列表类型上的等价语义。`;return result}function isStructuralDirective(node){for(const prop of node.props)if(prop.type===NodeTypes.DIRECTIVE){if(prop.name===`if`||prop.name===`else-if`||prop.name===`else`)return{type:`if`,directive:prop};if(prop.name===`for`)return{type:`for`,directive:prop}}return{type:null,directive:void 0}}function pushScope$1(context,names){if(!names.length)return;context.scopeStack.push(new Set(names))}function popScope$1(context){if(context.scopeStack.length)context.scopeStack.pop()}function pushForScope(context,info){if(!info.listExp)return;context.forStack.push({...info})}function popForScope(context){if(context.forStack.length)context.forStack.pop()}function withForScope(context,info,fn){pushForScope(context,info);try{return fn()}finally{popForScope(context)}}function pushSlotProps(context,mapping){if(!Object.keys(mapping).length)return;context.slotPropStack.push(mapping)}function popSlotProps(context){if(context.slotPropStack.length)context.slotPropStack.pop()}function withScope(context,names,fn){pushScope$1(context,names);try{return fn()}finally{popScope$1(context)}}function withSlotProps(context,mapping,fn){pushSlotProps(context,mapping);try{return fn()}finally{popSlotProps(context)}}const IDENTIFIER_RE$2=/^[A-Z_$][\w$]*$/i;const BIND_SHORTHAND_ARG_RE=/^[A-Z_$][\w$]*(?:-[A-Z_$][\w$]*)*$/i;const BACKSLASH_RE$2=/\\/g;const SINGLE_QUOTE_RE$2=/'/g;const CR_RE$1=/\r/g;const LF_RE$1=/\n/g;function camelizeBindShorthandArg(value){return value.replace(/-([\w$])/g,(_,char)=>char.toUpperCase())}function getBindDirectiveExpression(node){const rawExp=node.exp?.type===NodeTypes.SIMPLE_EXPRESSION?node.exp.content:``;if(rawExp)return rawExp;if(node.name!==`bind`||node.arg?.type!==NodeTypes.SIMPLE_EXPRESSION||!node.arg.isStatic)return``;const rawArg=node.arg.content.trim();if(!rawArg||!BIND_SHORTHAND_ARG_RE.test(rawArg))return``;return camelizeBindShorthandArg(rawArg)}function collectScopePropMapping(context){const mapping={};if(!context.slotMultipleInstance)return mapping;const nativeAliases=new Set(context.forStack.flatMap(info=>Object.values(info.nativeAliases??{})));for(const scope of context.scopeStack)for(const name of scope){if(!IDENTIFIER_RE$2.test(name)||nativeAliases.has(name))continue;if(!hasOwn(mapping,name))mapping[name]=name}return mapping}function toWxmlStringLiteral$1(value){return`'${value.replace(BACKSLASH_RE$2,`\\\\`).replace(SINGLE_QUOTE_RE$2,`\\'`).replace(CR_RE$1,`\\r`).replace(LF_RE$1,`\\n`)}'`}function buildScopePropsExpression(context){const mapping=collectScopePropMapping(context);const keys=Object.keys(mapping);if(!keys.length)return null;const renamed=context.forStack.some(info=>info.nativeAliases);return`[${keys.map(key=>{const access=renamed?normalizeWxmlExpressionWithContext(key,context):getForItemAccess(context,key);return`${toWxmlStringLiteral$1(key)},${access}`}).join(`,`)}]`}function hashString(input){let hash=0;for(let i=0;i<input.length;i++){hash=(hash<<5)-hash+input.charCodeAt(i);hash|=0}return Math.abs(hash).toString(36)}function isScopedSlotsDisabled(context){return context.scopedSlotsCompiler===`off`}function findSlotDirective(node){return node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`slot`)}function renderMustache$1(expression,context){if(context.mustacheInterpolation===`spaced`)return`{{ ${expression} }}`;return`{{${expression.endsWith(`}`)?`${expression} `:expression}}}`}function createConsoleErrorGuard(message,errorId){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`error`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`error`)),[t.stringLiteral(message),t.cloneNode(errorId)]))]))}function createConsoleWarnGuard(message,item){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`warn`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`warn`)),[t.stringLiteral(message),t.cloneNode(item)]))]))}function createHasOwnPropertyCall(item,field){return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`prototype`)),t.identifier(`hasOwnProperty`)),t.identifier(`call`)),[t.cloneNode(item),t.stringLiteral(field)])}function createSafeKeyExpression(exp,rawExp,seed,item){const errorId=t.identifier(`__wv_for_key_error_${seed}`);const shouldReportError=item?t.binaryExpression(`!=`,t.cloneNode(item),t.nullLiteral()):t.booleanLiteral(true);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(exp,true))]),t.catchClause(errorId,t.blockStatement([t.ifStatement(shouldReportError,t.blockStatement([createConsoleErrorGuard(`[wevu] v-for :key 表达式执行失败: ${rawExp}`,errorId)])),t.returnStatement(t.identifier(`undefined`))])),null)])),[])}function createProjectedItemExpression(item,keyExp,rawKeyExp,keyField,valueField,seed){const isObject=t.logicalExpression(`&&`,t.binaryExpression(`!=`,t.cloneNode(item),t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.cloneNode(item)),t.stringLiteral(`object`)));const projected=t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.ifStatement(t.logicalExpression(`||`,createHasOwnPropertyCall(item,keyField),createHasOwnPropertyCall(item,valueField)),t.blockStatement([createConsoleWarnGuard(`[wevu] v-for :key 内部字段冲突,投影将使用保留字段 ${keyField} / ${valueField}`,item)])),t.returnStatement(t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),t.cloneNode(item),t.objectExpression([t.objectProperty(t.stringLiteral(valueField),t.cloneNode(item)),t.objectProperty(t.stringLiteral(keyField),createSafeKeyExpression(keyExp,rawKeyExp,seed,item))])]))])),[]);const primitiveProjected=t.objectExpression([t.objectProperty(t.stringLiteral(valueField),t.cloneNode(item)),t.objectProperty(t.stringLiteral(keyField),createSafeKeyExpression(keyExp,rawKeyExp,seed,item))]);return t.conditionalExpression(isObject,projected,primitiveProjected)}function createArrayProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const itemId=forInfo.item&&t.isValidIdentifier(forInfo.item)?t.identifier(forInfo.item):t.identifier(`__wv_for_key_item_${seed}`);const indexId=forInfo.index&&t.isValidIdentifier(forInfo.index)?t.identifier(forInfo.index):t.identifier(`__wv_for_key_index_${seed}`);const body=[];if(forInfo.key&&t.isValidIdentifier(forInfo.key)&&forInfo.key!==indexId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.key),t.cloneNode(indexId))]));body.push(t.returnStatement(createProjectedItemExpression(itemId,keyExp,rawKeyExp,keyField,valueField,seed)));return t.callExpression(t.memberExpression(t.cloneNode(sourceId),t.identifier(`map`)),[t.arrowFunctionExpression([itemId,indexId],t.blockStatement(body))])}function createObjectProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const resultId=t.identifier(`__wv_for_key_result_${seed}`);const keysId=t.identifier(`__wv_for_key_keys_${seed}`);const loopIndexId=t.identifier(`__wv_for_key_loop_index_${seed}`);const sourceKeyId=t.identifier(`__wv_for_key_source_key_${seed}`);const sourceItemId=t.identifier(`__wv_for_key_source_item_${seed}`);const body=[t.variableDeclaration(`const`,[t.variableDeclarator(sourceKeyId,t.memberExpression(keysId,loopIndexId,true))]),t.variableDeclaration(`const`,[t.variableDeclarator(sourceItemId,t.memberExpression(sourceId,sourceKeyId,true))])];if(forInfo.item&&t.isValidIdentifier(forInfo.item)&&forInfo.item!==sourceItemId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.item),t.cloneNode(sourceItemId))]));if(forInfo.key&&t.isValidIdentifier(forInfo.key)&&forInfo.key!==sourceKeyId.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.key),t.cloneNode(sourceKeyId))]));if(forInfo.index&&t.isValidIdentifier(forInfo.index)){const source=forInfo.key?loopIndexId:sourceKeyId;if(forInfo.index!==source.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(forInfo.index),t.cloneNode(source))]))}body.push(t.expressionStatement(t.assignmentExpression(`=`,t.memberExpression(resultId,sourceKeyId,true),createProjectedItemExpression(sourceItemId,keyExp,rawKeyExp,keyField,valueField,seed))));return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(resultId,t.objectExpression([]))]),t.variableDeclaration(`const`,[t.variableDeclarator(keysId,t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`keys`)),[t.cloneNode(sourceId)]))]),t.forStatement(t.variableDeclaration(`let`,[t.variableDeclarator(loopIndexId,t.numericLiteral(0))]),t.binaryExpression(`<`,loopIndexId,t.memberExpression(keysId,t.identifier(`length`))),t.updateExpression(`++`,loopIndexId),t.blockStatement(body)),t.returnStatement(resultId)])),[])}function createForKeyProjectionExpression(sourceExp,keyExp,rawKeyExp,keyField,valueField,forInfo,seed){const sourceId=t.identifier(`__wv_for_key_source_${seed}`);const objectCheck=t.logicalExpression(`&&`,t.binaryExpression(`!=`,t.cloneNode(sourceId),t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.cloneNode(sourceId)),t.stringLiteral(`object`)));return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(sourceId,t.cloneNode(sourceExp,true))]),t.ifStatement(t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`isArray`)),[t.cloneNode(sourceId)]),t.blockStatement([t.returnStatement(createArrayProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed))])),t.ifStatement(objectCheck,t.blockStatement([t.returnStatement(createObjectProjection$1(sourceId,keyExp,rawKeyExp,keyField,valueField,forInfo,seed))])),t.returnStatement(t.cloneNode(sourceId))])),[])}const SIMPLE_IDENTIFIER_RE$1=/^[A-Z_$][\w$]*$/i;const SIMPLE_MEMBER_PATH_RE=/^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*)*$/i;const RUNTIME_BINDING_REF_RE$1=/^__wv_bind_\d+(?:\[[A-Z_$][\w$]*\])*$/i;function createSourceContext(context){return{...context,forStack:context.forStack.map(forInfo=>({...forInfo,itemAccess:void 0}))}}function hasKnownPrimitiveItems(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp)||t.isBooleanLiteral(exp)||t.isNullLiteral(exp))return true;if(!t.isArrayExpression(exp))return false;return exp.elements.every(element=>{return element==null||t.isStringLiteral(element)||t.isNumericLiteral(element)||t.isBooleanLiteral(element)||t.isNullLiteral(element)})}function resolveItemAliasKeyField(trimmed,forInfo){const aliasExp=forInfo.itemAliases?.[trimmed]?.trim();if(!aliasExp||!forInfo.item||!aliasExp.startsWith(`${forInfo.item}.`))return null;const remainder=aliasExp.slice(forInfo.item.length+1);return SIMPLE_MEMBER_PATH_RE.test(remainder)&&!remainder.includes(`.`)?remainder:null}function resolveNativeForKeyValue(exp,forInfo,keyThisValue){const trimmed=exp.trim();if(!forInfo)return null;if(forInfo.item&&trimmed===forInfo.item||forInfo.key&&trimmed===forInfo.key)return keyThisValue;if(forInfo.item&&trimmed.startsWith(`${forInfo.item}.`)){const remainder=trimmed.slice(forInfo.item.length+1);if(SIMPLE_MEMBER_PATH_RE.test(remainder)&&!remainder.includes(`.`))return remainder;return null}if(SIMPLE_IDENTIFIER_RE$1.test(trimmed)){if(forInfo.index===trimmed)return trimmed;return resolveItemAliasKeyField(trimmed,forInfo)}return null}function createForKeyProjection(node,forInfo,context,nativeKeyValue=resolveNativeForKeyValue(getBindDirectiveExpression(node),forInfo,context.platform.keyThisValue)){const rawKeyExp=getBindDirectiveExpression(node).trim();if(!rawKeyExp||!forInfo.listExp||nativeKeyValue)return null;const listExp=forInfo.listExp?.trim()??``;const projectionContext={...context,forStack:context.forStack.slice(0,-1),scopeStack:context.scopeStack.slice(0,-1)};const sourceContext=createSourceContext(context);const projectionSourceAst=RUNTIME_BINDING_REF_RE$1.test(listExp)?normalizeRuntimeBindingReference(listExp,projectionContext):forInfo.rawListExpAst??forInfo.listExpAst;if(!projectionSourceAst)return null;if(hasKnownPrimitiveItems(projectionSourceAst))return null;const keyExpAst=normalizeJsExpressionWithContext(rawKeyExp,sourceContext,{hint:`v-for :key`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});if(!keyExpAst)return null;const bindingSeed=context.classStyleBindings.filter(binding=>binding.type===`bind`).length;const bindingName=`__wv_bind_${bindingSeed}`;const keyField=`__wv_key_${bindingSeed}`;const valueField=`__wv_value_${bindingSeed}`;const outerForStack=context.forStack.slice(0,-1).map(info=>({...info}));context.classStyleBindings.push({name:bindingName,type:`bind`,exp:`v-for :key ${rawKeyExp}`,expAst:createForKeyProjectionExpression(projectionSourceAst,keyExpAst,rawKeyExp,keyField,valueField,forInfo,bindingSeed),forStack:outerForStack,conditions:context.bindingConditions?.slice()});const indexAccess=outerForStack.map(info=>`[${info.index??`index`}]`).join(``);return{keyAttr:context.platform.keyAttr(keyField),keyField,listExp:`${bindingName}${indexAccess}`,itemAccess:`${forInfo.item}.${valueField}`}}function unwrapTsExpression$3(node){if(node.type===`TSAsExpression`||node.type===`TSNonNullExpression`||node.type===`TSTypeAssertion`)return unwrapTsExpression$3(node.expression);return node}function isTopLevelObjectLiteral(exp){const parsed=parseBabelExpression(exp);if(!parsed)return false;return unwrapTsExpression$3(parsed).type===`ObjectExpression`}function isStaticLiteralNode(node){const normalized=unwrapTsExpression$3(node);if(normalized.type===`StringLiteral`||normalized.type===`NumericLiteral`||normalized.type===`BooleanLiteral`||normalized.type===`NullLiteral`)return true;if(normalized.type===`UnaryExpression`)return(normalized.operator===`-`||normalized.operator===`+`)&&normalized.argument.type===`NumericLiteral`;if(normalized.type===`ArrayExpression`){for(const element of normalized.elements)if(!element||element.type===`SpreadElement`||!isStaticLiteralNode(element))return false;return true}if(normalized.type===`ObjectExpression`){for(const property of normalized.properties){if(property.type!==`ObjectProperty`||property.computed)return false;const value=property.value;if(!t.isExpression(value)||!isStaticLiteralNode(value))return false}return true}return false}function isStaticObjectLiteral(exp){const parsed=parseBabelExpression(exp);if(!parsed)return false;const normalized=unwrapTsExpression$3(parsed);return normalized.type===`ObjectExpression`&&isStaticLiteralNode(normalized)}function createBindRuntimeAttr(argValue,rawExpValue,context){const bindingRef=registerRuntimeBindingExpression(rawExpValue,context,{hint:`:${argValue} 绑定`});if(!bindingRef)return null;return`${argValue}="${renderMustache$1(bindingRef,context)}"`}function createInlineObjectLiteralAttr(argValue,rawExpValue,context){const normalized=normalizeWxmlExpressionWithContext(rawExpValue,context).trim();const parsed=parseBabelExpression(normalized);const expValue=parsed?generateExpression(parsed):normalized;if(context.mustacheInterpolation===`spaced`)return`${argValue}="${renderMustache$1(expValue,context)}"`;return`${argValue}="{{ ${expValue} }}"`}const COMPONENT_NON_PROP_BINDINGS=/* @__PURE__ */ new Set([`class`,`style`,`id`,`key`,`ref`,`is`,`slot`,`layout-host`]);function collectFunctionPropPath(rawExpValue){const parsed=parseBabelExpression(rawExpValue);if(!parsed)return null;const normalized=unwrapTsExpression$3(parsed);if(normalized.type===`Identifier`)return normalized.name;if(normalized.type!==`MemberExpression`||normalized.computed)return null;const parts=[];let current=normalized;while(current.type===`MemberExpression`&&!current.computed){if(current.property.type!==`Identifier`)return null;parts.unshift(current.property.name);current=unwrapTsExpression$3(current.object)}if(current.type!==`Identifier`)return null;parts.unshift(current.name);return parts.join(`.`)}function isComputedMemberExpression(rawExpValue){const parsed=parseBabelExpression(rawExpValue);if(!parsed)return false;const normalized=unwrapTsExpression$3(parsed);return normalized.type===`MemberExpression`&&normalized.computed}function shouldUseRuntimeFunctionPropBinding(argValue,context){return context.functionPropNames.some(matcher=>{if(typeof matcher===`string`)return matcher===argValue;matcher.lastIndex=0;return matcher.test(argValue)})}function shouldWrapStaticMemberFunctionProp(argValue,path,context){return path.includes(`.`)&&shouldUseRuntimeFunctionPropBinding(argValue,context)}function createFunctionPropRuntimeAttr(argValue,rawExpValue,context){const bindingRef=registerRuntimeBindingExpression(rawExpValue,context,{hint:`:${argValue} 函数 prop 绑定`});if(!bindingRef)return null;const bindingName=bindingRef.split(`[`)[0]||bindingRef;context.functionPropPaths.add(bindingName);return`${argValue}="${renderMustache$1(bindingRef,context)}"`}function rejectUnsupportedDynamicBindName(node,context){const{arg}=node;if(arg?.type!==NodeTypes.SIMPLE_EXPRESSION||arg.isStatic)return false;warn(context,`小程序模板暂不支持动态 v-bind 参数名,已忽略该绑定。`,node.loc);return true}function transformBindDirective(node,context,forInfo,options){const{arg,exp}=node;if(!arg){if(exp?.type===NodeTypes.SIMPLE_EXPRESSION&&exp.content.trim())warn(context,`小程序暂不支持对象形式 v-bind,已忽略该对象绑定;请改用显式属性绑定。`,node.loc);else warn(context,`v-bind 缺少对象绑定表达式。`,node.loc,`template`,`WV2001`);return null}if(rejectUnsupportedDynamicBindName(node,context))return null;const argValue=arg.type===NodeTypes.SIMPLE_EXPRESSION?arg.content:``;const outputArgValue=options?.isComponent?normalizeComponentHostName(argValue):argValue;const rawExpValue=getBindDirectiveExpression(node);if(!rawExpValue)return null;if(options?.isComponent&&!COMPONENT_NON_PROP_BINDINGS.has(argValue)){const path=collectFunctionPropPath(rawExpValue);if(path){if(shouldWrapStaticMemberFunctionProp(argValue,path,context)){const runtimeAttr=createFunctionPropRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}else context.functionPropPaths.add(path)}else if(shouldUseRuntimeFunctionPropBinding(argValue,context)&&isComputedMemberExpression(rawExpValue)){const runtimeAttr=createFunctionPropRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}}if(argValue===`key`){const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);const trimmed=expValue.trim();const nativeKeyValue=resolveNativeForKeyValue(trimmed,forInfo,context.platform.keyThisValue);if(nativeKeyValue)return context.platform.keyAttr(nativeKeyValue);if(forInfo){warn(context,`v-for :key "${trimmed}" 无法生成运行时 key 投影,已降级为 ${context.platform.keyAttr(context.platform.keyThisValue)}。建议使用稳定的基础类型 key。`,node.loc);return context.platform.keyAttr(context.platform.keyThisValue)}return context.platform.keyAttr(expValue)}if(isTopLevelObjectLiteral(rawExpValue)){if(context.objectLiteralBindMode===`inline`||isStaticObjectLiteral(rawExpValue))return createInlineObjectLiteralAttr(outputArgValue,rawExpValue,context);return createBindRuntimeAttr(outputArgValue,rawExpValue,context)}if(shouldFallbackToRuntimeBinding(rawExpValue,context.templateSafeCallNames,context)){const runtimeAttr=createBindRuntimeAttr(outputArgValue,rawExpValue,context);if(runtimeAttr)return runtimeAttr}const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);return`${outputArgValue}="${renderMustache$1(expValue,context)}"`}const IDENTIFIER_RE$1=/^[a-z_$][\w$]*$/i;function transformCustomDirective(name,exp,arg,context,location){if((/* @__PURE__ */ new Set([`bind`,`on`,`model`,`show`,`html`,`text`,`if`,`else-if`,`else`,`for`,`slot`,`cloak`,`once`])).has(name))return null;const dataAttrName=`data-v-${name}`;if(exp&&exp.type===NodeTypes.SIMPLE_EXPRESSION){recordBindingExpression(context,{kind:`attribute`,expression:exp.content,sourceLocation:exp.loc});const expValue=normalizeWxmlExpressionWithContext(exp.content,context);if(IDENTIFIER_RE$1.test(expValue))return`${dataAttrName}="${renderMustache$1(expValue,context)}"`;return`${dataAttrName}="${renderMustache$1(expValue,context)}"`}if(arg&&arg.type===NodeTypes.SIMPLE_EXPRESSION)return`${dataAttrName}="${arg.content}"`;warn(context,`自定义指令 v-${name} 可能需要运行时支持。已生成 data 属性:${dataAttrName}`,location);return dataAttrName}function getElementType(element){if(!element)return``;for(const prop of element.props)if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`type`){if(prop.value&&prop.value.type===NodeTypes.TEXT)return prop.value.content}return``}const CAMELIZE_RE=/-([a-z0-9])/gi;const IDENTIFIER_RE=/^[A-Z_$][\w$]*$/i;const NATIVE_MODEL_TAGS=/* @__PURE__ */ new Set([`input`,`textarea`,`select`,`switch`,`checkbox`,`slider`,`picker`]);function camelize(value){return value.replace(CAMELIZE_RE,(_,char)=>char.toUpperCase())}function isNativeModelElement(element){if(!element||element.tag!==element.tag.toLowerCase())return false;return NATIVE_MODEL_TAGS.has(element.tag)}function transformVModel(element,expValue,context,location){const escapedModel=escapeWxmlAttribute(expValue);const bindModel=event=>{return`${context.platform.eventBindingAttr(event)}="${WEVU_MODEL_HANDLER}" data-wv-model="${escapedModel}"`};if(!element)return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`;const tag=element.tag;const typeAttr=getElementType(element);switch(tag){case`input`:switch(typeAttr){case`checkbox`:return`checked="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`radio`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;default:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`}case`textarea`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`;case`select`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`switch`:case`checkbox`:return`checked="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`slider`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;case`picker`:return`value="${renderMustache$1(expValue,context)}" ${bindModel(`change`)}`;default:warn(context,`在 <${tag}> 上使用 v-model 可能无法按预期工作,已使用默认绑定。`,location);return`value="${renderMustache$1(expValue,context)}" ${bindModel(`input`)}`}}function transformComponentModelDirective(node,context){const rawExpValue=getBindDirectiveExpression(node).trim();if(!rawExpValue)return null;const rawModelName=node.arg?.type===NodeTypes.SIMPLE_EXPRESSION?node.arg.content.trim():``;if(node.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&!node.arg.isStatic){warn(context,`暂不支持动态 v-model 参数,已忽略该 v-model。`,node.loc);return null}const modelProp=rawModelName||`modelValue`;if(!modelProp)return null;const updateEvent=`update:${camelize(modelProp)}`;const eventSuffix=normalizeEventDatasetSuffix(updateEvent);const bindAttr=context.platform.eventBindingAttr(updateEvent);const updateExpression=IDENTIFIER_RE.test(rawExpValue)?`this.${rawExpValue} = $event`:`${rawExpValue} = $event`;const inlineExpression=registerInlineExpression$1(updateExpression,context);if(!inlineExpression){warn(context,`v-model="${rawExpValue}" 需要是可赋值的成员表达式。`,node.loc,`expression`);return null}const modelAttr=modelProp===`modelValue`?`model-value="${renderMustache$1(normalizeWxmlExpressionWithContext(rawExpValue,context),context)}"`:transformBindDirective(node,context,void 0,{isComponent:true});const updateAttr=[`data-${`wd`}-${eventSuffix}="1"`,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `);const modifierNames=node.modifiers.map(modifier=>modifier.content.trim()).filter(Boolean);const modifierProperties=modifierNames.map(name=>`${JSON.stringify(name)}:true`).join(`,`);const modifiersProp=normalizeComponentHostName(modelProp===`modelValue`?`modelModifiers`:`${modelProp}Modifiers`);const modifiersRef=modifierNames.length?registerRuntimeBindingExpression(`{${modifierProperties}}`,context,{hint:`v-model modifiers`}):null;if(modifiersRef)recordBindingExpression(context,{kind:`component-prop`,expression:`{${modifierProperties}}`,outputPath:modifiersRef.split(`[`)[0],sourceLocation:node.loc});return[modelAttr,updateAttr,modifiersRef?`${modifiersProp}="${renderMustache$1(modifiersRef,context)}"`:null].filter(Boolean).join(` `)}function transformModelDirective(node,context,elementNode,options){const{exp}=node;if(!exp)return null;if(options?.isComponent===true&&!isNativeModelElement(elementNode))return transformComponentModelDirective(node,context);if(node.arg){warn(context,`原生小程序元素不支持 v-model 参数,已忽略该 v-model。`,node.loc);return null}const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content:``;return transformVModel(elementNode,normalizeWxmlExpressionWithContext(rawExpValue,context),context,node.loc)}const SIMPLE_IDENTIFIER_RE=/^[A-Z_$][\w$]*$/i;const isSimpleHandler=value=>SIMPLE_IDENTIFIER_RE.test(value);function isScriptSetupHandlerBinding(value,context){return isSimpleHandler(value)&&Boolean(context.scriptSetupBindings?.[value])}function shouldUseDetailPayload(options){return options?.isComponent===true}function buildInlineScopeAttrs(scopeBindings,context){return scopeBindings.map((binding,index)=>{const escaped=escapeWxmlAttribute(binding);return`data-wv-s${index}="${renderMustache$1(escaped,context)}"`})}function buildInlineIndexAttrs(indexBindings,context){return indexBindings.map((binding,index)=>{const escaped=escapeWxmlAttribute(binding);return`data-wv-i${index}="${renderMustache$1(escaped,context)}"`})}function resolveEventPrefix(modifiers){const hasCatch=modifiers.some(modifier=>modifier.content===`catch`);const hasStop=modifiers.some(modifier=>modifier.content===`stop`);const hasCapture=modifiers.some(modifier=>modifier.content===`capture`);const hasMut=modifiers.some(modifier=>modifier.content===`mut`);if((hasCatch||hasStop)&&hasCapture)return`capture-catch`;if(hasCatch||hasStop)return`catch`;if(hasMut)return`mut-bind`;if(hasCapture)return`capture-bind`;return`bind`}function rejectUnsupportedDynamicOnName(node,context){const{arg}=node;if(arg?.type!==NodeTypes.SIMPLE_EXPRESSION||arg.isStatic)return false;warn(context,`小程序模板暂不支持动态 v-on 参数名,已忽略该事件绑定。`,node.loc);return true}function transformOnDirective(node,context,options){const{exp,arg}=node;if(!arg){if(exp?.type===NodeTypes.SIMPLE_EXPRESSION&&exp.content.trim())warn(context,`小程序暂不支持对象形式 v-on,已忽略该对象监听;请改用显式事件绑定。`,node.loc);else warn(context,`v-on 缺少对象监听表达式。`,node.loc,`template`,`WV2001`);return null}if(rejectUnsupportedDynamicOnName(node,context))return null;const argValue=arg.type===NodeTypes.SIMPLE_EXPRESSION?arg.content:``;if(!exp)return null;const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content.trim():``;const useDetailPayload=shouldUseDetailPayload(options);const inlineSource=(useDetailPayload||isScriptSetupHandlerBinding(rawExpValue,context))&&isSimpleHandler(rawExpValue)?`${rawExpValue}($event)`:rawExpValue;const isInlineExpression=inlineSource&&!isSimpleHandler(inlineSource);const inlineExpression=isInlineExpression?registerInlineExpression$1(inlineSource,context):null;const mappedEvent=options?.isComponent===true?argValue:context.platform.mapEventName(argValue);const eventSuffix=normalizeEventDatasetSuffix(mappedEvent);const eventPrefix=resolveEventPrefix(node.modifiers);const bindAttr=eventPrefix===`bind`&&options?.isComponent!==true?context.platform.eventBindingAlias?.(argValue,options?.tagName)??context.platform.eventBindingAttr(`${eventPrefix}:${mappedEvent}`):context.platform.eventBindingAttr(`${eventPrefix}:${mappedEvent}`);const detailAttr=useDetailPayload?`data-${`wd`}-${eventSuffix}="1"`:``;if(context.rewriteScopedSlot){if(inlineExpression){const scopeAttrs=buildInlineScopeAttrs(inlineExpression.scopeBindings,context);const indexAttrs=buildInlineIndexAttrs(inlineExpression.indexBindings,context);return[detailAttr,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,...scopeAttrs,...indexAttrs,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `)}if(!isInlineExpression&&rawExpValue)return[detailAttr,`data-${`wh`}-${eventSuffix}="${rawExpValue}"`,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `);if(isInlineExpression){warn(context,`作用域插槽的事件处理解析失败,请使用简单的方法引用。`,node.loc,`expression`);return[detailAttr,`${bindAttr}="${WEVU_OWNER_HANDLER}"`].filter(Boolean).join(` `)}}const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);if(inlineExpression){const scopeAttrs=buildInlineScopeAttrs(inlineExpression.scopeBindings,context);const indexAttrs=buildInlineIndexAttrs(inlineExpression.indexBindings,context);return[detailAttr,`data-${`wi`}-${eventSuffix}="${inlineExpression.id}"`,...scopeAttrs,...indexAttrs,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `)}if(isInlineExpression)return[detailAttr,`data-wv-inline-${eventSuffix}="${escapeWxmlAttribute(inlineSource)}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`].filter(Boolean).join(` `);return[detailAttr,`${bindAttr}="${expValue}"`].filter(Boolean).join(` `)}function transformShowDirective(node,context){const{exp}=node;if(!exp)return null;const rawExpValue=exp.type===NodeTypes.SIMPLE_EXPRESSION?exp.content:``;const expValue=normalizeWxmlExpressionWithContext(rawExpValue,context);return`style="${renderMustache$1(`${expValue} ? '' : 'display: none'`,context)}"`}function omitUnsupportedDynamicDirectiveNames(node,context){let compatibleProps;for(let index=0;index<node.props.length;index++){const prop=node.props[index];if(prop.type===NodeTypes.DIRECTIVE&&(prop.name===`bind`&&rejectUnsupportedDynamicBindName(prop,context)||prop.name===`on`&&rejectUnsupportedDynamicOnName(prop,context))){compatibleProps??=node.props.slice(0,index);continue}compatibleProps?.push(prop)}return compatibleProps?{...node,props:compatibleProps}:node}function transformDirective(node,context,elementNode,forInfo,options){const{name,exp,arg}=node;if(name===`bind`)return transformBindDirective(node,context,forInfo,options);if(name===`on`)return transformOnDirective(node,context,{...options,tagName:elementNode?.tag});if(name===`model`)return transformModelDirective(node,context,elementNode,options);if(name===`show`)return transformShowDirective(node,context);if(name===`html`){warn(context,`小程序不支持 v-html,请使用 rich-text 组件替代。`,node.loc);return null}if(name===`cloak`)return null;if(name===`once`){warn(context,`小程序对 v-once 支持不完整,元素将按普通方式渲染。`,node.loc);return null}return transformCustomDirective(name,exp,arg,context,node.loc)}function usesNativeDeclarationContext(context){return context.nativeSlotContext===true&&context.platform.name===`wechat`&&context.platform.nativeSlotContext!==false&&context.scopedSlotsRequireProps}function normalizeNativeForAliases(info,context){if(!usesNativeDeclarationContext(context)||!(context.nativeSlotContextTags??context.wevuComponentTags)?.size)return;const outerNames=new Set(context.forStack.flatMap(scope=>[scope.item,scope.index,scope.key,...Object.keys(scope.itemAliases??{})]));const aliases={};for(const key of[`item`,`index`,`key`]){const name=info[key];if(!name||!outerNames.has(name)&&!INLINE_GLOBALS.has(name))continue;let replacement;do replacement=`__wv_native_${key}_${context.forIndexSeed++}`;while(context.source.includes(replacement));aliases[name]=replacement;info[key]=replacement}if(!Object.keys(aliases).length)return;const itemAliases={};for(const[name,expression]of Object.entries(info.itemAliases??{})){const parsed=parseBabelExpressionFile(expression);if(!parsed)continue;traverse(parsed.ast,{Identifier(path){const replacement=aliases[path.node.name];if(replacement&&path.isReferencedIdentifier()&&!path.scope.getBinding(path.node.name)){path.replaceWith(t.identifier(replacement));path.skip()}}});const statement=parsed.ast.program.body[0];if(t.isExpressionStatement(statement))itemAliases[name]=generateExpression(statement.expression)}info.nativeAliases=aliases;info.itemAliases={...itemAliases,...aliases}}function createLoopIdentity(info){const key=info.effectiveNativeKey;if(!key||key.kind===`position`)return t.identifier(info.key??info.index??`index`);const item=t.identifier(info.item??`item`);const value=key.kind===`self`?item:t.memberExpression(item,t.stringLiteral(key.field),true);return t.callExpression(t.identifier(`String`),[t.logicalExpression(`??`,value,t.stringLiteral(``))])}function createNativeDeclaration(node,context){if(!usesNativeDeclarationContext(context)||!(context.nativeSlotContextTags??context.wevuComponentTags)?.has(node.tag))return;const site=`s${node.loc.start.offset}`;let keyExpression=`'${site}'`;if(context.forStack.length){const expression=t.callExpression(t.memberExpression(t.identifier(`JSON`),t.identifier(`stringify`)),[t.arrayExpression([t.stringLiteral(site),...context.forStack.map(createLoopIdentity)])]);keyExpression=registerRuntimeBindingAst(`native declaration ${site}`,expression,context);const outputPath=keyExpression.split(`[`)[0];recordBindingExpression({...context,rewriteScopedSlot:false},{kind:`component-prop`,expression:outputPath,outputPath,sourceLocation:node.loc})}return{site,loopDepth:context.forStack.length,keyExpression}}function appendNativeDeclarationAttributes(attrs,declaration,context){const parent=context.nativeDeclarationStack.at(-1)?.keyExpression??`''`;attrs.push(`${WEVU_NATIVE_DECLARATION_ADDRESS_PROP}="${renderMustache$1(`[${declaration.keyExpression},${parent}]`,context)}"`);attrs.push(`bind:${WEVU_NATIVE_DECLARATION_EVENT}="${WEVU_NATIVE_DECLARATION_METHOD}"`)}function nativeSlotParentAttribute(context){const parent=context.nativeDeclarationStack.at(-1)?.keyExpression;return`${WEVU_NATIVE_SLOT_PARENT_DATASET_ATTR}="${parent?renderMustache$1(parent,context):``}"`}function withNativeDeclarationScope(context,declaration,render){if(!declaration)return render();context.nativeDeclarationStack.push(declaration);try{return render()}finally{context.nativeDeclarationStack.pop()}}const BACKSLASH_RE$1=/\\/g;const SINGLE_QUOTE_RE$1=/'/g;const CR_RE=/\r/g;const LF_RE=/\n/g;function toWxmlStringLiteral(value){return`'${value.replace(BACKSLASH_RE$1,`\\\\`).replace(SINGLE_QUOTE_RE$1,`\\'`).replace(CR_RE,`\\r`).replace(LF_RE,`\\n`)}'`}function cloneForStack(context){return context.forStack.map(info=>({...info}))}function buildForIndexAccess(context){if(!context.forStack.length)return``;return context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}function generateExpressionCode(exp){const{code}=generate(exp,{compact:true});return code}const TRAILING_SEMICOLONS_RE=/;+\s*$/;function normalizeStyleFallbackValue(value){return value.trim().replace(TRAILING_SEMICOLONS_RE,``)}function buildStyleErrorFallback(staticValue,shouldHideByDefault){const segments=[];if(staticValue?.trim())segments.push(normalizeStyleFallbackValue(staticValue));if(shouldHideByDefault)segments.push(`display: none`);return segments.join(`;`)}function mergeJsExpressionParts(parts){if(!parts.length)return t.stringLiteral(``);if(parts.length===1)return parts[0];return t.arrayExpression(parts)}function unwrapTsExpression$2(node){if(t.isTSAsExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node))return unwrapTsExpression$2(node.expression);return node}function shouldPreferJsClassStyleRuntime(exp){const ast=parseBabelExpression(exp);if(!ast)return true;const visit=node=>{const current=unwrapTsExpression$2(node);if(t.isIdentifier(current)||t.isMemberExpression(current)||t.isOptionalMemberExpression(current)||t.isCallExpression(current)||t.isOptionalCallExpression(current)||t.isThisExpression(current)||t.isSuper(current)||t.isAwaitExpression(current)||t.isYieldExpression(current)||t.isNewExpression(current))return true;if(t.isStringLiteral(current)||t.isNumericLiteral(current)||t.isBooleanLiteral(current)||t.isNullLiteral(current)||t.isBigIntLiteral(current)||t.isRegExpLiteral(current))return false;if(t.isTemplateLiteral(current))return current.expressions.some(exp=>visit(exp));if(t.isArrayExpression(current)){for(const element of current.elements){if(!element||t.isSpreadElement(element))return true;if(visit(element))return true}return false}if(t.isObjectExpression(current)){for(const property of current.properties)if(t.isSpreadElement(property)||!t.isObjectProperty(property))return true;return false}if(t.isConditionalExpression(current))return visit(current.test)||visit(current.consequent)||visit(current.alternate);if(t.isLogicalExpression(current)||t.isBinaryExpression(current)){if(t.isPrivateName(current.left)||t.isPrivateName(current.right))return true;return visit(current.left)||visit(current.right)}if(t.isUnaryExpression(current))return visit(current.argument);return true};return visit(ast)}function createClassStyleBinding(context,type,exp,expAst,errorFallback){const sameTypeCount=context.classStyleBindings.filter(binding=>binding.type===type).length;const binding={name:type===`class`?`__wv_cls_${sameTypeCount}`:type===`style`?`__wv_style_${sameTypeCount}`:`__wv_bind_${sameTypeCount}`,type,exp,expAst,forStack:cloneForStack(context),conditions:context.bindingConditions?.slice()};if(errorFallback!==void 0)binding.errorFallback=errorFallback;return binding}function renderClassAttribute(staticClass,dynamicClassExp,context){const staticValue=staticClass?.trim();if(!dynamicClassExp)return staticValue?`class="${staticValue}"`:void 0;const parts=[];if(staticValue)parts.push(toWxmlStringLiteral(staticValue));if(context.classStyleRuntime===`wxs`&&!shouldPreferJsClassStyleRuntime(dynamicClassExp)){const normalizedParts=normalizeClassBindingExpression(dynamicClassExp,context);for(const part of normalizedParts)parts.push(`(${part})`);const mergedExp=parts.length>1?`[${parts.join(`,`)}]`:parts[0];context.classStyleWxs=true;return`class="${renderMustache$1(`${WEVU_CLASS_STYLE_RUNTIME_MODULE}.cls(${mergedExp})`,context)}"`}const jsParts=[];if(staticValue)jsParts.push(t.stringLiteral(staticValue));const dynamicAst=normalizeJsExpressionWithContext(dynamicClassExp,context,{hint:`class 绑定`,runtimePropAccess:`helper`});if(dynamicAst)jsParts.push(dynamicAst);const expAst=mergeJsExpressionParts(jsParts);const binding=createClassStyleBinding(context,`class`,generateExpressionCode(expAst),expAst,staticValue??``);context.classStyleBindings.push(binding);const indexAccess=buildForIndexAccess(context);return`class="${renderMustache$1(`${binding.name}${indexAccess}`,context)}"`}function renderStyleAttribute(staticStyle,dynamicStyleExp,vShowExp,context){const staticValue=staticStyle?.trim();if(!Boolean(dynamicStyleExp||vShowExp))return staticValue?`style="${staticValue}"`:void 0;const parts=[];if(staticValue)parts.push(toWxmlStringLiteral(staticValue));if(context.classStyleRuntime===`wxs`&&(!dynamicStyleExp||!shouldPreferJsClassStyleRuntime(dynamicStyleExp))){if(dynamicStyleExp){const normalizedParts=normalizeStyleBindingExpression(dynamicStyleExp,context);for(const part of normalizedParts)parts.push(`(${part})`)}if(vShowExp){const normalizedShow=normalizeWxmlExpressionWithContext(vShowExp,context);parts.push(`(${normalizedShow}) ? '' : 'display: none'`)}const mergedExp=parts.length>1?`[${parts.join(`,`)}]`:parts[0]||`''`;context.classStyleWxs=true;return`style="${renderMustache$1(`${WEVU_CLASS_STYLE_RUNTIME_MODULE}.style(${mergedExp})`,context)}"`}const jsParts=[];if(staticValue)jsParts.push(t.stringLiteral(staticValue));if(dynamicStyleExp){const dynamicAst=normalizeJsExpressionWithContext(dynamicStyleExp,context,{hint:`style 绑定`,runtimePropAccess:`helper`});if(dynamicAst)jsParts.push(dynamicAst)}if(vShowExp){const showAst=normalizeJsExpressionWithContext(vShowExp,context,{hint:`v-show`,runtimePropAccess:`helper`});if(showAst)jsParts.push(t.conditionalExpression(showAst,t.stringLiteral(``),t.stringLiteral(`display: none`)))}const expAst=mergeJsExpressionParts(jsParts);const binding=createClassStyleBinding(context,`style`,generateExpressionCode(expAst),expAst,buildStyleErrorFallback(staticValue,Boolean(vShowExp)));context.classStyleBindings.push(binding);const indexAccess=buildForIndexAccess(context);return`style="${renderMustache$1(`${binding.name}${indexAccess}`,context)}"`}function normalizeNativeAttributeValue(value,context){if(!usesNativeDeclarationContext(context)||!value.includes(`{{`)||!context.forStack.some(info=>info.itemAliases||info.itemAccess))return value;return value.replace(/\{\{([\s\S]+?)\}\}/g,(_match,expression)=>{return renderMustache$1(normalizeWxmlExpressionWithContext(expression,context),context)})}function transformAttribute(node,context,nameOverride){const{value}=node;const name=nameOverride??node.name;if(!value)return name;if(value.type===NodeTypes.TEXT){const content=node.name===context.platform.directives.forAttr?value.content:normalizeNativeAttributeValue(value.content,context);return`${name}="${escapeWxmlAttribute(content)}"`}return`${name}=""`}const builtinTagSet=new Set(components.map(tag=>tag.toLowerCase()));const MUSTACHE_EXPRESSION_RE$1=/\{\{([\s\S]*?)\}\}/g;function recordStaticAttributeBindings(prop,context,isComponentElement){const value=prop.value?.content;if(!value?.includes(`{{`))return;if(prop.name===WEVU_SLOT_OWNER_ID_ATTR)context.bindingManifest.features.scopedSlots=true;let kind=isComponentElement?`component-prop`:`attribute`;if(prop.name===context.platform.directives.forAttr)kind=`for`;else if(prop.name===context.platform.directives.ifAttr||prop.name===context.platform.directives.elifAttr)kind=`if`;else if(prop.name===`class`)kind=`class`;else if(prop.name===`style`)kind=`style`;for(const match of value.matchAll(MUSTACHE_EXPRESSION_RE$1)){const expression=match[1]?.trim();if(!expression)continue;recordBindingExpression(context,{kind,expression,sourceLocation:prop.value?.loc})}}function isBuiltinTag(tag){return builtinTagSet.has(tag.toLowerCase())}function prependStaticClass(staticClass,className){const tokens=staticClass?.split(/\s+/).filter(Boolean)??[];if(!tokens.includes(className))tokens.unshift(className);return tokens.join(` `)}function collectElementAttributes(node,context,options){const{props}=node;const resolvedTag=options?.resolvedTag??resolveTemplateTagName(node.tag,context);const isComponentElement=options?.isComponent??!isBuiltinTag(resolvedTag);const attrs=options?.extraAttrs?[...options.extraAttrs]:[];const declaration=isComponentElement?createNativeDeclaration(node,context):void 0;if(declaration){appendNativeDeclarationAttributes(attrs,declaration,context);attrs.push(`bind:${WEVU_NATIVE_SLOT_PARENT_EVENT}="${WEVU_NATIVE_SLOT_PARENT_METHOD}"`)}if(context.scopeId)attrs.push(`${context.scopeId}=""`);const mappedTagClass=resolveMappedHtmlTagClassName(node.tag,context,resolvedTag);let staticClass;let staticId;let dynamicClassExp;let dynamicClassLocation;let staticStyle;let dynamicStyleExp;let dynamicStyleLocation;let vShowExp;let vShowLocation;let vTextExp;let templateRef;let layoutHostKey;let hasDynamicIdBinding=false;const inFor=Boolean(options?.forInfo||context.forStack.length);for(const prop of props){if(prop.type===NodeTypes.ATTRIBUTE){recordStaticAttributeBindings(prop,context,isComponentElement);if(prop.name===`layout-host`){const rawKey=prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():``;if(!isComponentElement)warn(context,`layout-host 仅支持声明在组件节点上,当前节点已忽略。`,prop.loc);else if(!rawKey)warn(context,`layout-host 需要提供非空字符串 key。`,prop.loc);else layoutHostKey=rawKey;continue}if(prop.name===`slot-wrapper`||prop.name.startsWith(`slot-wrapper-`)||prop.name.startsWith(`slot-wrapper:`)||prop.name===`slot-single-root-no-wrapper`||prop.name.startsWith(`slot-single-root-no-wrapper-`)||prop.name.startsWith(`slot-single-root-no-wrapper:`))continue;if(prop.name===`ref`){if(prop.value?.type===NodeTypes.TEXT){const name=prop.value.content.trim();if(name)templateRef={name}}continue}if(prop.name===`class`&&prop.value?.type===NodeTypes.TEXT){staticClass=normalizeNativeAttributeValue(prop.value.content,context);continue}if(prop.name===`id`&&prop.value?.type===NodeTypes.TEXT){staticId=normalizeNativeAttributeValue(prop.value.content.trim(),context);continue}if(prop.name===`style`&&prop.value?.type===NodeTypes.TEXT){staticStyle=normalizeNativeAttributeValue(prop.value.content,context);continue}const attr=transformAttribute(prop,context,isComponentElement?normalizeComponentHostName(prop.name):void 0);if(attr)attrs.push(attr);continue}if(prop.type===NodeTypes.DIRECTIVE){if(options?.skipSlotDirective&&prop.name===`slot`)continue;if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`ref`){const rawExp=getBindDirectiveExpression(prop);if(rawExp){const expAst=normalizeJsExpressionWithContext(rawExp,context,{hint:`ref 绑定`});if(expAst)templateRef={expAst}}continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`id`)hasDynamicIdBinding=true;if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`layout-host`){warn(context,`暂不支持动态 layout-host,已忽略该绑定。`,prop.loc);continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&(prop.arg.content===`slot-wrapper`||prop.arg.content.startsWith(`slot-wrapper-`)||prop.arg.content.startsWith(`slot-wrapper:`)||prop.arg.content===`slot-single-root-no-wrapper`||prop.arg.content.startsWith(`slot-single-root-no-wrapper-`)||prop.arg.content.startsWith(`slot-single-root-no-wrapper:`))){if(prop.arg.content.endsWith(`-class`)||prop.arg.content.endsWith(`:class`)||prop.arg.content.endsWith(`-style`)||prop.arg.content.endsWith(`:style`))continue;warn(context,`暂不支持动态 ${prop.arg.content},已忽略该绑定。`,prop.loc);continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`class`){dynamicClassExp=getBindDirectiveExpression(prop)||void 0;dynamicClassLocation=prop.exp?.loc??prop.loc;continue}if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`style`){dynamicStyleExp=getBindDirectiveExpression(prop)||void 0;dynamicStyleLocation=prop.exp?.loc??prop.loc;continue}if(prop.name===`show`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){vShowExp=prop.exp.content;vShowLocation=prop.exp.loc;continue}if(prop.name===`text`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){const rawExp=prop.exp.content;const runtimeExp=shouldFallbackToRuntimeBinding(rawExp,context.templateSafeCallNames,context)?registerRuntimeBindingExpression(rawExp,context,{hint:`v-text`}):null;vTextExp=runtimeExp??normalizeWxmlExpressionWithContext(rawExp,context);recordBindingExpression(context,{kind:`text`,expression:rawExp,outputPath:runtimeExp?.split(`[`)[0],sourceLocation:prop.exp.loc});continue}const bindingCount=context.classStyleBindings.length;const functionPropCount=context.functionPropPaths.size;const inlineExpressionCount=context.inlineExpressions.length;const dir=transformDirective(prop,context,node,options?.forInfo,{isComponent:isComponentElement});if(prop.name===`bind`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){const arg=prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION?prop.arg.content:``;if(arg&&arg!==`ref`&&arg!==`class`&&arg!==`style`&&arg!==`key`&&arg!==`layout-host`){const generatedBinding=context.classStyleBindings.slice(bindingCount).find(binding=>binding.type===`bind`);recordBindingExpression(context,{kind:isComponentElement?`component-prop`:`attribute`,expression:getBindDirectiveExpression(prop),outputPath:generatedBinding?.name,sourceLocation:prop.exp.loc})}}else if(prop.name===`model`&&prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){context.bindingManifest.features.model=true;recordBindingExpression(context,{kind:isComponentElement?`component-prop`:`attribute`,expression:prop.exp.content,sourceLocation:prop.exp.loc})}if(context.functionPropPaths.size>functionPropCount)context.bindingManifest.features.functionProps=true;if(context.inlineExpressions.length>inlineExpressionCount)context.bindingManifest.features.inlineEvents=true;if(dir)attrs.push(dir)}}if(mappedTagClass)staticClass=prependStaticClass(staticClass,mappedTagClass);if(templateRef){const refIndex=context.templateRefIndexSeed++;const className=`${WEVU_TEMPLATE_REF_CLASS_PREFIX}${refIndex}`;staticClass=staticClass?`${staticClass} ${className}`:className;context.templateRefs.push({selector:`.${className}`,inFor,name:templateRef.name,expAst:templateRef.expAst,kind:isComponentElement?`component`:`element`});context.bindingManifest.features.templateRefs=true}if(layoutHostKey){if(!staticId&&hasDynamicIdBinding)warn(context,`layout-host 暂不支持与动态 id 同时使用,当前节点已忽略。`,node.loc);else{const hostIndex=context.layoutHostIndexSeed++;const hostId=staticId||`${WEVU_LAYOUT_HOST_ID_PREFIX}${hostIndex}`;const hostRefName=`${WEVU_LAYOUT_HOST_REF_PREFIX}${hostIndex}`;staticId=hostId;context.templateRefs.push({selector:`#${hostId}`,inFor:false,name:hostRefName,kind:`component`});context.bindingManifest.features.templateRefs=true;context.layoutHosts.push({key:layoutHostKey,refName:hostRefName,selector:`#${hostId}`,kind:`component`});context.bindingManifest.features.layout=true}}if(staticId)attrs.unshift(`id="${staticId}"`);const classBindingCount=context.classStyleBindings.length;const classAttr=renderClassAttribute(staticClass,dynamicClassExp,context);if(dynamicClassExp){const generatedBinding=context.classStyleBindings.slice(classBindingCount).find(binding=>binding.type===`class`);recordBindingExpression(context,{kind:`class`,expression:dynamicClassExp,outputPath:generatedBinding?.name,sourceLocation:dynamicClassLocation})}if(classAttr)attrs.unshift(classAttr);const styleBindingCount=context.classStyleBindings.length;const styleAttr=renderStyleAttribute(staticStyle,context.cssVars?dynamicStyleExp?`[${dynamicStyleExp}, ${WEVU_CSS_VARS_STYLE_KEY}]`:WEVU_CSS_VARS_STYLE_KEY:dynamicStyleExp,vShowExp,context);const generatedStyleBinding=context.classStyleBindings.slice(styleBindingCount).find(binding=>binding.type===`style`);if(dynamicStyleExp)recordBindingExpression(context,{kind:`style`,expression:dynamicStyleExp,outputPath:generatedStyleBinding?.name,sourceLocation:dynamicStyleLocation});if(vShowExp)recordBindingExpression(context,{kind:`style`,expression:vShowExp,outputPath:generatedStyleBinding?.name,sourceLocation:vShowLocation});if(context.cssVars)recordBindingExpression(context,{kind:`style`,expression:WEVU_CSS_VARS_STYLE_KEY,outputPath:generatedStyleBinding?.name});if(styleAttr)attrs.unshift(styleAttr);return{attrs,vTextExp,declaration}}function createStaticObjectKey$1(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function createValidIdentifier(name,fallback){if(name&&t.isValidIdentifier(name))return t.identifier(name);return t.identifier(fallback)}function buildConsoleErrorGuard(message,errorId){return t.ifStatement(t.logicalExpression(`&&`,t.binaryExpression(`!==`,t.unaryExpression(`typeof`,t.identifier(`console`)),t.stringLiteral(`undefined`)),t.binaryExpression(`===`,t.unaryExpression(`typeof`,t.memberExpression(t.identifier(`console`),t.identifier(`error`))),t.stringLiteral(`function`))),t.blockStatement([t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`console`),t.identifier(`error`)),[t.stringLiteral(message),t.cloneNode(errorId)]))]))}function buildRuntimeExpressionErrorGuard(binding,errorId){return buildConsoleErrorGuard(`[wevu] 模板运行时表达式执行失败: ${binding.name} = ${binding.exp}`,errorId)}function isScopedSlotOwnerBinding(exp){if(!exp)return false;const seen=/* @__PURE__ */ new WeakSet;const visit=node=>{if(!node||typeof node!==`object`)return false;if(seen.has(node))return false;seen.add(node);if(node.type===`MemberExpression`){const member=node;const property=member.property;if(!member.computed&&member.object?.type===`ThisExpression`&&property?.type===`Identifier`&&(property.name===WEVU_SLOT_OWNER_PROXY_KEY||property.name===WEVU_SLOT_OWNER_KEY))return true}for(const value of Object.values(node))if(Array.isArray(value)){if(value.some(item=>visit(item)))return true}else if(visit(value))return true;return false};return visit(exp)}function shouldReportRuntimeExpressionError(binding){return binding.type===`bind`&&!isScopedSlotOwnerBinding(binding.expAst)}function shouldReportForSourceError(info){const listExp=info.listExp?.trim()??``;return!listExp.startsWith(`${WEVU_SLOT_PROPS_DATA_KEY}.`)&&!listExp.startsWith(`${WEVU_SLOT_OWNER_KEY}.`)&&!isScopedSlotOwnerBinding(info.listExpAst)}function createDataPropsFallbackExpression(fallback){const propsObject=t.memberExpression(t.thisExpression(),t.identifier(WEVU_PROPS_KEY));const propsAccess=t.memberExpression(propsObject,t.identifier(`data`));const hasPropsObject=t.binaryExpression(`!=`,propsObject,t.nullLiteral());const hasPropsValue=t.logicalExpression(`&&`,hasPropsObject,t.logicalExpression(`||`,t.binaryExpression(`!==`,propsAccess,t.identifier(`undefined`)),t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`prototype`)),t.identifier(`hasOwnProperty`)),t.identifier(`call`)),[propsObject,t.stringLiteral(`data`)])));return t.conditionalExpression(hasPropsValue,propsAccess,fallback)}function createDataRuntimeAccess(helpers){const unrefHelper=helpers.unref?t.cloneNode(helpers.unref):t.identifier(`unref`);return t.callExpression(unrefHelper,[createDataPropsFallbackExpression(t.memberExpression(t.thisExpression(),t.identifier(`data`)))])}function rewriteDataAccessExpression(exp,helpers){if(t.isIdentifier(exp)&&exp.name===`data`)return createDataRuntimeAccess(helpers);if(t.isMemberExpression(exp))return t.memberExpression(rewriteDataAccessExpression(exp.object,helpers),t.cloneNode(exp.property),exp.computed);if(t.isObjectExpression(exp))return t.objectExpression(exp.properties.map(property=>{if(!t.isObjectProperty(property)||!t.isExpression(property.value))return t.cloneNode(property,true);return t.objectProperty(t.cloneNode(property.key),rewriteDataAccessExpression(property.value,helpers),property.computed,property.shorthand)}));if(t.isArrayExpression(exp))return t.arrayExpression(exp.elements.map(element=>{if(!element||t.isSpreadElement(element))return element?t.cloneNode(element,true):null;return rewriteDataAccessExpression(element,helpers)}));if(t.isBinaryExpression(exp))return t.isPrivateName(exp.left)||t.isPrivateName(exp.right)?t.cloneNode(exp,true):t.binaryExpression(exp.operator,rewriteDataAccessExpression(exp.left,helpers),rewriteDataAccessExpression(exp.right,helpers));if(t.isLogicalExpression(exp))return t.logicalExpression(exp.operator,rewriteDataAccessExpression(exp.left,helpers),rewriteDataAccessExpression(exp.right,helpers));if(t.isConditionalExpression(exp))return t.conditionalExpression(rewriteDataAccessExpression(exp.test,helpers),rewriteDataAccessExpression(exp.consequent,helpers),rewriteDataAccessExpression(exp.alternate,helpers));if(t.isUnaryExpression(exp))return t.unaryExpression(exp.operator,rewriteDataAccessExpression(exp.argument,helpers),exp.prefix);if(t.isCallExpression(exp))return t.callExpression(rewriteDataAccessExpression(exp.callee,helpers),exp.arguments.map(arg=>{if(t.isSpreadElement(arg))return t.cloneNode(arg,true);return rewriteDataAccessExpression(arg,helpers)}));return t.cloneNode(exp,true)}function buildNormalizedExpression(binding,helpers){const errorId=t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER);if(binding.type===`bind`){const exp=binding.expAst?t.cloneNode(binding.expAst,true):t.identifier(`undefined`);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(exp)]),t.catchClause(t.cloneNode(errorId),t.blockStatement([...shouldReportRuntimeExpressionError(binding)?[buildRuntimeExpressionErrorGuard(binding,errorId)]:[],t.returnStatement(t.identifier(`undefined`))])),null)])),[])}const normalizeHelper=binding.type===`class`?helpers.normalizeClass:helpers.normalizeStyle;const errorFallback=binding.errorFallback??``;const exp=binding.expAst?rewriteDataAccessExpression(binding.expAst,helpers):t.stringLiteral(``);const normalizedCall=t.callExpression(t.cloneNode(normalizeHelper),[exp]);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(normalizedCall)]),t.catchClause(t.cloneNode(errorId),t.blockStatement([...shouldReportRuntimeExpressionError(binding)?[buildRuntimeExpressionErrorGuard(binding,errorId)]:[],t.returnStatement(t.stringLiteral(errorFallback))])),null)])),[])}function buildArrayMapExpression(binding,forStack,level,listId,helpers){const itemParam=createValidIdentifier(forStack[level].item,`__wv_item_${level}`);const indexParam=createValidIdentifier(forStack[level].index,`__wv_index_${level}`);const body=[];const keyName=forStack[level].key;if(keyName&&t.isValidIdentifier(keyName)&&keyName!==indexParam.name)body.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(keyName),indexParam)]));const inner=buildForExpression(binding,forStack,level+1,helpers);body.push(t.returnStatement(inner));const callback=t.arrowFunctionExpression([itemParam,indexParam],t.blockStatement(body));return t.callExpression(t.memberExpression(listId,t.identifier(`map`)),[callback])}function buildObjectMapExpression(binding,forStack,level,listId,helpers){const resId=t.identifier(`__wv_res_${level}`);const keysId=t.identifier(`__wv_keys_${level}`);const loopIndexId=t.identifier(`__wv_i_${level}`);const keyId=t.identifier(`__wv_key_${level}`);const itemId=t.identifier(`__wv_item_${level}`);const itemAlias=forStack[level].item;const indexAlias=forStack[level].index;const keyAlias=forStack[level].key;const hasKeyAlias=Boolean(keyAlias&&t.isValidIdentifier(keyAlias));const loopBody=[t.variableDeclaration(`const`,[t.variableDeclarator(keyId,t.memberExpression(keysId,loopIndexId,true))]),t.variableDeclaration(`const`,[t.variableDeclarator(itemId,t.memberExpression(listId,keyId,true))])];if(itemAlias&&t.isValidIdentifier(itemAlias)&&itemAlias!==itemId.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(itemAlias),itemId)]));if(hasKeyAlias&&keyAlias&&keyAlias!==keyId.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(keyAlias),keyId)]));if(indexAlias&&t.isValidIdentifier(indexAlias)){const source=hasKeyAlias?loopIndexId:keyId;if(indexAlias!==source.name)loopBody.push(t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(indexAlias),source)]))}const inner=buildForExpression(binding,forStack,level+1,helpers);loopBody.push(t.expressionStatement(t.assignmentExpression(`=`,t.memberExpression(resId,keyId,true),inner)));const loop=t.forStatement(t.variableDeclaration(`let`,[t.variableDeclarator(loopIndexId,t.numericLiteral(0))]),t.binaryExpression(`<`,loopIndexId,t.memberExpression(keysId,t.identifier(`length`))),t.updateExpression(`++`,loopIndexId),t.blockStatement(loopBody));return t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(resId,t.objectExpression([]))]),t.variableDeclaration(`const`,[t.variableDeclarator(keysId,t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`keys`)),[listId]))]),loop,t.returnStatement(resId)])}function buildNumericListNormalization(level,listId){const indexId=t.identifier(`__wv_numeric_index_${level}`);const numberCheck=t.logicalExpression(`&&`,t.binaryExpression(`===`,t.unaryExpression(`typeof`,listId),t.stringLiteral(`number`)),t.callExpression(t.memberExpression(t.identifier(`Number`),t.identifier(`isFinite`)),[listId]));const length=t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`max`)),[t.numericLiteral(0),t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`floor`)),[listId])]);const normalized=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`from`)),[t.objectExpression([t.objectProperty(t.identifier(`length`),length)]),t.arrowFunctionExpression([t.identifier(`_`),indexId],indexId)]);return t.ifStatement(numberCheck,t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,listId,normalized))]))}function buildForExpression(binding,forStack,level,helpers){const expression=buildForExpressionBody(binding,forStack,level,helpers);const conditions=binding.conditions?.filter(condition=>condition.forDepth===level)??[];if(!conditions.length)return expression;const isProjectionBinding=binding.exp.startsWith(`v-for :key `);const condition=conditions.map(item=>t.cloneNode(isProjectionBinding?item.rawExpAst??item.expAst:item.expAst,true)).reduce((left,right)=>t.logicalExpression(`&&`,left,right));const fallback=level<forStack.length?t.arrayExpression([]):binding.type===`bind`?t.identifier(`undefined`):t.stringLiteral(``);return t.conditionalExpression(condition,expression,fallback)}function buildForExpressionBody(binding,forStack,level,helpers){if(level>=forStack.length)return buildNormalizedExpression(binding,helpers);const info=forStack[level];const listId=t.identifier(`__wv_list_${level}`);const listExpAst=binding.exp.startsWith(`v-for :key `)?info.rawListExpAst??info.listExpAst:info.projectedListExpAst??info.listExpAst;const listExp=listExpAst?t.cloneNode(listExpAst,true):t.arrayExpression([]);const unrefHelper=helpers.unref?t.cloneNode(helpers.unref):t.identifier(`unref`);const listUnrefExp=t.callExpression(unrefHelper,[listExp]);const listDecl=t.variableDeclaration(`let`,[t.variableDeclarator(listId,t.arrayExpression([]))]);const listSafeAssign=t.tryStatement(t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,listId,listUnrefExp))]),t.catchClause(t.identifier(`__wv_err_${level}`),t.blockStatement([...shouldReportForSourceError(info)?[buildConsoleErrorGuard(`[wevu] 模板 v-for 数据源表达式执行失败: ${info.listExp}`,t.identifier(`__wv_err_${level}`))]:[],t.expressionStatement(t.assignmentExpression(`=`,listId,t.arrayExpression([])))])),null);const arrayCheck=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`isArray`)),[listId]);const arrayMap=buildArrayMapExpression(binding,forStack,level,listId,helpers);const objectCheck=t.logicalExpression(`&&`,t.binaryExpression(`!=`,listId,t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,listId),t.stringLiteral(`object`)));const objectBlock=buildObjectMapExpression(binding,forStack,level,listId,helpers);const fallbackReturn=t.returnStatement(t.arrayExpression([]));const body=t.blockStatement([listDecl,listSafeAssign,buildNumericListNormalization(level,listId),t.ifStatement(arrayCheck,t.blockStatement([t.returnStatement(arrayMap)]),t.ifStatement(objectCheck,objectBlock,t.blockStatement([fallbackReturn])))]);return t.callExpression(t.arrowFunctionExpression([],body),[])}function buildComputedFunctionBody(binding,helpers){const expr=buildForExpression(binding,binding.forStack??[],0,helpers);return t.blockStatement([t.returnStatement(expr)])}function createMemberAccess(target,prop){if(t.isValidIdentifier(prop))return t.memberExpression(target,t.identifier(prop));return t.memberExpression(target,t.stringLiteral(prop),true)}function applyPropsAliasesToExpression(expression,propsAliases,forStack){if(!propsAliases||!Object.keys(propsAliases).length)return expression;const ast=t.file(t.program([t.expressionStatement(expression)]));traverse(ast,{Identifier(path){if(!path.isReferencedIdentifier())return;const name=path.node.name;const propName=propsAliases[name];if(!propName||path.scope.hasBinding(name)||forStack.some(scope=>scope.item===name||scope.index===name||scope.key===name))return;const replacement=createMemberAccess(t.memberExpression(t.thisExpression(),t.identifier(`__wevuProps`)),propName);const parent=path.parentPath;if(parent.isObjectProperty()&&parent.node.shorthand&&parent.node.key===path.node){parent.node.shorthand=false;parent.node.value=replacement;return}path.replaceWith(replacement)}});const statement=ast.program.body[0];return t.isExpressionStatement(statement)?statement.expression:expression}function buildClassStyleComputedEntries(bindings,helpers,propsAliases){const entries=[];for(const binding of bindings){const key=createStaticObjectKey$1(binding.name);const body=buildComputedFunctionBody({...binding,expAst:binding.expAst?applyPropsAliasesToExpression(t.cloneNode(binding.expAst,true),propsAliases,binding.forStack):binding.expAst},helpers);const fn=t.functionExpression(null,[],body);entries.push(t.objectProperty(key,fn))}return entries}function buildClassStyleComputedObject(bindings,helpers){if(!bindings.length)return null;const entries=buildClassStyleComputedEntries(bindings,helpers);if(!entries.length)return null;return t.objectExpression(entries)}function buildClassStyleComputedCode(bindings,helpers){if(!bindings.length)return null;const obj=buildClassStyleComputedObject(bindings,{normalizeClass:t.identifier(helpers.normalizeClassName),normalizeStyle:t.identifier(helpers.normalizeStyleName),unref:t.identifier(helpers.unrefName??`unref`)});if(!obj)return null;const{code}=generate(obj,{compact:true});return code}function buildInlineExpressionMap(inlineExpressions,unrefImport){return t.objectExpression(inlineExpressions.map(entry=>{const{parameterNames}=entry;let fn=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],parseBabelExpression(entry.expression)??t.identifier(`undefined`));if(entry.runtimeHelpers?.unref){if(!unrefImport)throw new Error(`生成 maybe-ref 内联表达式需要 unref 运行时导入。`);fn=t.callExpression(t.arrowFunctionExpression([t.identifier(entry.runtimeHelpers.unref)],fn),[t.cloneNode(unrefImport)])}const properties=[t.objectProperty(t.identifier(`keys`),t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)))),t.objectProperty(t.identifier(`fn`),fn)];if(entry.indexBindings?.length)properties.push(t.objectProperty(t.identifier(`indexKeys`),t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)))));if(entry.scopeResolvers?.length){const resolvers=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));properties.push(t.objectProperty(t.identifier(`scopeResolvers`),t.arrayExpression(entry.scopeKeys.map(key=>parseBabelExpression(resolvers.get(key)??``)??t.identifier(`undefined`)))))}return t.objectProperty(t.stringLiteral(entry.id),t.objectExpression(properties))}))}function buildInlineExpressionMapCode(inlineExpressions){if(!inlineExpressions.length)return null;return generate(buildInlineExpressionMap(inlineExpressions,t.identifier(`__wevuUnref`)),{compact:true}).code}function buildTemplateRefsCode(templateRefs){if(!templateRefs.length)return null;return`[${templateRefs.map(binding=>{const fields=[`selector:${JSON.stringify(binding.selector)}`,`inFor:${binding.inFor}`];if(binding.name)fields.push(`name:${JSON.stringify(binding.name)}`);if(binding.expAst)fields.push(`get:function(){return ${generate(binding.expAst,{compact:true}).code}}`);if(binding.kind)fields.push(`kind:${JSON.stringify(binding.kind)}`);return`{${fields.join(`,`)}}`}).join(`,`)}]`}function buildScopedSlotComponentScript(options){const computedCode=options.classStyleBindings.length?buildClassStyleComputedCode(options.classStyleBindings,{normalizeClassName:`__wevuNormalizeClass`,normalizeStyleName:`__wevuNormalizeStyle`,unrefName:`__wevuUnref`}):null;const inlineMapCode=buildInlineExpressionMapCode(options.inlineExpressions);const templateRefsCode=buildTemplateRefsCode(options.templateRefs);const layoutHostsCode=options.layoutHosts.length?JSON.stringify(options.layoutHosts):null;const requiredCapabilitySet=new Set(options.runtimeCapabilities?.required);const installerNames=WE_VU_RUNTIME_CAPABILITY_ORDER.filter(capability=>requiredCapabilitySet.has(capability)).map(capability=>WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability]);const lines=[`import { ${[`${WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent} as _createWevuScopedSlotComponent`,...installerNames.map(installerName=>`${installerName} as _${installerName}`)].join(`, `)} } from '${WE_VU_COMPILER_RUNTIME_MODULE_ID}';`];if(computedCode)lines.push(`import { normalizeClass as __wevuNormalizeClass, normalizeStyle as __wevuNormalizeStyle } from '${WE_VU_COMPILER_TEMPLATE_MODULE_ID}';`);if(computedCode||templateRefsCode||options.inlineExpressions.some(entry=>entry.runtimeHelpers?.unref))lines.push(`import { unref as __wevuUnref } from '${WE_VU_COMPILER_REACTIVITY_MODULE_ID}';`);lines.push(...installerNames.map(installerName=>`_${installerName}();`));lines.push(`const globalObject = typeof globalThis !== 'undefined' ? globalThis : undefined;`,`const createWevuScopedSlotComponent = globalObject?.${WEVU_SCOPED_SLOT_CREATOR_KEY}`,` ?? _createWevuScopedSlotComponent;`);if(computedCode)lines.push(`const __wevuComputed = ${computedCode};`);if(inlineMapCode)lines.push(`const __wevuInlineMap = ${inlineMapCode};`);if(templateRefsCode)lines.push(`const __wevuTemplateRefs = ${templateRefsCode};`);if(layoutHostsCode)lines.push(`const __wevuLayoutHosts = ${layoutHostsCode};`);const overrideParts=[`${JSON.stringify(WEVU_BINDING_MANIFEST_KEY)}:Object.freeze(${JSON.stringify(createRuntimeBindingManifest(options.bindingManifest,options.runtimeBindingManifest))})`];if(options.nativeSlotContext)overrideParts.push(`${JSON.stringify(WEVU_NATIVE_SLOT_CONTEXT_KEY)}:true`);if(computedCode)overrideParts.push(`computed:__wevuComputed`);if(layoutHostsCode)overrideParts.push(`layoutHosts:__wevuLayoutHosts`);if(inlineMapCode)overrideParts.push(`inlineMap:__wevuInlineMap`);if(templateRefsCode)overrideParts.push(`templateRefs:__wevuTemplateRefs`);lines.push(`if (typeof createWevuScopedSlotComponent === 'function') {`,` createWevuScopedSlotComponent({${overrideParts.join(`,`)}});`,`}`,``);return lines.join(`
|
|
7
7
|
`)}const BACKSLASH_RE=/\\/g;const SINGLE_QUOTE_RE=/'/g;function isFunctionBindingExpression(exp){try{const stmt=parse$3(`(${exp})`,{sourceType:`module`,plugins:[`typescript`]}).program.body[0];const expression=stmt&&`expression`in stmt?stmt.expression:void 0;return t.isArrowFunctionExpression(expression)||t.isFunctionExpression(expression)}catch{return false}}function createSlotFunctionBinding(exp,context,location){if(!isFunctionBindingExpression(exp))return null;const inline=registerInlineExpression$1(`(${exp})(...$event)`,context);if(!inline){warn(context,`作用域插槽函数参数编译失败。`,location,`expression`);return null}context.bindingManifest.features.functionProps=true;context.bindingManifest.features.inlineEvents=true;const scopeBindings=`[${inline.scopeBindings.join(`,`)}]`;const indexBindings=`[${inline.indexBindings.join(`,`)}]`;return`[${toWxmlStringLiteral$1(WEVU_SLOT_FUNCTION_TOKEN)},${toWxmlStringLiteral$1(inline.id)},${scopeBindings},${indexBindings}]`}function parseSlotPropsExpression(exp,context,location){const trimmed=exp.trim();if(!trimmed)return{};try{const stmt=parse$3(`(${trimmed}) => {}`,{sourceType:`module`,plugins:[`typescript`]}).program.body[0];if(!stmt||!(`expression`in stmt))return{};const expression=stmt.expression;if(!t.isArrowFunctionExpression(expression))return{};const param=expression.params[0];if(!param)return{};if(t.isIdentifier(param))return{[param.name]:``};if(t.isObjectPattern(param)){const mapping={};for(const prop of param.properties){if(t.isRestElement(prop)){warn(context,`小程序不支持作用域插槽的剩余解构元素。`,location);continue}if(!t.isObjectProperty(prop))continue;const key=prop.key;const propName=t.isIdentifier(key)?key.name:t.isStringLiteral(key)?key.value:void 0;if(!propName){warn(context,`小程序不支持作用域插槽的计算属性键。`,location);continue}const value=prop.value;if(t.isIdentifier(value)){mapping[value.name]=propName;continue}if(t.isAssignmentPattern(value)&&t.isIdentifier(value.left)){mapping[value.left.name]=propName;warn(context,`不支持作用域插槽参数的默认值,默认值将被忽略。`,location);continue}warn(context,`作用域插槽解构仅支持标识符绑定。`,location)}return mapping}}catch{warn(context,`作用域插槽参数解析失败,已回退为空参数。`,location,`expression`)}return{}}function collectSlotBindingExpression(node,context){let bindObjectExp=null;const namedBindings=[];const hasForDirective=node.props.some(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`for`);for(const prop of node.props){if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`name`)continue;if(prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`){if(prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION){const rawExpValue=getBindDirectiveExpression(prop);if(prop.arg.content===`name`||hasForDirective&&prop.arg.content===`key`)continue;if(rawExpValue)namedBindings.push({key:prop.arg.content,value:createSlotFunctionBinding(rawExpValue,context,prop.loc)??normalizeWxmlExpressionWithContext(rawExpValue,context)});continue}if(prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION){bindObjectExp=normalizeWxmlExpressionWithContext(prop.exp.content,context);continue}}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name!==`name`){const literal=prop.value?.type===NodeTypes.TEXT?prop.value.content:``;if(literal)namedBindings.push({key:prop.name,value:`'${literal.replace(BACKSLASH_RE,`\\\\`).replace(SINGLE_QUOTE_RE,`\\'`)}'`})}}if(bindObjectExp&&namedBindings.length){warn(context,`作用域插槽参数使用 v-bind 对象时,将忽略额外的命名绑定。`,node.loc);namedBindings.length=0}if(bindObjectExp)return bindObjectExp;if(!namedBindings.length)return null;return`[${namedBindings.map(entry=>`${toWxmlStringLiteral$1(entry.key)},${entry.value}`).join(`,`)}]`}function renderSlotNameAttribute(info,context,attrName){if(info.type===`static`&&info.value!=="default")return`${attrName}="${normalizeNativeAttributeValue(info.value,context)}"`;if(info.type===`dynamic`){const expValue=normalizeWxmlExpressionWithContext(info.exp,context);recordBindingExpression(context,{kind:attrName===`slot`?`component-prop`:`attribute`,expression:info.exp,sourceLocation:info.loc});return`${attrName}="${renderMustache$1(expValue,context)}"`}}function resolveSlotNameFromDirective(slotDirective){if(!slotDirective.arg)return{type:`default`};if(slotDirective.arg.type!==NodeTypes.SIMPLE_EXPRESSION)return{type:`default`};if(slotDirective.arg.isStatic)return{type:`static`,value:slotDirective.arg.content};return{type:`dynamic`,exp:slotDirective.arg.content,loc:slotDirective.loc}}function resolveSlotNameFromSlotElement(node){for(const prop of node.props){if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`name`){const value=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``;return value?{type:`static`,value}:{type:`default`}}if(prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`){if(prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`name`){const raw=getBindDirectiveExpression(prop);if(raw)return{type:`dynamic`,exp:raw,loc:prop.loc}}}}return{type:`default`}}function resolveSlotKey(context,info){if(info.type==="default")return`default`;if(info.type===`static`)return info.value||`default`;const key=`dyn-${hashString(info.exp)}`;warn(context,`动态插槽名通过表达式哈希匹配,请确保提供方与使用方的表达式一致。`,info.loc);return key}function stringifySlotName(info,context){if(info.type==="default")return`'default'`;if(info.type===`static`)return info.value==="default"?`'default'`:`'${info.value}'`;return normalizeWxmlExpressionWithContext(info.exp,context)}function resolveSlotStaticName(info){if(info.type==="default")return`default`;if(info.type===`static`)return info.value||`default`}const SLOT_PRESENCE_IDENTIFIER_RE=/^[A-Z_$][\w$]*$/i;function createSlotPresenceExpression(info){const slotName=resolveSlotStaticName(info);if(!slotName)return;const access=SLOT_PRESENCE_IDENTIFIER_RE.test(slotName)?`${WEVU_SLOT_NAMES_PROP}.${slotName}`:`${WEVU_SLOT_NAMES_PROP}['${slotName.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}']`;return`${WEVU_SLOT_NAMES_PROP}&&${access}`}function buildSlotDeclaration(name,propsExp,children,context,options){return{name,props:propsExp?parseSlotPropsExpression(propsExp,context,options?.location):{},children,implicitDefault:options?.implicitDefault,conditionKind:options?.conditionKind,condition:options?.condition,bindingCondition:options?.bindingCondition,wrapper:options?.wrapper}}function createScopedSlotComponent(context,slotKey,props,children,transformNode,options){const ownerHash=hashString(context.filename);const index=context.scopedSlotComponents.length;const id=`${slotKey}-${index}`;const componentName=`scoped-slot-${ownerHash}-${slotKey}-${index}`;const bindingManifest=createBindingManifest(context.bindingManifest.sourceFile);bindingManifest.features.scopedSlots=true;const asset={id,componentName,hostComponentName:options?.hostComponentName,slotKey,template:``,script:``,bindingManifest};context.scopedSlotComponents.push(asset);if(!context.bindingManifest.features.scopedSlots){context.bindingManifest.features.scopedSlots=true;context.bindingManifest.bindings.push({id:`b${context.bindingManifest.bindings.length}`,kind:`component-prop`,outputPath:WEVU_SLOT_OWNER_ID_KEY,sourceRoots:[WEVU_SLOT_OWNER_ID_KEY],sourcePaths:[WEVU_SLOT_OWNER_ID_KEY],dependencies:[{root:WEVU_SLOT_OWNER_ID_KEY,path:WEVU_SLOT_OWNER_ID_KEY,updateMode:`exact-path`}],scopes:[{kind:`root`,depth:0}],updateMode:`exact-path`})}const scopedContext={...context,bindingManifest,scopedSlotComponents:context.scopedSlotComponents,componentGenerics:{},miniProgramComponentTags:context.miniProgramComponentTags,scopeStack:[],slotPropStack:[],rewriteScopedSlot:true,hasSlotOutlet:false,classStyleBindings:[],bindingConditions:void 0,classStyleWxs:false,forStack:[],nativeDeclarationStack:[],forIndexSeed:0,inlineExpressions:[],inlineExpressionSeed:0,templateRefs:[],templateRefIndexSeed:0,layoutHosts:[],layoutHostIndexSeed:0,functionPropPaths:/* @__PURE__ */ new Set,functionPropNames:context.functionPropNames};const slotMapping={...collectScopePropMapping(context),...props};let template=withSlotProps(scopedContext,slotMapping,()=>{return withBindingCondition(scopedContext,options?.bindingCondition,()=>children.map(child=>transformNode(child,scopedContext)).join(``))});if(scopedContext.classStyleWxs){const ext=scopedContext.classStyleWxsExtension||`wxs`;template=`${buildClassStyleWxsTag(ext,scopedContext.classStyleWxsSrc,scopedContext.platform.name)}\n${template}`}asset.template=template;asset.componentGenerics=Object.keys(scopedContext.componentGenerics).length?scopedContext.componentGenerics:void 0;asset.classStyleWxs=scopedContext.classStyleWxs||void 0;asset.inlineExpressions=scopedContext.inlineExpressions.length?scopedContext.inlineExpressions:void 0;asset.templateRefs=scopedContext.templateRefs.length?scopedContext.templateRefs:void 0;asset.layoutHosts=scopedContext.layoutHosts.length?scopedContext.layoutHosts:void 0;const requiredCapabilities=[`scopedSlots`];if(bindingManifest.features.templateRefs)requiredCapabilities.push(`templateRefs`);if(bindingManifest.features.inlineEvents)requiredCapabilities.push(`inlineEvents`);if(bindingManifest.features.layout)requiredCapabilities.push(`layout`);const runtimeCapabilities=createWevuRuntimeCapabilityMetadata(requiredCapabilities);asset.runtimeCapabilities=runtimeCapabilities;asset.script=buildScopedSlotComponentScript({classStyleBindings:scopedContext.classStyleBindings,inlineExpressions:scopedContext.inlineExpressions,layoutHosts:scopedContext.layoutHosts,templateRefs:scopedContext.templateRefs,bindingManifest,runtimeBindingManifest:scopedContext.runtimeBindingManifest,runtimeCapabilities,nativeSlotContext:usesNativeDeclarationContext(scopedContext)});return{componentName,slotKey}}function injectAttributesIntoOpeningTag(source,attrs){if(!attrs.length)return source;if(!source.startsWith(`<`)||source.startsWith(`</`)||source.startsWith(`<!--`))return null;let tagNameEnd=1;while(tagNameEnd<source.length){const char=source[tagNameEnd];if(char===` `||char===`
|
|
8
8
|
`||char===`\r`||char===` `||char===`/`||char===`>`)break;tagNameEnd+=1}if(tagNameEnd<=1)return null;return`${source.slice(0,tagNameEnd)} ${attrs.join(` `)}${source.slice(tagNameEnd)}`}function createSlotAttributeNode(sourceNode,attr){const match=/^slot="([\s\S]*)"$/.exec(attr);if(!match)return null;return{type:NodeTypes.ATTRIBUTE,name:`slot`,nameLoc:sourceNode.loc,value:{type:NodeTypes.TEXT,content:match[1],loc:sourceNode.loc},loc:sourceNode.loc}}function injectSlotAttributeIntoElementNode(child,slotAttr,extraAttrs,transformNode,context){if(child.type!==NodeTypes.ELEMENT||child.tag===`template`)return null;const sourceNode=child;const slotAttribute=createSlotAttributeNode(sourceNode,slotAttr);if(!slotAttribute)return null;return injectAttributesIntoOpeningTag(transformNode({...sourceNode,props:[slotAttribute,...sourceNode.props]},context),extraAttrs)}function isRenderableFallbackChild(child){if(child.type===NodeTypes.COMMENT)return false;if(child.type===NodeTypes.TEXT)return child.content.trim().length>0;return true}function canInjectSlotAttributeIntoFallbackChild(child){if(child.type!==NodeTypes.ELEMENT)return true;return child.tag!==`slot`}function matchesSlotFallbackWrapperMatcher(matcher,value){if(!matcher)return true;if(!value)return false;if(Array.isArray(matcher))return matcher.some(item=>matchesSlotFallbackWrapperMatcher(item,value));return typeof matcher===`string`?matcher===value:matcher.test(value)}function normalizeSlotFallbackWrapperTag(tag){return tag?.trim()||`view`}function mergeSlotFallbackWrapperAttrs(base,override){if(!base)return override;if(!override)return base;return{...base,...override}}function resolveSlotFallbackWrapper(context,info){const resolved={tag:normalizeSlotFallbackWrapperTag(context.slotFallbackWrapper.tag),attrs:context.slotFallbackWrapper.attrs,singleRootNoWrapper:context.slotFallbackWrapper.singleRootNoWrapper??context.slotSingleRootNoWrapper};for(const rule of context.slotFallbackWrapper.rules)if(matchesSlotFallbackWrapperMatcher(rule.component,info.component)&&matchesSlotFallbackWrapperMatcher(rule.componentName,info.componentName)&&matchesSlotFallbackWrapperMatcher(rule.slot,info.slot)){if(rule.tag)resolved.tag=normalizeSlotFallbackWrapperTag(rule.tag);if(rule.attrs)resolved.attrs=mergeSlotFallbackWrapperAttrs(resolved.attrs,rule.attrs);if(rule.singleRootNoWrapper!==void 0)resolved.singleRootNoWrapper=rule.singleRootNoWrapper}if(info.local?.tag)resolved.tag=normalizeSlotFallbackWrapperTag(info.local.tag);if(info.local?.staticClass!==void 0)resolved.staticClass=info.local.staticClass;if(info.local?.dynamicClassExp!==void 0)resolved.dynamicClassExp=info.local.dynamicClassExp;if(info.local?.staticStyle!==void 0)resolved.staticStyle=info.local.staticStyle;if(info.local?.dynamicStyleExp!==void 0)resolved.dynamicStyleExp=info.local.dynamicStyleExp;if(info.local?.singleRootNoWrapper!==void 0)resolved.singleRootNoWrapper=info.local.singleRootNoWrapper;return resolved}function createStaticAttributeNode(name,value){return{type:NodeTypes.ATTRIBUTE,name,nameLoc:void 0,value:{type:NodeTypes.TEXT,content:value,loc:void 0},loc:void 0}}function renderSlotFallbackWrapperAttrs(wrapper,context){const attrs=[];for(const[name,value]of Object.entries(wrapper.attrs??{})){if(name===`class`&&(wrapper.staticClass!==void 0||wrapper.dynamicClassExp!==void 0))continue;if(name===`style`&&(wrapper.staticStyle!==void 0||wrapper.dynamicStyleExp!==void 0))continue;const attr=transformAttribute(createStaticAttributeNode(name,value),context);if(attr)attrs.push(attr)}const classBindingCount=context.classStyleBindings.length;const classAttr=renderClassAttribute(wrapper.staticClass,wrapper.dynamicClassExp,context);if(wrapper.dynamicClassExp){const binding=context.classStyleBindings.slice(classBindingCount).find(item=>item.type===`class`);recordBindingExpression(context,{kind:`class`,expression:wrapper.dynamicClassExp,outputPath:binding?.name})}if(classAttr)attrs.push(classAttr);const styleBindingCount=context.classStyleBindings.length;const styleAttr=renderStyleAttribute(wrapper.staticStyle,wrapper.dynamicStyleExp,void 0,context);if(wrapper.dynamicStyleExp){const binding=context.classStyleBindings.slice(styleBindingCount).find(item=>item.type===`style`);recordBindingExpression(context,{kind:`style`,expression:wrapper.dynamicStyleExp,outputPath:binding?.name})}if(styleAttr)attrs.push(styleAttr);return attrs}function reportNoArgumentSlotDirectiveDiagnostics(node,context){for(const prop of node.props){if(prop.type!==NodeTypes.DIRECTIVE||prop.arg)continue;if(prop.name===`on`)transformOnDirective(prop,context);else if(prop.name===`bind`&&!(prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.exp.content.trim()))transformBindDirective(prop,context)}}function renderPlainSlotOutlet(node,context,transformNode){const compatibleNode=omitUnsupportedDynamicDirectiveNames(node,context);reportNoArgumentSlotDirectiveDiagnostics(compatibleNode,context);const slotNameInfo=resolveSlotNameFromSlotElement(compatibleNode);const hasScopeBindings=compatibleNode.props.some(prop=>{if(prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`){if(!prop.arg)return prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION&&Boolean(prop.exp.content.trim());return prop.arg.type!==NodeTypes.SIMPLE_EXPRESSION||prop.arg.content!==`name`}return false});if(hasScopeBindings)warn(context,`已禁用作用域插槽参数,插槽绑定将被忽略。`,compatibleNode.loc);const fallbackContent=compatibleNode.children.map(child=>transformNode(child,context)).join(``);const slotAttrs=[];if(context.slottedScopeId)slotAttrs.push(`${context.slottedScopeId}=""`);const nameAttr=renderSlotNameAttribute(slotNameInfo,context,`name`);if(nameAttr)slotAttrs.push(nameAttr);if(usesNativeDeclarationContext(context)){slotAttrs.push(`bind:${WEVU_NATIVE_SLOT_PARENT_EVENT}="${WEVU_NATIVE_SLOT_PARENT_METHOD}"`);slotAttrs.push(nativeSlotParentAttribute(context))}const slotAttrString=slotAttrs.length?` ${slotAttrs.join(` `)}`:``;if(context.preserveComments&&fallbackContent&&!compatibleNode.children.some(isRenderableFallbackChild))return`${fallbackContent}<slot${slotAttrString} />`;if(!hasScopeBindings&&fallbackContent){const slotPresentExp=createSlotPresenceExpression(slotNameInfo);if(slotPresentExp){const slotTag=`<slot${slotAttrString} />`;return`${context.platform.wrapIf(slotPresentExp,slotTag,exp=>renderMustache$1(exp,context))}${context.platform.wrapElse(fallbackContent)}`}}return fallbackContent?`<slot${slotAttrString}>${fallbackContent}</slot>`:`<slot${slotAttrString} />`}function transformFallbackChild(child,context,transformNode){if(child.type===NodeTypes.ELEMENT&&child.tag===`slot`)return renderPlainSlotOutlet(child,context,transformNode);return transformNode(child,context)}function renderSlotFallback(decl,context,transformNode,options){return withBindingCondition(context,decl.bindingCondition,()=>renderSlotFallbackContent(decl,context,transformNode,options))}function renderSlotFallbackContent(decl,context,transformNode,options){const slotAttr=renderSlotNameAttribute(decl.name,context,`slot`);const wrapCondition=content=>{if(decl.conditionKind===`else`)return context.platform.wrapElse(content);if(decl.conditionKind===`else-if`&&decl.condition)return context.platform.wrapElseIf(decl.condition,content,exp=>renderMustache$1(exp,context));if(decl.conditionKind===`if`&&decl.condition)return context.platform.wrapIf(decl.condition,content,exp=>renderMustache$1(exp,context));return decl.condition?context.platform.wrapIf(decl.condition,content,exp=>renderMustache$1(exp,context)):content};if(!slotAttr){const rawContent=decl.children.map(child=>transformNode(child,context)).join(``);if(!rawContent)return``;return wrapCondition(rawContent)}const renderableChildren=decl.children.filter(isRenderableFallbackChild);if(!renderableChildren.length)return context.preserveComments?decl.children.map(child=>child.type===NodeTypes.COMMENT?transformNode(child,context):``).join(``):``;const staticSlotName=resolveSlotStaticName(decl.name);const wrapper=resolveSlotFallbackWrapper(context,{component:options?.component,componentName:options?.componentName,slot:staticSlotName,local:{...options?.wrapper,...decl.wrapper}});const wrapperAttrs=renderSlotFallbackWrapperAttrs(wrapper,context);const wrapperAttrString=wrapperAttrs.length?` ${wrapperAttrs.join(` `)}`:``;if(!wrapper.singleRootNoWrapper){const rawContent=decl.children.map(child=>transformFallbackChild(child,context,transformNode)).join(``);if(!rawContent)return``;return wrapCondition(`<${wrapper.tag} ${slotAttr}${wrapperAttrString}>${rawContent}</${wrapper.tag}>`)}if(renderableChildren.length===1){const child=renderableChildren[0];let projected=null;if(canInjectSlotAttributeIntoFallbackChild(child))projected=child.type===NodeTypes.ELEMENT&&isStructuralDirective(child).type?injectSlotAttributeIntoElementNode(child,slotAttr,wrapperAttrs,transformNode,context):injectAttributesIntoOpeningTag(transformNode(child,context),[slotAttr,...wrapperAttrs]);if(projected)return wrapCondition(context.preserveComments?decl.children.map(sourceChild=>sourceChild===child?projected:transformFallbackChild(sourceChild,context,transformNode)).join(``):projected)}const content=(context.preserveComments?decl.children:renderableChildren).map(child=>transformFallbackChild(child,context,transformNode)).join(``);return wrapCondition(`<${wrapper.tag} ${slotAttr}${wrapperAttrString}>${content}</${wrapper.tag}>`)}function recordSlotPropBindings(node,context){const hasForDirective=node.props.some(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`for`);for(const prop of node.props){if(prop.type!==NodeTypes.DIRECTIVE||prop.name!==`bind`)continue;if(prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION){if(prop.arg.content===`name`||hasForDirective&&prop.arg.content===`key`)continue;const expression=getBindDirectiveExpression(prop);if(expression)recordBindingExpression(context,{kind:`component-prop`,expression,sourceLocation:prop.exp?.loc??prop.loc});continue}if(prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION)recordBindingExpression(context,{kind:`component-prop`,expression:prop.exp.content,sourceLocation:prop.exp.loc})}}function transformSlotElement(node,context,transformNode){context.hasSlotOutlet=true;if(isScopedSlotsDisabled(context))return transformSlotElementPlain(node,context,transformNode);reportNoArgumentSlotDirectiveDiagnostics(node,context);const slotNameInfo=resolveSlotNameFromSlotElement(node);let slotPropsExp=collectSlotBindingExpression(node,context);recordSlotPropBindings(node,context);let fallbackContent=``;if(node.children.length>0)fallbackContent=node.children.map(child=>transformNode(child,context)).join(``);const slotAttrs=[];if(context.slottedScopeId)slotAttrs.push(`${context.slottedScopeId}=""`);const nameAttr=renderSlotNameAttribute(slotNameInfo,context,`name`);if(nameAttr)slotAttrs.push(nameAttr);if(!slotPropsExp&&usesNativeDeclarationContext(context)){slotAttrs.push(`bind:${WEVU_NATIVE_SLOT_PARENT_EVENT}="${WEVU_NATIVE_SLOT_PARENT_METHOD}"`);slotAttrs.push(nativeSlotParentAttribute(context))}const slotAttrString=slotAttrs.length?` ${slotAttrs.join(` `)}`:``;let slotTag=`<slot${slotAttrString} />`;const hasFallbackContent=fallbackContent&&(!context.preserveComments||node.children.some(isRenderableFallbackChild));const slotPresentExp=hasFallbackContent?createSlotPresenceExpression(slotNameInfo):void 0;if(hasFallbackContent){if(!slotPropsExp&&slotPresentExp)slotTag=`${context.platform.wrapIf(slotPresentExp,slotTag,exp=>renderMustache$1(exp,context))}${context.platform.wrapElse(fallbackContent)}`;else if(!slotPropsExp)slotTag=`<slot${slotAttrString}>${fallbackContent}</slot>`}if(!slotPropsExp&&(context.scopedSlotsRequireProps||slotNameInfo.type!=="default"||!context.isPage))return fallbackContent&&!hasFallbackContent?`${fallbackContent}${slotTag}`:slotTag;context.bindingManifest.features.scopedSlots=true;const hasScopeBindings=Boolean(slotPropsExp);const genericKey=`scoped-slots-${resolveSlotKey(context,slotNameInfo)}`;context.componentGenerics[genericKey]=true;slotPropsExp=slotPropsExp??`[]`;const scopedAttrs=[`${context.platform.directives.ifAttr}="${renderMustache$1(WEVU_SLOT_OWNER_ID_PROP,context)}"`,`${WEVU_SLOT_OWNER_ID_ATTR}="${renderMustache$1(WEVU_SLOT_OWNER_ID_PROP,context)}"`,`${WEVU_SLOT_PROPS_ATTR}="${renderMustache$1(slotPropsExp,context)}"`];if(context.slottedScopeId)scopedAttrs.push(`${context.slottedScopeId}=""`);if(context.slotMultipleInstance)scopedAttrs.push(`${WEVU_SLOT_SCOPE_ATTR}="${renderMustache$1(WEVU_SLOT_SCOPE_KEY,context)}"`);const scopedTag=`<${genericKey}${scopedAttrs.length?` ${scopedAttrs.join(` `)}`:``} />`;const nativeFallbackTag=context.forStack.length>0?``:context.platform.wrapIf(`!${WEVU_SLOT_OWNER_ID_PROP}`,slotTag,exp=>renderMustache$1(exp,context));const projectedContent=hasScopeBindings?`${scopedTag}${nativeFallbackTag}`:`${scopedTag}${context.platform.wrapElse(slotTag)}`;if(fallbackContent&&slotPresentExp)return`${context.platform.wrapIf(slotPresentExp,projectedContent,exp=>renderMustache$1(exp,context))}${context.platform.wrapElse(fallbackContent)}`;return fallbackContent&&!hasFallbackContent?`${fallbackContent}${projectedContent}`:projectedContent}function transformSlotElementPlain(node,context,transformNode){return renderPlainSlotOutlet(node,context,transformNode)}function hasLegacySlotAttribute(children){return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;return child.props.some(prop=>prop.type===NodeTypes.ATTRIBUTE&&prop.name===`slot`)})}function isRenderableSlotChild(child){if(child.type===NodeTypes.COMMENT)return false;if(child.type===NodeTypes.TEXT)return child.content.trim().length>0;return true}function hasDirectComponentSlotChild(children,context){return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;if(child.tag===`component`)return true;if(child.tag===`template`)return false;if(isBuiltinTag(resolveTemplateTagName(child.tag,context)))return false;return/^[A-Z]/.test(child.tag)})}function isWevuComponentTag(node,context){return context.wevuComponentTags?context.wevuComponentTags.has(node.tag):/^[A-Z]/.test(node.tag)}function hasDirectWevuComponentSlotChild(children,context){return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;const element=child;if(element.tag===`template`||isBuiltinTag(resolveTemplateTagName(element.tag,context)))return false;return isWevuComponentTag(element,context)})}function hasExplicitWevuComponentSlotDescendant(children,context){if(!context.wevuComponentTags?.size)return false;return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;const element=child;if(element.tag!==`template`&&!isBuiltinTag(resolveTemplateTagName(element.tag,context))&&context.wevuComponentTags.has(element.tag))return true;return hasExplicitWevuComponentSlotDescendant(element.children,context)})}function hasMiniProgramComponentSlotDescendant(children,context){const componentTags=context.miniProgramComponentTags;if(!componentTags?.size)return false;return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;const element=child;if(componentTags.has(element.tag))return true;return hasMiniProgramComponentSlotDescendant(element.children,context)})}function hasNativeComponentSlotDescendant(children,context){return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;const element=child;const resolvedTag=resolveTemplateTagName(element.tag,context);if(!isBuiltinTag(resolvedTag)&&element.tag.includes(`-`)&&!isWevuComponentTag(element,context))return true;return hasNativeComponentSlotDescendant(element.children,context)})}function hasForwardedSlotOutlet(children){return children.some(child=>{if(child.type!==NodeTypes.ELEMENT)return false;const element=child;return element.tag===`slot`||hasForwardedSlotOutlet(element.children)})}function shouldAugmentPlainSlot(decl,context,ownerNode,hasScopedSlotPropsSibling){if(context.scopedSlotsRequireProps)return false;if(hasForwardedSlotOutlet(decl.children))return false;if(context.rewriteScopedSlot&&!isWevuComponentTag(ownerNode,context))return false;if(context.rewriteScopedSlot){if(context.scopedSlotsCompiler===`augmented`&&!decl.implicitDefault)return true;return context.scopedSlotsCompiler===`augmented`?hasMiniProgramComponentSlotDescendant(decl.children,context)||hasExplicitWevuComponentSlotDescendant(decl.children,context):hasExplicitWevuComponentSlotDescendant(decl.children,context)||hasScopedSlotPropsSibling&&hasDirectComponentSlotChild(decl.children,context)}if(context.scopedSlotsCompiler===`augmented`){if(!decl.implicitDefault)return true;return hasMiniProgramComponentSlotDescendant(decl.children,context)||hasExplicitWevuComponentSlotDescendant(decl.children,context)||!isWevuComponentTag(ownerNode,context)&&hasNativeComponentSlotDescendant(decl.children,context)}if(!isWevuComponentTag(ownerNode,context))return false;return hasScopedSlotPropsSibling||hasDirectWevuComponentSlotChild(decl.children,context)||hasExplicitWevuComponentSlotDescendant(decl.children,context)}function resolveTemplateSlotCondition(node,context){const directive=node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&(prop.name===`if`||prop.name===`else-if`||prop.name===`else`)&&(prop.name===`else`||prop.exp?.type===NodeTypes.SIMPLE_EXPRESSION));if(!directive)return{};return resolveConditionalBranch(directive,context)}function resolveInlineStaticSlotName(name){if(!name.startsWith(`'`)||!name.endsWith(`'`))return null;const normalizedName=name.slice(1,-1);return/^[A-Z_$][\w$]*$/i.test(normalizedName)?normalizedName:null}function pushSlotNamesAttr(attrs,slotNames,context,options){if(!slotNames.length)return;const seen=/* @__PURE__ */ new Set;const entries=/* @__PURE__ */ new Map;for(const item of slotNames){const dedupeKey=`${item.name}:${item.condition??``}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);const entry=entries.get(item.name)??{conditions:[],unconditional:false};if(item.condition){if(!entry.unconditional)entry.conditions.push(item.condition)}else{entry.conditions.length=0;entry.unconditional=true}entries.set(item.name,entry)}const properties=[];const inlineProperties=[];let canInlineStatic=!options?.forInfo;for(const[name,entry]of entries){const value=entry.conditions.length?entry.conditions.map(condition=>`(${condition})`).join(`||`):`true`;const inlineName=resolveInlineStaticSlotName(name);if(value!==`true`||!inlineName)canInlineStatic=false;properties.push(`[${name}]:${value}`);inlineProperties.push(`${inlineName}:${value}`)}if(canInlineStatic){const inlineSlots=`{${inlineProperties.join(`,`)}}`;const mustache=context.mustacheInterpolation===`spaced`?renderMustache$1(inlineSlots,context):`{{ ${inlineSlots} }}`;attrs.push(`${WEVU_SLOT_NAMES_ATTR}="${mustache}"`);return}const slotNamesRef=registerRuntimeBindingExpression(`{${properties.join(`,`)}}`,context,{hint:`vue-slots 元数据`});if(slotNamesRef)recordBindingExpression(context,{kind:`component-prop`,expression:`{${properties.join(`,`)}}`,outputPath:slotNamesRef.split(`[`)[0]});if(slotNamesRef)attrs.push(`${WEVU_SLOT_NAMES_ATTR}="${renderMustache$1(slotNamesRef,context)}"`)}function shouldExposePlainSlotPresence(node){return node.tag===`component`}function normalizeBooleanAttributeValue(value){if(value===void 0||value===``)return true;if(value===`true`)return true;if(value===`false`)return false}function isSlotFallbackWrapperName(name,baseName,slotName){return name===baseName||slotName!==void 0&&(name===`${baseName}-${slotName}`||name===`${baseName}:${slotName}`)}function isSlotFallbackWrapperAttr(name,baseName,slotName,attrName){if(!attrName)return isSlotFallbackWrapperName(name,baseName,slotName);return name===`${baseName}-${attrName}`||slotName!==void 0&&(name===`${baseName}-${slotName}-${attrName}`||name===`${baseName}:${slotName}:${attrName}`)}function resolveLocalSlotFallbackWrapperConfig(node,context,slotName){const wrapper={};let hasConfig=false;for(const prop of node.props)if(prop.type===NodeTypes.ATTRIBUTE){if(isSlotFallbackWrapperAttr(prop.name,`slot-wrapper`,slotName)){const tag=prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():``;if(tag){wrapper.tag=tag;hasConfig=true}else warn(context,`slot-wrapper 需要提供非空标签名,已忽略该配置。`,prop.loc)}else if(isSlotFallbackWrapperAttr(prop.name,`slot-single-root-no-wrapper`,slotName)){const value=normalizeBooleanAttributeValue(prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():void 0);if(value===void 0)warn(context,`slot-single-root-no-wrapper 仅支持 true / false 静态值,已忽略该配置。`,prop.loc);else{wrapper.singleRootNoWrapper=value;hasConfig=true}}else if(isSlotFallbackWrapperAttr(prop.name,`slot-wrapper`,slotName,`class`)){const value=prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():``;if(value){wrapper.staticClass=value;hasConfig=true}}else if(isSlotFallbackWrapperAttr(prop.name,`slot-wrapper`,slotName,`style`)){const value=prop.value?.type===NodeTypes.TEXT?prop.value.content.trim():``;if(value){wrapper.staticStyle=value;hasConfig=true}}}else if(prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION){if(isSlotFallbackWrapperAttr(prop.arg.content,`slot-wrapper`,slotName,`class`)){const exp=getBindDirectiveExpression(prop);if(exp){wrapper.dynamicClassExp=exp;hasConfig=true}}else if(isSlotFallbackWrapperAttr(prop.arg.content,`slot-wrapper`,slotName,`style`)){const exp=getBindDirectiveExpression(prop);if(exp){wrapper.dynamicStyleExp=exp;hasConfig=true}}}return hasConfig?wrapper:void 0}function mergeLocalSlotFallbackWrapperConfig(base,override){if(!base)return override;if(!override)return base;return{...base,...override}}function renderPlainSlotContentInSourceOrder(renderItems,plainSlotDeclarations,implicitDefaultDeclaration,ownerComponent,ownerComponentName,ownerWrapper,context,transformNode){const plainSlots=new Set(plainSlotDeclarations);const shouldRenderImplicitDefault=implicitDefaultDeclaration?plainSlots.has(implicitDefaultDeclaration):false;return renderItems.map(item=>{if(item.type===`declaration`)return plainSlots.has(item.declaration)?renderSlotFallback(item.declaration,context,transformNode,{component:ownerComponent,componentName:ownerComponentName,wrapper:ownerWrapper}):``;return shouldRenderImplicitDefault||!implicitDefaultDeclaration&&item.child.type===NodeTypes.COMMENT?transformNode(item.child,context):``}).join(``)}function shouldTransformAsComponentWithSlots(node,context,resolvedTag=resolveTemplateTagName(node.tag,context)){const slotDirective=findSlotDirective(node);const templateSlotChildren=node.children.filter(child=>child.type===NodeTypes.ELEMENT&&child.tag===`template`&&findSlotDirective(child));const shouldUseAugmentedDefaultSlot=node.children.length>0&&!context.scopedSlotsRequireProps&&!isBuiltinTag(resolvedTag);const shouldUseSlotPresenceMetadata=node.children.length>0&&isWevuComponentTag(node,context);return slotDirective||templateSlotChildren.length>0||shouldUseAugmentedDefaultSlot||shouldUseSlotPresenceMetadata}function transformComponentWithSlots(node,context,transformNode,options){if(isScopedSlotsDisabled(context))return transformComponentWithSlotsFallback(node,context,transformNode,options);const extraAttrs=options?.extraAttrs??[];const slotDeclarations=[];const slotDirective=findSlotDirective(node);const ownerWrapper=resolveLocalSlotFallbackWrapperConfig(node,context);const nonTemplateChildren=[];const renderItems=[];for(const child of node.children){const compatibleChild=child.type===NodeTypes.ELEMENT?omitUnsupportedDynamicDirectiveNames(child,context):child;if(compatibleChild.type===NodeTypes.ELEMENT&&compatibleChild.tag===`template`){const templateSlot=findSlotDirective(compatibleChild);if(templateSlot){const slotName=resolveSlotNameFromDirective(templateSlot);const templateSlotCondition=resolveTemplateSlotCondition(compatibleChild,context);const declaration=buildSlotDeclaration(slotName,templateSlot.exp?.type===NodeTypes.SIMPLE_EXPRESSION?templateSlot.exp.content:void 0,compatibleChild.children,context,{...templateSlotCondition,location:templateSlot.loc,wrapper:mergeLocalSlotFallbackWrapperConfig(resolveLocalSlotFallbackWrapperConfig(node,context,slotName.type===`static`?slotName.value:void 0),resolveLocalSlotFallbackWrapperConfig(compatibleChild,context))});slotDeclarations.push(declaration);renderItems.push({type:`declaration`,declaration});continue}}nonTemplateChildren.push(compatibleChild);if(isRenderableSlotChild(compatibleChild)||context.preserveComments&&compatibleChild.type===NodeTypes.COMMENT)renderItems.push({type:`default-child`,child:compatibleChild})}const defaultSlotChildren=nonTemplateChildren.filter(isRenderableSlotChild);const defaultSlotContent=context.preserveComments?nonTemplateChildren:defaultSlotChildren;let implicitDefaultDeclaration;if(slotDirective){if(slotDeclarations.length)warn(context,`组件上的 v-slot 与 <template v-slot> 不能同时使用;仅使用组件上的 v-slot。`,slotDirective.loc);slotDeclarations.length=0;slotDeclarations.push(buildSlotDeclaration(resolveSlotNameFromDirective(slotDirective),slotDirective.exp?.type===NodeTypes.SIMPLE_EXPRESSION?slotDirective.exp.content:void 0,node.children,context,{wrapper:ownerWrapper,location:slotDirective.loc}))}else if(slotDeclarations.length&&defaultSlotChildren.length){if(slotDeclarations.some(decl=>decl.name.type==="default"||decl.name.type===`static`&&decl.name.value==="default"))warn(context,`存在显式的 v-slot:default,默认插槽内容将被忽略。`,node.loc);else{implicitDefaultDeclaration=buildSlotDeclaration({type:`default`},void 0,defaultSlotContent,context,{implicitDefault:true});slotDeclarations.push(implicitDefaultDeclaration)}}else if(!slotDeclarations.length&&defaultSlotChildren.length&&!context.scopedSlotsRequireProps&&!hasLegacySlotAttribute(defaultSlotChildren)){implicitDefaultDeclaration=buildSlotDeclaration({type:`default`},void 0,defaultSlotContent,context,{implicitDefault:true});slotDeclarations.push(implicitDefaultDeclaration)}if(!slotDeclarations.length){const{attrs,vTextExp,declaration}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=withNativeDeclarationScope(context,declaration,()=>node.children.map(child=>transformNode(child,context)).join(``));if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);if(children&&defaultSlotChildren.length&&!hasLegacySlotAttribute(defaultSlotChildren)&&isWevuComponentTag(node,context))pushSlotNamesAttr(attrs,[{name:`'default'`}],context,{forInfo:options?.forInfo});const mergedAttrs=[...extraAttrs,...attrs];const attrString=mergedAttrs.length?` ${mergedAttrs.join(` `)}`:``;const tag=resolveTemplateTagName(node.tag,context);return children?`<${tag}${attrString}>${children}</${tag}>`:`<${tag}${attrString} />`}const scopedSlotDeclarations=[];const plainSlotDeclarations=[];const hasScopedSlotProps=slotDeclarations.some(decl=>Object.keys(decl.props).length>0);for(const decl of slotDeclarations)if(Object.keys(decl.props).length>0||shouldAugmentPlainSlot(decl,context,node,hasScopedSlotProps))scopedSlotDeclarations.push(decl);else plainSlotDeclarations.push(decl);const slotNames=[];const slotGenericAttrs=[];const ownerComponentName=context.componentNameMap?.[node.tag];for(const decl of scopedSlotDeclarations){const slotKey=resolveSlotKey(context,decl.name);const{componentName}=createScopedSlotComponent(context,slotKey,decl.props,decl.children,transformNode,{hostComponentName:resolveTemplateTagName(node.tag,context),bindingCondition:decl.bindingCondition});slotNames.push({name:stringifySlotName(decl.name,context),condition:decl.condition});slotGenericAttrs.push(`generic:scoped-slots-${slotKey}="${componentName}"`)}if(shouldExposePlainSlotPresence(node)||isWevuComponentTag(node,context))for(const decl of plainSlotDeclarations)slotNames.push({name:stringifySlotName(decl.name,context),condition:decl.condition});const{attrs,declaration}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});const mergedAttrs=[...extraAttrs,...attrs,...slotGenericAttrs];pushSlotNamesAttr(mergedAttrs,slotNames,context,{forInfo:options?.forInfo});if(scopedSlotDeclarations.length){const scopePropsExp=buildScopePropsExpression(context);if(scopePropsExp){mergedAttrs.push(`${WEVU_SLOT_SCOPE_ATTR}="${renderMustache$1(scopePropsExp,context)}"`);recordBindingExpression(context,{kind:`component-prop`,expression:scopePropsExp})}const ownerIdExp=context.rewriteScopedSlot?`${WEVU_SLOT_OWNER_ID_PROP} || ${WEVU_SLOT_OWNER_ID_KEY} || ''`:`${WEVU_SLOT_OWNER_ID_KEY} || ''`;mergedAttrs.push(`${WEVU_SLOT_OWNER_ID_ATTR}="${renderMustache$1(ownerIdExp,context)}"`);recordBindingExpression(context,{kind:`component-prop`,expression:ownerIdExp})}const attrString=mergedAttrs.length?` ${mergedAttrs.join(` `)}`:``;const tag=resolveTemplateTagName(node.tag,context);const plainSlotContent=withNativeDeclarationScope(context,declaration,()=>slotDirective?plainSlotDeclarations.map(decl=>renderSlotFallback(decl,context,transformNode,{component:node.tag,componentName:ownerComponentName,wrapper:ownerWrapper})).join(``):renderPlainSlotContentInSourceOrder(renderItems,plainSlotDeclarations,implicitDefaultDeclaration,node.tag,ownerComponentName,ownerWrapper,context,transformNode));return plainSlotContent?`<${tag}${attrString}>${plainSlotContent}</${tag}>`:`<${tag}${attrString} />`}function transformComponentWithSlotsFallback(node,context,transformNode,options){const extraAttrs=options?.extraAttrs??[];const slotDeclarations=[];const slotDirective=findSlotDirective(node);const ownerWrapper=resolveLocalSlotFallbackWrapperConfig(node,context);const nonTemplateChildren=[];const renderItems=[];for(const child of node.children){const compatibleChild=child.type===NodeTypes.ELEMENT?omitUnsupportedDynamicDirectiveNames(child,context):child;if(compatibleChild.type===NodeTypes.ELEMENT&&compatibleChild.tag===`template`){const templateSlot=findSlotDirective(compatibleChild);if(templateSlot){const slotName=resolveSlotNameFromDirective(templateSlot);const templateSlotCondition=resolveTemplateSlotCondition(compatibleChild,context);const declaration=buildSlotDeclaration(slotName,templateSlot.exp?.type===NodeTypes.SIMPLE_EXPRESSION?templateSlot.exp.content:void 0,compatibleChild.children,context,{...templateSlotCondition,location:templateSlot.loc,wrapper:mergeLocalSlotFallbackWrapperConfig(resolveLocalSlotFallbackWrapperConfig(node,context,slotName.type===`static`?slotName.value:void 0),resolveLocalSlotFallbackWrapperConfig(compatibleChild,context))});slotDeclarations.push(declaration);renderItems.push({type:`declaration`,declaration});continue}}nonTemplateChildren.push(compatibleChild);if(isRenderableSlotChild(compatibleChild)||context.preserveComments&&compatibleChild.type===NodeTypes.COMMENT)renderItems.push({type:`default-child`,child:compatibleChild})}const defaultSlotChildren=nonTemplateChildren.filter(isRenderableSlotChild);const defaultSlotContent=context.preserveComments?nonTemplateChildren:defaultSlotChildren;let implicitDefaultDeclaration;if(slotDirective){if(slotDeclarations.length)warn(context,`组件上的 v-slot 与 <template v-slot> 不能同时使用;仅使用组件上的 v-slot。`,slotDirective.loc);slotDeclarations.length=0;slotDeclarations.push(buildSlotDeclaration(resolveSlotNameFromDirective(slotDirective),slotDirective.exp?.type===NodeTypes.SIMPLE_EXPRESSION?slotDirective.exp.content:void 0,node.children,context,{wrapper:ownerWrapper,location:slotDirective.loc}))}else if(slotDeclarations.length&&defaultSlotChildren.length){if(slotDeclarations.some(decl=>decl.name.type==="default"||decl.name.type===`static`&&decl.name.value==="default"))warn(context,`存在显式的 v-slot:default,默认插槽内容将被忽略。`,node.loc);else{implicitDefaultDeclaration=buildSlotDeclaration({type:`default`},void 0,defaultSlotContent,context);slotDeclarations.push(implicitDefaultDeclaration)}}if(!slotDeclarations.length){const{attrs,vTextExp,declaration}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=withNativeDeclarationScope(context,declaration,()=>node.children.map(child=>transformNode(child,context)).join(``));if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);if(children&&defaultSlotChildren.length&&!hasLegacySlotAttribute(defaultSlotChildren)&&isWevuComponentTag(node,context))pushSlotNamesAttr(attrs,[{name:`'default'`}],context,{forInfo:options?.forInfo});const mergedAttrs=[...extraAttrs,...attrs];const attrString=mergedAttrs.length?` ${mergedAttrs.join(` `)}`:``;const tag=resolveTemplateTagName(node.tag,context);return children?`<${tag}${attrString}>${children}</${tag}>`:`<${tag}${attrString} />`}if(slotDeclarations.some(decl=>Object.keys(decl.props).length))warn(context,`已禁用作用域插槽参数,插槽绑定将被忽略。`,node.loc);const{attrs,declaration}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});const renderedSlots=withNativeDeclarationScope(context,declaration,()=>slotDirective?slotDeclarations.map(decl=>renderSlotFallback(decl,context,transformNode,{component:node.tag,componentName:context.componentNameMap?.[node.tag],wrapper:ownerWrapper})).join(``):renderPlainSlotContentInSourceOrder(renderItems,slotDeclarations,implicitDefaultDeclaration,node.tag,context.componentNameMap?.[node.tag],ownerWrapper,context,transformNode));const mergedAttrs=[...extraAttrs,...attrs];if(shouldExposePlainSlotPresence(node)||isWevuComponentTag(node,context))pushSlotNamesAttr(mergedAttrs,slotDeclarations.map(decl=>({name:stringifySlotName(decl.name,context),condition:decl.condition})),context,{forInfo:options?.forInfo});const attrString=mergedAttrs.length?` ${mergedAttrs.join(` `)}`:``;const tag=resolveTemplateTagName(node.tag,context);return renderedSlots?`<${tag}${attrString}>${renderedSlots}</${tag}>`:`<${tag}${attrString} />`}function transformComponentElement(node,context,transformNode){let isDirective;for(const prop of node.props)if(prop.type===NodeTypes.DIRECTIVE){if(prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`is`){isDirective=prop;break}}if(!isDirective){warn(context,`<component> 未提供 :is 绑定,将按普通元素处理。`,node.loc);return transformNormalElement(node,context,transformNode)}const componentVar=getBindDirectiveExpression(isDirective);if(!componentVar){warn(context,`<component> 未提供 :is 绑定,将按普通元素处理。`,isDirective.loc);return transformNormalElement(node,context,transformNode)}recordBindingExpression(context,{kind:`component-prop`,expression:componentVar,sourceLocation:isDirective.exp?.loc});const otherProps=node.props.filter(prop=>prop!==isDirective);const slotDirective=findSlotDirective(node);const templateSlotChildren=node.children.filter(child=>child.type===NodeTypes.ELEMENT&&child.tag===`template`&&findSlotDirective(child));const shouldUseAugmentedDefaultSlot=node.children.length>0&&!context.scopedSlotsRequireProps;if(slotDirective||templateSlotChildren.length>0||shouldUseAugmentedDefaultSlot)return transformComponentWithSlots({...node,props:otherProps},context,transformNode,{extraAttrs:[`data-is="${renderMustache$1(componentVar,context)}"`]});const componentNode={...node,props:otherProps};const{attrs,vTextExp}=collectElementAttributes(componentNode,context,{isComponent:true,resolvedTag:`component`});let children=node.children.map(child=>transformNode(child,context)).join(``);if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);const attrString=attrs.length?` ${attrs.join(` `)}`:``;warn(context,`动态组件使用 data-is 属性,可能需要小程序运行时支持。`,node.loc);return`<component data-is="${renderMustache$1(componentVar,context)}"${attrString}>${children}</component>`}function transformNormalElement(node,context,transformNode){const tag=resolveTemplateTagName(node.tag,context);if(shouldTransformAsComponentWithSlots(node,context,tag))return transformComponentWithSlots(node,context,transformNode);const{attrs,vTextExp,declaration}=collectElementAttributes(node,context,{resolvedTag:tag});let children=``;if(node.children.length>0)children=withNativeDeclarationScope(context,declaration,()=>node.children.map(child=>transformNode(child,context)).join(``));if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);const attrString=attrs.length?` ${attrs.join(` `)}`:``;return children?`<${tag}${attrString}>${children}</${tag}>`:`<${tag}${attrString} />`}const RUNTIME_BINDING_REF_RE=/^__wv_bind_\d+(?:\[[A-Z_$][\w$]*\])*$/i;function createProjectionIdentifiers(sourceExpression,projector,reservedNames){const reservedBindings=[...reservedNames].filter(name=>t.isValidIdentifier(name)).map(name=>t.variableDeclarator(t.identifier(name)));const ast=t.file(t.program([...reservedBindings.length?[t.variableDeclaration(`let`,reservedBindings)]:[],t.expressionStatement(t.sequenceExpression([t.cloneNode(sourceExpression,true),t.cloneNode(projector,true)]))]));let identifiers;traverse(ast,{Program(path){identifiers={source:path.scope.generateUidIdentifierBasedOnNode(sourceExpression,`source`),arrayItem:path.scope.generateUidIdentifier(`item`),arrayIndex:path.scope.generateUidIdentifier(`index`),result:path.scope.generateUidIdentifier(`result`),keys:path.scope.generateUidIdentifier(`keys`),loopIndex:path.scope.generateUidIdentifier(`loopIndex`),key:path.scope.generateUidIdentifier(`key`),objectItem:path.scope.generateUidIdentifier(`item`)};path.stop()}});if(!identifiers)throw new Error(`无法为 v-for 解构投影分配局部标识符。`);return identifiers}function parseItemPattern(source){try{const statement=parseJsLike(`(${source}) => {}`).program.body[0];if(!statement||!t.isExpressionStatement(statement))return null;const expression=statement.expression;if(!t.isArrowFunctionExpression(expression)||expression.params.length!==1)return null;const pattern=expression.params[0];return t.isRestElement(pattern)?null:pattern}catch{return null}}function createPatternProjector(pattern,aliasNames,forInfo){const params=[t.cloneNode(pattern,true)];if(forInfo.index&&t.isValidIdentifier(forInfo.index))params.push(t.identifier(forInfo.index));const projected=t.objectExpression(aliasNames.map(name=>{return t.objectProperty(t.stringLiteral(name),t.identifier(name),true)}));return t.arrowFunctionExpression(params,projected)}function callPatternProjector(projector,item,index,forInfo){const args=[t.cloneNode(item,true)];if(forInfo.index&&t.isValidIdentifier(forInfo.index))args.push(t.cloneNode(index,true));return t.callExpression(t.cloneNode(projector,true),args)}function createArrayProjection(source,projector,forInfo,identifiers){const{arrayIndex:index,arrayItem:item}=identifiers;return t.callExpression(t.memberExpression(t.cloneNode(source),t.identifier(`map`)),[t.arrowFunctionExpression([item,index],callPatternProjector(projector,item,index,forInfo))])}function createObjectProjection(source,projector,forInfo,identifiers){const{key,keys,loopIndex,objectItem:item,result}=identifiers;return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(result,t.objectExpression([]))]),t.variableDeclaration(`const`,[t.variableDeclarator(keys,t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`keys`)),[t.cloneNode(source)]))]),t.forStatement(t.variableDeclaration(`let`,[t.variableDeclarator(loopIndex,t.numericLiteral(0))]),t.binaryExpression(`<`,loopIndex,t.memberExpression(keys,t.identifier(`length`))),t.updateExpression(`++`,loopIndex),t.blockStatement([t.variableDeclaration(`const`,[t.variableDeclarator(key,t.memberExpression(keys,loopIndex,true))]),t.variableDeclaration(`const`,[t.variableDeclarator(item,t.memberExpression(source,key,true))]),t.expressionStatement(t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`defineProperty`)),[result,key,t.objectExpression([t.objectProperty(t.identifier(`configurable`),t.booleanLiteral(true)),t.objectProperty(t.identifier(`enumerable`),t.booleanLiteral(true)),t.objectProperty(t.identifier(`value`),callPatternProjector(projector,item,key,forInfo)),t.objectProperty(t.identifier(`writable`),t.booleanLiteral(true))])]))])),t.returnStatement(result)])),[])}function createForPatternProjectionExpression(sourceExpression,projector,forInfo,identifiers){const{source}=identifiers;const numberCheck=t.logicalExpression(`&&`,t.binaryExpression(`===`,t.unaryExpression(`typeof`,source),t.stringLiteral(`number`)),t.callExpression(t.memberExpression(t.identifier(`Number`),t.identifier(`isFinite`)),[t.cloneNode(source)]));const stringCheck=t.binaryExpression(`===`,t.unaryExpression(`typeof`,source),t.stringLiteral(`string`));const objectCheck=t.logicalExpression(`&&`,t.binaryExpression(`!=`,source,t.nullLiteral()),t.binaryExpression(`===`,t.unaryExpression(`typeof`,source),t.stringLiteral(`object`)));const normalizeNumber=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`from`)),[t.objectExpression([t.objectProperty(t.identifier(`length`),t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`max`)),[t.numericLiteral(0),t.callExpression(t.memberExpression(t.identifier(`Math`),t.identifier(`floor`)),[t.cloneNode(source)])]))]),t.arrowFunctionExpression([t.cloneNode(identifiers.arrayItem),t.cloneNode(identifiers.arrayIndex)],t.cloneNode(identifiers.arrayIndex))]);const normalizeString=t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`from`)),[t.cloneNode(source)]);return t.callExpression(t.arrowFunctionExpression([],t.blockStatement([t.variableDeclaration(`let`,[t.variableDeclarator(source,t.cloneNode(sourceExpression,true))]),t.ifStatement(numberCheck,t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,source,normalizeNumber))])),t.ifStatement(stringCheck,t.blockStatement([t.expressionStatement(t.assignmentExpression(`=`,source,normalizeString))])),t.ifStatement(t.callExpression(t.memberExpression(t.identifier(`Array`),t.identifier(`isArray`)),[t.cloneNode(source)]),t.blockStatement([t.returnStatement(createArrayProjection(source,projector,forInfo,identifiers))])),t.ifStatement(objectCheck,t.blockStatement([t.returnStatement(createObjectProjection(source,projector,forInfo,identifiers))])),t.returnStatement(t.cloneNode(source))])),[])}function registerForPatternProjection(forInfo,listExp,listExpAst,context){const pattern=forInfo.itemPattern;const sourceAst=RUNTIME_BINDING_REF_RE.test(listExp)?normalizeRuntimeBindingReference(listExp,context):listExpAst;if(!pattern||!sourceAst)return null;const rawPattern=parseItemPattern(pattern);const rawProjector=rawPattern?createPatternProjector(rawPattern,Object.keys(forInfo.itemAliases??{}),forInfo):null;const projector=rawProjector?normalizeJsExpressionWithContext(generateExpression(rawProjector),context,{hint:`v-for 解构绑定`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true}):null;if(!projector||!t.isArrowFunctionExpression(projector))return null;const reservedNames=/* @__PURE__ */ new Set;for(const scope of context.scopeStack)for(const name of scope)reservedNames.add(name);for(const scope of context.forStack)for(const name of[scope.item,scope.index,scope.key,...Object.keys(scope.itemAliases??{})])if(name)reservedNames.add(name);for(const name of[forInfo.item,forInfo.index,forInfo.key,...Object.keys(forInfo.itemAliases??{})])if(name)reservedNames.add(name);const seed=context.classStyleBindings.filter(binding=>binding.type===`bind`).length;const projectionAst=createForPatternProjectionExpression(sourceAst,projector,forInfo,createProjectionIdentifiers(sourceAst,projector,reservedNames));const bindingName=`__wv_bind_${seed}`;const outerForStack=context.forStack.map(info=>({...info}));context.classStyleBindings.push({name:bindingName,type:`bind`,exp:`v-for 解构 ${pattern}`,expAst:projectionAst,forStack:outerForStack,conditions:context.bindingConditions?.slice()});const projectedListExp=`${bindingName}${outerForStack.map(info=>`[${info.index??`index`}]`).join(``)}`;const projectedListExpAst=normalizeRuntimeBindingReference(projectedListExp,context);return projectedListExpAst?{listExp:projectedListExp,listExpAst:projectedListExpAst}:null}const REGEX_SPECIAL_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function resolveListExpression(rawExpValue,context,hint){return(context.rewriteScopedSlot||shouldFallbackToRuntimeBinding(rawExpValue,context.templateSafeCallNames,context)?registerRuntimeBindingExpression(rawExpValue,context,{hint}):null)??normalizeWxmlExpressionWithContext(rawExpValue,context)}function requiresRuntimeForKeyProjection(node,context){const forDirective=node.props.find(prop=>{return prop.type===NodeTypes.DIRECTIVE&&prop.name===`for`});const keyDirective=node.props.find(prop=>{return prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`key`});if(forDirective?.exp?.type===NodeTypes.SIMPLE_EXPRESSION&&keyDirective){const forInfo=parseForExpression(forDirective.exp.content);const rawKeyExp=getBindDirectiveExpression(keyDirective).trim();if(rawKeyExp&&!resolveNativeForKeyValue(rawKeyExp,forInfo,context.platform.keyThisValue))return true}return node.children.some(child=>{return child.type===NodeTypes.ELEMENT&&requiresRuntimeForKeyProjection(child,context)})}function transformIfElement(node,context,transformNode){const renderTemplateMustache=exp=>renderMustache$1(exp,context);const ifDirective=node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&(prop.name===`if`||prop.name===`else-if`||prop.name===`else`));if(!ifDirective)
|
|
9
9
|
/* istanbul ignore next */
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wevu/compiler",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "7.11.0-dev.
|
|
4
|
+
"version": "7.11.0-dev.20261115.1",
|
|
5
5
|
"description": "wevu 编译器基础包,面向小程序模板的编译与转换",
|
|
6
6
|
"author": "ice breaker <1324318532@qq.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -66,10 +66,10 @@
|
|
|
66
66
|
"@vue/babel-plugin-jsx": "3.0.0",
|
|
67
67
|
"@vue/compiler-core": "^3.5.45",
|
|
68
68
|
"@vue/compiler-dom": "^3.5.45",
|
|
69
|
-
"@weapp-core/constants": "0.6.0-dev.
|
|
70
|
-
"@weapp-core/shared": "3.5.0-dev.
|
|
71
|
-
"@weapp-vite/ast": "7.11.0-dev.
|
|
72
|
-
"@weapp-vite/wxml": "0.0.2-dev.
|
|
69
|
+
"@weapp-core/constants": "0.6.0-dev.20261115.1",
|
|
70
|
+
"@weapp-core/shared": "3.5.0-dev.20261115.1",
|
|
71
|
+
"@weapp-vite/ast": "7.11.0-dev.20261115.1",
|
|
72
|
+
"@weapp-vite/wxml": "0.0.2-dev.20261115.1",
|
|
73
73
|
"comment-json": "^5.0.0",
|
|
74
74
|
"lru-cache": "^11.5.3",
|
|
75
75
|
"magic-string": "^1.4.5",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
"pathe": "^2.0.3",
|
|
78
78
|
"postcss": "^8.5.32",
|
|
79
79
|
"postcss-selector-parser": "^7.2.1",
|
|
80
|
-
"rolldown-require": "2.1.4-dev.
|
|
80
|
+
"rolldown-require": "2.1.4-dev.20261115.1",
|
|
81
81
|
"vue": "^3.5.45"
|
|
82
82
|
},
|
|
83
83
|
"tsd": {
|
|
@@ -93,9 +93,9 @@
|
|
|
93
93
|
},
|
|
94
94
|
"repoctlSnapshot": {
|
|
95
95
|
"kind": "nightly",
|
|
96
|
-
"commit": "
|
|
97
|
-
"buildId": "
|
|
98
|
-
"identityKey": "
|
|
96
|
+
"commit": "f3693c09b01bae2d6805c1d621aacf2e44d64cc4",
|
|
97
|
+
"buildId": "43665076788-1",
|
|
98
|
+
"identityKey": "73d798fdc7fc7b6de9dae22159bc39f6ef7c896eac6ccd9058a2e871a5da073a",
|
|
99
99
|
"tag": "snapshot-nightly"
|
|
100
100
|
},
|
|
101
101
|
"scripts": {
|