@wevu/compiler 7.2.2 → 7.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/index.d.mts +44 -13
- package/dist/index.mjs +16 -16
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
import{WEAPP_I18N_RUNTIME_MARKER,WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID,WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID,WEAPP_VITE_RUNTIME_VIRTUAL_ID,WEVU_BINDING_MANIFEST_KEY,WEVU_CLASS_STYLE_RUNTIME_FILE,WEVU_CLASS_STYLE_RUNTIME_MODULE,WEVU_CSS_MODULES_KEY,WEVU_CSS_VARS_STYLE_KEY,WEVU_DEFINE_PAGE_MACRO,WEVU_DEFINE_PAGE_META_MACRO,WEVU_EXPRESSION_ERROR_IDENTIFIER,WEVU_FUNCTION_PROP_PATHS_KEY,WEVU_INLINE_HANDLER,WEVU_INLINE_MAP_KEY,WEVU_IS_PAGE_KEY,WEVU_JSX_ISLAND_DATA_KEY,WEVU_JSX_ISLAND_HANDLER,WEVU_JSX_ISLAND_TEMPLATE_NAME,WEVU_LAYOUT_BIND_PREFIX,WEVU_LAYOUT_HOSTS_KEY,WEVU_LAYOUT_HOST_ID_PREFIX,WEVU_LAYOUT_HOST_REF_PREFIX,WEVU_MODEL_HANDLER,WEVU_OWNER_HANDLER,WEVU_PAGE_LAYOUT_NAME_KEY,WEVU_PAGE_LAYOUT_PROPS_KEY,WEVU_PROPS_ALIASES_KEY,WEVU_PROPS_DERIVED_KEYS_KEY,WEVU_PROPS_KEY,WEVU_ROUTER_MODULE_ID,WEVU_SCOPED_SLOT_CREATOR_KEY,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,WEVU_SLOT_FUNCTION_TOKEN,WEVU_SLOT_NAMES_ATTR,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_ATTR,WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_OWNER_PROXY_KEY,WEVU_SLOT_PROPS_ATTR,WEVU_SLOT_PROPS_DATA_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_SCOPE_ATTR,WEVU_SLOT_SCOPE_KEY,WEVU_TEMPLATE_REFS_KEY,WEVU_TEMPLATE_REF_CLASS_PREFIX}from"@weapp-core/constants";import MagicString,{Bundle}from"magic-string";import{NodeTypes,baseParse}from"@vue/compiler-core";import*as compilerDom from"@vue/compiler-dom";import{parse}from"@vue/compiler-dom";import{LRUCache}from"lru-cache";import{compileScript,compileStyleAsync,parse as parse$1}from"vue/compiler-sfc";import{access,mkdir,readFile as readFile$1,rm,stat,writeFile}from"node:fs/promises";import path from"pathe";import{fileURLToPath}from"node:url";import*as t from"@weapp-vite/ast/babelTypes";import{BABEL_TS_MODULE_PARSER_OPTIONS,BABEL_TS_MODULE_PLUGINS,generate,parse as parse$3,parseJsLike,traverse}from"@weapp-vite/ast/babel";import path$1 from"node:path";import{escapeWxmlAttribute,escapeWxmlText,getMiniProgramRuntimeGlobalKeys,getMiniProgramTemplatePreset,removeExtensionDeep}from"@weapp-core/shared";import{createHash}from"node:crypto";import{recursive}from"merge";import{bundleRequire}from"rolldown-require";import fs,{readFileSync}from"node:fs";import os from"node:os";import process from"node:process";import{collectJsxImportedComponentsAndDefaultExportFromBabelAst,collectJsxTemplateTagsFromBabelExpression,collectScriptCallStringLiterals,collectScriptStringLiterals,getObjectPropertyByKey,getRenderPropertyFromComponentOptions,mayContainScriptCallOrModuleSyntax,parseJsLikeWithEngine,resolveRenderExpressionFromComponentOptions,toStaticObjectKey,unwrapTypeScriptExpression}from"@weapp-vite/ast";import vueJsxPlugin from"@vue/babel-plugin-jsx";import{transformSync}from"@weapp-vite/ast/babelCore";import postcss from"postcss";import selectorParser from"postcss-selector-parser";import{parse as parse$2}from"comment-json";import
|
|
1
|
+
import{WEAPP_I18N_RUNTIME_MARKER,WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID,WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID,WEAPP_VITE_RUNTIME_VIRTUAL_ID,WEVU_BINDING_MANIFEST_KEY,WEVU_CLASS_STYLE_RUNTIME_FILE,WEVU_CLASS_STYLE_RUNTIME_MODULE,WEVU_CSS_MODULES_KEY,WEVU_CSS_VARS_STYLE_KEY,WEVU_DEFINE_PAGE_MACRO,WEVU_DEFINE_PAGE_META_MACRO,WEVU_EXPRESSION_ERROR_IDENTIFIER,WEVU_FUNCTION_PROP_PATHS_KEY,WEVU_INLINE_HANDLER,WEVU_INLINE_MAP_KEY,WEVU_IS_PAGE_KEY,WEVU_JSX_ISLAND_DATA_KEY,WEVU_JSX_ISLAND_HANDLER,WEVU_JSX_ISLAND_TEMPLATE_NAME,WEVU_LAYOUT_BIND_PREFIX,WEVU_LAYOUT_HOSTS_KEY,WEVU_LAYOUT_HOST_ID_PREFIX,WEVU_LAYOUT_HOST_REF_PREFIX,WEVU_MODEL_HANDLER,WEVU_OWNER_HANDLER,WEVU_PAGE_LAYOUT_NAME_KEY,WEVU_PAGE_LAYOUT_PROPS_KEY,WEVU_PROPS_ALIASES_KEY,WEVU_PROPS_DERIVED_KEYS_KEY,WEVU_PROPS_KEY,WEVU_ROUTER_MODULE_ID,WEVU_SCOPED_SLOT_CREATOR_KEY,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,WEVU_SLOT_FUNCTION_TOKEN,WEVU_SLOT_NAMES_ATTR,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_ATTR,WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_OWNER_KEY,WEVU_SLOT_OWNER_PROXY_KEY,WEVU_SLOT_PROPS_ATTR,WEVU_SLOT_PROPS_DATA_KEY,WEVU_SLOT_PROPS_KEY,WEVU_SLOT_SCOPE_ATTR,WEVU_SLOT_SCOPE_KEY,WEVU_TEMPLATE_REFS_KEY,WEVU_TEMPLATE_REF_CLASS_PREFIX}from"@weapp-core/constants";import MagicString,{Bundle}from"magic-string";import{TraceMap,originalPositionFor}from"@jridgewell/trace-mapping";import{NodeTypes,baseParse}from"@vue/compiler-core";import*as compilerDom from"@vue/compiler-dom";import{parse}from"@vue/compiler-dom";import{LRUCache}from"lru-cache";import{compileScript,compileStyleAsync,parse as parse$1}from"vue/compiler-sfc";import remapping from"@jridgewell/remapping";import{access,mkdir,readFile as readFile$1,rm,stat,writeFile}from"node:fs/promises";import path from"pathe";import{fileURLToPath}from"node:url";import*as t from"@weapp-vite/ast/babelTypes";import{BABEL_TS_MODULE_PARSER_OPTIONS,BABEL_TS_MODULE_PLUGINS,generate,parse as parse$3,parseJsLike,traverse}from"@weapp-vite/ast/babel";import path$1 from"node:path";import{escapeWxmlAttribute,escapeWxmlText,getMiniProgramRuntimeGlobalKeys,getMiniProgramTemplatePreset,removeExtensionDeep}from"@weapp-core/shared";import{createHash}from"node:crypto";import{recursive}from"merge";import{bundleRequire}from"rolldown-require";import fs,{readFileSync}from"node:fs";import os from"node:os";import process from"node:process";import{collectJsxImportedComponentsAndDefaultExportFromBabelAst,collectJsxTemplateTagsFromBabelExpression,collectScriptCallStringLiterals,collectScriptStringLiterals,getObjectPropertyByKey,getRenderPropertyFromComponentOptions,mayContainScriptCallOrModuleSyntax,parseJsLikeWithEngine,resolveRenderExpressionFromComponentOptions,toStaticObjectKey,unwrapTypeScriptExpression}from"@weapp-vite/ast";import vueJsxPlugin from"@vue/babel-plugin-jsx";import{transformSync}from"@weapp-vite/ast/babelCore";import postcss from"postcss";import selectorParser from"postcss-selector-parser";import{parse as parse$2}from"comment-json";import vm from"node:vm";const components=[`wxs`,`template`,`block`,`import`,`include`,`cover-image`,`cover-view`,`match-media`,`movable-area`,`movable-view`,`page-container`,`root-portal`,`scroll-view`,`swiper`,`swiper-item`,`view`,`icon`,`progress`,`rich-text`,`selection`,`text`,`button`,`checkbox`,`checkbox-group`,`editor`,`editor-portal`,`form`,`input`,`keyboard-accessory`,`label`,`picker`,`picker-view`,`picker-view-column`,`radio`,`radio-group`,`slider`,`switch`,`textarea`,`double-tap-gesture-handler`,`force-press-gesture-handler`,`horizontal-drag-gesture-handler`,`long-press-gesture-handler`,`pan-gesture-handler`,`scale-gesture-handler`,`tap-gesture-handler`,`vertical-drag-gesture-handler`,`draggable-sheet`,`grid-builder`,`grid-view`,`list-builder`,`list-view`,`nested-scroll-body`,`nested-scroll-header`,`open-container`,`open-data-item`,`open-data-list`,`share-element`,`snapshot`,`span`,`sticky-header`,`sticky-section`,`functional-page-navigator`,`navigator`,`audio`,`camera`,`channel-live`,`channel-video`,`image`,`live-player`,`live-pusher`,`video`,`voip-room`,`map`,`canvas`,`ad`,`ad-custom`,`official-account`,`official-account-publish`,`open-data`,`store-coupon`,`store-gift`,`store-home`,`store-product`,`web-view`,`native-component`,`aria-component`,`navigation-bar`,`page-meta`];const builtinComponentsSet=new Set(components);function isBuiltinComponent(tag){return builtinComponentsSet.has(tag)}function createRuntimeBindingManifest(manifest,mode=`compact`){const bindings=manifest.bindings.map(binding=>({id:binding.id,outputPath:binding.outputPath,...mode===`diagnostic`&&binding.sourceFile?{sourceFile:binding.sourceFile}:{},...binding.updateMode===`exact-path`?{}:{updateMode:binding.updateMode},...binding.updateMode===`snapshot-fallback`&&binding.sourceRoots.length?{sourceRoots:binding.sourceRoots}:{},...mode===`diagnostic`&&binding.sourceLocation?{sourceLocation:binding.sourceLocation}:{}}));const features=manifest.features.scopedSlots?{scopedSlots:true}:void 0;return{version:1,sourceFile:manifest.sourceFile,bindings,...features?{features}:{}}}const WE_VU_PAGE_HOOK_TO_FEATURE={onPageScroll:`enableOnPageScroll`,usePageScrollRestoration:`enableOnPageScroll`,onPullDownRefresh:`enableOnPullDownRefresh`,onReachBottom:`enableOnReachBottom`,onRouteDone:`enableOnRouteDone`,onTabItemTap:`enableOnTabItemTap`,onResize:`enableOnResize`,onShareAppMessage:`enableOnShareAppMessage`,onShareTimeline:`enableOnShareTimeline`,onAddToFavorites:`enableOnAddToFavorites`,onSaveExitState:`enableOnSaveExitState`};const WE_VU_MODULE_ID=`wevu`;const WE_VU_INTERNAL_RUNTIME_MODULE_ID=`wevu/internal-runtime`;const WE_VU_INTERNAL_REACTIVITY_MODULE_ID=`wevu/internal-reactivity`;const WE_VU_INTERNAL_TEMPLATE_MODULE_ID=`wevu/internal-template`;const WE_VU_COMPILER_RUNTIME_MODULE_ID=WEAPP_VITE_RUNTIME_VIRTUAL_ID;const WE_VU_COMPILER_REACTIVITY_MODULE_ID=WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID;const WE_VU_COMPILER_TEMPLATE_MODULE_ID=WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID;const WE_VU_RUNTIME_MODULE_IDS=[WE_VU_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID];function isWevuRuntimeModuleId(moduleId){return WE_VU_RUNTIME_MODULE_IDS.includes(moduleId)}function isWevuPageFeatureModuleId(moduleId){return isWevuRuntimeModuleId(moduleId)||moduleId===`wevu/router`||moduleId===`wevu/dev/router`}const WE_VU_RUNTIME_APIS={createApp:`createApp`,createWevuComponent:`createWevuComponent`,createWevuScopedSlotComponent:`createWevuScopedSlotComponent`,defineAppSetup:`defineAppSetup`,defineComponent:`defineComponent`,setWevuDefaults:`setWevuDefaults`};const WE_VU_INTERNAL_REACTIVITY_APIS=[`addMutationRecorder`,`batch`,`computed`,`customRef`,`effect`,`effectScope`,`endBatch`,`getCurrentScope`,`getDeepWatchStrategy`,`getReactiveVersion`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`markRaw`,`nextTick`,`onScopeDispose`,`prelinkReactiveTree`,`reactive`,`readonly`,`ref`,`removeMutationRecorder`,`setDeepWatchStrategy`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`toRaw`,`toRef`,`toRefs`,`toValue`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAsyncDerivation`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`];const WE_VU_INTERNAL_TEMPLATE_APIS=[`normalizeClass`,`normalizeStyle`,`resolvePropValue`];const WE_VU_INTERNAL_REACTIVITY_API_SET=new Set(WE_VU_INTERNAL_REACTIVITY_APIS);const WE_VU_INTERNAL_TEMPLATE_API_SET=new Set(WE_VU_INTERNAL_TEMPLATE_APIS);function resolveWevuInternalImportModuleId(apiName){if(WE_VU_INTERNAL_REACTIVITY_API_SET.has(apiName))return WE_VU_COMPILER_REACTIVITY_MODULE_ID;if(WE_VU_INTERNAL_TEMPLATE_API_SET.has(apiName))return WE_VU_COMPILER_TEMPLATE_MODULE_ID;return WE_VU_COMPILER_RUNTIME_MODULE_ID}var CompilerDiagnosticError=class extends Error{code;severity;filename;source;loc;constructor(diagnostic,options){super(diagnostic.message,options);this.name=`CompilerDiagnosticError`;this.code=diagnostic.code;this.severity=diagnostic.severity;this.filename=diagnostic.filename;this.source=diagnostic.source;this.loc=diagnostic.loc}};function getReadFileCheckMtime(config){return Boolean(config?.isDev)}function isEncodedSourceMapLike(value){return Boolean(value&&typeof value===`object`&&`version`in value&&`mappings`in value&&`names`in value&&`sources`in value)}function composeSourceMaps(transformedMap,originalMap){if(isEncodedSourceMapLike(transformedMap)&&isEncodedSourceMapLike(originalMap))return remapping([transformedMap,originalMap],()=>null);if(isEncodedSourceMapLike(transformedMap))return transformedMap;if(isEncodedSourceMapLike(originalMap))return originalMap;return null}function composeSourceMapForSource(transformedMap,originalMap,sourceFile){if(!isEncodedSourceMapLike(transformedMap))return null;if(!isEncodedSourceMapLike(originalMap))return transformedMap;const transformedMapInput=transformedMap;const sourceIndex=transformedMap.sources.indexOf(sourceFile);if(sourceIndex<0)return transformedMap;const resolvedSourceFile=new TraceMap(transformedMapInput).resolvedSources[sourceIndex];return remapping(transformedMapInput,(file,context)=>{if(context.depth!==1||file!==resolvedSourceFile)return null;context.source=``;return originalMap})}const CRLF_RE=/\r\n?/g;const HYPHENATE_RE=/\B([A-Z])/g;function hyphenate(value){return value.replace(HYPHENATE_RE,`-$1`).toLowerCase()}function normalizeComponentHostName(value){return value.startsWith(`__wv`)?value:hyphenate(value)}function normalizeLineEndings(source){if(!source.includes(`\r`))return source;return source.replace(CRLF_RE,`
|
|
2
2
|
`)}async function ensureDir(path){await mkdir(path,{recursive:true})}async function remove(path){await rm(path,{recursive:true,force:true})}async function pathExists$1(path){try{await access(path);return true}catch{return false}}const mtimeCache=/* @__PURE__ */ new Map;const loadCache=new LRUCache({max:1024});const pathExistsCache=new LRUCache({max:4096});const sourceSignatures=new LRUCache({max:1024});const pendingReads=/* @__PURE__ */ new Map;const transientRenameRetryDelays=[10,25,50];function isMissingFileError(error){return error instanceof Error&&`code`in error&&error.code===`ENOENT`}async function readFileSignature(id){const stats=await stat(id);const mtimeMs=typeof stats?.mtimeMs===`number`?stats.mtimeMs:NaN;const ctimeMs=typeof stats?.ctimeMs===`number`?stats.ctimeMs:NaN;const size=typeof stats?.size===`number`?stats.size:NaN;const ino=typeof stats?.ino===`number`?stats.ino:NaN;return[mtimeMs,ctimeMs,size,ino].every(Number.isFinite)?{mtimeMs,ctimeMs,size,ino}:void 0}function sameFileSignature(left,right){return left!==void 0&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.size===right.size&&left.ino===right.ino}async function isInvalidate(id){const signature=await readFileSignature(id);if(!signature)return true;const unchanged=sameFileSignature(mtimeCache.get(id),signature);mtimeCache.set(id,signature);return!unchanged}async function readFile(id,options){const checkMtime=options?.checkMtime??true;const encoding=options?.encoding??`utf8`;if(!checkMtime){const cached=loadCache.get(id);if(cached!==void 0)return cached}const token={};pendingReads.set(id,token);try{for(let attempt=0;;attempt+=1)try{const signature=checkMtime?await readFileSignature(id):void 0;if(signature){const cached=sourceSignatures.get(id);if(cached&&sameFileSignature(cached.signature,signature)&&loadCache.get(id)===cached.source){if(pendingReads.get(id)===token)mtimeCache.set(id,signature);return cached.source}}const content=normalizeLineEndings(await readFile$1(id,encoding));if(pendingReads.get(id)===token){loadCache.set(id,content);if(signature){sourceSignatures.set(id,{source:content,signature});mtimeCache.set(id,signature)}else{sourceSignatures.delete(id);mtimeCache.delete(id)}}return content}catch(error){const retryDelay=transientRenameRetryDelays[attempt];if(!isMissingFileError(error)||retryDelay===void 0)throw error;await new Promise(resolve=>setTimeout(resolve,retryDelay))}}finally{if(pendingReads.get(id)===token)pendingReads.delete(id)}}async function pathExists(id,options){const ttlMs=options?.ttlMs;const cached=pathExistsCache.get(id);if(cached!==void 0)return cached;const exists=await pathExists$1(id);if(typeof ttlMs===`number`&&Number.isFinite(ttlMs)&&ttlMs>0)pathExistsCache.set(id,exists,{ttl:ttlMs});else pathExistsCache.set(id,exists);return exists}function invalidateFileCache(id){pendingReads.delete(id);sourceSignatures.delete(id);mtimeCache.delete(id);loadCache.delete(id);pathExistsCache.delete(id)}function clearFileCaches(){pendingReads.clear();sourceSignatures.clear();mtimeCache.clear();loadCache.clear();pathExistsCache.clear()}const VUE_VIRTUAL_MODULE_PREFIX=`\0vue:`;const BACKSLASH_RE$4=/\\/g;function normalizeViteId(id,options){const stripQuery=options?.stripQuery!==false;const fileProtocolToPathEnabled=options?.fileProtocolToPath!==false;const stripAtFsPrefix=options?.stripAtFsPrefix!==false;const stripVueVirtualPrefix=options?.stripVueVirtualPrefix===true;const stripLeadingNullByte=options?.stripLeadingNullByte===true;let clean=id;if(stripVueVirtualPrefix&&clean.startsWith(VUE_VIRTUAL_MODULE_PREFIX))clean=clean.slice(5);if(clean.includes(`\\`))clean=clean.replace(BACKSLASH_RE$4,`/`);if(stripQuery)clean=clean.split(`?`,1)[0];if(fileProtocolToPathEnabled&&clean.startsWith(`file://`))try{clean=fileURLToPath(clean)}catch{}if(stripAtFsPrefix&&clean.startsWith(`/@fs/`))clean=clean.slice(4);if(stripLeadingNullByte&&clean.startsWith(`\0`))clean=clean.slice(1);return clean}function isSkippableResolvedId(id){if(!id)return true;return id.startsWith(`\0`)||id.startsWith(`node:`)}function normalizeFsResolvedId(id,options){const normalizeOptions={stripVueVirtualPrefix:true};if(options?.normalize)Object.assign(normalizeOptions,options.normalize);if(options?.stripLeadingNullByte)normalizeOptions.stripLeadingNullByte=true;return normalizeViteId(id,normalizeOptions)}const SCRIPT_LANG_EXT=/* @__PURE__ */ new Map([[`.ts`,`ts`],[`.tsx`,`tsx`],[`.js`,`js`],[`.jsx`,`jsx`],[`.mjs`,`js`],[`.cjs`,`js`]]);const STYLE_LANG_EXT=/* @__PURE__ */ new Map([[`.css`,`css`],[`.scss`,`scss`],[`.sass`,`sass`],[`.less`,`less`],[`.styl`,`styl`],[`.stylus`,`styl`]]);const TEMPLATE_LANG_EXT=/* @__PURE__ */ new Map([[`.html`,`html`],[`.htm`,`html`],[`.pug`,`pug`],[`.jade`,`pug`]]);const CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX=`__WEVU_SFC_CSS_VARS_CLOSE_`;function createCssVarsCloseTagSentinel(styles){let index=0;while(styles.some(style=>style.content.includes(`${CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX}${index}_`)))index++;return`${CSS_VARS_CLOSE_TAG_SENTINEL_PREFIX}${index}_`}function resolveDescriptorCssVars(styles,filename){const sentinel=createCssVarsCloseTagSentinel(styles);const closeTagRestorations=[];let closeTagIndex=0;const styleSource=styles.map(style=>{return`<style>${style.content.replace(/<\/style/gi,source=>{const token=`${sentinel}${closeTagIndex++}__`;closeTagRestorations.push([token,source]);return token})}</style>`}).join(`
|
|
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,options){const reader=options?.readFile??readFile;const checkMtime=options?.checkMtime;try{return await reader(resolvedId,{checkMtime})}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:读取 ${resolvedId} 失败:${message}`)}}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,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 parseSfcAst(source,options,onScriptSrc){const ast=compilerDom.parse(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}}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,edits:[...routeAnalysis.edits,...getImportRemovalEdits(runtimeImports),...calls.map(call=>({block:call.block,start:call.statement.start??0,end:call.statement.end??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 createSfcParseError(filename,error){if(typeof error===`string`)return/* @__PURE__ */ new Error(`${filename}:1:1 解析页面声明 SFC 失败:${error}`);let line=1;let column=1;if(error&&typeof error===`object`&&`loc`in error){const location=error.loc;if(location&&typeof location===`object`&&`start`in location){const start=location.start;if(start&&typeof start===`object`){if(`line`in start&&typeof start.line===`number`)line=start.line;if(`column`in start&&typeof start.column===`number`)column=start.column}}}const message=error instanceof Error?error.message:String(error);return/* @__PURE__ */ new Error(`${filename}:${line}:${column} 解析页面声明 SFC 失败:${message}`)}function parsePageDeclarationSfc(source,filename,ignoreEmpty=true){const parsed=parseVueSfc(source,{filename,ignoreEmpty,templateParseOptions:{prefixIdentifiers:false}});if(parsed.errors.length)throw createSfcParseError(filename,parsed.errors[0]);return parsed.descriptor}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(`
|
|
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,options){const reader=options?.readFile??readFile;const checkMtime=options?.checkMtime;try{return await reader(resolvedId,{checkMtime})}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:读取 ${resolvedId} 失败:${message}`)}}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,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=compilerDom.parse(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}}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,edits:[...routeAnalysis.edits,...getImportRemovalEdits(runtimeImports),...calls.map(call=>({block:call.block,start:call.statement.start??0,end:call.statement.end??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 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(`
|
|
4
4
|
<\/script>
|
|
5
|
-
`);source+=openingTag;const startOffset=source.length;source+=`${content}\n<\/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}}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,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 stripPageCompileTimeMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap=true,resolvedIds={}){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analyzePageCompileTimeMacroBlocks(blocks))}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`];const WE_VU_RUNTIME_CAPABILITY_INSTALLERS={patchStrategy:`installPatchStrategy`,templateRefs:`installTemplateRefs`,inlineEvents:`installInlineEvents`,setDataHighFrequencyWarning:`installSetDataHighFrequencyWarning`,scopedSlots:`installScopedSlots`,layout:`installLayout`};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`);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 collectVueTemplateTags(template,options){const tags=/* @__PURE__ */ new Set;const warn=options.warn;const warnLabel=options.warnLabel||`模板标签收集`;const filename=options.filename||`<未知文件>`;try{const ast=baseParse(template,{onError:()=>{}});const visit=node=>{if(!node)return;if(Array.isArray(node)){node.forEach(visit);return}if(node.type===NodeTypes.ELEMENT){const tag=node.tag;if(typeof tag===`string`&&options.shouldCollect(tag)){if(!RESERVED_VUE_COMPONENT_TAGS.has(tag)&&!isBuiltinComponent(tag))tags.add(tag)}}if(node.children)visit(node.children);if(node.branches)visit(node.branches);if(node.consequent)visit(node.consequent);if(node.alternate)visit(node.alternate)};visit(ast.children)}catch(error){const message=error instanceof Error?error.message:String(error);warn?.(`[Vue 模板] 解析失败:${warnLabel}(${filename}):${message}`)}return 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(SCOPED_SLOT_GLOBALS.has(name))return;if(path.scope.hasBinding(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(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.hasBinding(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){const normalized=extension.startsWith(`.`)?extension.slice(1):extension;const resolvedSrc=src??`./${CLASS_STYLE_WXS_FILE}.${normalized}`;return`<${resolveScriptModuleTag(normalized)} module="${CLASS_STYLE_WXS_MODULE}" src="${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=isSjs?[`export default {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`]:[`module.exports = {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`];return[...bodyLines,...exportLines,``].join(`
|
|
6
|
-
`)}function warn(context,message,location,source=`template`,errorCode){context.diagnostics.push({code:errorCode??(source===`expression`?`WV1002`:`WV1001`),severity:errorCode?`error`:`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.hasBinding(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 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=forInfo?.listExp?.trim()??``;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=forInfo?.listExp?.trim()??``;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);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)));resolvedIndexes.set(forInfo.index?.trim()||`index`,indexExpression);if(forInfo.key)resolvedIndexes.set(forInfo.key,indexExpression)}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=forInfo?.listExp?.trim()??``;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`)}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 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 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,markLocal){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;path.replaceWith(buildCtxValueAccess(path.node));path.skip()}})}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});rewriteTopLevelRefLikeAccess(ast,context,parameterIdentifiers,locals,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(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(JS_RUNTIME_GLOBALS.has(name))return;if(path.scope.hasBinding(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(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){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;traverse(parsed.ast,{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()}});return shouldFallback}function registerRuntimeBindingExpression(exp,context,options){const expAst=normalizeJsExpressionWithContext(exp,context,{...options,runtimePropAccess:`helper`,unrefMemberAccess:true});if(!expAst)return null;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)}`}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)?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)});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){const inner=tokens.slice(openIndex+1,closeIndex);return inner.some(token=>token.type===`text`&&token.value.trim().length>0)&&inner.every(token=>token.type!==`tag`||isSelfClosingTag(token.value))}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).filter(token=>!isWhitespaceText(token));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`){const value=token.value.trim();if(value)appendLine(lines,level,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(`
|
|
7
|
-
`)}\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 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.filter(Boolean)}function splitForExpression(exp){let parenDepth=0;let bracketDepth=0;let braceDepth=0;let quote=``;let escaped=false;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;if(exp.startsWith(` in `,i)||exp.startsWith(` of `,i))return{source:exp.slice(0,i).trim(),list:exp.slice(i+4).trim()}}return null}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{};const segments=splitTopLevelByComma(stripOuterParentheses(split.source));if(!segments.length)return{listExp:split.list};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))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))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)&&rawIndex&&isIdentifier(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;for(const scope of context.scopeStack)for(const name of scope){if(!IDENTIFIER_RE$2.test(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;return`[${keys.map(key=>`${toWxmlStringLiteral$1(key)},${getForItemAccess(context,key)}`).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){const rawKeyExp=getBindDirectiveExpression(node).trim();if(!rawKeyExp||!forInfo.listExp||resolveNativeForKeyValue(rawKeyExp,forInfo,context.platform.keyThisValue))return null;const listExp=forInfo.listExp?.trim()??``;const rawListExp=forInfo.rawListExp?.trim()||listExp;const projectionListExp=RUNTIME_BINDING_REF_RE$1.test(listExp)?listExp:rawListExp;const sourceContext=createSourceContext(context);const projectionSourceAst=RUNTIME_BINDING_REF_RE$1.test(projectionListExp)?normalizeJsExpressionWithContext(projectionListExp,sourceContext,{hint:`v-for :key 数据源`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true}):normalizeJsExpressionWithContext(projectionListExp,sourceContext,{hint:`v-for :key 数据源`,preserveForItems:true});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),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)){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)}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 transformAttribute(node,_context,nameOverride){const{value}=node;const name=nameOverride??node.name;if(!value)return name;if(value.type===NodeTypes.TEXT)return`${name}="${escapeWxmlAttribute(value.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]:[];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=prop.value.content;continue}if(prop.name===`id`&&prop.value?.type===NodeTypes.TEXT){staticId=prop.value.content.trim();continue}if(prop.name===`style`&&prop.value?.type===NodeTypes.TEXT){staticStyle=prop.value.content;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)?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}}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){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 propName=propsAliases[path.node.name];if(!propName||path.scope.hasBinding(path.node.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.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 buildInlineExpressionMapCode(inlineExpressions){if(!inlineExpressions.length)return null;return`{${inlineExpressions.map(entry=>{const keys=JSON.stringify(entry.scopeKeys);const{parameterNames}=entry;return`${JSON.stringify(entry.id)}:{keys:${keys},fn:(${parameterNames.context},${parameterNames.scope},${parameterNames.event})=>${entry.expression}}`}).join(`,`)}}`}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)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(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(`
|
|
5
|
+
`);source+=openingTag;const startOffset=source.length;source+=`${content}\n<\/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}}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,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 stripPageCompileTimeMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap=true,resolvedIds={}){const blocks=collectSfcScriptBlocks(source,filename,descriptor,resolvedIds);return stripAnalyzedPageMacrosFromSfcDescriptor(source,filename,descriptor,sourceMap,blocks,analyzePageCompileTimeMacroBlocks(blocks))}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=baseParse(template,{onError:()=>{}});const visit=node=>{if(node.type===NodeTypes.ELEMENT){const tag=node.tag;if((!options||options.shouldCollect(tag))&&!RESERVED_VUE_COMPONENT_TAGS.has(tag)&&!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(SCOPED_SLOT_GLOBALS.has(name))return;if(path.scope.hasBinding(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(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.hasBinding(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){const normalized=extension.startsWith(`.`)?extension.slice(1):extension;const resolvedSrc=src??`./${CLASS_STYLE_WXS_FILE}.${normalized}`;return`<${resolveScriptModuleTag(normalized)} module="${CLASS_STYLE_WXS_MODULE}" src="${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=isSjs?[`export default {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`]:[`module.exports = {`,` cls: normalizeClass,`,` style: normalizeStyle,`,` stylePair: stylePair,`,`}`];return[...bodyLines,...exportLines,``].join(`
|
|
6
|
+
`)}function warn(context,message,location,source=`template`,errorCode){context.diagnostics.push({code:errorCode??(source===`expression`?`WV1002`:`WV1001`),severity:errorCode?`error`:`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.hasBinding(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 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=forInfo?.listExp?.trim()??``;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=forInfo?.listExp?.trim()??``;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);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)));resolvedIndexes.set(forInfo.index?.trim()||`index`,indexExpression);if(forInfo.key)resolvedIndexes.set(forInfo.key,indexExpression)}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=forInfo?.listExp?.trim()??``;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`)}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 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 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,markLocal){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;path.replaceWith(buildCtxValueAccess(path.node));path.skip()}})}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});rewriteTopLevelRefLikeAccess(ast,context,parameterIdentifiers,locals,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(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(JS_RUNTIME_GLOBALS.has(name))return;if(path.scope.hasBinding(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(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){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;traverse(parsed.ast,{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()}});return shouldFallback}function registerRuntimeBindingExpression(exp,context,options){const expAst=normalizeJsExpressionWithContext(exp,context,{...options,runtimePropAccess:`helper`,unrefMemberAccess:true});if(!expAst)return null;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)}`}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)?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){const inner=tokens.slice(openIndex+1,closeIndex);return inner.some(token=>token.type===`text`&&token.value.trim().length>0)&&inner.every(token=>token.type!==`tag`||isSelfClosingTag(token.value))}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).filter(token=>!isWhitespaceText(token));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`){const value=token.value.trim();if(value)appendLine(lines,level,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(`
|
|
7
|
+
`)}\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;for(const scope of context.scopeStack)for(const name of scope){if(!IDENTIFIER_RE$2.test(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;return`[${keys.map(key=>`${toWxmlStringLiteral$1(key)},${getForItemAccess(context,key)}`).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){const rawKeyExp=getBindDirectiveExpression(node).trim();if(!rawKeyExp||!forInfo.listExp||resolveNativeForKeyValue(rawKeyExp,forInfo,context.platform.keyThisValue))return null;const listExp=forInfo.listExp?.trim()??``;const rawListExp=forInfo.rawListExp?.trim()||listExp;const projectionListExp=RUNTIME_BINDING_REF_RE$1.test(listExp)?listExp:rawListExp;const sourceContext=createSourceContext(context);const projectionSourceAst=RUNTIME_BINDING_REF_RE$1.test(projectionListExp)?normalizeJsExpressionWithContext(projectionListExp,sourceContext,{hint:`v-for :key 数据源`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true}):normalizeJsExpressionWithContext(projectionListExp,sourceContext,{hint:`v-for :key 数据源`,preserveForItems:true});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),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)){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)}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 transformAttribute(node,_context,nameOverride){const{value}=node;const name=nameOverride??node.name;if(!value)return name;if(value.type===NodeTypes.TEXT)return`${name}="${escapeWxmlAttribute(value.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]:[];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=prop.value.content;continue}if(prop.name===`id`&&prop.value?.type===NodeTypes.TEXT){staticId=prop.value.content.trim();continue}if(prop.name===`style`&&prop.value?.type===NodeTypes.TEXT){staticStyle=prop.value.content;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)?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}}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){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 propName=propsAliases[path.node.name];if(!propName||path.scope.hasBinding(path.node.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.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 buildInlineExpressionMapCode(inlineExpressions){if(!inlineExpressions.length)return null;return`{${inlineExpressions.map(entry=>{const keys=JSON.stringify(entry.scopeKeys);const{parameterNames}=entry;return`${JSON.stringify(entry.id)}:{keys:${keys},fn:(${parameterNames.context},${parameterNames.scope},${parameterNames.event})=>${entry.expression}}`}).join(`,`)}}`}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)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(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(`
|
|
8
8
|
`)}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}="${info.value}"`;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:[],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)}\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});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===`
|
|
9
|
-
`||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);const slotAttrString=slotAttrs.length?` ${slotAttrs.join(` `)}`:``;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``;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(projected)}const content=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);const slotAttrString=slotAttrs.length?` ${slotAttrs.join(` `)}`:``;let slotTag=`<slot${slotAttrString} />`;const slotPresentExp=fallbackContent?createSlotPresenceExpression(slotNameInfo):void 0;if(fallbackContent){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 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 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):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)}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?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))renderItems.push({type:`default-child`,child:compatibleChild})}const defaultSlotChildren=nonTemplateChildren.filter(isRenderableSlotChild);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,defaultSlotChildren,context,{implicitDefault:true});slotDeclarations.push(implicitDefaultDeclaration)}}else if(!slotDeclarations.length&&defaultSlotChildren.length&&!context.scopedSlotsRequireProps&&!hasLegacySlotAttribute(defaultSlotChildren)){implicitDefaultDeclaration=buildSlotDeclaration({type:`default`},void 0,defaultSlotChildren,context,{implicitDefault:true});slotDeclarations.push(implicitDefaultDeclaration)}if(!slotDeclarations.length){const{attrs,vTextExp}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=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}=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=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))renderItems.push({type:`default-child`,child:compatibleChild})}const defaultSlotChildren=nonTemplateChildren.filter(isRenderableSlotChild);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,defaultSlotChildren,context);slotDeclarations.push(implicitDefaultDeclaration)}}if(!slotDeclarations.length){const{attrs,vTextExp}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=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 renderedSlots=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{attrs}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});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}=collectElementAttributes(node,context,{resolvedTag:tag});let children=``;if(node.children.length>0)children=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)?normalizeJsExpressionWithContext(listExp,context,{hint:`v-for 解构数据源`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true}):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=normalizeJsExpressionWithContext(projectedListExp,context,{hint:`v-for 解构列表`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});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)?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
|
+
`||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);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);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):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)}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}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=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}=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=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}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});let children=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 renderedSlots=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{attrs}=collectElementAttributes(node,context,{skipSlotDirective:true,forInfo:options?.forInfo,isComponent:true});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}=collectElementAttributes(node,context,{resolvedTag:tag});let children=``;if(node.children.length>0)children=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)?normalizeJsExpressionWithContext(listExp,context,{hint:`v-for 解构数据源`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true}):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=normalizeJsExpressionWithContext(projectedListExp,context,{hint:`v-for 解构列表`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});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)?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)
|
|
10
10
|
/* istanbul ignore next */
|
|
11
|
-
return transformNormalElement(node,context,transformNode);const{conditionKind,condition,bindingCondition}=resolveConditionalBranch(ifDirective,context);const content=withBindingCondition(context,bindingCondition,()=>{const elementWithoutIf={...node,props:node.props.filter(prop=>prop!==ifDirective)};if(elementWithoutIf.tag===`template`)return elementWithoutIf.children.map(child=>transformNode(child,context)).join(``);const slotDirective=findSlotDirective(elementWithoutIf);const hasSlotChildren=elementWithoutIf.children.some(child=>child.type===NodeTypes.ELEMENT&&child.tag===`template`&&findSlotDirective(child));return elementWithoutIf.tag===`slot`?transformSlotElement(elementWithoutIf,context,transformNode):slotDirective||hasSlotChildren?transformComponentWithSlots(elementWithoutIf,context,transformNode):transformNormalElement(elementWithoutIf,context,transformNode)});if(conditionKind===`if`&&condition)return context.platform.wrapIf(condition,content,renderTemplateMustache);if(conditionKind===`else-if`&&condition)return context.platform.wrapElseIf(condition,content,renderTemplateMustache);return conditionKind===`else`?context.platform.wrapElse(content):content}function transformForElement(node,context,transformNode){const renderTemplateMustache=exp=>renderMustache$1(exp,context);const forDirective=node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`for`);if(!forDirective||!forDirective.exp)return transformNormalElement(node,context,transformNode);const expValue=forDirective.exp.type===NodeTypes.SIMPLE_EXPRESSION?forDirective.exp.content:``;const forInfo=parseForExpression(expValue);if(forInfo.itemPatternError){warn(context,forInfo.itemPatternError,forDirective.exp.loc,`template`,`WV2001`);return``}if(forInfo.item===`__wv_for_item__`){const generatedItem=`__wv_item_${context.forIndexSeed++}`;forInfo.item=generatedItem;if(forInfo.itemAliases){const escaped=FOR_ITEM_ALIAS_PLACEHOLDER.replace(REGEX_SPECIAL_CHARS_RE,`\\$&`);const placeholderRE=new RegExp(`\\b${escaped}\\b`,`g`);forInfo.itemAliases=Object.fromEntries(Object.entries(forInfo.itemAliases).map(([alias,expression])=>{return[alias,expression.replace(placeholderRE,generatedItem)]}))}}if((context.classStyleRuntime===`js`||requiresRuntimeForKeyProjection(node,context))&&!forInfo.index)forInfo.index=`__wv_index_${context.forIndexSeed++}`;const rawListExp=forInfo.listExp?.trim();let listExp=forInfo.listExp?resolveListExpression(forInfo.listExp,context,`v-for 列表`):void 0;let listExpAst=forInfo.listExp?normalizeJsExpressionWithContext(forInfo.listExp,context,{hint:`v-for 列表`}):void 0;const rawListExpAst=rawListExp&&context.forStack.some(info=>info.itemAccess)?normalizeJsExpressionWithContext(rawListExp,{...context,forStack:context.forStack.map(info=>({...info,itemAccess:void 0}))},{hint:`v-for 原始列表`}):listExpAst;if(forInfo.itemPatternRequiresProjection&&listExp&&listExpAst){const projected=registerForPatternProjection(forInfo,listExp,listExpAst,context);if(!projected){warn(context,`v-for 别名模式无法生成等价的逻辑层投影。`,forDirective.exp.loc,`template`,`WV2001`);return``}listExp=projected.listExp;listExpAst=projected.listExpAst}const scopedForInfo=listExp?{...forInfo,listExp,rawListExp,listExpAst:listExpAst??void 0,rawListExpAst:rawListExpAst??void 0}:{...forInfo,rawListExp,listExpAst:listExpAst??void 0,rawListExpAst:rawListExpAst??void 0};const scopeNames=[forInfo.item,forInfo.index,forInfo.key,...Object.keys(forInfo.itemAliases??{})].filter(Boolean);return withForScope(context,scopedForInfo,()=>withScope(context,scopeNames,()=>{const otherProps=node.props.filter(prop=>prop!==forDirective);const elementWithoutFor={...node,props:otherProps};const keyDirective=otherProps.find(prop=>{return prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`key`});const keyProjection=keyDirective?createForKeyProjection(keyDirective,scopedForInfo,context):null;const rawKeyExp=keyDirective?getBindDirectiveExpression(keyDirective).trim():``;const projectedOutputPath=keyProjection?.listExp??(listExp?.startsWith(`__wv_bind_`)?listExp:void 0);recordBindingExpression(context,{kind:`for`,expression:rawKeyExp?`(${rawListExp}, ${rawKeyExp})`:rawListExp??``,outputPath:projectedOutputPath?.split(`[`)[0],sourceLocation:forDirective.exp?.loc});if(keyProjection){scopedForInfo.itemAccess=keyProjection.itemAccess;const projectionContext={...context,forStack:context.forStack.map(forInfo=>({...forInfo,itemAccess:void 0}))};const projectedListExpAst=normalizeJsExpressionWithContext(keyProjection.listExp,projectionContext,{hint:`v-for 投影列表`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});scopedForInfo.projectedListExp=keyProjection.listExp;scopedForInfo.projectedListExpAst=projectedListExpAst??scopedForInfo.projectedListExpAst;const currentForInfo=context.forStack[context.forStack.length-1];if(currentForInfo){currentForInfo.itemAccess=keyProjection.itemAccess;currentForInfo.projectedListExp=scopedForInfo.projectedListExp;currentForInfo.projectedListExpAst=scopedForInfo.projectedListExpAst}}const renderElement=keyProjection?{...elementWithoutFor,props:otherProps.filter(prop=>prop!==keyDirective)}:elementWithoutFor;const templateListExp=keyProjection?.listExp??listExp;const extraAttrs=templateListExp?context.platform.forAttrs(templateListExp,renderTemplateMustache,forInfo.item,forInfo.index):[];if(keyProjection)extraAttrs.push(keyProjection.keyAttr);if(renderElement.tag===`slot`){const slotKeyDirective=keyProjection?void 0:keyDirective;const slotElementWithoutForKey={...renderElement,props:renderElement.props.filter(prop=>prop!==slotKeyDirective)};const content=transformSlotElement(slotElementWithoutForKey,context,transformNode);const keyAttr=slotKeyDirective?transformBindDirective(slotKeyDirective,context,scopedForInfo):null;if(keyAttr)extraAttrs.push(keyAttr);const attrString=extraAttrs.length?` ${extraAttrs.join(` `)}`:``;return attrString?`<block${attrString}>${content}</block>`:content}const resolvedTag=resolveTemplateTagName(renderElement.tag,context);if(shouldTransformAsComponentWithSlots(renderElement,context,resolvedTag))return transformComponentWithSlots(renderElement,context,transformNode,{extraAttrs,forInfo:scopedForInfo});const{attrs,vTextExp}=collectElementAttributes(renderElement,context,{forInfo:scopedForInfo,extraAttrs,resolvedTag});let children=``;if(renderElement.children.length>0)children=renderElement.children.map(child=>transformNode(child,context)).join(``);if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);const tag=resolvedTag;const attrString=attrs.length?` ${attrs.join(` `)}`:``;return children?`<${tag}${attrString}>${children}</${tag}>`:`<${tag}${attrString} />`}))}const TEMPLATE_OPEN_RE=/<template/g;const TEMPLATE_CLOSE_RE=/<\/template>/g;const MUSTACHE_EXPRESSION_RE=/\{\{([\s\S]*?)\}\}/g;const TEMPLATE_DATA_SPREAD_RE=/^\.\.\./;function recordTemplateAttributeBindings(prop,context){const value=prop.value?.content;if(!value?.includes(`{{`))return;for(const match of value.matchAll(MUSTACHE_EXPRESSION_RE)){const expression=match[1]?.trim().replace(TEMPLATE_DATA_SPREAD_RE,``);if(!expression)continue;recordBindingExpression(context,{kind:`attribute`,expression,sourceLocation:prop.value?.loc})}}function transformTransitionElement(node,context,transformNode){warn(context,`<transition> 组件:过渡效果需要动画库或运行时支持,仅渲染子节点。`,node.loc);const children=node.children.map(child=>transformNode(child,context)).join(``);if(node.children.length===1)return children;return children||``}function transformKeepAliveElement(node,context,transformNode){warn(context,`<keep-alive> 组件:需要运行时状态管理,渲染子节点并添加标记。`,node.loc);return`<block data-keep-alive="true">${node.children.map(child=>transformNode(child,context)).join(``)}</block>`}function transformTemplateElement(node,context,transformNode){let nameAttr=``;let isAttr=``;let dataAttr=``;let hasOtherDirective=false;let structuralDirective;for(const prop of node.props){if(prop.type===NodeTypes.DIRECTIVE){if(prop.name===`slot`){warn(context,`<template v-slot> 应作为组件元素的子节点;已忽略。`,prop.loc);continue}hasOtherDirective=true;if(!structuralDirective&&(prop.name===`if`||prop.name===`else-if`||prop.name===`else`||prop.name===`for`))structuralDirective=prop}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`name`){recordTemplateAttributeBindings(prop,context);nameAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`is`){recordTemplateAttributeBindings(prop,context);isAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`data`){recordTemplateAttributeBindings(prop,context);dataAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}}if(!nameAttr&&!isAttr&&!dataAttr){if(structuralDirective?.name===`for`)return transformForElement({...node,tag:`block`},context,transformNode);if(structuralDirective&&[`if`,`else-if`,`else`].includes(structuralDirective.name))return transformIfElement(node,context,transformNode);if(hasOtherDirective)return transformNormalElement(node,context,transformNode).replace(TEMPLATE_OPEN_RE,`<block`).replace(TEMPLATE_CLOSE_RE,`</block>`);return node.children.map(child=>transformNode(child,context)).join(``)}const attrs=[];if(nameAttr)attrs.push(`name="${nameAttr}"`);if(isAttr)attrs.push(`is="${isAttr}"`);if(dataAttr)attrs.push(`data="${dataAttr}"`);return`<template${attrs.length?` ${attrs.join(` `)}`:``}>${node.children.map(child=>transformNode(child,context)).join(``)}</template>`}function transformElement(node,context,transformNode){const compatibleNode=omitUnsupportedDynamicDirectiveNames(node,context);const{tag}=compatibleNode;if(tag===`template`)return transformTemplateElement(compatibleNode,context,transformNode);if(tag===`slot`){const{type}=isStructuralDirective(compatibleNode);if(type===`if`)return transformIfElement(compatibleNode,context,transformNode);if(type===`for`)return transformForElement(compatibleNode,context,transformNode);return transformSlotElement(compatibleNode,context,transformNode)}if(tag===`component`)return transformComponentElement(compatibleNode,context,transformNode);if(tag===`transition`)return transformTransitionElement(compatibleNode,context,transformNode);if(tag===`keep-alive`)return transformKeepAliveElement(compatibleNode,context,transformNode);const{type}=isStructuralDirective(compatibleNode);if(type===`if`)return transformIfElement(compatibleNode,context,transformNode);if(type===`for`)return transformForElement(compatibleNode,context,transformNode);return transformNormalElement(compatibleNode,context,transformNode)}const NATIVE_FOR_EXPRESSION_RE=/^\s*\{\{([\s\S]+)\}\}\s*$/;function getNativeForAttribute(node,name){return node.props.find(prop=>prop.type===NodeTypes.ATTRIBUTE&&prop.name===name)}function transformElementWithNativeForScope(node,context,transformChild){const listExpression=(getNativeForAttribute(node,context.platform.directives.forAttr)?.value?.content.match(NATIVE_FOR_EXPRESSION_RE))?.[1]?.trim();if(!listExpression)return transformElement(node,context,transformChild);const item=getNativeForAttribute(node,context.platform.directives.forItemAttr)?.value?.content.trim()||`item`;const index=getNativeForAttribute(node,context.platform.directives.forIndexAttr)?.value?.content.trim()||`index`;context.forStack.push({item,index,listExp:listExpression,rawListExp:listExpression});context.scopeStack.push(/* @__PURE__ */ new Set([item,index]));try{return transformElement(node,context,transformChild)}finally{context.scopeStack.pop();context.forStack.pop()}}function transformText(node,_context){return escapeWxmlText(node.content)}function transformInterpolation(node,context){const{content}=node;if(content.type===NodeTypes.SIMPLE_EXPRESSION){const rawExpValue=content.content;const runtimeExp=shouldFallbackToRuntimeBinding(rawExpValue,context.templateSafeCallNames)?registerRuntimeBindingExpression(rawExpValue,context,{hint:`插值表达式`}):null;recordBindingExpression(context,{kind:`text`,expression:rawExpValue,outputPath:runtimeExp?.split(`[`)[0],sourceLocation:content.loc});const expValue=runtimeExp??normalizeWxmlExpressionWithContext(rawExpValue,context);return renderMustache$1(expValue,context)}
|
|
11
|
+
return transformNormalElement(node,context,transformNode);const{conditionKind,condition,bindingCondition}=resolveConditionalBranch(ifDirective,context);const content=withBindingCondition(context,bindingCondition,()=>{const elementWithoutIf={...node,props:node.props.filter(prop=>prop!==ifDirective)};if(elementWithoutIf.tag===`template`)return elementWithoutIf.children.map(child=>transformNode(child,context)).join(``);const slotDirective=findSlotDirective(elementWithoutIf);const hasSlotChildren=elementWithoutIf.children.some(child=>child.type===NodeTypes.ELEMENT&&child.tag===`template`&&findSlotDirective(child));return elementWithoutIf.tag===`slot`?transformSlotElement(elementWithoutIf,context,transformNode):slotDirective||hasSlotChildren?transformComponentWithSlots(elementWithoutIf,context,transformNode):transformNormalElement(elementWithoutIf,context,transformNode)});if(conditionKind===`if`&&condition)return context.platform.wrapIf(condition,content,renderTemplateMustache);if(conditionKind===`else-if`&&condition)return context.platform.wrapElseIf(condition,content,renderTemplateMustache);return conditionKind===`else`?context.platform.wrapElse(content):content}function transformForElement(node,context,transformNode){const renderTemplateMustache=exp=>renderMustache$1(exp,context);const forDirective=node.props.find(prop=>prop.type===NodeTypes.DIRECTIVE&&prop.name===`for`);if(!forDirective)return transformNormalElement(node,context,transformNode);if(!forDirective.exp){warn(context,`v-for 表达式缺少循环项别名与列表。`,forDirective.loc,`template`,`WV2001`);return``}const expValue=forDirective.exp.type===NodeTypes.SIMPLE_EXPRESSION?forDirective.exp.content:``;const forInfo=parseForExpression(expValue);const parseError=forInfo.error??forInfo.itemPatternError;if(parseError){warn(context,parseError,forDirective.exp.loc,`template`,`WV2001`);return``}if(forInfo.item===`__wv_for_item__`){const generatedItem=`__wv_item_${context.forIndexSeed++}`;forInfo.item=generatedItem;if(forInfo.itemAliases){const escaped=FOR_ITEM_ALIAS_PLACEHOLDER.replace(REGEX_SPECIAL_CHARS_RE,`\\$&`);const placeholderRE=new RegExp(`\\b${escaped}\\b`,`g`);forInfo.itemAliases=Object.fromEntries(Object.entries(forInfo.itemAliases).map(([alias,expression])=>{return[alias,expression.replace(placeholderRE,generatedItem)]}))}}if((context.classStyleRuntime===`js`||requiresRuntimeForKeyProjection(node,context))&&!forInfo.index)forInfo.index=`__wv_index_${context.forIndexSeed++}`;const rawListExp=forInfo.listExp?.trim();let listExpAst=forInfo.listExp?normalizeJsExpressionWithContext(forInfo.listExp,context,{hint:`v-for 列表`}):void 0;if(!listExpAst){warn(context,`v-for 列表表达式无法解析。`,forDirective.exp.loc,`template`,`WV2001`);return``}let listExp=forInfo.listExp?resolveListExpression(forInfo.listExp,context,`v-for 列表`):void 0;const rawListExpAst=rawListExp&&context.forStack.some(info=>info.itemAccess)?normalizeJsExpressionWithContext(rawListExp,{...context,forStack:context.forStack.map(info=>({...info,itemAccess:void 0}))},{hint:`v-for 原始列表`}):listExpAst;if(forInfo.itemPatternRequiresProjection&&listExp&&listExpAst){const projected=registerForPatternProjection(forInfo,listExp,listExpAst,context);if(!projected){warn(context,`v-for 别名模式无法生成等价的逻辑层投影。`,forDirective.exp.loc,`template`,`WV2001`);return``}listExp=projected.listExp;listExpAst=projected.listExpAst}const scopedForInfo=listExp?{...forInfo,listExp,rawListExp,listExpAst:listExpAst??void 0,rawListExpAst:rawListExpAst??void 0}:{...forInfo,rawListExp,listExpAst:listExpAst??void 0,rawListExpAst:rawListExpAst??void 0};const scopeNames=[forInfo.item,forInfo.index,forInfo.key,...Object.keys(forInfo.itemAliases??{})].filter(Boolean);return withForScope(context,scopedForInfo,()=>withScope(context,scopeNames,()=>{const otherProps=node.props.filter(prop=>prop!==forDirective);const elementWithoutFor={...node,props:otherProps};const keyDirective=otherProps.find(prop=>{return prop.type===NodeTypes.DIRECTIVE&&prop.name===`bind`&&prop.arg?.type===NodeTypes.SIMPLE_EXPRESSION&&prop.arg.content===`key`});const keyProjection=keyDirective?createForKeyProjection(keyDirective,scopedForInfo,context):null;const rawKeyExp=keyDirective?getBindDirectiveExpression(keyDirective).trim():``;const projectedOutputPath=keyProjection?.listExp??(listExp?.startsWith(`__wv_bind_`)?listExp:void 0);recordBindingExpression(context,{kind:`for`,expression:rawKeyExp?`(${rawListExp}, ${rawKeyExp})`:rawListExp??``,outputPath:projectedOutputPath?.split(`[`)[0],sourceLocation:forDirective.exp?.loc});if(keyProjection){scopedForInfo.itemAccess=keyProjection.itemAccess;const projectionContext={...context,forStack:context.forStack.map(forInfo=>({...forInfo,itemAccess:void 0}))};const projectedListExpAst=normalizeJsExpressionWithContext(keyProjection.listExp,projectionContext,{hint:`v-for 投影列表`,runtimePropAccess:`helper`,unrefMemberAccess:true,preserveForItems:true});scopedForInfo.projectedListExp=keyProjection.listExp;scopedForInfo.projectedListExpAst=projectedListExpAst??scopedForInfo.projectedListExpAst;const currentForInfo=context.forStack[context.forStack.length-1];if(currentForInfo){currentForInfo.itemAccess=keyProjection.itemAccess;currentForInfo.projectedListExp=scopedForInfo.projectedListExp;currentForInfo.projectedListExpAst=scopedForInfo.projectedListExpAst}}const renderElement=keyProjection?{...elementWithoutFor,props:otherProps.filter(prop=>prop!==keyDirective)}:elementWithoutFor;const templateListExp=keyProjection?.listExp??listExp;const extraAttrs=templateListExp?context.platform.forAttrs(templateListExp,renderTemplateMustache,forInfo.item,forInfo.index):[];if(keyProjection)extraAttrs.push(keyProjection.keyAttr);if(renderElement.tag===`slot`){const slotKeyDirective=keyProjection?void 0:keyDirective;const slotElementWithoutForKey={...renderElement,props:renderElement.props.filter(prop=>prop!==slotKeyDirective)};const content=transformSlotElement(slotElementWithoutForKey,context,transformNode);const keyAttr=slotKeyDirective?transformBindDirective(slotKeyDirective,context,scopedForInfo):null;if(keyAttr)extraAttrs.push(keyAttr);const attrString=extraAttrs.length?` ${extraAttrs.join(` `)}`:``;return attrString?`<block${attrString}>${content}</block>`:content}const resolvedTag=resolveTemplateTagName(renderElement.tag,context);if(shouldTransformAsComponentWithSlots(renderElement,context,resolvedTag))return transformComponentWithSlots(renderElement,context,transformNode,{extraAttrs,forInfo:scopedForInfo});const{attrs,vTextExp}=collectElementAttributes(renderElement,context,{forInfo:scopedForInfo,extraAttrs,resolvedTag});let children=``;if(renderElement.children.length>0)children=renderElement.children.map(child=>transformNode(child,context)).join(``);if(vTextExp!==void 0)children=renderMustache$1(vTextExp,context);const tag=resolvedTag;const attrString=attrs.length?` ${attrs.join(` `)}`:``;return children?`<${tag}${attrString}>${children}</${tag}>`:`<${tag}${attrString} />`}))}const TEMPLATE_OPEN_RE=/<template/g;const TEMPLATE_CLOSE_RE=/<\/template>/g;const MUSTACHE_EXPRESSION_RE=/\{\{([\s\S]*?)\}\}/g;const TEMPLATE_DATA_SPREAD_RE=/^\.\.\./;function recordTemplateAttributeBindings(prop,context){const value=prop.value?.content;if(!value?.includes(`{{`))return;for(const match of value.matchAll(MUSTACHE_EXPRESSION_RE)){const expression=match[1]?.trim().replace(TEMPLATE_DATA_SPREAD_RE,``);if(!expression)continue;recordBindingExpression(context,{kind:`attribute`,expression,sourceLocation:prop.value?.loc})}}function transformTransitionElement(node,context,transformNode){warn(context,`<transition> 组件:过渡效果需要动画库或运行时支持,仅渲染子节点。`,node.loc);const children=node.children.map(child=>transformNode(child,context)).join(``);if(node.children.length===1)return children;return children||``}function transformKeepAliveElement(node,context,transformNode){warn(context,`<keep-alive> 组件:需要运行时状态管理,渲染子节点并添加标记。`,node.loc);return`<block data-keep-alive="true">${node.children.map(child=>transformNode(child,context)).join(``)}</block>`}function transformTemplateElement(node,context,transformNode){let nameAttr=``;let isAttr=``;let dataAttr=``;let hasOtherDirective=false;let structuralDirective;for(const prop of node.props){if(prop.type===NodeTypes.DIRECTIVE){if(prop.name===`slot`){warn(context,`<template v-slot> 应作为组件元素的子节点;已忽略。`,prop.loc);continue}hasOtherDirective=true;if(!structuralDirective&&(prop.name===`if`||prop.name===`else-if`||prop.name===`else`||prop.name===`for`))structuralDirective=prop}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`name`){recordTemplateAttributeBindings(prop,context);nameAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`is`){recordTemplateAttributeBindings(prop,context);isAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}if(prop.type===NodeTypes.ATTRIBUTE&&prop.name===`data`){recordTemplateAttributeBindings(prop,context);dataAttr=prop.value&&prop.value.type===NodeTypes.TEXT?prop.value.content:``}}if(!nameAttr&&!isAttr&&!dataAttr){if(structuralDirective?.name===`for`)return transformForElement({...node,tag:`block`},context,transformNode);if(structuralDirective&&[`if`,`else-if`,`else`].includes(structuralDirective.name))return transformIfElement(node,context,transformNode);if(hasOtherDirective)return transformNormalElement(node,context,transformNode).replace(TEMPLATE_OPEN_RE,`<block`).replace(TEMPLATE_CLOSE_RE,`</block>`);return node.children.map(child=>transformNode(child,context)).join(``)}const attrs=[];if(nameAttr)attrs.push(`name="${nameAttr}"`);if(isAttr)attrs.push(`is="${isAttr}"`);if(dataAttr)attrs.push(`data="${dataAttr}"`);return`<template${attrs.length?` ${attrs.join(` `)}`:``}>${node.children.map(child=>transformNode(child,context)).join(``)}</template>`}function transformElement(node,context,transformNode){const compatibleNode=omitUnsupportedDynamicDirectiveNames(node,context);const{tag}=compatibleNode;if(tag===`template`)return transformTemplateElement(compatibleNode,context,transformNode);if(tag===`slot`){const{type}=isStructuralDirective(compatibleNode);if(type===`if`)return transformIfElement(compatibleNode,context,transformNode);if(type===`for`)return transformForElement(compatibleNode,context,transformNode);return transformSlotElement(compatibleNode,context,transformNode)}if(tag===`component`)return transformComponentElement(compatibleNode,context,transformNode);if(tag===`transition`)return transformTransitionElement(compatibleNode,context,transformNode);if(tag===`keep-alive`)return transformKeepAliveElement(compatibleNode,context,transformNode);const{type}=isStructuralDirective(compatibleNode);if(type===`if`)return transformIfElement(compatibleNode,context,transformNode);if(type===`for`)return transformForElement(compatibleNode,context,transformNode);return transformNormalElement(compatibleNode,context,transformNode)}const NATIVE_FOR_EXPRESSION_RE=/^\s*\{\{([\s\S]+)\}\}\s*$/;function getNativeForAttribute(node,name){return node.props.find(prop=>prop.type===NodeTypes.ATTRIBUTE&&prop.name===name)}function transformElementWithNativeForScope(node,context,transformChild){const listExpression=(getNativeForAttribute(node,context.platform.directives.forAttr)?.value?.content.match(NATIVE_FOR_EXPRESSION_RE))?.[1]?.trim();if(!listExpression)return transformElement(node,context,transformChild);const item=getNativeForAttribute(node,context.platform.directives.forItemAttr)?.value?.content.trim()||`item`;const index=getNativeForAttribute(node,context.platform.directives.forIndexAttr)?.value?.content.trim()||`index`;context.forStack.push({item,index,listExp:listExpression,rawListExp:listExpression});context.scopeStack.push(/* @__PURE__ */ new Set([item,index]));try{return transformElement(node,context,transformChild)}finally{context.scopeStack.pop();context.forStack.pop()}}function transformText(node,_context){return escapeWxmlText(node.content)}function transformInterpolation(node,context){const{content}=node;if(content.type===NodeTypes.SIMPLE_EXPRESSION){const rawExpValue=content.content;const runtimeExp=shouldFallbackToRuntimeBinding(rawExpValue,context.templateSafeCallNames)?registerRuntimeBindingExpression(rawExpValue,context,{hint:`插值表达式`}):null;recordBindingExpression(context,{kind:`text`,expression:rawExpValue,outputPath:runtimeExp?.split(`[`)[0],sourceLocation:content.loc});const expValue=runtimeExp??normalizeWxmlExpressionWithContext(rawExpValue,context);return renderMustache$1(expValue,context)}
|
|
12
12
|
/* istanbul ignore next */
|
|
13
|
-
return renderMustache$1(``,context)}function transformNode(node,context){switch(node.type){case NodeTypes.ELEMENT:return transformElementWithNativeForScope(node,context,transformNode);case NodeTypes.TEXT:return transformText(node,context);case NodeTypes.INTERPOLATION:return transformInterpolation(node,context);case NodeTypes.COMMENT:return
|
|
13
|
+
return renderMustache$1(``,context)}function transformNode(node,context){switch(node.type){case NodeTypes.ELEMENT:return transformElementWithNativeForScope(node,context,transformNode);case NodeTypes.TEXT:return transformText(node,context);case NodeTypes.INTERPOLATION:return transformInterpolation(node,context);case NodeTypes.COMMENT:return context.preserveComments?`<!--${node.content}-->`:``;default:
|
|
14
14
|
/* istanbul ignore next */
|
|
15
|
-
return``}}function createMiniProgramDirectiveAttrs(prefix,separator=`:`){const resolveAttr=suffix=>`${prefix}${separator}${suffix}`;return{ifAttr:resolveAttr(`if`),elifAttr:resolveAttr(`elif`),elseAttr:resolveAttr(`else`),forAttr:resolveAttr(`for`),forItemAttr:resolveAttr(`for-item`),forIndexAttr:resolveAttr(`for-index`),keyAttr:resolveAttr(`key`)}}const WEAPP_JSX_EVENT_NAME_ALIASES={ad:{close:`bindclose`,error:`binderror`,load:`bindload`},"ad-custom":{error:`binderror`,load:`bindload`},audio:{ended:`bindended`,error:`binderror`,pause:`bindpause`,play:`bindplay`,timeUpdate:`bindtimeupdate`},button:{agreePrivacyAuthorization:`bindagreeprivacyauthorization`,chooseAvatar:`bindchooseavatar`,contact:`bindcontact`,createLiveActivity:`createliveactivity`,error:`binderror`,getPhoneNumber:`bindgetphonenumber`,getRealtimePhoneNumber:`bindgetrealtimephonenumber`,getUserInfo:`bindgetuserinfo`,launchApp:`bindlaunchapp`,openSetting:`bindopensetting`,tap:`bindtap`},camera:{error:`binderror`,initdone:`bindinitdone`,scanCode:`bindscancode`,stop:`bindstop`},canvas:{error:`binderror`,longTap:`bindlongtap`,touchCancel:`bindtouchcancel`,touchEnd:`bindtouchend`,touchMove:`bindtouchmove`,touchStart:`bindtouchstart`},"checkbox-group":{change:`bind:change`},"cover-image":{error:`bind:error`,load:`bind:load`},editor:{blur:`bindblur`,focus:`bindfocus`,input:`bindinput`,ready:`bindready`,statuschange:`bindstatuschange`},form:{reset:`bindreset`,submit:`bindsubmit`,submitToGroup:`bindsubmitToGroup`},"functional-page-navigator":{cancel:`bindcancel`,fail:`bindfail`,success:`bindsuccess`},image:{error:`binderror`,load:`bindload`},input:{blur:`bindblur`,change:`bindchange`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,keyboardcompositionend:`bind:keyboardcompositionend`,keyboardcompositionstart:`bind:keyboardcompositionstart`,keyboardcompositionupdate:`bind:keyboardcompositionupdate`,nicknameReview:`bindnicknamereview`,selectionchange:`bind:selectionchange`,workletOnkeyboardheightchange:`worklet:onkeyboardheightchange`},"live-player":{audiovolumenotify:`bindaudiovolumenotify`,castinginterrupt:`bindcastinginterrupt`,castingstatechange:`bindcastingstatechange`,castinguserselect:`bindcastinguserselect`,enterpictureinpicture:`bindenterpictureinpicture`,fullScreenChange:`bindfullscreenchange`,leavepictureinpicture:`bindleavepictureinpicture`,netstatus:`bindnetstatus`,statechange:`bindstatechange`},"live-pusher":{audiovolumenotify:`bindaudiovolumenotify`,bgmcomplete:`bindbgmcomplete`,bgmprogress:`bindbgmprogress`,bgmstart:`bindbgmstart`,enterpictureinpicture:`bindenterpictureinpicture`,error:`binderror`,leavepictureinpicture:`bindleavepictureinpicture`,netstatus:`bindnetstatus`,statechange:`bindstatechange`},map:{abilityfail:`bindabilityfail`,abilitysuccess:`bindabilitysuccess`,authsuccess:`bindauthsuccess`,calloutTap:`bindcallouttap`,controlTap:`bindcontroltap`,error:`binderror`,interpolatepoint:`bindinterpolatepoint`,labeltap:`bindlabeltap`,markerTap:`bindmarkertap`,poitap:`bindpoitap`,polylinetap:`bindpolylinetap`,regionChange:`bindregionchange`,tap:`bindtap`,updated:`bindupdated`},"movable-area":{change:`bindchange`,htouchmove:`htouchmove`,scale:`bindscale`,vtouchmove:`vtouchmove`},"movable-view":{change:`bindchange`,htouchmove:`htouchmove`,scale:`bindscale`,vtouchmove:`vtouchmove`},navigator:{complete:`bindcomplete`,fail:`bindfail`,success:`bindsuccess`},"official-account":{error:`binderror`,load:`bindload`},"open-data":{error:`binderror`},"page-container":{afterEnter:`bind:afterenter`,afterLeave:`bind:afterleave`,beforeEnter:`bind:beforeenter`,beforeLeave:`bind:beforeleave`,clickOverlay:`bind:clickoverlay`,enter:`bind:enter`,leave:`bind:leave`},"page-meta":{resize:`bindresize`,scroll:`bindscroll`,scrolldone:`bindscrolldone`},picker:{cancel:`bindcancel`,change:`bindchange`,columnchange:`bindcolumnchange`},"picker-view":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},"picker-view-column":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},progress:{activeend:`bindactiveend`},"radio-group":{change:`bind:change`},"scroll-view":{dragend:`binddragend`,dragging:`binddragging`,dragstart:`binddragstart`,refresherabort:`bindrefresherabort`,refresherpulling:`bindrefresherpulling`,refresherrefresh:`bindrefresherrefresh`,refresherrestore:`bindrefresherrestore`,refresherstatuschange:`bind:refresherstatuschange`,refresherwillrefresh:`bind:refresherwillrefresh`,scroll:`bindscroll`,scrollToLower:`bindscrolltolower`,scrollToUpper:`bindscrolltoupper`,scrollend:`bind:scrollend`,scrollstart:`bind:scrollstart`,workletAdjustDecelerationVelocity:`worklet:adjust-deceleration-velocity`,workletOnscrollend:`worklet:onscrollend`,workletOnscrollstart:`worklet:onscrollstart`,workletOnscrollupdate:`worklet:onscrollupdate`},"share-element":{workletOnframe:`worklet:onframe`},slider:{change:`bindchange`,changing:`bindchanging`},swiper:{animationfinish:`bindanimationfinish`,change:`bindchange`,transition:`bindtransition`,workletOnscrollend:`worklet:onscrollend`,workletOnscrollstart:`worklet:onscrollstart`,workletOnscrollupdate:`worklet:onscrollupdate`},switch:{change:`bindchange`},textarea:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,keyboardcompositionend:`bind:keyboardcompositionend`,keyboardcompositionstart:`bind:keyboardcompositionstart`,keyboardcompositionupdate:`bind:keyboardcompositionupdate`,linechange:`bindlinechange`,selectionchange:`bind:selectionchange`},video:{castinginterrupt:`bindcastinginterrupt`,castingstatechange:`bindcastingstatechange`,castinguserselect:`bindcastinguserselect`,controlstoggle:`bindcontrolstoggle`,ended:`bindended`,enterpictureinpicture:`bindenterpictureinpicture`,error:`binderror`,fullScreenChange:`bindfullscreenchange`,leavepictureinpicture:`bindleavepictureinpicture`,loadedmetadata:`bindloadedmetadata`,pause:`bindpause`,play:`bindplay`,progress:`bindprogress`,seekcomplete:`bindseekcomplete`,timeUpdate:`bindtimeupdate`,waiting:`bindwaiting`},view:{tap:`bindtap`},"voip-room":{error:`binderror`},"web-view":{error:`binderror`,load:`bindload`,message:`bindmessage`}};const ALIPAY_JSX_EVENT_NAME_ALIASES={button:{chooseAvatar:`onChooseAvatar`,error:`onError`,followLifestyle:`onFollowLifestyle`,getAuthorize:`onGetAuthorize`,getPhoneNumber:`onGetPhoneNumber`,getUserInfo:`onGetUserInfo`,tap:`onTap`},camera:{error:`onError`,ready:`onReady`,scanCode:`onScanCode`,stop:`onStop`},canvas:{longTap:`onLongTap`,ready:`onReady`,tap:`onTap`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},checkbox:{change:`onChange`},"checkbox-group":{change:`onChange`},"cover-image":{tap:`onTap`},"cover-view":{tap:`onTap`},form:{reset:`onReset`,submit:`onSubmit`},image:{error:`onError`,load:`onLoad`,tap:`onTap`},input:{blur:`onBlur`,confirm:`onConfirm`,focus:`onFocus`,input:`onInput`},lifestyle:{follow:`onFollow`},lottie:{animationCancel:`onAnimationCancel`,animationEnd:`onAnimationEnd`,animationRepeat:`onAnimationRepeat`,animationStart:`onAnimationStart`,dataFailed:`onDataFailed`,dataLoadReady:`onDataLoadReady`,dataReady:`onDataReady`},map:{calloutTap:`onCalloutTap`,controlTap:`onControlTap`,initComplete:`onInitComplete`,markerTap:`onMarkerTap`,panelTap:`onPanelTap`,regionChange:`onRegionChange`,tap:`onTap`},"movable-view":{change:`onChange`,changeEnd:`onChangeEnd`,scale:`onScale`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},"page-container":{afterEnter:`onAfterEnter`,afterLeave:`onAfterLeave`,beforeEnter:`onBeforeEnter`,beforeLeave:`onBeforeLeave`,clickOverlay:`onClickOverlay`,enter:`onEnter`,enterCancelled:`onEnterCancelled`,leave:`onLeave`,leaveCancelled:`onLeaveCancelled`},"page-meta":{scroll:`onScroll`},picker:{change:`onChange`},"picker-view":{change:`onChange`,pickEnd:`onPickEnd`,pickStart:`onPickStart`},"radio-group":{change:`onChange`},"rich-text":{longTap:`onLongtap`,tap:`onTap`,touchCancel:`onTouchcancel`,touchEnd:`onTouchend`,touchMove:`onTouchmove`,touchStart:`onTouchstart`},"scroll-view":{scroll:`onScroll`,scrollToLower:`onScrollToLower`,scrollToUpper:`onScrollToUpper`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},slider:{change:`onChange`,changing:`onChanging`},"subscribe-message":{complete:`onComplete`},swiper:{animationEnd:`onAnimationEnd`,change:`onChange`,transition:`onTransition`},switch:{change:`onChange`},textarea:{blur:`onBlur`,confirm:`onConfirm`,focus:`onFocus`,input:`onInput`},video:{ended:`onEnded`,error:`onError`,fullScreenChange:`onFullScreenChange`,loading:`onLoading`,pause:`onPause`,play:`onPlay`,renderStart:`onRenderStart`,stop:`onStop`,tap:`onTap`,timeUpdate:`onTimeUpdate`,userAction:`onUserAction`},view:{animationEnd:`onAnimationEnd`,animationIteration:`onAnimationIteration`,animationStart:`onAnimationStart`,appear:`onAppear`,disappear:`onDisappear`,firstAppear:`onFirstAppear`,longTap:`onLongTap`,tap:`onTap`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`,transitionEnd:`onTransitionEnd`},"web-view":{error:`onError`,load:`onLoad`,message:`onMessage`}};const TT_JSX_EVENT_NAME_ALIASES={"aweme-data":{error:`binderror`},"aweme-user-card":{error:`binderror`},button:{agreePrivacyAuthorization:`bindagreeprivacyauthorization`,getPhoneNumber:`bindgetphonenumber`,tap:`bindtap`},camera:{error:`binderror`,initdone:`bindinitdone`,scanCode:`bindscancode`,stop:`bindstop`},canvas:{touchCancel:`bindtouchcancel`,touchEnd:`bindtouchend`,touchMove:`bindtouchmove`,touchStart:`bindtouchstart`},"checkbox-group":{change:`bindchange`},"draw-ad":{error:`binderror`,play:`bindplay`,stop:`bindstop`},form:{reset:`bindreset`,submit:`bindsubmit`},image:{error:`binderror`,load:`bindload`},input:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`},"live-player":{error:`binderror`,fullScreenChange:`bindfullscreenchange`,statechange:`bindstatechange`},map:{anchorpointtap:`bindanchorpointtap`,calloutTap:`bindcallouttap`,labeltap:`bindlabeltap`,markerTap:`bindmarkertap`,regionChange:`bindregionchange`,tap:`bindtap`,updated:`bindupdated`},"movable-view":{change:`bindchange`,htouchmove:`bindhtouchmove`,scale:`bindscale`,vtouchmove:`bindvtouchmove`},"open-data":{error:`binderror`},picker:{cancel:`bindcancel`,change:`bindchange`,columnchange:`bindcolumnchange`},"picker-view":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},progress:{activeend:`bindactiveend`},"radio-group":{change:`bindchange`},"rtc-room":{error:`binderror`},"scroll-view":{refresherabort:`bindrefresherabort`,refresherpulling:`bindrefresherpulling`,refresherrefresh:`bindrefresherrefresh`,refresherrestore:`bindrefresherrestore`,scroll:`bindscroll`,scrollToLower:`bindscrolltolower`,scrollToUpper:`bindscrolltoupper`},slider:{change:`bindchange`,changing:`bindchanging`},swiper:{animationfinish:`bindanimationfinish`,change:`bindchange`,transition:`bindtransition`},switch:{change:`bindchange`},textarea:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,linechange:`bindlinechange`},video:{closebackground:`bindclosebackground`,controlTap:`bindcontroltap`,controlstoggle:`bindcontrolstoggle`,ended:`bindended`,enterbackground:`bindenterbackground`,error:`binderror`,fullScreenChange:`bindfullscreenchange`,leavebackground:`bindleavebackground`,loadedmetadata:`bindloadedmetadata`,mutechange:`bindmutechange`,pause:`bindpause`,play:`bindplay`,playbackratechange:`bindplaybackratechange`,playbackratelistchange:`bindplaybackratelistchange`,progress:`bindprogress`,seekcomplete:`bindseekcomplete`,timeUpdate:`bindtimeupdate`,waiting:`bindwaiting`},view:{tap:`bindtap`},"web-view":{error:`binderror`,load:`bindload`,message:`bindmessage`}};const eventMap$3={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchcancel:`touchCancel`,longtap:`longTap`,longpress:`longTap`};const PASCALIZE_EVENT_RE=/(^|-)([a-z0-9])/g;function toPascalEventName(eventName){return eventName.replace(PASCALIZE_EVENT_RE,(_match,_separator,character)=>character.toUpperCase())}function toOnEventName(eventName){return`on${toPascalEventName(eventName)}`}const EVENT_BINDING_PREFIX_RE$3=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$3(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$3.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function toAlipayDirectiveEvent(prefix,eventName){if(!eventName)return`on`;const pascalEvent=toPascalEventName(eventName);switch(prefix){case`catch`:return`catch${pascalEvent}`;case`capture-bind`:return`capture${pascalEvent}`;case`capture-catch`:return`captureCatch${pascalEvent}`;default:return toOnEventName(eventName)}}const directives$3=createMiniProgramDirectiveAttrs(`a`);const alipayPlatform={name:`alipay`,directives:directives$3,wrapIf:(exp,content,renderMustache)=>`<block ${directives$3.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$3.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$3.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$3.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$3.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$3.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$3.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$3[eventName.toLowerCase()]||eventName,eventBindingAlias:(eventName,tagName)=>tagName?ALIPAY_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$3(eventName);return toAlipayDirectiveEvent(prefix,normalizeMiniProgramEventName(name))}};const eventMap$2={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchstart:`touchstart`,touchmove:`touchmove`,touchend:`touchend`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE$2=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$2(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$2.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding$2(name){return name.includes(`:`)||name.includes(`-`)}const directives$2=createMiniProgramDirectiveAttrs(`wx`);const defaultMiniProgramPlatform={name:`wechat`,directives:directives$2,wrapIf:(exp,content,renderMustache)=>`<block ${directives$2.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$2.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$2.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$2.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$2.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$2.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$2.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$2[eventName.toLowerCase()]??eventName,eventBindingAlias:(eventName,tagName)=>tagName?WEAPP_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$2(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding$2(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding$2(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const defaultPlatform=defaultMiniProgramPlatform;const eventMap$1={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE$1=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$1(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$1.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding$1(name){return name.includes(`:`)||name.includes(`-`)}const directives$1=createMiniProgramDirectiveAttrs(`s`,`-`);const swanPlatform={name:`swan`,directives:directives$1,wrapIf:(exp,content,renderMustache)=>`<block ${directives$1.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$1.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$1.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$1.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$1.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$1.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$1.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$1[eventName.toLowerCase()]||eventName,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$1(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding$1(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding$1(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const eventMap={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchstart:`touchstart`,touchmove:`touchmove`,touchend:`touchend`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding(eventName){const prefixed=EVENT_BINDING_PREFIX_RE.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding(name){return name.includes(`:`)||name.includes(`-`)}const directives=createMiniProgramDirectiveAttrs(`tt`);const ttPlatform={name:`tt`,directives,wrapIf:(exp,content,renderMustache)=>`<block ${directives.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives.forItemAttr}="${item}"`);if(index)attrs.push(`${directives.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives.keyAttr}="${value}"`,mapEventName:eventName=>eventMap[eventName.toLowerCase()]??eventName,eventBindingAlias:(eventName,tagName)=>tagName?TT_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const TEMPLATE_PRESET_PLATFORMS={wechat:defaultMiniProgramPlatform,alipay:alipayPlatform,tt:ttPlatform,swan:swanPlatform};function getDefaultMiniProgramTemplatePlatform(){return TEMPLATE_PRESET_PLATFORMS[getMiniProgramTemplatePreset()]}const getDefaultMiniProgramPlatform=getDefaultMiniProgramTemplatePlatform;const defaultMiniProgramTemplatePlatform=getDefaultMiniProgramTemplatePlatform();const wechatPlatform=defaultMiniProgramPlatform;function getMiniProgramTemplatePlatform(platform){const preset=getMiniProgramTemplatePreset(platform);return TEMPLATE_PRESET_PLATFORMS[preset]??getDefaultMiniProgramTemplatePlatform()}function retainScopedSlotOwnerBindings(manifest,slots){const retained=/* @__PURE__ */ new Set;for(const slot of slots){if(!isBindingManifestComplete(slot.bindingManifest))markBindingManifestIncomplete(manifest);for(const binding of slot.bindingManifest.bindings)for(const dependency of binding.dependencies??[]){if(dependency.root!==WEVU_SLOT_OWNER_KEY)continue;const prefix=`${WEVU_SLOT_OWNER_KEY}.`;if(!dependency.path?.startsWith(prefix)){markBindingManifestIncomplete(manifest);continue}const ownerPath=dependency.path.slice(prefix.length);const root=/^[A-Z_$][\w$]*/i.exec(ownerPath)?.[0];if(!root||retained.has(ownerPath))continue;retained.add(ownerPath);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:`component-prop`,outputPath:ownerPath,sourceRoots:[root],sourcePaths:[ownerPath],dependencies:[{root,path:ownerPath,updateMode:`exact-path`}],scopes:[{kind:`root`,depth:0}],updateMode:`exact-path`,sourceLocation:binding.sourceLocation})}}}const HTML_VOID_TAGS=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`embed`,`hr`,`img`,`input`,`link`,`meta`,`param`,`source`,`track`,`wbr`]);function resolveTemplateIsPage(filename,options){if(options?.isPage!==true)return false;const normalized=filename.replace(/\\/g,`/`);return!/(?:^|\/)(?:components|layouts|custom-tab-bar)\//.test(normalized)}function resolveSlotFallbackWrapperComponent(strategy){if(strategy!==`virtual-host`)return;return{tagName:WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,componentBase:WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,template:`<slot></slot>`,script:`Component({options:{virtualHost:true,multipleSlots:true}})`,config:{component:true}}}function resolveSlotFallbackWrapperConfig(config,strategy){if(typeof config===`string`)return{tag:config||`view`,rules:[]};return{tag:config?.tag||(strategy===`virtual-host`?WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME:`view`),attrs:config?.attrs,singleRootNoWrapper:config?.singleRootNoWrapper,rules:config?.rules??[]}}function compileVueTemplateToWxml(template,filename,options){const diagnostics=[];const runtimeMode=options?.classStyleRuntime??`js`;const resolvedRuntime=runtimeMode===`auto`?options?.wxsExtension?`wxs`:`js`:runtimeMode===`wxs`&&!options?.wxsExtension?`js`:runtimeMode;const wxsExtension=options?.wxsExtension;const scopedSlotsRequireProps=options?.scopedSlotsRequireProps??options?.scopedSlotsCompiler!==`augmented`;const slotSingleRootNoWrapper=options?.slotSingleRootNoWrapper??false;const slotFallbackWrapperStrategy=options?.slotFallbackWrapperStrategy??`view`;const slotFallbackWrapper=resolveSlotFallbackWrapperConfig(options?.slotFallbackWrapper,slotFallbackWrapperStrategy);const slotFallbackWrapperComponent=slotFallbackWrapper.tag===WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME?resolveSlotFallbackWrapperComponent(slotFallbackWrapperStrategy):void 0;const htmlTagToWxmlMap=resolveHtmlTagToWxmlMap(options?.htmlTagToWxml);try{const ast=parse(template,{isVoidTag:tag=>HTML_VOID_TAGS.has(tag),onError:error=>warn({diagnostics,filename},`模板解析失败:${error.message}`,error.loc,`template`,`WV2001`)});const context={source:template,filename,diagnostics,bindingManifest:createBindingManifest(filename),runtimeBindingManifest:options?.runtimeBindingManifest??`compact`,platform:options?.platform??getMiniProgramTemplatePlatform(),isPage:resolveTemplateIsPage(filename,options),propsAliases:options?.propsAliases,propsDerivedKeys:options?.propsDerivedKeys,scriptSetupBindings:options?.scriptSetupBindings,htmlTagToWxmlMap,htmlTagToWxmlTagClass:options?.htmlTagToWxmlTagClass??true,scopedSlotsCompiler:options?.scopedSlotsCompiler??`auto`,scopedSlotsRequireProps,slotSingleRootNoWrapper,slotFallbackWrapper,slotFallbackWrapperComponent,slotMultipleInstance:options?.slotMultipleInstance??true,scopedSlotComponents:[],componentGenerics:{},componentNameMap:options?.componentNameMap,scopeStack:[],slotPropStack:[],rewriteScopedSlot:false,hasSlotOutlet:false,classStyleRuntime:resolvedRuntime===`wxs`?`wxs`:`js`,objectLiteralBindMode:options?.objectLiteralBindMode??`runtime`,mustacheInterpolation:options?.mustacheInterpolation??`compact`,formatWxml:options?.formatWxml??false,classStyleBindings:[],classStyleWxs:false,classStyleWxsExtension:wxsExtension,classStyleWxsSrc:options?.classStyleWxsSrc,forStack:[],forIndexSeed:0,templateRefs:[],templateRefIndexSeed:0,layoutHosts:[],layoutHostIndexSeed:0,inlineExpressions:[],inlineExpressionSeed:0,functionPropPaths:/* @__PURE__ */ new Set,functionPropNames:Array.from(options?.functionPropNames??[]),templateSafeCallNames:new Set(options?.templateSafeCallNames??[]),wevuComponentTags:options?.wevuComponentTags?new Set(options.wevuComponentTags):void 0,miniProgramComponentTags:options?.miniProgramComponentTags?new Set(options.miniProgramComponentTags):void 0,scopeId:options?.scopeId,slottedScopeId:options?.slottedScopeId,cssVars:options?.cssVars};collectConditionalBranches(ast.children);let wxml=ast.children.map(child=>transformNode(child,context)).join(``);if(context.classStyleWxs){const ext=context.classStyleWxsExtension||`wxs`;wxml=`${buildClassStyleWxsTag(ext,context.classStyleWxsSrc)}\n${wxml}`}if(context.formatWxml)wxml=formatWxml(wxml);retainScopedSlotOwnerBindings(context.bindingManifest,context.scopedSlotComponents);const result={code:wxml,diagnostics,bindingManifest:context.bindingManifest};if(context.scopedSlotComponents.length)result.scopedSlotComponents=context.scopedSlotComponents;if(context.slotFallbackWrapperComponent&&wxml.includes(`<${context.slotFallbackWrapperComponent.tagName}`))result.slotFallbackWrapperComponent=context.slotFallbackWrapperComponent;if(Object.keys(context.componentGenerics).length)result.componentGenerics=context.componentGenerics;if(context.classStyleWxs)result.classStyleWxs=true;if(context.classStyleBindings.length){result.classStyleBindings=context.classStyleBindings;result.classStyleRuntime=context.classStyleRuntime}if(context.templateRefs.length)result.templateRefs=context.templateRefs;if(context.layoutHosts.length)result.layoutHosts=context.layoutHosts;if(context.inlineExpressions.length)result.inlineExpressions=context.inlineExpressions;if(context.functionPropPaths.size)result.functionPropPaths=[...context.functionPropPaths];if(context.hasSlotOutlet)result.hasSlotOutlet=true;result.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(context.bindingManifest);return result}catch(error){warn({diagnostics,filename},`模板编译失败:${error}`,void 0,`template`,`WV2002`);const bindingManifest=createBindingManifest(filename);markBindingManifestIncomplete(bindingManifest);bindingManifest.bindings.push({id:`b0`,kind:`text`,outputPath:`*`,sourceRoots:[],dependencies:[],scopes:[{kind:`root`,depth:0}],updateMode:`snapshot-fallback`});return{code:template,bindingManifest,diagnostics}}}const LAYOUT_OWNER_EXPRESSION=`${WEVU_SLOT_OWNER_ID_PROP} || ${WEVU_SLOT_OWNER_ID_KEY} || ''`;const LAYOUT_SLOT_OWNER_ATTR=`${WEVU_SLOT_OWNER_ID_ATTR}="{{${LAYOUT_OWNER_EXPRESSION}}}"`;const CAMEL_TO_KEBAB_RE=/([a-z0-9])([A-Z])/g;const LAYOUT_NAME_SEPARATORS_RE=/[_\s]+/g;const DUPLICATE_DASH_RE=/-+/g;const EDGE_DASH_RE=/^-|-$/g;function toKebabCase(value){return value.replace(CAMEL_TO_KEBAB_RE,`$1-$2`).replace(LAYOUT_NAME_SEPARATORS_RE,`-`).replace(DUPLICATE_DASH_RE,`-`).replace(EDGE_DASH_RE,``).toLowerCase()}function serializeLayoutProps(props){const attrs=[LAYOUT_SLOT_OWNER_ATTR];for(const[key,value]of Object.entries(props??{})){const attrName=toKebabCase(key);if(typeof value===`string`)attrs.push(`${attrName}="${escapeWxmlAttribute(value)}"`);else if(typeof value===`object`&&value&&value.kind===`expression`)attrs.push(`${attrName}="{{${WEVU_LAYOUT_BIND_PREFIX}${key}}}"`);else attrs.push(`${attrName}="{{${String(value)}}}"`)}return` ${attrs.join(` `)}`}function serializeFallbackLayoutValue(value,key){const runtimeValue=`${WEVU_PAGE_LAYOUT_PROPS_KEY}&&${WEVU_PAGE_LAYOUT_PROPS_KEY}.${key}`;if(value===void 0)return`(${runtimeValue})`;const fallback=typeof value===`object`&&value?.kind===`expression`?`${WEVU_LAYOUT_BIND_PREFIX}${key}`:JSON.stringify(value);return`(${runtimeValue})!==undefined?${WEVU_PAGE_LAYOUT_PROPS_KEY}.${key}:${fallback}`}function buildDynamicLayoutTemplate(template,currentLayout,layouts,propKeys,platform){return`${layouts.map((layout,index)=>{const attrs=[LAYOUT_SLOT_OWNER_ATTR];for(const key of propKeys)attrs.push(`${toKebabCase(key)}="{{${serializeFallbackLayoutValue(currentLayout?.props?.[key],key)}}}"`);const condition=currentLayout?.layoutName===layout.layoutName?`{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`:`{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;return`<block ${index===0?platform.directives.ifAttr:platform.directives.elifAttr}="${condition}"><${layout.tagName} ${attrs.join(` `)}>${template}</${layout.tagName}></block>`}).join(``)}<block ${platform.directives.elseAttr}>${template}</block>`}function hasDynamicLayoutWrapper(template,plan,platform){if(!plan.layouts.length||!template.startsWith(`<block ${platform.directives.ifAttr}=`))return false;return plan.layouts.every((layout,index)=>{const condition=plan.currentLayout?.layoutName===layout.layoutName?`{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`:`{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;const directive=index===0?platform.directives.ifAttr:platform.directives.elifAttr;return template.includes(`<block ${directive}="${condition}"><${layout.tagName}`)})&&template.includes(`<block ${platform.directives.elseAttr}>`)}function recordLayoutBindings(manifest,plan){manifest.features.layout=true;manifest.features.scopedSlots=true;recordSyntheticBindingExpression(manifest,{kind:`attribute`,expression:LAYOUT_OWNER_EXPRESSION});if(plan.dynamicSwitch){recordSyntheticBindingExpression(manifest,{kind:`if`,expression:WEVU_PAGE_LAYOUT_NAME_KEY});if(plan.dynamicPropKeys.length)recordSyntheticBindingExpression(manifest,{kind:`component-prop`,expression:WEVU_PAGE_LAYOUT_PROPS_KEY})}for(const[key,value]of Object.entries(plan.currentLayout?.props??{})){if(typeof value!==`object`||!value||value.kind!==`expression`)continue;recordSyntheticBindingExpression(manifest,{kind:`component-prop`,expression:value.expression,outputPath:`${WEVU_LAYOUT_BIND_PREFIX}${key}`})}}function collapseNestedWrapper(template,tagName){const closeTag=`</${tagName}>`;let next=template;while(next.startsWith(`<${tagName}`)&&next.endsWith(closeTag)){const openTagEnd=next.indexOf(`>`);if(openTagEnd<0)break;const inner=next.slice(openTagEnd+1,-closeTag.length);if(!inner.startsWith(`<${tagName}`))break;next=inner}return next}function unwrapOuterWrapper(template,tagName){const closeTag=`</${tagName}>`;if(!template.startsWith(`<${tagName}`)||!template.endsWith(closeTag))return;const openTagEnd=template.indexOf(`>`);if(openTagEnd<0)return;return{openTag:template.slice(0,openTagEnd+1),content:template.slice(openTagEnd+1,-closeTag.length)}}function recordAppShellBinding(manifest){manifest.features.scopedSlots=true;recordSyntheticBindingExpression(manifest,{kind:`attribute`,expression:LAYOUT_OWNER_EXPRESSION})}function applyCompilerTemplateWrappers(options){const{manifest,platform,pageLayout,appShell}=options;let template=options.template;let existingAppShellOpenTag;if(appShell){const existingAppShell=unwrapOuterWrapper(collapseNestedWrapper(template,appShell.tagName),appShell.tagName);if(existingAppShell){existingAppShellOpenTag=existingAppShell.openTag;template=existingAppShell.content}}if(pageLayout){recordLayoutBindings(manifest,pageLayout);if(pageLayout.dynamicSwitch){if(!hasDynamicLayoutWrapper(template,pageLayout,platform))template=buildDynamicLayoutTemplate(template,pageLayout.currentLayout,pageLayout.layouts,pageLayout.dynamicPropKeys,platform)}else if(pageLayout.currentLayout){const layout=pageLayout.currentLayout;template=template.startsWith(`<${layout.tagName}`)?collapseNestedWrapper(template,layout.tagName):`<${layout.tagName}${serializeLayoutProps(layout.props)}>${template}</${layout.tagName}>`}}if(appShell){recordAppShellBinding(manifest);template=`${existingAppShellOpenTag??`<${appShell.tagName} ${LAYOUT_SLOT_OWNER_ATTR}>`}${template}</${appShell.tagName}>`}return template}function mergeCompilerLayoutUsingComponents(config,pageLayout,appShell){if(!pageLayout&&!appShell)return config;const parsed=config?JSON.parse(config):{};const usingComponents=parsed.usingComponents&&typeof parsed.usingComponents===`object`&&!Array.isArray(parsed.usingComponents)?parsed.usingComponents:{};for(const layout of pageLayout?.layouts??[])usingComponents[layout.tagName]=layout.importPath;if(!pageLayout?.dynamicSwitch&&pageLayout?.currentLayout)usingComponents[pageLayout.currentLayout.tagName]=pageLayout.currentLayout.importPath;if(appShell)usingComponents[appShell.tagName]=appShell.importPath;parsed.usingComponents=usingComponents;return JSON.stringify(parsed,null,2)}function collectPatternNames(pattern,out){if(!pattern)return;if(t.isIdentifier(pattern)){out.add(pattern.name);return}if(t.isRestElement(pattern)){collectPatternNames(pattern.argument,out);return}if(t.isAssignmentPattern(pattern)){collectPatternNames(pattern.left,out);return}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop))collectPatternNames(prop.argument,out);else if(t.isObjectProperty(prop))collectPatternNames(prop.value,out);return}if(t.isArrayPattern(pattern))for(const el of pattern.elements)collectPatternNames(el,out)}function declaredNamesInStatement(statement){const out=/* @__PURE__ */ new Set;if(t.isImportDeclaration(statement)){for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)||t.isImportNamespaceSpecifier(specifier)){if(t.isIdentifier(specifier.local))out.add(specifier.local.name)}return out}if(t.isVariableDeclaration(statement)){for(const decl of statement.declarations)collectPatternNames(decl.id,out);return out}if(t.isFunctionDeclaration(statement)||t.isClassDeclaration(statement)){if(statement.id&&t.isIdentifier(statement.id))out.add(statement.id.name);return out}if(t.isExportNamedDeclaration(statement)&&statement.declaration)return declaredNamesInStatement(statement.declaration);return out}function collectTopLevelReferencedNames(path){const names=/* @__PURE__ */ new Set;if(!path)return names;const addIfTopLevelReferenced=p=>{if(!p?.isReferencedIdentifier?.())return;const name=p.node.name;const binding=p.scope?.getBinding(name);if(!binding)return;if(binding.scope?.block?.type===`Program`)names.add(name)};addIfTopLevelReferenced(path);path.traverse({Function(p){if(p.node!==path.node)p.skip()},Class(p){if(p.node!==path.node)p.skip()},Identifier(p){addIfTopLevelReferenced(p)}});return names}function collectKeptStatementPaths(programPath,macroStatements){const bodyPaths=programPath.get(`body`);const nameToStatementPath=/* @__PURE__ */ new Map;for(const statementPath of bodyPaths){const declared=declaredNamesInStatement(statementPath.node);for(const name of declared)if(!nameToStatementPath.has(name))nameToStatementPath.set(name,statementPath)}const neededNames=/* @__PURE__ */ new Set;for(const statementPath of macroStatements){const deps=collectTopLevelReferencedNames(statementPath.get(`expression`).get(`arguments.0`));for(const dep of deps)neededNames.add(dep)}const keptStatementPaths=/* @__PURE__ */ new Set;const queue=[...neededNames];while(queue.length){const name=queue.pop();const declPath=nameToStatementPath.get(name);if(!declPath||keptStatementPaths.has(declPath))continue;keptStatementPaths.add(declPath);const deps=collectTopLevelReferencedNames(declPath);for(const dep of deps)if(dep!==name)queue.push(dep)}for(const statementPath of macroStatements)keptStatementPaths.add(statementPath);return{bodyPaths,keptStatementPaths}}const locks=/* @__PURE__ */ new Map;async function withTempDirLock(tempDir,fn){const previous=locks.get(tempDir)??Promise.resolve();let release;const gate=new Promise(resolve=>{release=resolve});const current=previous.then(()=>gate);locks.set(tempDir,current);try{await previous;return await fn()}finally{release?.();if(locks.get(tempDir)===current)locks.delete(tempDir)}}const PROJECT_WEVU_CONFIG_DIR=path.join(`.weapp-vite`,`wevu-config`);function getWevuConfigCacheRoot(){const env=process.env.WEAPP_VITE_WEVU_CONFIG_DIR?.trim();if(env)return path.resolve(env);const projectRoot=process.cwd();if(fs.existsSync(projectRoot))return path.join(projectRoot,PROJECT_WEVU_CONFIG_DIR);return path.join(os.tmpdir(),`weapp-vite`,`wevu-config`)}function resolveWevuConfigTempDir(fromDir){const root=getWevuConfigCacheRoot();const key=createHash(`sha256`).update(path.normalize(fromDir)).digest(`hex`).slice(0,8);return path.join(root,key)}function normalizeScriptSetupLang$1(lang){if(!lang)return`ts`;const lower=lang.toLowerCase();if(lower===`txt`)return`ts`;return lower}function resolveScriptSetupExtension$1(lang){const normalized=normalizeScriptSetupLang$1(lang);if(normalized===`ts`||normalized===`tsx`||normalized===`cts`||normalized===`mts`)return`ts`;return`js`}function resolveMacroAlias(macroName){return macroName===`defineAppJson`?`__weapp_defineAppJson`:macroName===`definePageJson`?`__weapp_definePageJson`:macroName===`defineComponentJson`?`__weapp_defineComponentJson`:macroName===`defineSitemapJson`?`__weapp_defineSitemapJson`:`__weapp_defineThemeJson`}async function evaluateScriptSetupJsonMacro(params){const{preambleContent,originalContent,filename,lang,macroName,macroStatements,bodyPaths,keptStatementPaths,options}=params;const combinedContent=preambleContent?`${preambleContent}\n${originalContent}`:originalContent;const ms=new MagicString(combinedContent);const dir=path.dirname(filename);const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.json-macro.${unique}`);for(const statementPath of keptStatementPaths){if(!statementPath.isImportDeclaration())continue;const sourceNode=statementPath.node.source;if(!sourceNode||!t.isStringLiteral(sourceNode))continue;const originalSource=sourceNode.value;if(!originalSource.startsWith(`.`))continue;const next=rewriteRelativeImportSource(originalSource,dir,tempDir);if(typeof sourceNode.start===`number`&&typeof sourceNode.end===`number`)ms.overwrite(sourceNode.start,sourceNode.end,JSON.stringify(next))}const alias=resolveMacroAlias(macroName);for(const statementPath of macroStatements){const calleePath=statementPath.get(`expression`).get(`callee`);if(calleePath?.isIdentifier()&&typeof calleePath.node.start===`number`&&typeof calleePath.node.end===`number`)ms.overwrite(calleePath.node.start,calleePath.node.end,alias)}for(const statementPath of bodyPaths){if(keptStatementPaths.has(statementPath))continue;const start=statementPath.node.start;const end=statementPath.node.end;if(typeof start===`number`&&typeof end===`number`)ms.remove(start,end)}const evalSource=`
|
|
15
|
+
return``}}function createMiniProgramDirectiveAttrs(prefix,separator=`:`){const resolveAttr=suffix=>`${prefix}${separator}${suffix}`;return{ifAttr:resolveAttr(`if`),elifAttr:resolveAttr(`elif`),elseAttr:resolveAttr(`else`),forAttr:resolveAttr(`for`),forItemAttr:resolveAttr(`for-item`),forIndexAttr:resolveAttr(`for-index`),keyAttr:resolveAttr(`key`)}}const WEAPP_JSX_EVENT_NAME_ALIASES={ad:{close:`bindclose`,error:`binderror`,load:`bindload`},"ad-custom":{error:`binderror`,load:`bindload`},audio:{ended:`bindended`,error:`binderror`,pause:`bindpause`,play:`bindplay`,timeUpdate:`bindtimeupdate`},button:{agreePrivacyAuthorization:`bindagreeprivacyauthorization`,chooseAvatar:`bindchooseavatar`,contact:`bindcontact`,createLiveActivity:`createliveactivity`,error:`binderror`,getPhoneNumber:`bindgetphonenumber`,getRealtimePhoneNumber:`bindgetrealtimephonenumber`,getUserInfo:`bindgetuserinfo`,launchApp:`bindlaunchapp`,openSetting:`bindopensetting`,tap:`bindtap`},camera:{error:`binderror`,initdone:`bindinitdone`,scanCode:`bindscancode`,stop:`bindstop`},canvas:{error:`binderror`,longTap:`bindlongtap`,touchCancel:`bindtouchcancel`,touchEnd:`bindtouchend`,touchMove:`bindtouchmove`,touchStart:`bindtouchstart`},"checkbox-group":{change:`bind:change`},"cover-image":{error:`bind:error`,load:`bind:load`},editor:{blur:`bindblur`,focus:`bindfocus`,input:`bindinput`,ready:`bindready`,statuschange:`bindstatuschange`},form:{reset:`bindreset`,submit:`bindsubmit`,submitToGroup:`bindsubmitToGroup`},"functional-page-navigator":{cancel:`bindcancel`,fail:`bindfail`,success:`bindsuccess`},image:{error:`binderror`,load:`bindload`},input:{blur:`bindblur`,change:`bindchange`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,keyboardcompositionend:`bind:keyboardcompositionend`,keyboardcompositionstart:`bind:keyboardcompositionstart`,keyboardcompositionupdate:`bind:keyboardcompositionupdate`,nicknameReview:`bindnicknamereview`,selectionchange:`bind:selectionchange`,workletOnkeyboardheightchange:`worklet:onkeyboardheightchange`},"live-player":{audiovolumenotify:`bindaudiovolumenotify`,castinginterrupt:`bindcastinginterrupt`,castingstatechange:`bindcastingstatechange`,castinguserselect:`bindcastinguserselect`,enterpictureinpicture:`bindenterpictureinpicture`,fullScreenChange:`bindfullscreenchange`,leavepictureinpicture:`bindleavepictureinpicture`,netstatus:`bindnetstatus`,statechange:`bindstatechange`},"live-pusher":{audiovolumenotify:`bindaudiovolumenotify`,bgmcomplete:`bindbgmcomplete`,bgmprogress:`bindbgmprogress`,bgmstart:`bindbgmstart`,enterpictureinpicture:`bindenterpictureinpicture`,error:`binderror`,leavepictureinpicture:`bindleavepictureinpicture`,netstatus:`bindnetstatus`,statechange:`bindstatechange`},map:{abilityfail:`bindabilityfail`,abilitysuccess:`bindabilitysuccess`,authsuccess:`bindauthsuccess`,calloutTap:`bindcallouttap`,controlTap:`bindcontroltap`,error:`binderror`,interpolatepoint:`bindinterpolatepoint`,labeltap:`bindlabeltap`,markerTap:`bindmarkertap`,poitap:`bindpoitap`,polylinetap:`bindpolylinetap`,regionChange:`bindregionchange`,tap:`bindtap`,updated:`bindupdated`},"movable-area":{change:`bindchange`,htouchmove:`htouchmove`,scale:`bindscale`,vtouchmove:`vtouchmove`},"movable-view":{change:`bindchange`,htouchmove:`htouchmove`,scale:`bindscale`,vtouchmove:`vtouchmove`},navigator:{complete:`bindcomplete`,fail:`bindfail`,success:`bindsuccess`},"official-account":{error:`binderror`,load:`bindload`},"open-data":{error:`binderror`},"page-container":{afterEnter:`bind:afterenter`,afterLeave:`bind:afterleave`,beforeEnter:`bind:beforeenter`,beforeLeave:`bind:beforeleave`,clickOverlay:`bind:clickoverlay`,enter:`bind:enter`,leave:`bind:leave`},"page-meta":{resize:`bindresize`,scroll:`bindscroll`,scrolldone:`bindscrolldone`},picker:{cancel:`bindcancel`,change:`bindchange`,columnchange:`bindcolumnchange`},"picker-view":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},"picker-view-column":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},progress:{activeend:`bindactiveend`},"radio-group":{change:`bind:change`},"scroll-view":{dragend:`binddragend`,dragging:`binddragging`,dragstart:`binddragstart`,refresherabort:`bindrefresherabort`,refresherpulling:`bindrefresherpulling`,refresherrefresh:`bindrefresherrefresh`,refresherrestore:`bindrefresherrestore`,refresherstatuschange:`bind:refresherstatuschange`,refresherwillrefresh:`bind:refresherwillrefresh`,scroll:`bindscroll`,scrollToLower:`bindscrolltolower`,scrollToUpper:`bindscrolltoupper`,scrollend:`bind:scrollend`,scrollstart:`bind:scrollstart`,workletAdjustDecelerationVelocity:`worklet:adjust-deceleration-velocity`,workletOnscrollend:`worklet:onscrollend`,workletOnscrollstart:`worklet:onscrollstart`,workletOnscrollupdate:`worklet:onscrollupdate`},"share-element":{workletOnframe:`worklet:onframe`},slider:{change:`bindchange`,changing:`bindchanging`},swiper:{animationfinish:`bindanimationfinish`,change:`bindchange`,transition:`bindtransition`,workletOnscrollend:`worklet:onscrollend`,workletOnscrollstart:`worklet:onscrollstart`,workletOnscrollupdate:`worklet:onscrollupdate`},switch:{change:`bindchange`},textarea:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,keyboardcompositionend:`bind:keyboardcompositionend`,keyboardcompositionstart:`bind:keyboardcompositionstart`,keyboardcompositionupdate:`bind:keyboardcompositionupdate`,linechange:`bindlinechange`,selectionchange:`bind:selectionchange`},video:{castinginterrupt:`bindcastinginterrupt`,castingstatechange:`bindcastingstatechange`,castinguserselect:`bindcastinguserselect`,controlstoggle:`bindcontrolstoggle`,ended:`bindended`,enterpictureinpicture:`bindenterpictureinpicture`,error:`binderror`,fullScreenChange:`bindfullscreenchange`,leavepictureinpicture:`bindleavepictureinpicture`,loadedmetadata:`bindloadedmetadata`,pause:`bindpause`,play:`bindplay`,progress:`bindprogress`,seekcomplete:`bindseekcomplete`,timeUpdate:`bindtimeupdate`,waiting:`bindwaiting`},view:{tap:`bindtap`},"voip-room":{error:`binderror`},"web-view":{error:`binderror`,load:`bindload`,message:`bindmessage`}};const ALIPAY_JSX_EVENT_NAME_ALIASES={button:{chooseAvatar:`onChooseAvatar`,error:`onError`,followLifestyle:`onFollowLifestyle`,getAuthorize:`onGetAuthorize`,getPhoneNumber:`onGetPhoneNumber`,getUserInfo:`onGetUserInfo`,tap:`onTap`},camera:{error:`onError`,ready:`onReady`,scanCode:`onScanCode`,stop:`onStop`},canvas:{longTap:`onLongTap`,ready:`onReady`,tap:`onTap`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},checkbox:{change:`onChange`},"checkbox-group":{change:`onChange`},"cover-image":{tap:`onTap`},"cover-view":{tap:`onTap`},form:{reset:`onReset`,submit:`onSubmit`},image:{error:`onError`,load:`onLoad`,tap:`onTap`},input:{blur:`onBlur`,confirm:`onConfirm`,focus:`onFocus`,input:`onInput`},lifestyle:{follow:`onFollow`},lottie:{animationCancel:`onAnimationCancel`,animationEnd:`onAnimationEnd`,animationRepeat:`onAnimationRepeat`,animationStart:`onAnimationStart`,dataFailed:`onDataFailed`,dataLoadReady:`onDataLoadReady`,dataReady:`onDataReady`},map:{calloutTap:`onCalloutTap`,controlTap:`onControlTap`,initComplete:`onInitComplete`,markerTap:`onMarkerTap`,panelTap:`onPanelTap`,regionChange:`onRegionChange`,tap:`onTap`},"movable-view":{change:`onChange`,changeEnd:`onChangeEnd`,scale:`onScale`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},"page-container":{afterEnter:`onAfterEnter`,afterLeave:`onAfterLeave`,beforeEnter:`onBeforeEnter`,beforeLeave:`onBeforeLeave`,clickOverlay:`onClickOverlay`,enter:`onEnter`,enterCancelled:`onEnterCancelled`,leave:`onLeave`,leaveCancelled:`onLeaveCancelled`},"page-meta":{scroll:`onScroll`},picker:{change:`onChange`},"picker-view":{change:`onChange`,pickEnd:`onPickEnd`,pickStart:`onPickStart`},"radio-group":{change:`onChange`},"rich-text":{longTap:`onLongtap`,tap:`onTap`,touchCancel:`onTouchcancel`,touchEnd:`onTouchend`,touchMove:`onTouchmove`,touchStart:`onTouchstart`},"scroll-view":{scroll:`onScroll`,scrollToLower:`onScrollToLower`,scrollToUpper:`onScrollToUpper`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`},slider:{change:`onChange`,changing:`onChanging`},"subscribe-message":{complete:`onComplete`},swiper:{animationEnd:`onAnimationEnd`,change:`onChange`,transition:`onTransition`},switch:{change:`onChange`},textarea:{blur:`onBlur`,confirm:`onConfirm`,focus:`onFocus`,input:`onInput`},video:{ended:`onEnded`,error:`onError`,fullScreenChange:`onFullScreenChange`,loading:`onLoading`,pause:`onPause`,play:`onPlay`,renderStart:`onRenderStart`,stop:`onStop`,tap:`onTap`,timeUpdate:`onTimeUpdate`,userAction:`onUserAction`},view:{animationEnd:`onAnimationEnd`,animationIteration:`onAnimationIteration`,animationStart:`onAnimationStart`,appear:`onAppear`,disappear:`onDisappear`,firstAppear:`onFirstAppear`,longTap:`onLongTap`,tap:`onTap`,touchCancel:`onTouchCancel`,touchEnd:`onTouchEnd`,touchMove:`onTouchMove`,touchStart:`onTouchStart`,transitionEnd:`onTransitionEnd`},"web-view":{error:`onError`,load:`onLoad`,message:`onMessage`}};const TT_JSX_EVENT_NAME_ALIASES={"aweme-data":{error:`binderror`},"aweme-user-card":{error:`binderror`},button:{agreePrivacyAuthorization:`bindagreeprivacyauthorization`,getPhoneNumber:`bindgetphonenumber`,tap:`bindtap`},camera:{error:`binderror`,initdone:`bindinitdone`,scanCode:`bindscancode`,stop:`bindstop`},canvas:{touchCancel:`bindtouchcancel`,touchEnd:`bindtouchend`,touchMove:`bindtouchmove`,touchStart:`bindtouchstart`},"checkbox-group":{change:`bindchange`},"draw-ad":{error:`binderror`,play:`bindplay`,stop:`bindstop`},form:{reset:`bindreset`,submit:`bindsubmit`},image:{error:`binderror`,load:`bindload`},input:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`},"live-player":{error:`binderror`,fullScreenChange:`bindfullscreenchange`,statechange:`bindstatechange`},map:{anchorpointtap:`bindanchorpointtap`,calloutTap:`bindcallouttap`,labeltap:`bindlabeltap`,markerTap:`bindmarkertap`,regionChange:`bindregionchange`,tap:`bindtap`,updated:`bindupdated`},"movable-view":{change:`bindchange`,htouchmove:`bindhtouchmove`,scale:`bindscale`,vtouchmove:`bindvtouchmove`},"open-data":{error:`binderror`},picker:{cancel:`bindcancel`,change:`bindchange`,columnchange:`bindcolumnchange`},"picker-view":{change:`bindchange`,pickEnd:`bindpickend`,pickStart:`bindpickstart`},progress:{activeend:`bindactiveend`},"radio-group":{change:`bindchange`},"rtc-room":{error:`binderror`},"scroll-view":{refresherabort:`bindrefresherabort`,refresherpulling:`bindrefresherpulling`,refresherrefresh:`bindrefresherrefresh`,refresherrestore:`bindrefresherrestore`,scroll:`bindscroll`,scrollToLower:`bindscrolltolower`,scrollToUpper:`bindscrolltoupper`},slider:{change:`bindchange`,changing:`bindchanging`},swiper:{animationfinish:`bindanimationfinish`,change:`bindchange`,transition:`bindtransition`},switch:{change:`bindchange`},textarea:{blur:`bindblur`,confirm:`bindconfirm`,focus:`bindfocus`,input:`bindinput`,keyboardHeightChange:`bindkeyboardheightchange`,linechange:`bindlinechange`},video:{closebackground:`bindclosebackground`,controlTap:`bindcontroltap`,controlstoggle:`bindcontrolstoggle`,ended:`bindended`,enterbackground:`bindenterbackground`,error:`binderror`,fullScreenChange:`bindfullscreenchange`,leavebackground:`bindleavebackground`,loadedmetadata:`bindloadedmetadata`,mutechange:`bindmutechange`,pause:`bindpause`,play:`bindplay`,playbackratechange:`bindplaybackratechange`,playbackratelistchange:`bindplaybackratelistchange`,progress:`bindprogress`,seekcomplete:`bindseekcomplete`,timeUpdate:`bindtimeupdate`,waiting:`bindwaiting`},view:{tap:`bindtap`},"web-view":{error:`binderror`,load:`bindload`,message:`bindmessage`}};const eventMap$3={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchcancel:`touchCancel`,longtap:`longTap`,longpress:`longTap`};const PASCALIZE_EVENT_RE=/(^|-)([a-z0-9])/g;function toPascalEventName(eventName){return eventName.replace(PASCALIZE_EVENT_RE,(_match,_separator,character)=>character.toUpperCase())}function toOnEventName(eventName){return`on${toPascalEventName(eventName)}`}const EVENT_BINDING_PREFIX_RE$3=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$3(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$3.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function toAlipayDirectiveEvent(prefix,eventName){if(!eventName)return`on`;const pascalEvent=toPascalEventName(eventName);switch(prefix){case`catch`:return`catch${pascalEvent}`;case`capture-bind`:return`capture${pascalEvent}`;case`capture-catch`:return`captureCatch${pascalEvent}`;default:return toOnEventName(eventName)}}const directives$3=createMiniProgramDirectiveAttrs(`a`);const alipayPlatform={name:`alipay`,directives:directives$3,wrapIf:(exp,content,renderMustache)=>`<block ${directives$3.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$3.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$3.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$3.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$3.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$3.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$3.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$3[eventName.toLowerCase()]||eventName,eventBindingAlias:(eventName,tagName)=>tagName?ALIPAY_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$3(eventName);return toAlipayDirectiveEvent(prefix,normalizeMiniProgramEventName(name))}};const eventMap$2={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchstart:`touchstart`,touchmove:`touchmove`,touchend:`touchend`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE$2=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$2(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$2.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding$2(name){return name.includes(`:`)||name.includes(`-`)}const directives$2=createMiniProgramDirectiveAttrs(`wx`);const defaultMiniProgramPlatform={name:`wechat`,directives:directives$2,wrapIf:(exp,content,renderMustache)=>`<block ${directives$2.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$2.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$2.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$2.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$2.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$2.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$2.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$2[eventName.toLowerCase()]??eventName,eventBindingAlias:(eventName,tagName)=>tagName?WEAPP_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$2(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding$2(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding$2(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const defaultPlatform=defaultMiniProgramPlatform;const eventMap$1={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE$1=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding$1(eventName){const prefixed=EVENT_BINDING_PREFIX_RE$1.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding$1(name){return name.includes(`:`)||name.includes(`-`)}const directives$1=createMiniProgramDirectiveAttrs(`s`,`-`);const swanPlatform={name:`swan`,directives:directives$1,wrapIf:(exp,content,renderMustache)=>`<block ${directives$1.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives$1.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives$1.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives$1.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives$1.forItemAttr}="${item}"`);if(index)attrs.push(`${directives$1.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives$1.keyAttr}="${value}"`,mapEventName:eventName=>eventMap$1[eventName.toLowerCase()]||eventName,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding$1(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding$1(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding$1(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const eventMap={click:`tap`,dblclick:`tap`,mousedown:`touchstart`,mouseup:`touchend`,tap:`tap`,input:`input`,change:`change`,submit:`submit`,focus:`focus`,blur:`blur`,confirm:`confirm`,cancel:`cancel`,load:`load`,error:`error`,scroll:`scroll`,scrolltoupper:`scrolltoupper`,scrolltolower:`scrolltolower`,touchstart:`touchstart`,touchmove:`touchmove`,touchend:`touchend`,touchcancel:`touchcancel`,longtap:`longtap`,longpress:`longpress`};const EVENT_BINDING_PREFIX_RE=/^(bind|catch|capture-bind|capture-catch|mut-bind):(.+)$/;function parseEventBinding(eventName){const prefixed=EVENT_BINDING_PREFIX_RE.exec(eventName);if(prefixed)return{prefix:prefixed[1],name:prefixed[2]};return{prefix:`bind`,name:eventName}}function shouldUseColonEventBinding(name){return name.includes(`:`)||name.includes(`-`)}const directives=createMiniProgramDirectiveAttrs(`tt`);const ttPlatform={name:`tt`,directives,wrapIf:(exp,content,renderMustache)=>`<block ${directives.ifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElseIf:(exp,content,renderMustache)=>`<block ${directives.elifAttr}="${renderMustache(exp)}">${content}</block>`,wrapElse:content=>`<block ${directives.elseAttr}>${content}</block>`,forAttrs:(listExp,renderMustache,item,index)=>{const attrs=[`${directives.forAttr}="${renderMustache(listExp)}"`];if(item)attrs.push(`${directives.forItemAttr}="${item}"`);if(index)attrs.push(`${directives.forIndexAttr}="${index}"`);return attrs},keyThisValue:`*this`,keyAttr:value=>`${directives.keyAttr}="${value}"`,mapEventName:eventName=>eventMap[eventName.toLowerCase()]??eventName,eventBindingAlias:(eventName,tagName)=>tagName?TT_JSX_EVENT_NAME_ALIASES[tagName]?.[eventName]:void 0,eventBindingAttr:eventName=>{const{prefix,name}=parseEventBinding(eventName);const normalizedName=normalizeMiniProgramEventName(name);switch(prefix){case`catch`:return shouldUseColonEventBinding(normalizedName)?`catch:${normalizedName}`:`catch${normalizedName}`;case`capture-bind`:return`capture-bind:${normalizedName}`;case`capture-catch`:return`capture-catch:${normalizedName}`;case`mut-bind`:return`mut-bind:${normalizedName}`;default:return shouldUseColonEventBinding(normalizedName)?`bind:${normalizedName}`:`bind${normalizedName}`}}};const TEMPLATE_PRESET_PLATFORMS={wechat:defaultMiniProgramPlatform,alipay:alipayPlatform,tt:ttPlatform,swan:swanPlatform};function getDefaultMiniProgramTemplatePlatform(){return TEMPLATE_PRESET_PLATFORMS[getMiniProgramTemplatePreset()]}const getDefaultMiniProgramPlatform=getDefaultMiniProgramTemplatePlatform;const defaultMiniProgramTemplatePlatform=getDefaultMiniProgramTemplatePlatform();const wechatPlatform=defaultMiniProgramPlatform;function getMiniProgramTemplatePlatform(platform){const preset=getMiniProgramTemplatePreset(platform);return TEMPLATE_PRESET_PLATFORMS[preset]??getDefaultMiniProgramTemplatePlatform()}function retainScopedSlotOwnerBindings(manifest,slots){const retained=/* @__PURE__ */ new Set;for(const slot of slots){if(!isBindingManifestComplete(slot.bindingManifest))markBindingManifestIncomplete(manifest);for(const binding of slot.bindingManifest.bindings)for(const dependency of binding.dependencies??[]){if(dependency.root!==WEVU_SLOT_OWNER_KEY)continue;const prefix=`${WEVU_SLOT_OWNER_KEY}.`;if(!dependency.path?.startsWith(prefix)){markBindingManifestIncomplete(manifest);continue}const ownerPath=dependency.path.slice(prefix.length);const root=/^[A-Z_$][\w$]*/i.exec(ownerPath)?.[0];if(!root||retained.has(ownerPath))continue;retained.add(ownerPath);manifest.bindings.push({id:`b${manifest.bindings.length}`,kind:`component-prop`,outputPath:ownerPath,sourceRoots:[root],sourcePaths:[ownerPath],dependencies:[{root,path:ownerPath,updateMode:`exact-path`}],scopes:[{kind:`root`,depth:0}],updateMode:`exact-path`,sourceLocation:binding.sourceLocation})}}}const HTML_VOID_TAGS=/* @__PURE__ */ new Set([`area`,`base`,`br`,`col`,`embed`,`hr`,`img`,`input`,`link`,`meta`,`param`,`source`,`track`,`wbr`]);function resolveTemplateIsPage(filename,options){if(options?.isPage!==true)return false;const normalized=filename.replace(/\\/g,`/`);return!/(?:^|\/)(?:components|layouts|custom-tab-bar)\//.test(normalized)}function resolveSlotFallbackWrapperComponent(strategy){if(strategy!==`virtual-host`)return;return{tagName:WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME,componentBase:WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE,template:`<slot></slot>`,script:`Component({options:{virtualHost:true,multipleSlots:true}})`,config:{component:true}}}function resolveSlotFallbackWrapperConfig(config,strategy){if(typeof config===`string`)return{tag:config||`view`,rules:[]};return{tag:config?.tag||(strategy===`virtual-host`?WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME:`view`),attrs:config?.attrs,singleRootNoWrapper:config?.singleRootNoWrapper,rules:config?.rules??[]}}function compileVueTemplateToWxml(template,filename,options){const diagnostics=[];const runtimeMode=options?.classStyleRuntime??`js`;const resolvedRuntime=runtimeMode===`auto`?options?.wxsExtension?`wxs`:`js`:runtimeMode===`wxs`&&!options?.wxsExtension?`js`:runtimeMode;const wxsExtension=options?.wxsExtension;const scopedSlotsRequireProps=options?.scopedSlotsRequireProps??options?.scopedSlotsCompiler!==`augmented`;const slotSingleRootNoWrapper=options?.slotSingleRootNoWrapper??false;const slotFallbackWrapperStrategy=options?.slotFallbackWrapperStrategy??`view`;const slotFallbackWrapper=resolveSlotFallbackWrapperConfig(options?.slotFallbackWrapper,slotFallbackWrapperStrategy);const slotFallbackWrapperComponent=slotFallbackWrapper.tag===WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME?resolveSlotFallbackWrapperComponent(slotFallbackWrapperStrategy):void 0;const htmlTagToWxmlMap=resolveHtmlTagToWxmlMap(options?.htmlTagToWxml);try{const ast=parse(template,{comments:options?.preserveComments?true:void 0,isVoidTag:tag=>HTML_VOID_TAGS.has(tag),onError:error=>warn({diagnostics,filename},`模板解析失败:${error.message}`,error.loc,`template`,`WV2001`)});const context={source:template,filename,diagnostics,bindingManifest:createBindingManifest(filename),runtimeBindingManifest:options?.runtimeBindingManifest??`compact`,platform:options?.platform??getMiniProgramTemplatePlatform(),isPage:resolveTemplateIsPage(filename,options),propsAliases:options?.propsAliases,propsDerivedKeys:options?.propsDerivedKeys,scriptSetupBindings:options?.scriptSetupBindings,htmlTagToWxmlMap,htmlTagToWxmlTagClass:options?.htmlTagToWxmlTagClass??true,scopedSlotsCompiler:options?.scopedSlotsCompiler??`auto`,scopedSlotsRequireProps,slotSingleRootNoWrapper,slotFallbackWrapper,slotFallbackWrapperComponent,slotMultipleInstance:options?.slotMultipleInstance??true,scopedSlotComponents:[],componentGenerics:{},componentNameMap:options?.componentNameMap,scopeStack:[],slotPropStack:[],rewriteScopedSlot:false,hasSlotOutlet:false,classStyleRuntime:resolvedRuntime===`wxs`?`wxs`:`js`,objectLiteralBindMode:options?.objectLiteralBindMode??`runtime`,mustacheInterpolation:options?.mustacheInterpolation??`compact`,formatWxml:options?.formatWxml??false,preserveComments:options?.preserveComments??false,classStyleBindings:[],classStyleWxs:false,classStyleWxsExtension:wxsExtension,classStyleWxsSrc:options?.classStyleWxsSrc,forStack:[],forIndexSeed:0,templateRefs:[],templateRefIndexSeed:0,layoutHosts:[],layoutHostIndexSeed:0,inlineExpressions:[],inlineExpressionSeed:0,functionPropPaths:/* @__PURE__ */ new Set,functionPropNames:Array.from(options?.functionPropNames??[]),templateSafeCallNames:new Set(options?.templateSafeCallNames??[]),wevuComponentTags:options?.wevuComponentTags?new Set(options.wevuComponentTags):void 0,miniProgramComponentTags:options?.miniProgramComponentTags?new Set(options.miniProgramComponentTags):void 0,scopeId:options?.scopeId,slottedScopeId:options?.slottedScopeId,cssVars:options?.cssVars};collectConditionalBranches(ast.children);let wxml=ast.children.map(child=>transformNode(child,context)).join(``);if(context.classStyleWxs){const ext=context.classStyleWxsExtension||`wxs`;wxml=`${buildClassStyleWxsTag(ext,context.classStyleWxsSrc)}\n${wxml}`}if(context.formatWxml)wxml=formatWxml(wxml);retainScopedSlotOwnerBindings(context.bindingManifest,context.scopedSlotComponents);const result={code:wxml,diagnostics,bindingManifest:context.bindingManifest};if(context.scopedSlotComponents.length)result.scopedSlotComponents=context.scopedSlotComponents;if(context.slotFallbackWrapperComponent&&wxml.includes(`<${context.slotFallbackWrapperComponent.tagName}`))result.slotFallbackWrapperComponent=context.slotFallbackWrapperComponent;if(Object.keys(context.componentGenerics).length)result.componentGenerics=context.componentGenerics;if(context.classStyleWxs)result.classStyleWxs=true;if(context.classStyleBindings.length){result.classStyleBindings=context.classStyleBindings;result.classStyleRuntime=context.classStyleRuntime}if(context.templateRefs.length)result.templateRefs=context.templateRefs;if(context.layoutHosts.length)result.layoutHosts=context.layoutHosts;if(context.inlineExpressions.length)result.inlineExpressions=context.inlineExpressions;if(context.functionPropPaths.size)result.functionPropPaths=[...context.functionPropPaths];if(context.hasSlotOutlet)result.hasSlotOutlet=true;result.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(context.bindingManifest);return result}catch(error){warn({diagnostics,filename},`模板编译失败:${error}`,void 0,`template`,`WV2002`);const bindingManifest=createBindingManifest(filename);markBindingManifestIncomplete(bindingManifest);bindingManifest.bindings.push({id:`b0`,kind:`text`,outputPath:`*`,sourceRoots:[],dependencies:[],scopes:[{kind:`root`,depth:0}],updateMode:`snapshot-fallback`});return{code:template,bindingManifest,diagnostics}}}const LAYOUT_OWNER_EXPRESSION=`${WEVU_SLOT_OWNER_ID_PROP} || ${WEVU_SLOT_OWNER_ID_KEY} || ''`;const LAYOUT_SLOT_OWNER_ATTR=`${WEVU_SLOT_OWNER_ID_ATTR}="{{${LAYOUT_OWNER_EXPRESSION}}}"`;const CAMEL_TO_KEBAB_RE=/([a-z0-9])([A-Z])/g;const LAYOUT_NAME_SEPARATORS_RE=/[_\s]+/g;const DUPLICATE_DASH_RE=/-+/g;const EDGE_DASH_RE=/^-|-$/g;function toKebabCase(value){return value.replace(CAMEL_TO_KEBAB_RE,`$1-$2`).replace(LAYOUT_NAME_SEPARATORS_RE,`-`).replace(DUPLICATE_DASH_RE,`-`).replace(EDGE_DASH_RE,``).toLowerCase()}function serializeLayoutProps(props){const attrs=[LAYOUT_SLOT_OWNER_ATTR];for(const[key,value]of Object.entries(props??{})){const attrName=toKebabCase(key);if(typeof value===`string`)attrs.push(`${attrName}="${escapeWxmlAttribute(value)}"`);else if(typeof value===`object`&&value&&value.kind===`expression`)attrs.push(`${attrName}="{{${WEVU_LAYOUT_BIND_PREFIX}${key}}}"`);else attrs.push(`${attrName}="{{${String(value)}}}"`)}return` ${attrs.join(` `)}`}function serializeFallbackLayoutValue(value,key){const runtimeValue=`${WEVU_PAGE_LAYOUT_PROPS_KEY}&&${WEVU_PAGE_LAYOUT_PROPS_KEY}.${key}`;if(value===void 0)return`(${runtimeValue})`;const fallback=typeof value===`object`&&value?.kind===`expression`?`${WEVU_LAYOUT_BIND_PREFIX}${key}`:JSON.stringify(value);return`(${runtimeValue})!==undefined?${WEVU_PAGE_LAYOUT_PROPS_KEY}.${key}:${fallback}`}function buildDynamicLayoutTemplate(template,currentLayout,layouts,propKeys,platform){return`${layouts.map((layout,index)=>{const attrs=[LAYOUT_SLOT_OWNER_ATTR];for(const key of propKeys)attrs.push(`${toKebabCase(key)}="{{${serializeFallbackLayoutValue(currentLayout?.props?.[key],key)}}}"`);const condition=currentLayout?.layoutName===layout.layoutName?`{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`:`{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;return`<block ${index===0?platform.directives.ifAttr:platform.directives.elifAttr}="${condition}"><${layout.tagName} ${attrs.join(` `)}>${template}</${layout.tagName}></block>`}).join(``)}<block ${platform.directives.elseAttr}>${template}</block>`}function hasDynamicLayoutWrapper(template,plan,platform){if(!plan.layouts.length||!template.startsWith(`<block ${platform.directives.ifAttr}=`))return false;return plan.layouts.every((layout,index)=>{const condition=plan.currentLayout?.layoutName===layout.layoutName?`{{!${WEVU_PAGE_LAYOUT_NAME_KEY} || ${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`:`{{${WEVU_PAGE_LAYOUT_NAME_KEY} === '${layout.layoutName}'}}`;const directive=index===0?platform.directives.ifAttr:platform.directives.elifAttr;return template.includes(`<block ${directive}="${condition}"><${layout.tagName}`)})&&template.includes(`<block ${platform.directives.elseAttr}>`)}function recordLayoutBindings(manifest,plan){manifest.features.layout=true;manifest.features.scopedSlots=true;recordSyntheticBindingExpression(manifest,{kind:`attribute`,expression:LAYOUT_OWNER_EXPRESSION});if(plan.dynamicSwitch){recordSyntheticBindingExpression(manifest,{kind:`if`,expression:WEVU_PAGE_LAYOUT_NAME_KEY});if(plan.dynamicPropKeys.length)recordSyntheticBindingExpression(manifest,{kind:`component-prop`,expression:WEVU_PAGE_LAYOUT_PROPS_KEY})}for(const[key,value]of Object.entries(plan.currentLayout?.props??{})){if(typeof value!==`object`||!value||value.kind!==`expression`)continue;recordSyntheticBindingExpression(manifest,{kind:`component-prop`,expression:value.expression,outputPath:`${WEVU_LAYOUT_BIND_PREFIX}${key}`})}}function collapseNestedWrapper(template,tagName){const closeTag=`</${tagName}>`;let next=template;while(next.startsWith(`<${tagName}`)&&next.endsWith(closeTag)){const openTagEnd=next.indexOf(`>`);if(openTagEnd<0)break;const inner=next.slice(openTagEnd+1,-closeTag.length);if(!inner.startsWith(`<${tagName}`))break;next=inner}return next}function unwrapOuterWrapper(template,tagName){const closeTag=`</${tagName}>`;if(!template.startsWith(`<${tagName}`)||!template.endsWith(closeTag))return;const openTagEnd=template.indexOf(`>`);if(openTagEnd<0)return;return{openTag:template.slice(0,openTagEnd+1),content:template.slice(openTagEnd+1,-closeTag.length)}}function recordAppShellBinding(manifest){manifest.features.scopedSlots=true;recordSyntheticBindingExpression(manifest,{kind:`attribute`,expression:LAYOUT_OWNER_EXPRESSION})}function applyCompilerTemplateWrappers(options){const{manifest,platform,pageLayout,appShell}=options;let template=options.template;let existingAppShellOpenTag;if(appShell){const existingAppShell=unwrapOuterWrapper(collapseNestedWrapper(template,appShell.tagName),appShell.tagName);if(existingAppShell){existingAppShellOpenTag=existingAppShell.openTag;template=existingAppShell.content}}if(pageLayout){recordLayoutBindings(manifest,pageLayout);if(pageLayout.dynamicSwitch){if(!hasDynamicLayoutWrapper(template,pageLayout,platform))template=buildDynamicLayoutTemplate(template,pageLayout.currentLayout,pageLayout.layouts,pageLayout.dynamicPropKeys,platform)}else if(pageLayout.currentLayout){const layout=pageLayout.currentLayout;template=template.startsWith(`<${layout.tagName}`)?collapseNestedWrapper(template,layout.tagName):`<${layout.tagName}${serializeLayoutProps(layout.props)}>${template}</${layout.tagName}>`}}if(appShell){recordAppShellBinding(manifest);template=`${existingAppShellOpenTag??`<${appShell.tagName} ${LAYOUT_SLOT_OWNER_ATTR}>`}${template}</${appShell.tagName}>`}return template}function mergeCompilerLayoutUsingComponents(config,pageLayout,appShell){if(!pageLayout&&!appShell)return config;const parsed=config?JSON.parse(config):{};const usingComponents=parsed.usingComponents&&typeof parsed.usingComponents===`object`&&!Array.isArray(parsed.usingComponents)?parsed.usingComponents:{};for(const layout of pageLayout?.layouts??[])usingComponents[layout.tagName]=layout.importPath;if(!pageLayout?.dynamicSwitch&&pageLayout?.currentLayout)usingComponents[pageLayout.currentLayout.tagName]=pageLayout.currentLayout.importPath;if(appShell)usingComponents[appShell.tagName]=appShell.importPath;parsed.usingComponents=usingComponents;return JSON.stringify(parsed,null,2)}function collectPatternNames(pattern,out){if(!pattern)return;if(t.isIdentifier(pattern)){out.add(pattern.name);return}if(t.isRestElement(pattern)){collectPatternNames(pattern.argument,out);return}if(t.isAssignmentPattern(pattern)){collectPatternNames(pattern.left,out);return}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop))collectPatternNames(prop.argument,out);else if(t.isObjectProperty(prop))collectPatternNames(prop.value,out);return}if(t.isArrayPattern(pattern))for(const el of pattern.elements)collectPatternNames(el,out)}function declaredNamesInStatement(statement){const out=/* @__PURE__ */ new Set;if(t.isImportDeclaration(statement)){for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)||t.isImportNamespaceSpecifier(specifier)){if(t.isIdentifier(specifier.local))out.add(specifier.local.name)}return out}if(t.isVariableDeclaration(statement)){for(const decl of statement.declarations)collectPatternNames(decl.id,out);return out}if(t.isFunctionDeclaration(statement)||t.isClassDeclaration(statement)){if(statement.id&&t.isIdentifier(statement.id))out.add(statement.id.name);return out}if(t.isExportNamedDeclaration(statement)&&statement.declaration)return declaredNamesInStatement(statement.declaration);return out}function collectTopLevelReferencedNames(path){const names=/* @__PURE__ */ new Set;if(!path)return names;const addIfTopLevelReferenced=p=>{if(!p?.isReferencedIdentifier?.())return;const name=p.node.name;const binding=p.scope?.getBinding(name);if(!binding)return;if(binding.scope?.block?.type===`Program`)names.add(name)};addIfTopLevelReferenced(path);path.traverse({Function(p){if(p.node!==path.node)p.skip()},Class(p){if(p.node!==path.node)p.skip()},Identifier(p){addIfTopLevelReferenced(p)}});return names}function collectKeptStatementPaths(programPath,macroStatements){const bodyPaths=programPath.get(`body`);const nameToStatementPath=/* @__PURE__ */ new Map;for(const statementPath of bodyPaths){const declared=declaredNamesInStatement(statementPath.node);for(const name of declared)if(!nameToStatementPath.has(name))nameToStatementPath.set(name,statementPath)}const neededNames=/* @__PURE__ */ new Set;for(const statementPath of macroStatements){const deps=collectTopLevelReferencedNames(statementPath.get(`expression`).get(`arguments.0`));for(const dep of deps)neededNames.add(dep)}const keptStatementPaths=/* @__PURE__ */ new Set;const queue=[...neededNames];while(queue.length){const name=queue.pop();const declPath=nameToStatementPath.get(name);if(!declPath||keptStatementPaths.has(declPath))continue;keptStatementPaths.add(declPath);const deps=collectTopLevelReferencedNames(declPath);for(const dep of deps)if(dep!==name)queue.push(dep)}for(const statementPath of macroStatements)keptStatementPaths.add(statementPath);return{bodyPaths,keptStatementPaths}}const locks=/* @__PURE__ */ new Map;async function withTempDirLock(tempDir,fn){const previous=locks.get(tempDir)??Promise.resolve();let release;const gate=new Promise(resolve=>{release=resolve});const current=previous.then(()=>gate);locks.set(tempDir,current);try{await previous;return await fn()}finally{release?.();if(locks.get(tempDir)===current)locks.delete(tempDir)}}const PROJECT_WEVU_CONFIG_DIR=path.join(`.weapp-vite`,`wevu-config`);function getWevuConfigCacheRoot(){const env=process.env.WEAPP_VITE_WEVU_CONFIG_DIR?.trim();if(env)return path.resolve(env);const projectRoot=process.cwd();if(fs.existsSync(projectRoot))return path.join(projectRoot,PROJECT_WEVU_CONFIG_DIR);return path.join(os.tmpdir(),`weapp-vite`,`wevu-config`)}function resolveWevuConfigTempDir(fromDir){const root=getWevuConfigCacheRoot();const key=createHash(`sha256`).update(path.normalize(fromDir)).digest(`hex`).slice(0,8);return path.join(root,key)}function normalizeScriptSetupLang$1(lang){if(!lang)return`ts`;const lower=lang.toLowerCase();if(lower===`txt`)return`ts`;return lower}function resolveScriptSetupExtension$1(lang){const normalized=normalizeScriptSetupLang$1(lang);if(normalized===`ts`||normalized===`tsx`||normalized===`cts`||normalized===`mts`)return`ts`;return`js`}function resolveMacroAlias(macroName){return macroName===`defineAppJson`?`__weapp_defineAppJson`:macroName===`definePageJson`?`__weapp_definePageJson`:macroName===`defineComponentJson`?`__weapp_defineComponentJson`:macroName===`defineSitemapJson`?`__weapp_defineSitemapJson`:`__weapp_defineThemeJson`}async function evaluateScriptSetupJsonMacro(params){const{preambleContent,originalContent,filename,lang,macroName,macroStatements,bodyPaths,keptStatementPaths,options}=params;const combinedContent=preambleContent?`${preambleContent}\n${originalContent}`:originalContent;const ms=new MagicString(combinedContent);const dir=path.dirname(filename);const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.json-macro.${unique}`);for(const statementPath of keptStatementPaths){if(!statementPath.isImportDeclaration())continue;const sourceNode=statementPath.node.source;if(!sourceNode||!t.isStringLiteral(sourceNode))continue;const originalSource=sourceNode.value;if(!originalSource.startsWith(`.`))continue;const next=rewriteRelativeImportSource(originalSource,dir,tempDir);if(typeof sourceNode.start===`number`&&typeof sourceNode.end===`number`)ms.overwrite(sourceNode.start,sourceNode.end,JSON.stringify(next))}const alias=resolveMacroAlias(macroName);for(const statementPath of macroStatements){const calleePath=statementPath.get(`expression`).get(`callee`);if(calleePath?.isIdentifier()&&typeof calleePath.node.start===`number`&&typeof calleePath.node.end===`number`)ms.overwrite(calleePath.node.start,calleePath.node.end,alias)}for(const statementPath of bodyPaths){if(keptStatementPaths.has(statementPath))continue;const start=statementPath.node.start;const end=statementPath.node.end;if(typeof start===`number`&&typeof end===`number`)ms.remove(start,end)}const evalSource=`
|
|
16
16
|
const __weapp_json_macro_values = []
|
|
17
17
|
const __weapp_defineAppJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
18
18
|
const __weapp_definePageJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
19
19
|
const __weapp_defineComponentJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
20
20
|
const __weapp_defineSitemapJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
21
21
|
const __weapp_defineThemeJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
22
|
-
`.trimStart()+ms.toString()+`\nexport default __weapp_json_macro_values\n`;const extension=resolveScriptSetupExtension$1(lang);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.json-macro.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const resolved=mod?.default??mod;const values=Array.isArray(resolved)?resolved:[resolved];let accumulator={};for(const raw of values){if(raw===void 0)continue;let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`宏的返回值必须解析为对象。`);if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}if(!Object.keys(accumulator).length)return{dependencies};return{config:accumulator,dependencies}}finally{try{await remove(tempDir)}catch{}}})}const JSON_MACROS=/* @__PURE__ */ new Set([`defineAppJson`,`definePageJson`,`defineComponentJson`,`defineSitemapJson`,`defineThemeJson`]);const JSON_MACRO_HINT_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;function mayContainJsonMacro(content){return JSON_MACRO_HINT_RE.test(content)}function parseScriptSetupAst(content,filename){try{return parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 中的 <script setup> 失败:${message}`)}}function collectMacroCallPaths(ast,filename){const macroNames=/* @__PURE__ */ new Set;const macroStatements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee))return;if(!JSON_MACROS.has(callee.name))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))throw new Error(`${callee.name}() 必须在 <script setup> 顶层语句中使用(${filename})。`);macroNames.add(callee.name);macroStatements.push(path.parentPath)}});return{macroNames,macroStatements}}function assertSingleMacro(macroNames,filename){if(macroNames.size>1)throw new Error(`同一个 <script setup> 仅能使用 ${[...JSON_MACROS].join(`, `)} 中的一个(${filename})。`);return macroNames.values().next().value}function findProgramPath(ast){let programPath;traverse(ast,{Program(path){programPath=path;path.stop()}});return programPath}function stripScriptSetupMacroStatements(content,ast,filename,sourceMap){const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);const macroStatementSources=[];const body=ast.program?.body??[];for(const statement of body){if(!t.isExpressionStatement(statement))continue;const expr=statement.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))continue;const name=expr.callee.name;if(!JSON_MACROS.has(name))continue;if(expr.arguments.length!==1)throw new Error(`${name}() 在 ${filename} 中必须且只能传 1 个参数。`);if(typeof statement.start===`number`&&typeof statement.end===`number`)macroStatementSources.push(content.slice(statement.start,statement.end));if(typeof statement.start===`number`&&typeof statement.end===`number`)ms.remove(statement.start,statement.end)}const stripped=sourceMap?ms.slice(0,content.length):ms.toString();
|
|
23
|
-
`)).digest(`hex`).slice(0,12);const staticConfig=resolveStaticJsonMacroConfig(macroStatements,options);if(staticConfig)return withSourceMap({stripped,config:staticConfig,macroHash,dependencies:[]},map);const result=await evaluateJsonMacroConfig(content,filename,lang,options);return withSourceMap(result?{stripped,config:result.config,macroHash,dependencies:result.dependencies}:{stripped,macroHash},map)}async function extractJsonMacroFromScriptSetup(content,filename,lang,options){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options)}async function extractJsonMacroFromScriptSetupWithSourceMap(content,filename,lang,options,sourceMap){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap)}function toPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function mergeJsonWithStrategy(target,source,strategy,context){const base={...toPlainRecord(target)};const incoming=toPlainRecord(source);if(typeof strategy===`function`){const maybeNext=strategy(base,incoming,context);if(maybeNext&&typeof maybeNext===`object`&&!Array.isArray(maybeNext))return maybeNext;return base}if(strategy===`replace`)return{...incoming};if(strategy===`assign`)return{...base,...incoming};const merged={...base};recursive(merged,incoming);return merged}function createJsonMerger(strategy,baseContext){return(target,source,stage)=>{return mergeJsonWithStrategy(target,source,strategy,{...baseContext,stage})}}function resolveWarnHandler(warn){return warn??(message=>{console.warn(message)})}function isStaticObjectKeyMatch$1(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$3(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch$1(prop.key,key))return prop}return null}function buildInjectedFeaturesObject(enabled){return t.objectExpression(Array.from(enabled,key=>{return t.objectProperty(t.identifier(key),t.booleanLiteral(true))}))}function getObjectMemberIndexByKey(node,key){return node.properties.findIndex(prop=>{if(t.isObjectProperty(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);if(t.isObjectMethod(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);return false})}function isTopLevel(path){return path.getFunctionParent()==null}function injectWevuShareLifecycleHooksIntoOptionsObject(_optionsObject,_enabled){return false}function collectWevuPageFeatureFlags(ast){const namedHookLocals=/* @__PURE__ */ new Map;const namespaceLocals=/* @__PURE__ */ new Set;for(const stmt of ast.program.body){if(!t.isImportDeclaration(stmt)||!isWevuRuntimeModuleId(stmt.source.value))continue;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)namedHookLocals.set(specifier.local.name,matched)}else if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name)}if(namedHookLocals.size===0&&namespaceLocals.size===0)return/* @__PURE__ */ new Set;const enabled=/* @__PURE__ */ new Set;function consumeHookCallByName(name){const matched=namedHookLocals.get(name);if(matched)enabled.add(matched)}function consumeNamespaceHookCall(namespace,hookName){if(!namespaceLocals.has(namespace))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hookName];if(matched)enabled.add(matched)}traverse(ast,{CallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}},OptionalCallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}}});return enabled}function injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled){if(!enabled.size)return false;const expectedKeys=[...enabled];const existingFeaturesProp=getObjectPropertyByKey$3(optionsObject,`features`);let changed=false;if(!existingFeaturesProp){const featuresObject=buildInjectedFeaturesObject(enabled);const setupIndex=getObjectMemberIndexByKey(optionsObject,`setup`);const insertAt=setupIndex>=0?setupIndex:0;optionsObject.properties.splice(insertAt,0,t.objectProperty(t.identifier(`features`),featuresObject));changed=true}else if(t.isObjectExpression(existingFeaturesProp.value)){const featuresObject=existingFeaturesProp.value;const injectedProps=[];for(const key of expectedKeys){if(getObjectPropertyByKey$3(featuresObject,key))continue;injectedProps.push(t.objectProperty(t.identifier(key),t.booleanLiteral(true)))}if(injectedProps.length){featuresObject.properties.splice(0,0,...injectedProps);changed=true}}else if(t.isIdentifier(existingFeaturesProp.value)||t.isMemberExpression(existingFeaturesProp.value)){const base=t.cloneNode(existingFeaturesProp.value,true);const injected=buildInjectedFeaturesObject(enabled);injected.properties.push(t.spreadElement(base));existingFeaturesProp.value=injected;changed=true}changed=injectWevuShareLifecycleHooksIntoOptionsObject(optionsObject,enabled)||changed;return changed}function createEmptyModuleAnalysis(id,engine){return{id,engine,wevuNamedHookLocals:/* @__PURE__ */ new Map,wevuNamespaceLocals:/* @__PURE__ */ new Set,importedBindings:/* @__PURE__ */ new Map,localFunctions:/* @__PURE__ */ new Map,exports:/* @__PURE__ */ new Map}}const externalModuleAnalysisCache=new LRUCache({max:256});const moduleAnalysisCache=new LRUCache({max:512});function createExternalModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function createModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function getFunctionLikeFromExpression(node){if(!node)return null;if(t.isFunctionExpression(node)||t.isArrowFunctionExpression(node))return node;return null}function isOxcFunctionLike(node){return node?.type===`FunctionDeclaration`||node?.type===`FunctionExpression`||node?.type===`ArrowFunctionExpression`}function getImportedSpecifierName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function createModuleAnalysis(id,ast){const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(!node.id||!node.id.name)return;localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(!t.isIdentifier(node.id))return;const fn=getFunctionLikeFromExpression(node.init);if(!fn)return;localFunctions.set(node.id.name,fn)}for(const stmt of ast.program.body){if(t.isFunctionDeclaration(stmt)){registerFunctionDeclaration(stmt);continue}if(t.isVariableDeclaration(stmt)){for(const decl of stmt.declarations)registerVariableFunction(decl);continue}if(t.isImportDeclaration(stmt)){const source=stmt.source.value;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)){const imported=specifier.imported;if(isWevuRuntimeModuleId(source)&&t.isIdentifier(imported)){const importedName=imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName:t.isIdentifier(imported)?imported.name:String(imported.value)})}else if(t.isImportDefaultSpecifier(specifier))importedBindings.set(specifier.local.name,{kind:`default`,source});else if(t.isImportNamespaceSpecifier(specifier)){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuRuntimeModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(t.isExportNamedDeclaration(stmt)){if(stmt.declaration){if(t.isFunctionDeclaration(stmt.declaration)&&stmt.declaration.id){registerFunctionDeclaration(stmt.declaration);exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name})}else if(t.isVariableDeclaration(stmt.declaration))for(const decl of stmt.declaration.declarations){registerVariableFunction(decl);if(t.isIdentifier(decl.id))exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}if(stmt.source){const source=stmt.source.value;for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const importedName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!importedName)continue;exports.set(exportedName,{type:`reexport`,source,importedName})}}else for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const localName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!localName)continue;exports.set(exportedName,{type:`local`,localName})}continue}if(t.isExportDefaultDeclaration(stmt)){const decl=stmt.declaration;if(t.isFunctionDeclaration(decl)){registerFunctionDeclaration(decl);if(decl.id)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(t.isIdentifier(decl))exports.set(`default`,{type:`local`,localName:decl.name});else{const fn=getFunctionLikeFromExpression(decl);if(fn)exports.set(`default`,{type:`inline`,node:fn})}}}return{id,engine:`babel`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}function resolveOxcParseFilename(id){if(path.extname(id))return id;return`${id}.js`}function createModuleAnalysisWithOxc(id,code){const ast=parseJsLikeWithEngine(code,{engine:`oxc`,filename:resolveOxcParseFilename(id)});const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(node?.id?.type===`Identifier`)localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(node?.id?.type!==`Identifier`||!isOxcFunctionLike(node.init))return;localFunctions.set(node.id.name,node.init)}for(const stmt of ast.body??[]){if(stmt?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt);continue}if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])registerVariableFunction(decl);continue}if(stmt?.type===`ImportDeclaration`){const source=getImportedSpecifierName(stmt.source);if(!source)continue;for(const specifier of stmt.specifiers??[])if(specifier.type===`ImportSpecifier`&&specifier.local?.type===`Identifier`){const importedName=getImportedSpecifierName(specifier.imported);if(!importedName)continue;if(isWevuRuntimeModuleId(source)){const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName})}else if(specifier.type===`ImportDefaultSpecifier`&&specifier.local?.type===`Identifier`)importedBindings.set(specifier.local.name,{kind:`default`,source});else if(specifier.type===`ImportNamespaceSpecifier`&&specifier.local?.type===`Identifier`){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuRuntimeModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(stmt?.type===`ExportNamedDeclaration`){if(stmt.declaration?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt.declaration);if(stmt.declaration.id?.type===`Identifier`)exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name});continue}if(stmt.declaration?.type===`VariableDeclaration`){for(const decl of stmt.declaration.declarations??[]){registerVariableFunction(decl);if(decl.id?.type===`Identifier`)exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}const source=getImportedSpecifierName(stmt.source);for(const spec of stmt.specifiers??[]){if(spec?.type!==`ExportSpecifier`)continue;const exportedName=getImportedSpecifierName(spec.exported);const localName=getImportedSpecifierName(spec.local);if(!exportedName||!localName)continue;if(source)exports.set(exportedName,{type:`reexport`,source,importedName:localName});else exports.set(exportedName,{type:`local`,localName})}continue}if(stmt?.type===`ExportDefaultDeclaration`){const decl=stmt.declaration;if(decl?.type===`FunctionDeclaration`){registerFunctionDeclaration(decl);if(decl.id?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(decl?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.name});else if(isOxcFunctionLike(decl))exports.set(`default`,{type:`inline`,node:decl})}}return{id,engine:`oxc`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}const TS_WITHOUT_JSX_RE=/\.[cm]?ts(?:[?#].*)?$/i;function parseModuleAnalysisAst(id,code){const plugins=TS_WITHOUT_JSX_RE.test(id)?BABEL_TS_MODULE_PLUGINS.filter(plugin=>plugin!==`jsx`):BABEL_TS_MODULE_PLUGINS;return parse$3(code,{sourceType:`module`,plugins})}function createModuleAnalysisFromCode(id,code,options){const engine=options?.astEngine??`babel`;const cacheKey=createModuleAnalysisCacheKey(id,engine);const cached=moduleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;let analysis;if(engine===`oxc`){if(!code.includes(`import`)&&!code.includes(`export`))analysis=createEmptyModuleAnalysis(id,`oxc`);else analysis=createModuleAnalysisWithOxc(id,code)}else{const ast=parseModuleAnalysisAst(id,code);analysis=createModuleAnalysis(id,ast)}moduleAnalysisCache.set(cacheKey,{code,analysis});return analysis}function getOrCreateExternalModuleAnalysis(moduleId,code,options){const cacheKey=createExternalModuleAnalysisCacheKey(moduleId,options?.astEngine);const cached=externalModuleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;const analysis=createModuleAnalysisFromCode(moduleId,code,options);externalModuleAnalysisCache.set(cacheKey,{code,analysis});return analysis}const CALL_EXPRESSION_TEXT_RE=/\b[a-z_$][\w$]*(?:\s*<[^(){};]+>)?\s*(?:\?\.\s*)?\(/i;const WEVU_PAGE_HOOK_NAMES=Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE);function mayContainWevuPageFeatureHints(code){return WE_VU_RUNTIME_MODULE_IDS.some(moduleId=>code.includes(moduleId))&&CALL_EXPRESSION_TEXT_RE.test(code)&&WEVU_PAGE_HOOK_NAMES.some(hookName=>code.includes(hookName))}function collectWithBabel(code){const ast=parseJsLike(code);return collectWevuPageFeatureFlags(ast)}function collectWithOxc(code){const enabled=/* @__PURE__ */ new Set;const module=createModuleAnalysisFromCode(`<inline>`,code,{astEngine:`oxc`});if(module.wevuNamedHookLocals.size===0&&module.wevuNamespaceLocals.size===0)return enabled;const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(module.ast);return enabled}function collectWevuPageFeatureFlagsFromCode(code,options){if(!mayContainWevuPageFeatureHints(code))return/* @__PURE__ */ new Set;const engine=options?.astEngine??`babel`;try{return engine===`oxc`?collectWithOxc(code):collectWithBabel(code)}catch{return/* @__PURE__ */ new Set}}const WEVU_FACTORY_NAMES=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,WE_VU_RUNTIME_APIS.createWevuComponent]);const REGEXP_META_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_META_CHARS_RE,`\\$&`)}function mayContainNamedFactoryCall(code,localName){return new RegExp(`\\b${escapeRegExp(localName)}\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayContainNamespaceFactoryCall(code,namespaceName){const factoryAlternation=Array.from(WEVU_FACTORY_NAMES,name=>escapeRegExp(name)).join(`|`);return new RegExp(`\\b${escapeRegExp(namespaceName)}\\b\\s*\\.\\s*(?:${factoryAlternation})\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayCallWevuFactoryByText(code,module){for(const[localName,binding]of module.importedBindings.entries()){if(!isWevuRuntimeModuleId(binding.source))continue;if(binding.kind===`named`&&WEVU_FACTORY_NAMES.has(binding.importedName)){if(mayContainNamedFactoryCall(code,localName))return true;continue}if(binding.kind===`namespace`&&mayContainNamespaceFactoryCall(code,localName))return true}return false}function unwrapTypeLikeExpression$2(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$2(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$2(node.expression);return node}function resolveOptionsObjectFromExpression(node){const normalized=unwrapTypeLikeExpression$2(node);if(t.isObjectExpression(normalized))return normalized;if(t.isIdentifier(normalized))return null;if(t.isCallExpression(normalized)){const callee=normalized.callee;if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`}))for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(t.isSpreadElement(argument)||!t.isExpression(argument))continue;const candidate=resolveOptionsObjectFromExpression(argument);if(candidate)return candidate}}return null}function getOxcStaticPropertyName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function getSetupFunctionFromOptionsObject(options){for(const prop of options.properties)if(t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`)){if(t.isFunctionExpression(prop.value)||t.isArrowFunctionExpression(prop.value))return prop.value}else if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`))return prop;else if(prop?.type===`Property`&&!prop.computed&&getOxcStaticPropertyName(prop.key)===`setup`){if(prop.value?.type===`FunctionExpression`||prop.value?.type===`ArrowFunctionExpression`)return prop.value}return null}function collectTargetOptionsObjectsWithModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];traverse(ast,{VariableDeclarator(path){if(!isTopLevel(path))return;if(!t.isIdentifier(path.node.id))return;const init=path.node.init;if(t.isObjectExpression(init))constObjectBindings.set(path.node.id.name,init)},CallExpression(path){if(!isTopLevel(path))return;const node=path.node;if(t.isV8IntrinsicIdentifier(node.callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;const binding=t.isIdentifier(node.callee)?module.importedBindings.get(node.callee.name):void 0;if(t.isIdentifier(node.callee)){if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object)&&t.isIdentifier(node.callee.property)){const objectBinding=module.importedBindings.get(node.callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(node.callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&node.callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}},OptionalCallExpression(path){if(!isTopLevel(path))return;const node=path.node;const callee=node.callee;if(t.isV8IntrinsicIdentifier(callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;if(t.isIdentifier(callee)){const binding=module.importedBindings.get(callee.name);if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property)){const objectBinding=module.importedBindings.get(callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}}});for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function unwrapOxcTypeLikeExpression(node){if(node?.type===`TSAsExpression`||node?.type===`TSSatisfiesExpression`||node?.type===`TSNonNullExpression`||node?.type===`TSTypeAssertion`||node?.type===`ParenthesizedExpression`)return unwrapOxcTypeLikeExpression(node.expression);return node}function getOxcCallExpression(node){if(node?.type===`ChainExpression`)return getOxcCallExpression(node.expression);if(node?.type===`CallExpression`)return node;return null}function resolveOxcOptionsObjectFromExpression(node,bindings){const normalized=unwrapOxcTypeLikeExpression(node);if(normalized?.type===`ObjectExpression`)return normalized;if(normalized?.type===`Identifier`)return bindings.get(normalized.name)??null;if(normalized?.type!==`CallExpression`)return null;const callee=unwrapOxcTypeLikeExpression(normalized.callee);if(callee?.type!==`MemberExpression`||callee.computed||callee.object?.type!==`Identifier`||callee.object.name!==`Object`||callee.property?.type!==`Identifier`||callee.property.name!==`assign`)return null;for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(argument?.type===`SpreadElement`)continue;const candidate=resolveOxcOptionsObjectFromExpression(argument,bindings);if(candidate)return candidate}return null}function isOxcWevuFactoryCall(call,module){const callee=unwrapOxcTypeLikeExpression(call.callee);if(callee?.type===`Identifier`){const binding=module.importedBindings.get(callee.name);return binding?.kind===`named`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(binding.importedName)}if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){const binding=module.importedBindings.get(callee.object.name);return binding?.kind===`namespace`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(callee.property.name)}return false}function collectTargetOptionsObjectsWithOxcModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];for(const stmt of ast?.body??[]){if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])if(decl?.id?.type===`Identifier`&&decl.init?.type===`ObjectExpression`)constObjectBindings.set(decl.id.name,decl.init);continue}if(stmt?.type!==`ExpressionStatement`)continue;const call=getOxcCallExpression(stmt.expression);if(!call||!isOxcWevuFactoryCall(call,module))continue;const first=call.arguments?.[0];if(!first)continue;const inlineObject=resolveOxcOptionsObjectFromExpression(first,constObjectBindings);if(inlineObject)optionsObjects.push(inlineObject);else if(first.type===`Identifier`)pendingConstObjectRefs.push(first.name)}for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function collectTargetOptionsObjects(ast,moduleId){return collectTargetOptionsObjectsWithModule(ast,createModuleAnalysis(moduleId,ast))}function collectTargetOptionsObjectsFromCode(code,moduleId,options){if(options?.astEngine===`oxc`){if(!(code.includes(`wevu`)&&(code.includes(WE_VU_RUNTIME_APIS.defineComponent)||code.includes(WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module:createEmptyModuleAnalysis(moduleId,`oxc`)};const module=createModuleAnalysisFromCode(moduleId,code,options);if(![...module.importedBindings.values()].some(binding=>isWevuRuntimeModuleId(binding.source)&&(binding.kind===`namespace`||binding.kind===`named`&&(binding.importedName===WE_VU_RUNTIME_APIS.defineComponent||binding.importedName===WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module};if(!mayCallWevuFactoryByText(code,module))return{optionsObjects:[],module};return collectTargetOptionsObjectsWithOxcModule(module.ast,module)}const module=createModuleAnalysisFromCode(moduleId,code,options);return collectTargetOptionsObjectsWithModule(module.ast,module)}function getCallCalleeName(callee){if(t.isV8IntrinsicIdentifier(callee))return null;if(t.isIdentifier(callee))return{type:`ident`,name:callee.name};if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};return null}function collectCalledBindingsFromFunctionBody(fn,engine=`babel`){const called=[];if(engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`)called.push({type:`ident`,name:callee.name});else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`)called.push({type:`member`,object:callee.object.name,property:callee.property.name})}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return called}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}else if(t.isOptionalCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}});return called}function getMemberHookName(callee){if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};return null}function addNamespaceHookFeature(module,callee,enabled){const memberHook=getMemberHookName(callee);if(!memberHook||!module.wevuNamespaceLocals.has(memberHook.object))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[memberHook.hook];if(matched)enabled.add(matched)}function collectWevuHookCallsInFunctionBody(module,fn){const enabled=/* @__PURE__ */ new Set;if(module.engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return enabled}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}else if(t.isOptionalCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}});return enabled}function resolveExportedFunctionNode(module,exportName){const target=module.exports.get(exportName);if(!target)return null;if(target.type===`local`){const fn=module.localFunctions.get(target.localName);return fn?{type:`inline`,node:fn}:null}if(target.type===`reexport`)return target;if(target.type===`inline`)return target;return null}async function resolveExternalFunction(resolver,importerId,source,exportName,moduleCache,options){if(source===`wevu`)return null;const resolvedId=await resolver.resolveId(source,importerId);if(!resolvedId)return null;const code=await resolver.loadCode(resolvedId);if(!code)return null;let analysis=moduleCache.get(resolvedId);if(!analysis){analysis=getOrCreateExternalModuleAnalysis(resolvedId,code,options);moduleCache.set(resolvedId,analysis)}const target=resolveExportedFunctionNode(analysis,exportName);if(!target)return null;if(target.type===`reexport`)return{moduleId:resolvedId,reexport:{source:target.source,importedName:target.importedName}};if(target.type===`inline`)return{moduleId:resolvedId,fn:target.node,module:analysis};return null}async function walkReachableWevuFeatures(options){const{pageModule,setupFn,resolver,moduleCache}=options;const enabled=/* @__PURE__ */ new Set;const seedCalls=collectCalledBindingsFromFunctionBody(setupFn,pageModule.engine);const queue=[];const visitedLocal=/* @__PURE__ */ new Set;const visitedExternal=/* @__PURE__ */ new Set;const enqueueLocal=(moduleId,name)=>{const key=`${moduleId}::${name}`;if(visitedLocal.has(key))return;visitedLocal.add(key);queue.push({kind:`local`,moduleId,name})};const enqueueExternal=(importerId,source,exportName)=>{const key=`${importerId}::${source}::${exportName}`;if(visitedExternal.has(key))return;visitedExternal.add(key);queue.push({kind:`external`,importerId,source,exportName})};const seedFromCall=call=>{if(call.type===`ident`){const binding=pageModule.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(pageModule.id,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(pageModule.id,binding.source,`default`);else if(!binding&&pageModule.localFunctions.has(call.name))enqueueLocal(pageModule.id,call.name);return}const binding=pageModule.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(pageModule.id,binding.source,call.property)};for(const call of seedCalls)seedFromCall(call);let steps=0;const MAX_STEPS=128;while(queue.length&&steps<MAX_STEPS){steps+=1;const item=queue.shift();if(item.kind===`local`){if(item.moduleId!==pageModule.id)continue;const fn=pageModule.localFunctions.get(item.name);if(!fn)continue;for(const f of collectWevuHookCallsInFunctionBody(pageModule,fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(fn,pageModule.engine);for(const call of calls)seedFromCall(call);continue}const resolved=await resolveExternalFunction(resolver,item.importerId,item.source,item.exportName,moduleCache,{astEngine:options.astEngine});if(!resolved)continue;if(`reexport`in resolved){enqueueExternal(resolved.moduleId,resolved.reexport.source,resolved.reexport.importedName);continue}for(const f of collectWevuHookCallsInFunctionBody(resolved.module,resolved.fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(resolved.fn,resolved.module.engine);for(const call of calls)if(call.type===`ident`){const binding=resolved.module.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(resolved.moduleId,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(resolved.moduleId,binding.source,`default`);else if(!binding&&resolved.module.localFunctions.has(call.name)){const key=`${resolved.moduleId}::${call.name}`;if(!visitedLocal.has(key)){visitedLocal.add(key);const localFn=resolved.module.localFunctions.get(call.name);if(localFn){for(const f of collectWevuHookCallsInFunctionBody(resolved.module,localFn))enabled.add(f);for(const inner of collectCalledBindingsFromFunctionBody(localFn,resolved.module.engine))if(inner.type===`ident`){const innerBinding=resolved.module.importedBindings.get(inner.name);if(innerBinding?.kind===`named`)enqueueExternal(resolved.moduleId,innerBinding.source,innerBinding.importedName);else if(innerBinding?.kind==="default")enqueueExternal(resolved.moduleId,innerBinding.source,`default`)}}}}}else{const binding=resolved.module.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(resolved.moduleId,binding.source,call.property)}}return enabled}async function collectWevuFeaturesFromSetupReachableImports(pageModule,setupFn,resolver,moduleCache,options){return await walkReachableWevuFeatures({pageModule,setupFn,resolver,moduleCache,astEngine:options?.astEngine})}async function collectWevuFeaturesFromCodeReachableImports(code,options){const{optionsObjects,module}=collectTargetOptionsObjectsFromCode(code,options.id,{astEngine:options.astEngine});if(!optionsObjects.length)return/* @__PURE__ */ new Set;const moduleCache=/* @__PURE__ */ new Map([[options.id,module]]);const enabled=/* @__PURE__ */ new Set;for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const reachable=await collectWevuFeaturesFromSetupReachableImports(module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const feature of reachable)enabled.add(feature)}return enabled}function injectWevuPageFeaturesInJs(source,options){const enabled=collectWevuPageFeatureFlagsFromCode(source,options);if(!enabled.size)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,`<inline>`);if(!optionsObjects.length)return{code:source,transformed:false};let changed=false;for(const target of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(target,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}async function injectWevuPageFeaturesInJsWithResolver(source,options){const preflight=collectTargetOptionsObjectsFromCode(source,options.id,{astEngine:options.astEngine});if(!preflight.optionsObjects.length)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,options.id);if(!optionsObjects.length)return{code:source,transformed:false};const enabled=/* @__PURE__ */ new Set;for(const flag of collectWevuPageFeatureFlagsFromCode(source,options))enabled.add(flag);const moduleCache=/* @__PURE__ */ new Map;moduleCache.set(options.id,preflight.module);for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const fromImports=await collectWevuFeaturesFromSetupReachableImports(preflight.module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const flag of fromImports)enabled.add(flag)}if(!enabled.size)return{code:source,transformed:false};let changed=false;for(const optionsObject of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}function createPageEntryMatcher(source){let cached;const warn=resolveWarnHandler(source.warn);async function ensure(){if(cached)return cached;let entries;try{entries=await source.loadEntries()}catch(error){const message=error instanceof Error?error.message:String(error);warn(`[wevu] 解析页面入口失败:${message}`);return/* @__PURE__ */ new Set}const set=/* @__PURE__ */ new Set;for(const pageEntry of entries.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,normalized))}for(const meta of entries.subPackages??[]){const root=meta.root??``;for(const pageEntry of meta.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,root,normalized))}}for(const entry of entries.pluginPages??[]){const normalized=stripLeadingSlashes(String(entry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,removeExtensionDeep(normalized)))}cached=set;return set}return{markDirty(){cached=void 0},async isPageFile(filePath){const pages=await ensure();const normalized=removeExtensionDeep(filePath);return pages.has(normalized)}}}function isDefineComponentCall(node,aliases){return t.isIdentifier(node.callee)&&aliases.has(node.callee.name)}function isObjectAssignCall$1(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function unwrapTypeLikeExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$1(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$1(node.expression);return node}function resolveObjectExpressionFromAssignCall(node){if(!isObjectAssignCall$1(node))return null;for(let index=node.arguments.length-1;index>=0;index-=1){const arg=node.arguments[index];if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const normalized=unwrapTypeLikeExpression$1(arg);if(t.isObjectExpression(normalized))return normalized}return null}function unwrapDefineComponent(node,aliases){if(t.isCallExpression(node)&&isDefineComponentCall(node,aliases)){const arg=node.arguments[0];if(t.isObjectExpression(arg))return arg}return null}function resolveComponentExpression(declaration,defineComponentDecls,aliases){if(!declaration)return null;if(t.isObjectExpression(declaration))return declaration;if(t.isCallExpression(declaration)&&isDefineComponentCall(declaration,aliases)){const arg=declaration.arguments[0];if(t.isObjectExpression(arg))return arg;if(t.isIdentifier(arg)){const matched=defineComponentDecls.get(arg.name);return matched?t.cloneNode(matched,true):null}if(t.isExpression(arg))return arg;return null}if(t.isCallExpression(declaration)&&isObjectAssignCall$1(declaration))return declaration;if(t.isIdentifier(declaration)){const matched=defineComponentDecls.get(declaration.name);return matched?t.cloneNode(matched,true):null}return null}function resolveComponentOptionsObject(componentExpr){if(!componentExpr)return null;const normalized=unwrapTypeLikeExpression$1(componentExpr);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized))return resolveObjectExpressionFromAssignCall(normalized);return null}function isScriptSetupReturnedObject(path){const parent=path.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id,{name:`__returned__`}))return true;if(parent?.isReturnStatement())return true;return false}function isTemplateReturnGetterReference(path){const objectMethod=path.findParent(parent=>parent.isObjectMethod());if(objectMethod?.isObjectMethod()&&objectMethod.node.kind===`get`&&!objectMethod.node.computed&&t.isIdentifier(objectMethod.node.key,{name:path.node.name})&&objectMethod.parentPath?.isObjectExpression()&&isScriptSetupReturnedObject(objectMethod.parentPath)){const getter=objectMethod.node.body.body.find(statement=>t.isReturnStatement(statement));return Boolean(getter&&t.isReturnStatement(getter)&&t.isIdentifier(getter.argument,{name:path.node.name}))}return false}function isTemplateReturnPropertyReference(path){const property=path.parentPath;if(!property?.isObjectProperty())return false;if(!property.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(property.parentPath)||property.node.computed)return false;const key=property.node.key;const value=property.node.value;if(!t.isIdentifier(value,{name:path.node.name}))return false;if(t.isIdentifier(key,{name:path.node.name})||t.isStringLiteral(key,{value:path.node.name}))return true;return false}function isStaticPropertyNamed(node,name){return!node.computed&&(t.isIdentifier(node.key,{name})||t.isStringLiteral(node.key,{value:name}))}function isOptionsApiComponentsObject(path){const componentsProperty=path.parentPath;if(!componentsProperty?.isObjectProperty()||!isStaticPropertyNamed(componentsProperty.node,`components`))return false;const optionsObject=componentsProperty.parentPath;if(!optionsObject?.isObjectExpression())return false;const optionsParent=optionsObject.parentPath;if(optionsParent?.isExportDefaultDeclaration())return true;return Boolean(optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===optionsObject.node&&optionsParent.parentPath?.isExportDefaultDeclaration())}function isOptionsApiComponentRegistrationReference(path){const property=path.parentPath;return Boolean(property?.isObjectProperty()&&property.node.value===path.node&&property.parentPath?.isObjectExpression()&&isOptionsApiComponentsObject(property.parentPath))}function isReferencedOutsideTemplateReturn(path){if(!path.isReferencedIdentifier())return false;if(isTemplateReturnGetterReference(path)||isTemplateReturnPropertyReference(path)||isOptionsApiComponentRegistrationReference(path))return false;return true}function collectReferencedNames(ast,candidateNames){const referencedNames=/* @__PURE__ */ new Set;traverse(ast,{Identifier(path){const name=path.node.name;if(!candidateNames.has(name))return;if(isReferencedOutsideTemplateReturn(path))referencedNames.add(name)}});return referencedNames}function removeSetupReturnProperties(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectMethod(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.key))return;const name=path.node.key.name;if(!removableNames.has(name))return;if(path.node.kind!==`get`)return;const getter=path.node.body.body.find(statement=>t.isReturnStatement(statement));if(!getter||!t.isReturnStatement(getter)||!t.isIdentifier(getter.argument,{name}))return;path.remove();changed=true},ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.value))return;const name=path.node.value.name;if(!removableNames.has(name))return;if(!t.isIdentifier(path.node.key,{name})&&!t.isStringLiteral(path.node.key,{value:name}))return;path.remove();changed=true}});return changed}function removeOptionsApiComponentRegistrations(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isOptionsApiComponentsObject(path.parentPath)||!t.isIdentifier(path.node.value)||!removableNames.has(path.node.value.name))return;path.remove();changed=true}});traverse(ast,{ObjectProperty(path){if(!t.isObjectExpression(path.node.value)||!isStaticPropertyNamed(path.node,`components`)||path.node.value.properties.length>0||!path.parentPath?.isObjectExpression())return;const optionsParent=path.parentPath.parentPath;if(optionsParent?.isExportDefaultDeclaration()||optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===path.parentPath.node&&optionsParent.parentPath?.isExportDefaultDeclaration())path.remove()}});return changed}function pruneTemplateComponentMeta(ast,templateComponentMeta){if(!Object.keys(templateComponentMeta).length)return false;const candidateNames=new Set(Object.keys(templateComponentMeta));const referencedNames=collectReferencedNames(ast,candidateNames);const removableNames=new Set([...candidateNames].filter(name=>!referencedNames.has(name)));let changed=false;traverse(ast,{ImportDeclaration(path){if(!path.node.specifiers.length)return;const kept=path.node.specifiers.filter(specifier=>{if(!(`local`in specifier)||!t.isIdentifier(specifier.local))return true;const localName=specifier.local.name;return!removableNames.has(localName)});if(kept.length!==path.node.specifiers.length){changed=true;if(kept.length===0){path.remove();return}path.node.specifiers=kept}}});changed=removeSetupReturnProperties(ast,removableNames)||changed;changed=removeOptionsApiComponentRegistrations(ast,removableNames)||changed;return changed}function vueSfcTransformPlugin(){return{name:`vue-sfc-transform`,visitor:{ImportDeclaration(path){if(path.node.source.value===`vue`){const specifiers=path.node.specifiers;const filteredSpecifiers=specifiers.filter(s=>{if(s.type===`ImportSpecifier`&&t.isIdentifier(s.imported)&&s.imported.name===WE_VU_RUNTIME_APIS.defineComponent)return false;return true});if(filteredSpecifiers.length===0)path.remove();else if(filteredSpecifiers.length!==specifiers.length)path.node.specifiers=filteredSpecifiers}},ObjectExpression(path){const filtered=path.node.properties.filter(p=>{if(p.type===`ObjectProperty`){const key=p.key;if(key.type===`Identifier`&&key.name===`__name`)return false}return true});path.node.properties=filtered},CallExpression(path){if(t.isMemberExpression(path.node.callee)&&t.isIdentifier(path.node.callee.object,{name:`Object`})&&t.isIdentifier(path.node.callee.property,{name:`defineProperty`})&&t.isIdentifier(path.node.arguments[0],{name:`__returned__`})&&t.isStringLiteral(path.node.arguments[1],{value:`__isScriptSetup`})&&path.parentPath?.isExpressionStatement()){path.parentPath.remove();return}if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()&&path.node.arguments.length===0)path.parentPath.remove()}}}}function createCollectVisitors(state){return{VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))state.defineComponentDecls.set(path.node.id.name,t.cloneNode(path.node.init,true));const unwrapped=unwrapDefineComponent(path.node.init,state.defineComponentAliases);if(unwrapped){state.defineComponentDecls.set(path.node.id.name,t.cloneNode(unwrapped,true));path.node.init=unwrapped;state.transformed=true}},ExportDefaultDeclaration(path){state.defaultExportPath=path}}}const RUNTIME_IMPORT_PATH=WE_VU_COMPILER_RUNTIME_MODULE_ID;const COMPILED_DEFINE_COMPONENT_IMPORT_RE=/^import\s+\{\s*defineComponent\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s+from\s+['"]vue['"];?\n/;const EXPORT_DEFAULT_PURE_RE=/export\s+default\s+\/\*@__PURE__\*\/\s*/;const JSON_MACRO_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;const PAGE_META_RE=/\bdefinePageMeta\s*\(/;const OPTION_CAPABILITY_RE=/\b(?:createApp|createWevuComponent|setData|setWevuDefaults)\b/;const WEVU_RUNTIME_IMPORT_RE=/\bfrom\s*['"](?:wevu(?:\/internal-runtime)?|virtual:weapp-vite\/runtime)['"]/;const DYNAMIC_OPTIONS_PROPERTY_RE=/\.\.\.|\[/;function hasMetadataInjectionOptions(source,options){const hasWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0;return Boolean(options?.isTypeScript||options?.isApp||options?.skipComponentTransform||options?.minify||options?.sourceMap!==false||options?.templateComponentMeta||hasWevuDefaults||options?.classStyleBindings?.length||options?.templateRefs?.length||options?.layoutHosts?.length||options?.inlineExpressions?.length||options?.runtimeCapabilities?.required.length||options?.functionPropPaths?.length||options?.propsAliases||options?.propsDerivedKeys?.length||options?.relaxStructuredTypeOnlyProps||options?.bindingManifest||options?.pageLayout||options?.scopedSlotHostProperties||options?.stabilizeCssVarsRuntime||/\b(?:useSlots|options|extends|mixins|definitionFilter|behaviors)\b|\\/.test(source))}function findMatchingCallEnd(source,openParenIndex){let depth=0;let quote;let escaped=false;let lineComment=false;let blockComment=false;for(let index=openParenIndex;index<source.length;index+=1){const current=source[index];const next=source[index+1];if(lineComment){if(current===`
|
|
22
|
+
`.trimStart()+ms.toString()+`\nexport default __weapp_json_macro_values\n`;const extension=resolveScriptSetupExtension$1(lang);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.json-macro.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const resolved=mod?.default??mod;const values=Array.isArray(resolved)?resolved:[resolved];let accumulator={};for(const raw of values){if(raw===void 0)continue;let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`宏的返回值必须解析为对象。`);if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}if(!Object.keys(accumulator).length)return{dependencies};return{config:accumulator,dependencies}}finally{try{await remove(tempDir)}catch{}}})}const JSON_MACROS=/* @__PURE__ */ new Set([`defineAppJson`,`definePageJson`,`defineComponentJson`,`defineSitemapJson`,`defineThemeJson`]);const JSON_MACRO_HINT_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;function mayContainJsonMacro(content){return JSON_MACRO_HINT_RE.test(content)}function parseScriptSetupAst(content,filename){try{return parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 中的 <script setup> 失败:${message}`)}}function collectMacroCallPaths(ast,filename){const macroNames=/* @__PURE__ */ new Set;const macroStatements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee))return;if(!JSON_MACROS.has(callee.name))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))throw new Error(`${callee.name}() 必须在 <script setup> 顶层语句中使用(${filename})。`);macroNames.add(callee.name);macroStatements.push(path.parentPath)}});return{macroNames,macroStatements}}function assertSingleMacro(macroNames,filename){if(macroNames.size>1)throw new Error(`同一个 <script setup> 仅能使用 ${[...JSON_MACROS].join(`, `)} 中的一个(${filename})。`);return macroNames.values().next().value}function findProgramPath(ast){let programPath;traverse(ast,{Program(path){programPath=path;path.stop()}});return programPath}function stripScriptSetupMacroStatements(content,ast,filename,sourceMap){const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);const macroStatementSources=[];const body=ast.program?.body??[];for(const statement of body){if(!t.isExpressionStatement(statement))continue;const expr=statement.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))continue;const name=expr.callee.name;if(!JSON_MACROS.has(name))continue;if(expr.arguments.length!==1)throw new Error(`${name}() 在 ${filename} 中必须且只能传 1 个参数。`);if(typeof statement.start===`number`&&typeof statement.end===`number`)macroStatementSources.push(content.slice(statement.start,statement.end));if(typeof statement.start===`number`&&typeof statement.end===`number`)ms.remove(statement.start,statement.end)}const stripped=sourceMap?ms.slice(0,content.length):ms.toString();const result={stripped,macroStatementSources};if(!sourceMap||stripped===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}function splitJsonMacroCallsFromCode(code,filename){let ast;try{ast=parse$3(code,BABEL_TS_MODULE_PARSER_OPTIONS)}catch(error){try{ast=parseJsLike(code)}catch(fallbackError){const message=error instanceof Error?error.message:String(error);const fallbackMessage=fallbackError instanceof Error?fallbackError.message:String(fallbackError);throw new Error(`解析 ${filename} 的编译脚本失败:${message};兜底解析失败:${fallbackMessage}`)}}const ms=new MagicString(code);const macroSources=[];traverse(ast,{ExpressionStatement(path){const expr=path.node.expression;if(!t.isCallExpression(expr)||!t.isIdentifier(expr.callee))return;if(!JSON_MACROS.has(expr.callee.name))return;const start=path.node.start;const end=path.node.end;if(typeof start===`number`&&typeof end===`number`){macroSources.push(code.slice(start,end));ms.remove(start,end)}}});return{macroSources,stripped:ms.toString()}}function stripJsonMacroCallsFromCode(code,filename){return splitJsonMacroCallsFromCode(code,filename).stripped}function unwrapTsExpression$1(node){if(t.isTSAsExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node))return unwrapTsExpression$1(node.expression);return node}function resolveStaticLiteralValue(node){const normalized=unwrapTsExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized))return normalized.value;if(t.isNullLiteral(normalized))return null;if(t.isUnaryExpression(normalized)&&(normalized.operator===`-`||normalized.operator===`+`)&&t.isNumericLiteral(normalized.argument))return normalized.operator===`-`?-normalized.argument.value:normalized.argument.value;if(t.isArrayExpression(normalized)){const values=[];for(const element of normalized.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element))throw new Error(`unsupported static json macro array item`);values.push(resolveStaticLiteralValue(element))}return values}if(t.isObjectExpression(normalized)){const value={};for(const property of normalized.properties){if(!t.isObjectProperty(property)||property.computed||!t.isExpression(property.value))throw new Error(`unsupported static json macro object property`);const key=property.key;const keyName=t.isIdentifier(key)?key.name:t.isStringLiteral(key)||t.isNumericLiteral(key)?String(key.value):void 0;if(!keyName)throw new Error(`unsupported static json macro object key`);value[keyName]=resolveStaticLiteralValue(property.value)}return value}throw new Error(`unsupported static json macro value`)}function resolveStaticJsonMacroConfig(macroStatements,options){let accumulator={};for(const statementPath of macroStatements){const arg=statementPath.get(`expression`).get(`arguments.0`)?.node;if(!arg||!t.isExpression(arg))return;let next;try{next=resolveStaticLiteralValue(arg)}catch{return}if(!next||typeof next!==`object`||Array.isArray(next))return;if(hasOwn(next,`$schema`))delete next.$schema;if(options?.merge){const merged=options.merge(accumulator,next);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,next)}return Object.keys(accumulator).length?accumulator:void 0}function withSourceMap(result,rewrite){if(!(`map`in rewrite))return result;return{...result,get map(){return rewrite.map}}}async function evaluateJsonMacroConfig(content,filename,lang,options){const contentForEval=options?.preambleContent?`${options.preambleContent}\n${content}`:content;const ast=parseScriptSetupAst(contentForEval,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);const macroName=assertSingleMacro(macroNames,filename);if(!macroName||!macroStatements.length)return;const programPath=findProgramPath(ast);if(!programPath)return;const{bodyPaths,keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatements);return await evaluateScriptSetupJsonMacro({preambleContent:options?.preambleContent,originalContent:content,filename,lang,macroName,macroStatements,bodyPaths,keptStatementPaths,options})}async function extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap){if(!mayContainJsonMacro(content))return{stripped:content};const ast=parseScriptSetupAst(content,filename);const{macroNames,macroStatements}=collectMacroCallPaths(ast,filename);assertSingleMacro(macroNames,filename);const rewrite=stripScriptSetupMacroStatements(content,ast,filename,sourceMap);const{stripped,macroStatementSources}=rewrite;if(macroNames.size===0)return withSourceMap({stripped},rewrite);const macroHash=createHash(`sha256`).update(macroStatementSources.join(`
|
|
23
|
+
`)).digest(`hex`).slice(0,12);const staticConfig=resolveStaticJsonMacroConfig(macroStatements,options);if(staticConfig)return withSourceMap({stripped,config:staticConfig,macroHash,dependencies:[]},rewrite);const result=await evaluateJsonMacroConfig(content,filename,lang,options);return withSourceMap(result?{stripped,config:result.config,macroHash,dependencies:result.dependencies}:{stripped,macroHash},rewrite)}async function extractJsonMacroFromScriptSetup(content,filename,lang,options){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options)}async function extractJsonMacroFromScriptSetupWithSourceMap(content,filename,lang,options,sourceMap){return await extractJsonMacroFromScriptSetupInternal(content,filename,lang,options,sourceMap)}function toPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function mergeJsonWithStrategy(target,source,strategy,context){const base={...toPlainRecord(target)};const incoming=toPlainRecord(source);if(typeof strategy===`function`){const maybeNext=strategy(base,incoming,context);if(maybeNext&&typeof maybeNext===`object`&&!Array.isArray(maybeNext))return maybeNext;return base}if(strategy===`replace`)return{...incoming};if(strategy===`assign`)return{...base,...incoming};const merged={...base};recursive(merged,incoming);return merged}function createJsonMerger(strategy,baseContext){return(target,source,stage)=>{return mergeJsonWithStrategy(target,source,strategy,{...baseContext,stage})}}function resolveWarnHandler(warn){return warn??(message=>{console.warn(message)})}function isStaticObjectKeyMatch$1(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$3(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch$1(prop.key,key))return prop}return null}function buildInjectedFeaturesObject(enabled){return t.objectExpression(Array.from(enabled,key=>{return t.objectProperty(t.identifier(key),t.booleanLiteral(true))}))}function getObjectMemberIndexByKey(node,key){return node.properties.findIndex(prop=>{if(t.isObjectProperty(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);if(t.isObjectMethod(prop)&&!prop.computed)return isStaticObjectKeyMatch$1(prop.key,key);return false})}function isTopLevel(path){return path.getFunctionParent()==null}function injectWevuShareLifecycleHooksIntoOptionsObject(_optionsObject,_enabled){return false}function collectWevuPageFeatureFlags(ast){const namedHookLocals=/* @__PURE__ */ new Map;const namespaceLocals=/* @__PURE__ */ new Set;for(const stmt of ast.program.body){if(!t.isImportDeclaration(stmt)||!isWevuPageFeatureModuleId(stmt.source.value))continue;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)namedHookLocals.set(specifier.local.name,matched)}else if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name)}if(namedHookLocals.size===0&&namespaceLocals.size===0)return/* @__PURE__ */ new Set;const enabled=/* @__PURE__ */ new Set;function consumeHookCallByName(name){const matched=namedHookLocals.get(name);if(matched)enabled.add(matched)}function consumeNamespaceHookCall(namespace,hookName){if(!namespaceLocals.has(namespace))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hookName];if(matched)enabled.add(matched)}traverse(ast,{CallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}},OptionalCallExpression(path){const callee=path.node.callee;if(t.isIdentifier(callee)){consumeHookCallByName(callee.name);return}if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)){const property=callee.property;if(t.isIdentifier(property))consumeNamespaceHookCall(callee.object.name,property.name)}}});return enabled}function injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled){if(!enabled.size)return false;const expectedKeys=[...enabled];const existingFeaturesProp=getObjectPropertyByKey$3(optionsObject,`features`);let changed=false;if(!existingFeaturesProp){const featuresObject=buildInjectedFeaturesObject(enabled);const setupIndex=getObjectMemberIndexByKey(optionsObject,`setup`);const insertAt=setupIndex>=0?setupIndex:0;optionsObject.properties.splice(insertAt,0,t.objectProperty(t.identifier(`features`),featuresObject));changed=true}else if(t.isObjectExpression(existingFeaturesProp.value)){const featuresObject=existingFeaturesProp.value;const injectedProps=[];for(const key of expectedKeys){if(getObjectPropertyByKey$3(featuresObject,key))continue;injectedProps.push(t.objectProperty(t.identifier(key),t.booleanLiteral(true)))}if(injectedProps.length){featuresObject.properties.splice(0,0,...injectedProps);changed=true}}else if(t.isIdentifier(existingFeaturesProp.value)||t.isMemberExpression(existingFeaturesProp.value)){const base=t.cloneNode(existingFeaturesProp.value,true);const injected=buildInjectedFeaturesObject(enabled);injected.properties.push(t.spreadElement(base));existingFeaturesProp.value=injected;changed=true}changed=injectWevuShareLifecycleHooksIntoOptionsObject(optionsObject,enabled)||changed;return changed}function createEmptyModuleAnalysis(id,engine){return{id,engine,wevuNamedHookLocals:/* @__PURE__ */ new Map,wevuNamespaceLocals:/* @__PURE__ */ new Set,importedBindings:/* @__PURE__ */ new Map,localFunctions:/* @__PURE__ */ new Map,exports:/* @__PURE__ */ new Map}}const externalModuleAnalysisCache=new LRUCache({max:256});const moduleAnalysisCache=new LRUCache({max:512});function createExternalModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function createModuleAnalysisCacheKey(moduleId,astEngine){return`${astEngine??`babel`}::${moduleId}`}function getFunctionLikeFromExpression(node){if(!node)return null;if(t.isFunctionExpression(node)||t.isArrowFunctionExpression(node))return node;return null}function isOxcFunctionLike(node){return node?.type===`FunctionDeclaration`||node?.type===`FunctionExpression`||node?.type===`ArrowFunctionExpression`}function getImportedSpecifierName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function createModuleAnalysis(id,ast){const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(!node.id||!node.id.name)return;localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(!t.isIdentifier(node.id))return;const fn=getFunctionLikeFromExpression(node.init);if(!fn)return;localFunctions.set(node.id.name,fn)}for(const stmt of ast.program.body){if(t.isFunctionDeclaration(stmt)){registerFunctionDeclaration(stmt);continue}if(t.isVariableDeclaration(stmt)){for(const decl of stmt.declarations)registerVariableFunction(decl);continue}if(t.isImportDeclaration(stmt)){const source=stmt.source.value;for(const specifier of stmt.specifiers)if(t.isImportSpecifier(specifier)){const imported=specifier.imported;if(isWevuPageFeatureModuleId(source)&&t.isIdentifier(imported)){const importedName=imported.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName:t.isIdentifier(imported)?imported.name:String(imported.value)})}else if(t.isImportDefaultSpecifier(specifier))importedBindings.set(specifier.local.name,{kind:`default`,source});else if(t.isImportNamespaceSpecifier(specifier)){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(t.isExportNamedDeclaration(stmt)){if(stmt.declaration){if(t.isFunctionDeclaration(stmt.declaration)&&stmt.declaration.id){registerFunctionDeclaration(stmt.declaration);exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name})}else if(t.isVariableDeclaration(stmt.declaration))for(const decl of stmt.declaration.declarations){registerVariableFunction(decl);if(t.isIdentifier(decl.id))exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}if(stmt.source){const source=stmt.source.value;for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const importedName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!importedName)continue;exports.set(exportedName,{type:`reexport`,source,importedName})}}else for(const spec of stmt.specifiers){if(!t.isExportSpecifier(spec))continue;const exportedName=t.isIdentifier(spec.exported)?spec.exported.name:void 0;const localName=t.isIdentifier(spec.local)?spec.local.name:void 0;if(!exportedName||!localName)continue;exports.set(exportedName,{type:`local`,localName})}continue}if(t.isExportDefaultDeclaration(stmt)){const decl=stmt.declaration;if(t.isFunctionDeclaration(decl)){registerFunctionDeclaration(decl);if(decl.id)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(t.isIdentifier(decl))exports.set(`default`,{type:`local`,localName:decl.name});else{const fn=getFunctionLikeFromExpression(decl);if(fn)exports.set(`default`,{type:`inline`,node:fn})}}}return{id,engine:`babel`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}function resolveOxcParseFilename(id){if(path.extname(id))return id;return`${id}.js`}function createModuleAnalysisWithOxc(id,code){const ast=parseJsLikeWithEngine(code,{engine:`oxc`,filename:resolveOxcParseFilename(id)});const localFunctions=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const importedBindings=/* @__PURE__ */ new Map;const wevuNamedHookLocals=/* @__PURE__ */ new Map;const wevuNamespaceLocals=/* @__PURE__ */ new Set;function registerFunctionDeclaration(node){if(node?.id?.type===`Identifier`)localFunctions.set(node.id.name,node)}function registerVariableFunction(node){if(node?.id?.type!==`Identifier`||!isOxcFunctionLike(node.init))return;localFunctions.set(node.id.name,node.init)}for(const stmt of ast.body??[]){if(stmt?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt);continue}if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])registerVariableFunction(decl);continue}if(stmt?.type===`ImportDeclaration`){const source=getImportedSpecifierName(stmt.source);if(!source)continue;for(const specifier of stmt.specifiers??[])if(specifier.type===`ImportSpecifier`&&specifier.local?.type===`Identifier`){const importedName=getImportedSpecifierName(specifier.imported);if(!importedName)continue;if(isWevuPageFeatureModuleId(source)){const matched=WE_VU_PAGE_HOOK_TO_FEATURE[importedName];if(matched)wevuNamedHookLocals.set(specifier.local.name,matched)}importedBindings.set(specifier.local.name,{kind:`named`,source,importedName})}else if(specifier.type===`ImportDefaultSpecifier`&&specifier.local?.type===`Identifier`)importedBindings.set(specifier.local.name,{kind:`default`,source});else if(specifier.type===`ImportNamespaceSpecifier`&&specifier.local?.type===`Identifier`){importedBindings.set(specifier.local.name,{kind:`namespace`,source});if(isWevuPageFeatureModuleId(source))wevuNamespaceLocals.add(specifier.local.name)}continue}if(stmt?.type===`ExportNamedDeclaration`){if(stmt.declaration?.type===`FunctionDeclaration`){registerFunctionDeclaration(stmt.declaration);if(stmt.declaration.id?.type===`Identifier`)exports.set(stmt.declaration.id.name,{type:`local`,localName:stmt.declaration.id.name});continue}if(stmt.declaration?.type===`VariableDeclaration`){for(const decl of stmt.declaration.declarations??[]){registerVariableFunction(decl);if(decl.id?.type===`Identifier`)exports.set(decl.id.name,{type:`local`,localName:decl.id.name})}continue}const source=getImportedSpecifierName(stmt.source);for(const spec of stmt.specifiers??[]){if(spec?.type!==`ExportSpecifier`)continue;const exportedName=getImportedSpecifierName(spec.exported);const localName=getImportedSpecifierName(spec.local);if(!exportedName||!localName)continue;if(source)exports.set(exportedName,{type:`reexport`,source,importedName:localName});else exports.set(exportedName,{type:`local`,localName})}continue}if(stmt?.type===`ExportDefaultDeclaration`){const decl=stmt.declaration;if(decl?.type===`FunctionDeclaration`){registerFunctionDeclaration(decl);if(decl.id?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.id.name});else exports.set(`default`,{type:`inline`,node:decl})}else if(decl?.type===`Identifier`)exports.set(`default`,{type:`local`,localName:decl.name});else if(isOxcFunctionLike(decl))exports.set(`default`,{type:`inline`,node:decl})}}return{id,engine:`oxc`,ast,wevuNamedHookLocals,wevuNamespaceLocals,importedBindings,localFunctions,exports}}const TS_WITHOUT_JSX_RE=/\.[cm]?ts(?:[?#].*)?$/i;function parseModuleAnalysisAst(id,code){const plugins=TS_WITHOUT_JSX_RE.test(id)?BABEL_TS_MODULE_PLUGINS.filter(plugin=>plugin!==`jsx`):BABEL_TS_MODULE_PLUGINS;return parse$3(code,{sourceType:`module`,plugins})}function createModuleAnalysisFromCode(id,code,options){const engine=options?.astEngine??`babel`;const cacheKey=createModuleAnalysisCacheKey(id,engine);const cached=moduleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;let analysis;if(engine===`oxc`){if(!code.includes(`import`)&&!code.includes(`export`))analysis=createEmptyModuleAnalysis(id,`oxc`);else analysis=createModuleAnalysisWithOxc(id,code)}else{const ast=parseModuleAnalysisAst(id,code);analysis=createModuleAnalysis(id,ast)}moduleAnalysisCache.set(cacheKey,{code,analysis});return analysis}function getOrCreateExternalModuleAnalysis(moduleId,code,options){const cacheKey=createExternalModuleAnalysisCacheKey(moduleId,options?.astEngine);const cached=externalModuleAnalysisCache.get(cacheKey);if(cached&&cached.code===code)return cached.analysis;const analysis=createModuleAnalysisFromCode(moduleId,code,options);externalModuleAnalysisCache.set(cacheKey,{code,analysis});return analysis}const CALL_EXPRESSION_TEXT_RE=/\b[a-z_$][\w$]*(?:\s*<[^(){};]+>)?\s*(?:\?\.\s*)?\(/i;const WEVU_PAGE_HOOK_NAMES=Object.keys(WE_VU_PAGE_HOOK_TO_FEATURE);function mayContainWevuPageFeatureHints(code){return WE_VU_RUNTIME_MODULE_IDS.some(moduleId=>code.includes(moduleId))&&CALL_EXPRESSION_TEXT_RE.test(code)&&WEVU_PAGE_HOOK_NAMES.some(hookName=>code.includes(hookName))}function collectWithBabel(code){const ast=parseJsLike(code);return collectWevuPageFeatureFlags(ast)}function collectWithOxc(code){const enabled=/* @__PURE__ */ new Set;const module=createModuleAnalysisFromCode(`<inline>`,code,{astEngine:`oxc`});if(module.wevuNamedHookLocals.size===0&&module.wevuNamespaceLocals.size===0)return enabled;const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(module.ast);return enabled}function collectWevuPageFeatureFlagsFromCode(code,options){if(!mayContainWevuPageFeatureHints(code))return/* @__PURE__ */ new Set;const engine=options?.astEngine??`babel`;try{return engine===`oxc`?collectWithOxc(code):collectWithBabel(code)}catch{return/* @__PURE__ */ new Set}}const WEVU_FACTORY_NAMES=/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,WE_VU_RUNTIME_APIS.createWevuComponent]);const REGEXP_META_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_META_CHARS_RE,`\\$&`)}function mayContainNamedFactoryCall(code,localName){return new RegExp(`\\b${escapeRegExp(localName)}\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayContainNamespaceFactoryCall(code,namespaceName){const factoryAlternation=Array.from(WEVU_FACTORY_NAMES,name=>escapeRegExp(name)).join(`|`);return new RegExp(`\\b${escapeRegExp(namespaceName)}\\b\\s*\\.\\s*(?:${factoryAlternation})\\b(?:\\s*<[^(){};]+>)?\\s*(?:\\?\\.)?\\s*\\(`,`m`).test(code)}function mayCallWevuFactoryByText(code,module){for(const[localName,binding]of module.importedBindings.entries()){if(!isWevuRuntimeModuleId(binding.source))continue;if(binding.kind===`named`&&WEVU_FACTORY_NAMES.has(binding.importedName)){if(mayContainNamedFactoryCall(code,localName))return true;continue}if(binding.kind===`namespace`&&mayContainNamespaceFactoryCall(code,localName))return true}return false}function unwrapTypeLikeExpression$2(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$2(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$2(node.expression);return node}function resolveOptionsObjectFromExpression(node){const normalized=unwrapTypeLikeExpression$2(node);if(t.isObjectExpression(normalized))return normalized;if(t.isIdentifier(normalized))return null;if(t.isCallExpression(normalized)){const callee=normalized.callee;if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`}))for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(t.isSpreadElement(argument)||!t.isExpression(argument))continue;const candidate=resolveOptionsObjectFromExpression(argument);if(candidate)return candidate}}return null}function getOxcStaticPropertyName(node){if(node?.type===`Identifier`)return node.name;if((node?.type===`StringLiteral`||node?.type===`Literal`)&&typeof node.value===`string`)return node.value}function getSetupFunctionFromOptionsObject(options){for(const prop of options.properties)if(t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`)){if(t.isFunctionExpression(prop.value)||t.isArrowFunctionExpression(prop.value))return prop.value}else if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch$1(prop.key,`setup`))return prop;else if(prop?.type===`Property`&&!prop.computed&&getOxcStaticPropertyName(prop.key)===`setup`){if(prop.value?.type===`FunctionExpression`||prop.value?.type===`ArrowFunctionExpression`)return prop.value}return null}function collectTargetOptionsObjectsWithModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];traverse(ast,{VariableDeclarator(path){if(!isTopLevel(path))return;if(!t.isIdentifier(path.node.id))return;const init=path.node.init;if(t.isObjectExpression(init))constObjectBindings.set(path.node.id.name,init)},CallExpression(path){if(!isTopLevel(path))return;const node=path.node;if(t.isV8IntrinsicIdentifier(node.callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;const binding=t.isIdentifier(node.callee)?module.importedBindings.get(node.callee.name):void 0;if(t.isIdentifier(node.callee)){if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object)&&t.isIdentifier(node.callee.property)){const objectBinding=module.importedBindings.get(node.callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(node.callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&node.callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}},OptionalCallExpression(path){if(!isTopLevel(path))return;const node=path.node;const callee=node.callee;if(t.isV8IntrinsicIdentifier(callee))return;const first=node.arguments[0];if(!first||!t.isExpression(first))return;if(t.isIdentifier(callee)){const binding=module.importedBindings.get(callee.name);if(binding?.kind!==`named`||!isWevuRuntimeModuleId(binding.source))return;if(binding.importedName!==WE_VU_RUNTIME_APIS.defineComponent&&binding.importedName!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property)){const objectBinding=module.importedBindings.get(callee.object.name);if(objectBinding?.kind!==`namespace`||!isWevuRuntimeModuleId(objectBinding.source))return;if(callee.property.name!==WE_VU_RUNTIME_APIS.defineComponent&&callee.property.name!==WE_VU_RUNTIME_APIS.createWevuComponent)return}else return;const inlineObject=resolveOptionsObjectFromExpression(first);if(inlineObject)optionsObjects.push(inlineObject);else if(t.isIdentifier(first)){const target=constObjectBindings.get(first.name);if(target)optionsObjects.push(target);else pendingConstObjectRefs.push(first.name)}}});for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function unwrapOxcTypeLikeExpression(node){if(node?.type===`TSAsExpression`||node?.type===`TSSatisfiesExpression`||node?.type===`TSNonNullExpression`||node?.type===`TSTypeAssertion`||node?.type===`ParenthesizedExpression`)return unwrapOxcTypeLikeExpression(node.expression);return node}function getOxcCallExpression(node){if(node?.type===`ChainExpression`)return getOxcCallExpression(node.expression);if(node?.type===`CallExpression`)return node;return null}function resolveOxcOptionsObjectFromExpression(node,bindings){const normalized=unwrapOxcTypeLikeExpression(node);if(normalized?.type===`ObjectExpression`)return normalized;if(normalized?.type===`Identifier`)return bindings.get(normalized.name)??null;if(normalized?.type!==`CallExpression`)return null;const callee=unwrapOxcTypeLikeExpression(normalized.callee);if(callee?.type!==`MemberExpression`||callee.computed||callee.object?.type!==`Identifier`||callee.object.name!==`Object`||callee.property?.type!==`Identifier`||callee.property.name!==`assign`)return null;for(let index=normalized.arguments.length-1;index>=0;index-=1){const argument=normalized.arguments[index];if(argument?.type===`SpreadElement`)continue;const candidate=resolveOxcOptionsObjectFromExpression(argument,bindings);if(candidate)return candidate}return null}function isOxcWevuFactoryCall(call,module){const callee=unwrapOxcTypeLikeExpression(call.callee);if(callee?.type===`Identifier`){const binding=module.importedBindings.get(callee.name);return binding?.kind===`named`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(binding.importedName)}if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){const binding=module.importedBindings.get(callee.object.name);return binding?.kind===`namespace`&&isWevuRuntimeModuleId(binding.source)&&WEVU_FACTORY_NAMES.has(callee.property.name)}return false}function collectTargetOptionsObjectsWithOxcModule(ast,module){const optionsObjects=[];const constObjectBindings=/* @__PURE__ */ new Map;const pendingConstObjectRefs=[];for(const stmt of ast?.body??[]){if(stmt?.type===`VariableDeclaration`){for(const decl of stmt.declarations??[])if(decl?.id?.type===`Identifier`&&decl.init?.type===`ObjectExpression`)constObjectBindings.set(decl.id.name,decl.init);continue}if(stmt?.type!==`ExpressionStatement`)continue;const call=getOxcCallExpression(stmt.expression);if(!call||!isOxcWevuFactoryCall(call,module))continue;const first=call.arguments?.[0];if(!first)continue;const inlineObject=resolveOxcOptionsObjectFromExpression(first,constObjectBindings);if(inlineObject)optionsObjects.push(inlineObject);else if(first.type===`Identifier`)pendingConstObjectRefs.push(first.name)}for(const name of pendingConstObjectRefs){const target=constObjectBindings.get(name);if(target)optionsObjects.push(target)}return{optionsObjects,module}}function collectTargetOptionsObjects(ast,moduleId){return collectTargetOptionsObjectsWithModule(ast,createModuleAnalysis(moduleId,ast))}function collectTargetOptionsObjectsFromCode(code,moduleId,options){if(options?.astEngine===`oxc`){if(!(code.includes(`wevu`)&&(code.includes(WE_VU_RUNTIME_APIS.defineComponent)||code.includes(WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module:createEmptyModuleAnalysis(moduleId,`oxc`)};const module=createModuleAnalysisFromCode(moduleId,code,options);if(![...module.importedBindings.values()].some(binding=>isWevuRuntimeModuleId(binding.source)&&(binding.kind===`namespace`||binding.kind===`named`&&(binding.importedName===WE_VU_RUNTIME_APIS.defineComponent||binding.importedName===WE_VU_RUNTIME_APIS.createWevuComponent))))return{optionsObjects:[],module};if(!mayCallWevuFactoryByText(code,module))return{optionsObjects:[],module};return collectTargetOptionsObjectsWithOxcModule(module.ast,module)}const module=createModuleAnalysisFromCode(moduleId,code,options);return collectTargetOptionsObjectsWithModule(module.ast,module)}function getCallCalleeName(callee){if(t.isV8IntrinsicIdentifier(callee))return null;if(t.isIdentifier(callee))return{type:`ident`,name:callee.name};if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{type:`member`,object:callee.object.name,property:callee.property.name};return null}function collectCalledBindingsFromFunctionBody(fn,engine=`babel`){const called=[];if(engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`)called.push({type:`ident`,name:callee.name});else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`)called.push({type:`member`,object:callee.object.name,property:callee.property.name})}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return called}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}else if(t.isOptionalCallExpression(node)){const name=getCallCalleeName(node.callee);if(name)called.push(name)}});return called}function getMemberHookName(callee){if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};if(t.isOptionalMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&t.isIdentifier(callee.property))return{object:callee.object.name,hook:callee.property.name};return null}function addNamespaceHookFeature(module,callee,enabled){const memberHook=getMemberHookName(callee);if(!memberHook||!module.wevuNamespaceLocals.has(memberHook.object))return;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[memberHook.hook];if(matched)enabled.add(matched)}function collectWevuHookCallsInFunctionBody(module,fn){const enabled=/* @__PURE__ */ new Set;if(module.engine===`oxc`){const visit=node=>{if(!node)return;if(node.type===`CallExpression`){const callee=node.callee;if(callee?.type===`Identifier`){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched)}else if(callee?.type===`MemberExpression`&&!callee.computed&&callee.object?.type===`Identifier`&&callee.property?.type===`Identifier`){if(module.wevuNamespaceLocals.has(callee.object.name)){const hook=callee.property.name;const matched=WE_VU_PAGE_HOOK_TO_FEATURE[hook];if(matched)enabled.add(matched)}}}else if(node.type===`ChainExpression`){visit(node.expression);return}for(const value of Object.values(node)){if(!value)continue;if(Array.isArray(value)){for(const child of value)if(child&&typeof child===`object`&&typeof child.type===`string`)visit(child)}else if(typeof value===`object`&&typeof value.type===`string`)visit(value)}};visit(fn);return enabled}t.traverseFast(fn,node=>{if(t.isCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}else if(t.isOptionalCallExpression(node)){const callee=node.callee;if(t.isIdentifier(callee)){const matched=module.wevuNamedHookLocals.get(callee.name);if(matched)enabled.add(matched);return}addNamespaceHookFeature(module,callee,enabled)}});return enabled}function resolveExportedFunctionNode(module,exportName){const target=module.exports.get(exportName);if(!target)return null;if(target.type===`local`){const fn=module.localFunctions.get(target.localName);return fn?{type:`inline`,node:fn}:null}if(target.type===`reexport`)return target;if(target.type===`inline`)return target;return null}async function resolveExternalFunction(resolver,importerId,source,exportName,moduleCache,options){if(source===`wevu`)return null;const resolvedId=await resolver.resolveId(source,importerId);if(!resolvedId)return null;const code=await resolver.loadCode(resolvedId);if(!code)return null;let analysis=moduleCache.get(resolvedId);if(!analysis){analysis=getOrCreateExternalModuleAnalysis(resolvedId,code,options);moduleCache.set(resolvedId,analysis)}const target=resolveExportedFunctionNode(analysis,exportName);if(!target)return null;if(target.type===`reexport`)return{moduleId:resolvedId,reexport:{source:target.source,importedName:target.importedName}};if(target.type===`inline`)return{moduleId:resolvedId,fn:target.node,module:analysis};return null}async function walkReachableWevuFeatures(options){const{pageModule,setupFn,resolver,moduleCache}=options;const enabled=/* @__PURE__ */ new Set;const seedCalls=collectCalledBindingsFromFunctionBody(setupFn,pageModule.engine);const queue=[];const visitedLocal=/* @__PURE__ */ new Set;const visitedExternal=/* @__PURE__ */ new Set;const enqueueLocal=(moduleId,name)=>{const key=`${moduleId}::${name}`;if(visitedLocal.has(key))return;visitedLocal.add(key);queue.push({kind:`local`,moduleId,name})};const enqueueExternal=(importerId,source,exportName)=>{const key=`${importerId}::${source}::${exportName}`;if(visitedExternal.has(key))return;visitedExternal.add(key);queue.push({kind:`external`,importerId,source,exportName})};const seedFromCall=call=>{if(call.type===`ident`){const binding=pageModule.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(pageModule.id,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(pageModule.id,binding.source,`default`);else if(!binding&&pageModule.localFunctions.has(call.name))enqueueLocal(pageModule.id,call.name);return}const binding=pageModule.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(pageModule.id,binding.source,call.property)};for(const call of seedCalls)seedFromCall(call);let steps=0;const MAX_STEPS=128;while(queue.length&&steps<MAX_STEPS){steps+=1;const item=queue.shift();if(item.kind===`local`){if(item.moduleId!==pageModule.id)continue;const fn=pageModule.localFunctions.get(item.name);if(!fn)continue;for(const f of collectWevuHookCallsInFunctionBody(pageModule,fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(fn,pageModule.engine);for(const call of calls)seedFromCall(call);continue}const resolved=await resolveExternalFunction(resolver,item.importerId,item.source,item.exportName,moduleCache,{astEngine:options.astEngine});if(!resolved)continue;if(`reexport`in resolved){enqueueExternal(resolved.moduleId,resolved.reexport.source,resolved.reexport.importedName);continue}for(const f of collectWevuHookCallsInFunctionBody(resolved.module,resolved.fn))enabled.add(f);const calls=collectCalledBindingsFromFunctionBody(resolved.fn,resolved.module.engine);for(const call of calls)if(call.type===`ident`){const binding=resolved.module.importedBindings.get(call.name);if(binding?.kind===`named`)enqueueExternal(resolved.moduleId,binding.source,binding.importedName);else if(binding?.kind==="default")enqueueExternal(resolved.moduleId,binding.source,`default`);else if(!binding&&resolved.module.localFunctions.has(call.name)){const key=`${resolved.moduleId}::${call.name}`;if(!visitedLocal.has(key)){visitedLocal.add(key);const localFn=resolved.module.localFunctions.get(call.name);if(localFn){for(const f of collectWevuHookCallsInFunctionBody(resolved.module,localFn))enabled.add(f);for(const inner of collectCalledBindingsFromFunctionBody(localFn,resolved.module.engine))if(inner.type===`ident`){const innerBinding=resolved.module.importedBindings.get(inner.name);if(innerBinding?.kind===`named`)enqueueExternal(resolved.moduleId,innerBinding.source,innerBinding.importedName);else if(innerBinding?.kind==="default")enqueueExternal(resolved.moduleId,innerBinding.source,`default`)}}}}}else{const binding=resolved.module.importedBindings.get(call.object);if(binding?.kind===`namespace`)enqueueExternal(resolved.moduleId,binding.source,call.property)}}return enabled}async function collectWevuFeaturesFromSetupReachableImports(pageModule,setupFn,resolver,moduleCache,options){return await walkReachableWevuFeatures({pageModule,setupFn,resolver,moduleCache,astEngine:options?.astEngine})}async function collectWevuFeaturesFromCodeReachableImports(code,options){const{optionsObjects,module}=collectTargetOptionsObjectsFromCode(code,options.id,{astEngine:options.astEngine});if(!optionsObjects.length)return/* @__PURE__ */ new Set;const moduleCache=/* @__PURE__ */ new Map([[options.id,module]]);const enabled=/* @__PURE__ */ new Set;for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const reachable=await collectWevuFeaturesFromSetupReachableImports(module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const feature of reachable)enabled.add(feature)}return enabled}function injectWevuPageFeaturesInJs(source,options){const enabled=collectWevuPageFeatureFlagsFromCode(source,options);if(!enabled.size)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,`<inline>`);if(!optionsObjects.length)return{code:source,transformed:false};let changed=false;for(const target of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(target,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}async function injectWevuPageFeaturesInJsWithResolver(source,options){const preflight=collectTargetOptionsObjectsFromCode(source,options.id,{astEngine:options.astEngine});if(!preflight.optionsObjects.length)return{code:source,transformed:false};const ast=parseJsLike(source);const{optionsObjects}=collectTargetOptionsObjects(ast,options.id);if(!optionsObjects.length)return{code:source,transformed:false};const enabled=/* @__PURE__ */ new Set;for(const flag of collectWevuPageFeatureFlagsFromCode(source,options))enabled.add(flag);const moduleCache=/* @__PURE__ */ new Map;moduleCache.set(options.id,preflight.module);for(const optionsObject of optionsObjects){const setupFn=getSetupFunctionFromOptionsObject(optionsObject);if(!setupFn)continue;const fromImports=await collectWevuFeaturesFromSetupReachableImports(preflight.module,setupFn,options.resolver,moduleCache,{astEngine:options.astEngine});for(const flag of fromImports)enabled.add(flag)}if(!enabled.size)return{code:source,transformed:false};let changed=false;for(const optionsObject of optionsObjects)changed=injectWevuPageFeatureFlagsIntoOptionsObject(optionsObject,enabled)||changed;if(!changed)return{code:source,transformed:false};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.js`},source);return{code:generated.code,transformed:true,map:sourceMap?generated.map:null}}function createPageEntryMatcher(source){let cached;const warn=resolveWarnHandler(source.warn);async function ensure(){if(cached)return cached;let entries;try{entries=await source.loadEntries()}catch(error){const message=error instanceof Error?error.message:String(error);warn(`[wevu] 解析页面入口失败:${message}`);return/* @__PURE__ */ new Set}const set=/* @__PURE__ */ new Set;for(const pageEntry of entries.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,normalized))}for(const meta of entries.subPackages??[]){const root=meta.root??``;for(const pageEntry of meta.pages??[]){const normalized=stripLeadingSlashes(String(pageEntry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,root,normalized))}}for(const entry of entries.pluginPages??[]){const normalized=stripLeadingSlashes(String(entry));if(!normalized)continue;set.add(path.resolve(source.srcRoot,removeExtensionDeep(normalized)))}cached=set;return set}return{markDirty(){cached=void 0},async isPageFile(filePath){const pages=await ensure();const normalized=removeExtensionDeep(filePath);return pages.has(normalized)}}}function isDefineComponentCall(node,aliases){return t.isIdentifier(node.callee)&&aliases.has(node.callee.name)}function isObjectAssignCall$1(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function unwrapTypeLikeExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression$1(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression$1(node.expression);return node}function resolveObjectExpressionFromAssignCall(node){if(!isObjectAssignCall$1(node))return null;for(let index=node.arguments.length-1;index>=0;index-=1){const arg=node.arguments[index];if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const normalized=unwrapTypeLikeExpression$1(arg);if(t.isObjectExpression(normalized))return normalized}return null}function unwrapDefineComponent(node,aliases){if(t.isCallExpression(node)&&isDefineComponentCall(node,aliases)){const arg=node.arguments[0];if(t.isObjectExpression(arg))return arg}return null}function resolveComponentExpression(declaration,defineComponentDecls,aliases){if(!declaration)return null;if(t.isObjectExpression(declaration))return declaration;if(t.isCallExpression(declaration)&&isDefineComponentCall(declaration,aliases)){const arg=declaration.arguments[0];if(t.isObjectExpression(arg))return arg;if(t.isIdentifier(arg)){const matched=defineComponentDecls.get(arg.name);return matched?t.cloneNode(matched,true):null}if(t.isExpression(arg))return arg;return null}if(t.isCallExpression(declaration)&&isObjectAssignCall$1(declaration))return declaration;if(t.isIdentifier(declaration)){const matched=defineComponentDecls.get(declaration.name);return matched?t.cloneNode(matched,true):null}return null}function resolveComponentOptionsObject(componentExpr){if(!componentExpr)return null;const normalized=unwrapTypeLikeExpression$1(componentExpr);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized))return resolveObjectExpressionFromAssignCall(normalized);return null}function isScriptSetupReturnedObject(path){const parent=path.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id,{name:`__returned__`}))return true;if(parent?.isReturnStatement())return true;return false}function isTemplateReturnGetterReference(path){const objectMethod=path.findParent(parent=>parent.isObjectMethod());if(objectMethod?.isObjectMethod()&&objectMethod.node.kind===`get`&&!objectMethod.node.computed&&t.isIdentifier(objectMethod.node.key,{name:path.node.name})&&objectMethod.parentPath?.isObjectExpression()&&isScriptSetupReturnedObject(objectMethod.parentPath)){const getter=objectMethod.node.body.body.find(statement=>t.isReturnStatement(statement));return Boolean(getter&&t.isReturnStatement(getter)&&t.isIdentifier(getter.argument,{name:path.node.name}))}return false}function isTemplateReturnPropertyReference(path){const property=path.parentPath;if(!property?.isObjectProperty())return false;if(!property.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(property.parentPath)||property.node.computed)return false;const key=property.node.key;const value=property.node.value;if(!t.isIdentifier(value,{name:path.node.name}))return false;if(t.isIdentifier(key,{name:path.node.name})||t.isStringLiteral(key,{value:path.node.name}))return true;return false}function isStaticPropertyNamed(node,name){return!node.computed&&(t.isIdentifier(node.key,{name})||t.isStringLiteral(node.key,{value:name}))}function isOptionsApiComponentsObject(path){const componentsProperty=path.parentPath;if(!componentsProperty?.isObjectProperty()||!isStaticPropertyNamed(componentsProperty.node,`components`))return false;const optionsObject=componentsProperty.parentPath;if(!optionsObject?.isObjectExpression())return false;const optionsParent=optionsObject.parentPath;if(optionsParent?.isExportDefaultDeclaration())return true;return Boolean(optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===optionsObject.node&&optionsParent.parentPath?.isExportDefaultDeclaration())}function isOptionsApiComponentRegistrationReference(path){const property=path.parentPath;return Boolean(property?.isObjectProperty()&&property.node.value===path.node&&property.parentPath?.isObjectExpression()&&isOptionsApiComponentsObject(property.parentPath))}function isReferencedOutsideTemplateReturn(path){if(!path.isReferencedIdentifier())return false;if(isTemplateReturnGetterReference(path)||isTemplateReturnPropertyReference(path)||isOptionsApiComponentRegistrationReference(path))return false;return true}function collectReferencedNames(ast,candidateNames){const referencedNames=/* @__PURE__ */ new Set;traverse(ast,{Identifier(path){const name=path.node.name;if(!candidateNames.has(name))return;if(isReferencedOutsideTemplateReturn(path))referencedNames.add(name)}});return referencedNames}function removeSetupReturnProperties(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectMethod(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.key))return;const name=path.node.key.name;if(!removableNames.has(name))return;if(path.node.kind!==`get`)return;const getter=path.node.body.body.find(statement=>t.isReturnStatement(statement));if(!getter||!t.isReturnStatement(getter)||!t.isIdentifier(getter.argument,{name}))return;path.remove();changed=true},ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isScriptSetupReturnedObject(path.parentPath))return;if(path.node.computed||!t.isIdentifier(path.node.value))return;const name=path.node.value.name;if(!removableNames.has(name))return;if(!t.isIdentifier(path.node.key,{name})&&!t.isStringLiteral(path.node.key,{value:name}))return;path.remove();changed=true}});return changed}function removeOptionsApiComponentRegistrations(ast,removableNames){if(!removableNames.size)return false;let changed=false;traverse(ast,{ObjectProperty(path){if(!path.parentPath?.isObjectExpression()||!isOptionsApiComponentsObject(path.parentPath)||!t.isIdentifier(path.node.value)||!removableNames.has(path.node.value.name))return;path.remove();changed=true}});traverse(ast,{ObjectProperty(path){if(!t.isObjectExpression(path.node.value)||!isStaticPropertyNamed(path.node,`components`)||path.node.value.properties.length>0||!path.parentPath?.isObjectExpression())return;const optionsParent=path.parentPath.parentPath;if(optionsParent?.isExportDefaultDeclaration()||optionsParent?.isCallExpression()&&optionsParent.node.arguments[0]===path.parentPath.node&&optionsParent.parentPath?.isExportDefaultDeclaration())path.remove()}});return changed}function pruneTemplateComponentMeta(ast,templateComponentMeta){if(!Object.keys(templateComponentMeta).length)return false;const candidateNames=new Set(Object.keys(templateComponentMeta));const referencedNames=collectReferencedNames(ast,candidateNames);const removableNames=new Set([...candidateNames].filter(name=>!referencedNames.has(name)));let changed=false;traverse(ast,{ImportDeclaration(path){if(!path.node.specifiers.length)return;const kept=path.node.specifiers.filter(specifier=>{if(!(`local`in specifier)||!t.isIdentifier(specifier.local))return true;const localName=specifier.local.name;return!removableNames.has(localName)});if(kept.length!==path.node.specifiers.length){changed=true;if(kept.length===0){path.remove();return}path.node.specifiers=kept}}});changed=removeSetupReturnProperties(ast,removableNames)||changed;changed=removeOptionsApiComponentRegistrations(ast,removableNames)||changed;return changed}function vueSfcTransformPlugin(){return{name:`vue-sfc-transform`,visitor:{ImportDeclaration(path){if(path.node.source.value===`vue`){const specifiers=path.node.specifiers;const filteredSpecifiers=specifiers.filter(s=>{if(s.type===`ImportSpecifier`&&t.isIdentifier(s.imported)&&s.imported.name===WE_VU_RUNTIME_APIS.defineComponent)return false;return true});if(filteredSpecifiers.length===0)path.remove();else if(filteredSpecifiers.length!==specifiers.length)path.node.specifiers=filteredSpecifiers}},ObjectExpression(path){const filtered=path.node.properties.filter(p=>{if(p.type===`ObjectProperty`){const key=p.key;if(key.type===`Identifier`&&key.name===`__name`)return false}return true});path.node.properties=filtered},CallExpression(path){if(t.isMemberExpression(path.node.callee)&&t.isIdentifier(path.node.callee.object,{name:`Object`})&&t.isIdentifier(path.node.callee.property,{name:`defineProperty`})&&t.isIdentifier(path.node.arguments[0],{name:`__returned__`})&&t.isStringLiteral(path.node.arguments[1],{value:`__isScriptSetup`})&&path.parentPath?.isExpressionStatement()){path.parentPath.remove();return}if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()&&path.node.arguments.length===0)path.parentPath.remove()}}}}function createCollectVisitors(state){return{VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))state.defineComponentDecls.set(path.node.id.name,t.cloneNode(path.node.init,true));const unwrapped=unwrapDefineComponent(path.node.init,state.defineComponentAliases);if(unwrapped){state.defineComponentDecls.set(path.node.id.name,t.cloneNode(unwrapped,true));path.node.init=unwrapped;state.transformed=true}},ExportDefaultDeclaration(path){state.defaultExportPath=path}}}const RUNTIME_IMPORT_PATH=WE_VU_COMPILER_RUNTIME_MODULE_ID;const COMPILED_DEFINE_COMPONENT_IMPORT_RE=/^import\s+\{\s*defineComponent\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s+from\s+['"]vue['"];?\n/;const EXPORT_DEFAULT_PURE_RE=/export\s+default\s+\/\*@__PURE__\*\/\s*/;const JSON_MACRO_RE=/\bdefine(?:App|Page|Component|Sitemap|Theme)Json\s*\(/;const PAGE_META_RE=/\bdefinePageMeta\s*\(/;const OPTION_CAPABILITY_RE=/\b(?:createApp|createWevuComponent|setData|setWevuDefaults)\b/;const WEVU_RUNTIME_IMPORT_RE=/\bfrom\s*['"](?:wevu(?:\/internal-runtime)?|virtual:weapp-vite\/runtime)['"]/;const DYNAMIC_OPTIONS_PROPERTY_RE=/\.\.\.|\[/;function hasMetadataInjectionOptions(source,options){const hasWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0;return Boolean(options?.isTypeScript||options?.isApp||options?.skipComponentTransform||options?.minify||options?.sourceMap!==false||options?.templateComponentMeta||hasWevuDefaults||options?.classStyleBindings?.length||options?.templateRefs?.length||options?.layoutHosts?.length||options?.inlineExpressions?.length||options?.runtimeCapabilities?.required.length||options?.functionPropPaths?.length||options?.propsAliases||options?.propsDerivedKeys?.length||options?.relaxStructuredTypeOnlyProps||options?.bindingManifest||options?.pageLayout||options?.scopedSlotHostProperties||options?.stabilizeCssVarsRuntime||/\b(?:useSlots|options|extends|mixins|definitionFilter|behaviors)\b|\\/.test(source))}function findMatchingCallEnd(source,openParenIndex){let depth=0;let quote;let escaped=false;let lineComment=false;let blockComment=false;for(let index=openParenIndex;index<source.length;index+=1){const current=source[index];const next=source[index+1];if(lineComment){if(current===`
|
|
24
24
|
`||current===`\r`)lineComment=false;continue}if(blockComment){if(current===`*`&&next===`/`){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(current===`\\`)escaped=true;else if(current===quote)quote=void 0;continue}if(current===`/`&&next===`/`){lineComment=true;index+=1;continue}if(current===`/`&&next===`*`){blockComment=true;index+=1;continue}if(current===`"`||current===`'`||current==="`"){quote=current;continue}if(current===`(`){depth+=1;continue}if(current===`)`){depth-=1;if(depth===0)return index}}return-1}function stripCompiledScriptSetupMarkers(optionsSource){return optionsSource.replace(/^\s*__name:\s*['"][^'"]+['"],?\n?/m,``).replace(/\{\s*expose:\s*__expose\s*\}/g,`{ expose }`).replace(/\b__expose(?=\s*\()/g,`expose`).replace(/^\s*Object\.defineProperty\(\s*__returned__\s*,\s*['"]__isScriptSetup['"]\s*,\s*\{\s*enumerable:\s*false\s*,\s*value:\s*true\s*\}\s*\);?\n?/m,``)}function tryFastTransformCompiledScriptSetup(source,options){if(hasMetadataInjectionOptions(source,options))return;if(JSON_MACRO_RE.test(source)||PAGE_META_RE.test(source))return;const importMatch=source.match(COMPILED_DEFINE_COMPONENT_IMPORT_RE);if(!importMatch)return;const defineComponentLocal=importMatch[1];const afterImport=source.slice(importMatch[0].length);if(/from\s+['"]vue['"]/.test(afterImport))return;const exportMatch=EXPORT_DEFAULT_PURE_RE.exec(afterImport);if(!exportMatch||exportMatch.index<0)return;const beforeExport=afterImport.slice(0,exportMatch.index);const callStart=exportMatch.index+exportMatch[0].length;const expectedCall=`${defineComponentLocal}(`;if(!afterImport.startsWith(expectedCall,callStart))return;const openParenIndex=callStart+defineComponentLocal.length;const callEnd=findMatchingCallEnd(afterImport,openParenIndex);if(callEnd<0)return;const trailing=afterImport.slice(callEnd+1).trim();if(trailing&&trailing!==`;`)return;const componentOptions=stripCompiledScriptSetupMarkers(afterImport.slice(openParenIndex+1,callEnd).trim());if(!componentOptions.startsWith(`{`)||!componentOptions.endsWith(`}`)||OPTION_CAPABILITY_RE.test(source)||DYNAMIC_OPTIONS_PROPERTY_RE.test(componentOptions)||WEVU_RUNTIME_IMPORT_RE.test(source))return;const pageMarker=` __wevu_isPage: ${options?.isPage===true},\n`;return{code:[`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from "${RUNTIME_IMPORT_PATH}";`,beforeExport.trim(),`const __wevuOptions = {\n${pageMarker}${componentOptions.replace(/^\{\s*/,``).replace(/\s*\}$/,``)}\n};`,`export default __wevuOptions;`,`${WE_VU_RUNTIME_APIS.createWevuComponent}(__wevuOptions);`].filter(Boolean).join(`
|
|
25
|
-
`),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent={kind:`absent`};const unknown={kind:`unknown`};function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,next))}function resolve(node,scope,visited){node=unwrap(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent:unknown;let result=absent;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive(entry.key,resolved.scope):unknown;if(name.kind!==`known`)result=unknown;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive(entry.key,resolved.scope):unknown;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown,addGlobalClass:unknown};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent;return value.kind===`expression`?primitive(value.node,value.scope):unknown};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function buildInlineMapExpression(inlineExpressions){const entries=inlineExpressions.map(entry=>{const keysExpr=t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)));const exprAst=parseBabelExpression(entry.expression)??t.identifier(`undefined`);const{parameterNames}=entry;const fnExpr=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],exprAst);const entryObjProps=[t.objectProperty(t.identifier(`keys`),keysExpr),t.objectProperty(t.identifier(`fn`),fnExpr)];if(entry.indexBindings?.length){const indexKeysExpr=t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)));entryObjProps.push(t.objectProperty(t.identifier(`indexKeys`),indexKeysExpr))}if(entry.scopeResolvers?.length){const resolverMap=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));const resolverExpr=t.arrayExpression(entry.scopeKeys.map(key=>{const source=resolverMap.get(key);if(!source)return t.identifier(`undefined`);return parseBabelExpression(source)??t.identifier(`undefined`)}));entryObjProps.push(t.objectProperty(t.identifier(`scopeResolvers`),resolverExpr))}const entryObj=t.objectExpression(entryObjProps);return t.objectProperty(t.stringLiteral(entry.id),entryObj)});return t.objectExpression(entries)}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions){if(!inlineExpressions.length)return false;const inlineMapExpr=buildInlineMapExpression(inlineExpressions);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers)if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name);runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function createJsxDiagnostics(warnings,filename){return warnings.map(warning=>{return{code:`WV1003`,severity:`warning`,message:warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`,filename,source:`jsx`}})}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`normalizeJsxIsland`))],t.stringLiteral(`wevu`)));ast.program.body.unshift(t.importDeclaration([t.importSpecifier(t.identifier(`__wevuNormalizeClass`),t.identifier(`normalizeClass`)),t.importSpecifier(t.identifier(`__wevuNormalizeStyle`),t.identifier(`normalizeStyle`))],t.stringLiteral(`wevu/internal-template`)));return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function resolveFile(source,importer){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readFileSync(candidate,`utf8`)!==void 0)return candidate}catch{continue}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readFileSync(candidate,`utf8`)!==void 0)return candidate}catch{continue}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readFileSync(filename,`utf8`);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Teleport`){context.warnings.push(`小程序不支持 JSX <Teleport>,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}const DEFAULT_VUE_JSX_TRANSFORM_OPTIONS={enableObjectSlots:true,mergeProps:true,optimize:true,resolveType:false,transformOn:true};function readDirectiveExpression(attribute){if(!attribute.value)return t.booleanLiteral(true);if(!t.isJSXExpressionContainer(attribute.value)||t.isJSXEmptyExpression(attribute.value.expression))return;return t.isExpression(attribute.value.expression)?attribute.value.expression:void 0}function createWevuJsxDirectiveCompatibilityPlugin(){return{name:`wevu-jsx-directive-compatibility`,visitor:{JSXElement(path){const attributes=path.node.openingElement.attributes;let ifExpression;let textExpression;path.node.openingElement.attributes=attributes.filter(attribute=>{if(!t.isJSXAttribute(attribute))return true;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(name===`v-if`){ifExpression=readDirectiveExpression(attribute);return false}if(name===`v-text`){textExpression=readDirectiveExpression(attribute);return false}if(name?.startsWith(`v-`)&&![`v-html`,`v-model`,`v-models`,`v-show`,`v-slots`].includes(name))return false;return true});if(textExpression)path.node.children=[t.jsxExpressionContainer(textExpression)];if(ifExpression)path.replaceWith(t.conditionalExpression(ifExpression,path.node,t.nullLiteral()))}}}}function transformVueJsxScript(source,filename,sourceMaps=true,options){const result=transformSync(source,{filename,sourceType:`module`,sourceMaps,plugins:[createWevuJsxDirectiveCompatibilityPlugin,[vueJsxPlugin,{...DEFAULT_VUE_JSX_TRANSFORM_OPTIONS,...options}]],parserOpts:{plugins:[`typescript`,`jsx`]},generatorOpts:{retainLines:!sourceMaps}});return{code:result?.code??source,map:result?.map?{...result.map,file:result.map.file??void 0}:null}}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename):void 0;if(diagnostics&&options?.warn)diagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message));let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
|
|
25
|
+
`),map:null,transformed:true,componentStyleOptions:{styleIsolation:{kind:`absent`},addGlobalClass:{kind:`absent`}}}}function ensureRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.importKind!==`type`&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([t.importSpecifier(t.identifier(localName),t.identifier(importedName))],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport);return}if(!targetImport.specifiers.some(spec=>{if(!t.isImportSpecifier(spec)||spec.importKind===`type`)return false;if(!t.isIdentifier(spec.imported,{name:importedName}))return false;return t.isIdentifier(spec.local,{name:localName})}))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}const INTERNAL_RUNTIME_VALUE_EXPORTS=/* @__PURE__ */ new Set([`addMutationRecorder`,`batch`,`computed`,`createTextVNode`,`createVNode`,`createApp`,`createWevuComponent`,`createWevuScopedSlotComponent`,...Object.values(WE_VU_RUNTIME_CAPABILITY_INSTALLERS),`customRef`,`defineAppSetup`,`defineComponent`,`effect`,`effectScope`,`endBatch`,`getCurrentInstance`,`getCurrentPageStackSnapshot`,`getCurrentScope`,`getCurrentSetupContext`,`getDeepWatchStrategy`,`Fragment`,`getNavigationBarMetrics`,`getReactiveVersion`,`hasInjectionContext`,`inject`,`injectGlobal`,`isNoSetData`,`isProxy`,`isRaw`,`isReactive`,`isReadonly`,`isRef`,`isShallowReactive`,`isShallowRef`,`isVNode`,`markNoSetData`,`markRaw`,`mergeModels`,`mergeProps`,`mountRuntimeInstance`,`nextTick`,`normalizeClass`,`normalizeJsxIsland`,`normalizeStyle`,`onActivated`,`onAddToFavorites`,`onAttached`,`onBeforeMount`,`onBeforeUnmount`,`onBeforeUpdate`,`onDeactivated`,`onDetached`,`onError`,`onErrorCaptured`,`onHide`,`onLaunch`,`onLoad`,`onMemoryWarning`,`onMounted`,`onMoved`,`onPageNotFound`,`onPageScroll`,`onPullDownRefresh`,`onReachBottom`,`onReady`,`onResize`,`onRouteDone`,`onSaveExitState`,`onScopeDispose`,`onServerPrefetch`,`onShareAppMessage`,`onShareTimeline`,`onShow`,`onTabItemTap`,`onThemeChange`,`onUnhandledRejection`,`onUnload`,`onUnmounted`,`onUpdated`,`prelinkReactiveTree`,`provide`,`provideGlobal`,`reactive`,`resolveDirective`,`resolveComponent`,`readonly`,`ref`,`registerApp`,`registerComponent`,`removeMutationRecorder`,`resetWevuDefaults`,`resolveLayoutBridge`,`resolveLayoutHost`,`resolvePropValue`,`resolveRuntimePageLayoutName`,`runSetupFunction`,`setCurrentInstance`,`setCurrentSetupContext`,`setDeepWatchStrategy`,`setGlobalProvidedValue`,`setPageLayout`,`setRuntimeSetDataVisibility`,`setWevuDefaults`,`shallowReactive`,`shallowReadonly`,`shallowRef`,`startBatch`,`stop`,`syncRuntimePageLayoutState`,`syncRuntimePageLayoutStateFromRuntime`,`teardownRuntimeInstance`,`toRaw`,`toRef`,`toRefs`,`toValue`,`transformOn`,`touchReactive`,`traverse`,`triggerRef`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useAsyncDerivation`,`useAsyncPullDownRefresh`,`useBindModel`,`useBoundingClientRect`,`useChangeModel`,`useDisposables`,`useElementIntersectionObserver`,`useIntersectionObserver`,`useLayoutBridge`,`useLayoutHosts`,`useModel`,`useNativeInstance`,`useNativePageRouter`,`useNativeRouter`,`useNavigationBarMetrics`,`usePageLayout`,`usePageScrollThrottle`,`usePageStack`,`useScrollOffset`,`useSelectorFields`,`useSelectorQuery`,`useSlots`,`useTemplateRef`,`useUpdatePerformanceListener`,`version`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`,`waitForLayoutHost`,`watch`,`watchEffect`,`watchPostEffect`,`watchSyncEffect`]);function ensureInternalRuntimeImport(program,importedName,localName=importedName){const runtimeImportPath=resolveWevuInternalImportModuleId(importedName);let targetImport=program.body.find(node=>t.isImportDeclaration(node)&&node.source.value===runtimeImportPath);if(!targetImport){targetImport=t.importDeclaration([],t.stringLiteral(runtimeImportPath));program.body.unshift(targetImport)}if(!targetImport.specifiers.some(specifier=>t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:importedName})&&t.isIdentifier(specifier.local,{name:localName})))targetImport.specifiers.push(t.importSpecifier(t.identifier(localName),t.identifier(importedName)))}function splitWevuNamedImportsToInternalRuntime(path,program,state){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported)||!t.isIdentifier(specifier.local))return true;const importedName=specifier.imported.name;if(!INTERNAL_RUNTIME_VALUE_EXPORTS.has(importedName))return true;ensureInternalRuntimeImport(program,importedName,specifier.local.name);state.transformed=true;return false});if(remaining.length===0){path.remove();return}if(remaining.length!==path.node.specifiers.length)path.node.specifiers=remaining}function createImportVisitors(program,state){return{ImportDeclaration(path){if(path.node.source.value===`@vue/babel-helper-vue-transform-on`){const defaultImport=path.node.specifiers.find(specifier=>t.isImportDefaultSpecifier(specifier));if(defaultImport){ensureRuntimeImport(program,`transformOn`,defaultImport.local.name);state.transformed=true;path.remove();return}}if(path.node.source.value===`vue`){const movedVueRuntimeAPIs=/* @__PURE__ */ new Set([`createTextVNode`,`createVNode`,`Fragment`,`isVNode`,`mergeProps`,`resolveComponent`,`resolveDirective`,`unref`,`useAttrs`,`useCssModule`,`useCssVars`,`useSlots`,`useModel`,`mergeModels`,`useTemplateRef`,`vModelCheckbox`,`vModelRadio`,`vModelSelect`,`vModelText`,`vShow`,`withDirectives`]);const movedSpecifiers=[];const remaining=path.node.specifiers.filter(specifier=>{if(t.isImportSpecifier(specifier)&&specifier.imported.type===`Identifier`&&specifier.imported.name===WE_VU_RUNTIME_APIS.defineComponent){state.defineComponentAliases.add(specifier.local.name);state.transformed=true;return false}if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported)){const importedName=specifier.imported.name;if(movedVueRuntimeAPIs.has(importedName)&&t.isIdentifier(specifier.local)){movedSpecifiers.push({importedName,localName:specifier.local.name});state.transformed=true;return false}}return true});if(movedSpecifiers.length)for(const{importedName,localName}of movedSpecifiers)ensureRuntimeImport(program,importedName,localName);if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}if(path.node.importKind===`type`){state.transformed=true;path.remove();return}const kept=path.node.specifiers.filter(specifier=>{if(`importKind`in specifier&&specifier.importKind===`type`){state.transformed=true;return false}return true});if(kept.length!==path.node.specifiers.length){if(kept.length===0){path.remove();return}path.node.specifiers=kept}splitWevuNamedImportsToInternalRuntime(path,program,state)}}}function createAppSetupVisitors(program,state){return{CallExpression(path){if(!t.isIdentifier(path.node.callee,{name:WE_VU_RUNTIME_APIS.defineAppSetup}))return;ensureRuntimeImport(program,WE_VU_RUNTIME_APIS.defineAppSetup);state.transformed=true}}}function importedName(specifier){return t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value}function createPageMetaVisitors(ast,state){const macroCalls=new Set(collectPageMetaCallsForTransform(ast));return{ImportDeclaration(path){if(path.node.source.value!==`wevu`||path.node.importKind===`type`)return;const remaining=path.node.specifiers.filter(specifier=>{return!t.isImportSpecifier(specifier)||specifier.importKind===`type`||importedName(specifier)!==WEVU_DEFINE_PAGE_META_MACRO});if(remaining.length===path.node.specifiers.length)return;state.transformed=true;if(!remaining.length){path.remove();return}path.node.specifiers=remaining},CallExpression(path){if(!macroCalls.has(path.node)||!path.parentPath?.isExpressionStatement())return;path.parentPath.remove();state.transformed=true}}}function createSetupExposeVisitors(state){return{ObjectMethod(path){if(!t.isIdentifier(path.node.key,{name:`setup`})&&!t.isStringLiteral(path.node.key,{value:`setup`}))return;const params=path.node.params;if(params.length<2||!t.isObjectPattern(params[1]))return;const ctxParam=params[1];if(ctxParam.properties.some(property=>{if(!t.isObjectProperty(property))return false;return t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`__expose`})})&&path.scope.hasBinding(`__expose`)&&!path.scope.hasBinding(`expose`)){path.scope.rename(`__expose`,`expose`);state.transformed=true;for(const property of ctxParam.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.key,{name:`expose`})&&t.isIdentifier(property.value,{name:`expose`}))property.shorthand=true}}}}}function isOptionalPatternNode(node){return t.isIdentifier(node)||t.isAssignmentPattern(node)||t.isRestElement(node)||t.isArrayPattern(node)||t.isObjectPattern(node)||t.isVoidPattern(node)}function stripOptionalFlag(node){if(node?.optional!==true)return false;node.optional=false;return true}function stripOptionalFromPattern(pattern){if(!pattern)return false;if(t.isTSParameterProperty(pattern))return stripOptionalFromPattern(pattern.parameter);let changed=false;if(t.isIdentifier(pattern)||t.isAssignmentPattern(pattern)||t.isRestElement(pattern)||t.isArrayPattern(pattern)||t.isObjectPattern(pattern))changed=stripOptionalFlag(pattern)||changed;if(t.isIdentifier(pattern)||t.isVoidPattern(pattern))return changed;if(t.isAssignmentPattern(pattern)){if(isOptionalPatternNode(pattern.left))changed=stripOptionalFromPattern(pattern.left)||changed;return changed}if(t.isRestElement(pattern)){if(isOptionalPatternNode(pattern.argument))changed=stripOptionalFromPattern(pattern.argument)||changed;return changed}if(t.isObjectPattern(pattern)){for(const prop of pattern.properties)if(t.isRestElement(prop)){if(isOptionalPatternNode(prop.argument)&&stripOptionalFromPattern(prop.argument))changed=true}else if(t.isObjectProperty(prop)){if(isOptionalPatternNode(prop.value)&&stripOptionalFromPattern(prop.value))changed=true}return changed}if(t.isArrayPattern(pattern)){for(const element of pattern.elements)if(isOptionalPatternNode(element)&&stripOptionalFromPattern(element))changed=true}return changed}function stripTypeArguments(node){let stripped=false;if(node.typeParameters){node.typeParameters=null;stripped=true}if(node.typeArguments){node.typeArguments=null;stripped=true}return stripped}function createStripTypesVisitors(state){return{ExportNamedDeclaration(path){if(path.node.exportKind===`type`){state.transformed=true;path.remove();return}if(path.node.specifiers?.length){const remaining=path.node.specifiers.filter(spec=>{if(t.isExportSpecifier(spec))return spec.exportKind!==`type`;return true});if(remaining.length!==path.node.specifiers.length){state.transformed=true;if(remaining.length===0){path.remove();return}path.node.specifiers=remaining}}},CallExpression(path){if(t.isIdentifier(path.node.callee,{name:`__expose`})&&path.parentPath?.isExpressionStatement()){if(path.node.arguments.length===0){path.parentPath.remove();state.transformed=true;return}}if(stripTypeArguments(path.node))state.transformed=true},NewExpression(path){if(stripTypeArguments(path.node))state.transformed=true},ObjectProperty(path){if(t.isIdentifier(path.node.key,{name:`__name`})||t.isStringLiteral(path.node.key,{value:`__name`})){path.remove();state.transformed=true}},TSTypeAliasDeclaration(path){path.remove();state.transformed=true},TSInterfaceDeclaration(path){path.remove();state.transformed=true},TSEnumDeclaration(path){path.remove();state.transformed=true},TSModuleDeclaration(path){path.remove();state.transformed=true},TSImportEqualsDeclaration(path){path.remove();state.transformed=true},TSAsExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSSatisfiesExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAssertion(path){path.replaceWith(path.node.expression);state.transformed=true},TSNonNullExpression(path){path.replaceWith(path.node.expression);state.transformed=true},TSTypeAnnotation(path){path.remove();state.transformed=true},TSParameterProperty(path){path.replaceWith(path.node.parameter);state.transformed=true},Function(path){if(t.isIdentifier(path.node.params[0],{name:`this`})){path.node.params.shift();state.transformed=true}if(path.node.returnType){path.node.returnType=null;state.transformed=true}if(stripTypeArguments(path.node))state.transformed=true;for(const param of path.node.params)if(stripOptionalFromPattern(param))state.transformed=true},ClassMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateMethod(path){if(stripOptionalFlag(path.node))state.transformed=true},ClassAccessorProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true},ClassPrivateProperty(path){if(path.node.typeAnnotation){path.node.typeAnnotation=null;state.transformed=true}if(stripOptionalFlag(path.node))state.transformed=true}}}function createMacroVisitors(ast,state){const appSetupVisitors=createAppSetupVisitors(ast.program,state);const setupExposeVisitors=createSetupExposeVisitors(state);const stripTypesVisitors=createStripTypesVisitors(state);const pageMetaVisitors=createPageMetaVisitors(ast,state);const mergedVisitors={...appSetupVisitors,...setupExposeVisitors,...stripTypesVisitors,...pageMetaVisitors};mergedVisitors.CallExpression=path=>{appSetupVisitors.CallExpression?.(path);setupExposeVisitors.CallExpression?.(path);stripTypesVisitors.CallExpression?.(path);if(!path.removed)pageMetaVisitors.CallExpression?.(path)};return mergedVisitors}const absent={kind:`absent`};const unknown={kind:`unknown`};function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function isFactoryCall(path){if(!path.isCallExpression()||!t.isIdentifier(path.node.callee))return false;const binding=path.scope.getBinding(path.node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeReference(reference,visiting){let current=reference;while(current.parentPath){const parent=current.parentPath;if(parent.isExportDefaultDeclaration())return true;if(parent.isVariableDeclarator()&&t.isIdentifier(parent.node.id))return isSafeBinding(parent.scope.getBinding(parent.node.id.name),visiting);if(parent.isCallExpression()&&isFactoryCall(parent)){current=parent;continue}if(parent.isObjectProperty()&&!parent.node.computed||parent.isObjectExpression()||parent.isSpreadElement()||parent.isTSAsExpression()||parent.isTSSatisfiesExpression()||parent.isTSNonNullExpression()||parent.isParenthesizedExpression()){current=parent;continue}return false}return false}function isSafeBinding(binding,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration())return false;if(visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,next))}function resolve(node,scope,visited){node=unwrap(node);if(!t.isIdentifier(node)||node.name===`undefined`&&!scope?.getBinding(`undefined`))return{kind:`expression`,node,scope};const binding=scope?.getBinding(node.name);if(!isSafeBinding(binding)||!binding?.path.isVariableDeclarator()||visited.has(binding.path.node)||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;return resolve(binding.path.node.init,binding.path.scope,new Set(visited).add(binding.path.node))}function primitive(node,scope){const resolved=resolve(node,scope,/* @__PURE__ */ new Set);if(!resolved)return unknown;const value=resolved.node;if(t.isStringLiteral(value)||t.isBooleanLiteral(value)||t.isNumericLiteral(value))return{kind:`known`,value:value.value};if(t.isNullLiteral(value))return{kind:`known`,value:null};if(t.isTemplateLiteral(value)&&value.expressions.length===0)return{kind:`known`,value:value.quasis[0]?.value.cooked??value.quasis[0]?.value.raw??``};if(t.isIdentifier(value,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`))return{kind:`known`,value:void 0};if(t.isUnaryExpression(value)&&t.isNumericLiteral(value.argument)){if(value.operator===`void`)return{kind:`known`,value:void 0};if(value.operator===`-`||value.operator===`+`)return{kind:`known`,value:value.operator===`-`?-value.argument.value:value.argument.value}}return unknown}function resolveStaticObjectProperty(node,key,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return unknown;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&!resolved.scope?.getBinding(`Object`)&&t.isIdentifier(current.callee.property,{name:`assign`})){let result=absent;for(const argument of current.arguments){const part=t.isExpression(argument)?resolveStaticObjectProperty(argument,key,resolved.scope,next):unknown;if(part.kind!==`absent`)result=part}return result}if(!t.isObjectExpression(current))return t.isNullLiteral(current)||t.isStringLiteral(current)||t.isBooleanLiteral(current)||t.isNumericLiteral(current)||t.isIdentifier(current,{name:`undefined`})&&!resolved.scope?.getBinding(`undefined`)?absent:unknown;let result=absent;for(const entry of current.properties){if(t.isSpreadElement(entry)){const part=resolveStaticObjectProperty(entry.argument,key,resolved.scope,next);if(part.kind!==`absent`)result=part;continue}const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive(entry.key,resolved.scope):unknown;if(name.kind!==`known`)result=unknown;else if(String(name.value)===key)result=t.isObjectProperty(entry)&&t.isExpression(entry.value)?{kind:`expression`,node:entry.value,scope:resolved.scope,property:entry}:unknown}return result}function isSafeAssignOperand(node,scope,visited){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node)||!t.isObjectExpression(resolved.node))return false;const next=new Set(visited).add(resolved.node);return resolved.node.properties.every(entry=>{if(t.isSpreadElement(entry))return isSafeAssignOperand(entry.argument,resolved.scope,next);if(t.isObjectMethod(entry)&&entry.kind!==`method`)return false;const name=!entry.computed&&t.isIdentifier(entry.key)?{kind:`known`,value:entry.key.name}:t.isExpression(entry.key)?primitive(entry.key,resolved.scope):unknown;return name.kind===`known`&&name.value!==`__proto__`})}function hasUnsafeObjectEvaluation(node,scope,visited=/* @__PURE__ */ new Set){const resolved=resolve(node,scope,visited);if(!resolved||visited.has(resolved.node))return false;const current=resolved.node;const next=new Set(visited).add(current);if(t.isCallExpression(current)&&t.isMemberExpression(current.callee)&&!current.callee.computed&&t.isIdentifier(current.callee.object,{name:`Object`})&&t.isIdentifier(current.callee.property,{name:`assign`}))return Boolean(resolved.scope?.getBinding(`Object`))||current.arguments.some(argument=>!t.isExpression(argument)||!isSafeAssignOperand(argument,resolved.scope,/* @__PURE__ */ new Set)||hasUnsafeObjectEvaluation(argument,resolved.scope,next));if(t.isObjectExpression(current))return current.properties.some(entry=>{if(t.isSpreadElement(entry)){const operand=resolve(entry.argument,resolved.scope,next);return Boolean(operand&&t.isObjectExpression(operand.node)&&!isSafeAssignOperand(entry.argument,resolved.scope,next))||hasUnsafeObjectEvaluation(entry.argument,resolved.scope,next)}return t.isObjectProperty(entry)&&t.isExpression(entry.value)&&hasUnsafeObjectEvaluation(entry.value,resolved.scope,next)});return false}function analyzeComponentStyleOptions(node,scope){if(!node)return{styleIsolation:unknown,addGlobalClass:unknown};if(hasUnsafeObjectEvaluation(node,scope))return;const options=resolveStaticObjectProperty(node,`options`,scope);if([`definitionFilter`,`behaviors`,`extends`,`mixins`,`__proto__`].some(key=>resolveStaticObjectProperty(node,key,scope).kind!==`absent`))return;const read=key=>{const value=options.kind===`expression`?resolveStaticObjectProperty(options.node,key,options.scope):options;if(value.kind===`absent`)return absent;return value.kind===`expression`?primitive(value.node,value.scope):unknown};return{styleIsolation:read(`styleIsolation`),addGlobalClass:read(`addGlobalClass`)}}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function isStaticObjectKeyMatch(key,expected){if(t.isIdentifier(key))return key.name===expected;if(t.isStringLiteral(key))return key.value===expected;return false}function getObjectPropertyByKey$2(node,key){for(const prop of node.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;if(isStaticObjectKeyMatch(prop.key,key))return prop}return null}function createStaticObjectKey(key){return t.isValidIdentifier(key)?t.identifier(key):t.stringLiteral(key)}function mergeStableKeys(target,incoming){const seen=new Set(target);for(const key of incoming){if(!key||seen.has(key))continue;seen.add(key);target.push(key)}}function resolveOutputRoot(outputPath){return/^[A-Z_$][\w$]*/i.exec(outputPath)?.[0]}function resolveBindingManifestPickKeys(manifest,autoSetDataPick){const keys=[];if(!isBindingManifestComplete(manifest))return keys;const outputRoots=manifest.bindings.flatMap(binding=>{const root=resolveOutputRoot(binding.outputPath);return root?[root]:[]});if(manifest.bindings.some(binding=>{return binding.updateMode===`snapshot-fallback`&&!resolveOutputRoot(binding.outputPath)}))return keys;const requiresScopedSlotOwner=manifest.bindings.some(binding=>{return binding.outputPath===WEVU_SLOT_OWNER_ID_KEY||binding.outputPath===WEVU_SLOT_OWNER_ID_PROP});if(autoSetDataPick||requiresScopedSlotOwner)mergeStableKeys(keys,outputRoots);if(autoSetDataPick)mergeStableKeys(keys,[WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);if(requiresScopedSlotOwner)mergeStableKeys(keys,[WEVU_SLOT_OWNER_ID_KEY,WEVU_SLOT_NAMES_PROP,WEVU_SLOT_OWNER_ID_PROP,WEVU_SLOT_SCOPE_KEY]);return keys}function mergePickArray(array,keys){const existing=/* @__PURE__ */ new Set;for(const element of array.elements)if(t.isStringLiteral(element))existing.add(element.value);let changed=false;for(const key of keys){if(existing.has(key))continue;existing.add(key);array.elements.push(t.stringLiteral(key));changed=true}return changed}function injectSetDataPick(componentOptions,keys){if(!keys.length)return false;const pickArray=()=>t.arrayExpression(keys.map(key=>t.stringLiteral(key)));const setDataProp=getObjectPropertyByKey$2(componentOptions,`setData`);if(!setDataProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`setData`),t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray())])));return true}if(t.isObjectExpression(setDataProp.value)){const pickProp=getObjectPropertyByKey$2(setDataProp.value,`pick`);if(!pickProp){setDataProp.value.properties.unshift(t.objectProperty(t.identifier(`pick`),pickArray()));return true}return t.isArrayExpression(pickProp.value)&&mergePickArray(pickProp.value,keys)}if(t.isIdentifier(setDataProp.value)||t.isMemberExpression(setDataProp.value)||t.isCallExpression(setDataProp.value)){setDataProp.value=t.objectExpression([t.objectProperty(t.identifier(`pick`),pickArray()),t.spreadElement(t.cloneNode(setDataProp.value,true))]);return true}return false}function injectManifestMetadata(componentOptions,manifest,mode){const serialized=createRuntimeBindingManifest(manifest,mode);const value=t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`freeze`)),[t.valueToNode(serialized)]);const existing=getObjectPropertyByKey$2(componentOptions,WEVU_BINDING_MANIFEST_KEY);if(existing){existing.value=value;return true}componentOptions.properties.push(t.objectProperty(t.stringLiteral(WEVU_BINDING_MANIFEST_KEY),value));return true}function injectLayoutComputed(componentOptions,plan){const runtimeEntries=Object.entries(plan?.currentLayout?.props??{}).filter(entry=>{const value=entry[1];return typeof value===`object`&&value!==null&&value.kind===`expression`});if(!runtimeEntries.length)return false;const computedEntries=runtimeEntries.map(([key,value])=>{const expression=parseBabelExpression(value.expression)??t.identifier(`undefined`);return t.objectProperty(createStaticObjectKey(`${WEVU_LAYOUT_BIND_PREFIX}${key}`),t.functionExpression(null,[],t.blockStatement([t.tryStatement(t.blockStatement([t.returnStatement(t.cloneNode(expression,true))]),t.catchClause(t.identifier(WEVU_EXPRESSION_ERROR_IDENTIFIER),t.blockStatement([t.returnStatement(t.identifier(`undefined`))])))])))});const computedProp=getObjectPropertyByKey$2(componentOptions,`computed`);if(!computedProp){componentOptions.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression(computedEntries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...computedEntries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...computedEntries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}return false}function injectBindingManifestContract(componentOptions,options){let changed=injectLayoutComputed(componentOptions,options.pageLayout);if(!options.manifest)return changed;changed=injectManifestMetadata(componentOptions,options.manifest,options.runtimeBindingManifest??`compact`)||changed;changed=injectSetDataPick(componentOptions,resolveBindingManifestPickKeys(options.manifest,options.autoSetDataPick===true))||changed;return changed}function injectClassStyleComputed(optionsObject,bindings,propsAliases,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const helpers={normalizeClass:t.identifier(`__wevuNormalizeClass`),normalizeStyle:t.identifier(`__wevuNormalizeStyle`),unref:t.identifier(`__wevuUnref`),resolvePropValue:t.identifier(`__wevuResolvePropValue`)};const entries=buildClassStyleComputedEntries(bindings,helpers,propsAliases);if(!entries.length)return false;const computedProp=getObjectPropertyByKey$2(optionsObject,`computed`);if(!computedProp){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(`computed`),t.objectExpression(entries)));return true}if(t.isObjectExpression(computedProp.value)){computedProp.value.properties.push(...entries);return true}if(t.isIdentifier(computedProp.value)||t.isMemberExpression(computedProp.value)){computedProp.value=t.objectExpression([...entries,t.spreadElement(t.cloneNode(computedProp.value,true))]);return true}warnHandler(`无法自动注入 class/style 计算属性,请手动合并 computed。`);return false}function ensureClassStyleRuntimeImports(program){ensureRuntimeImport(program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(program,`normalizeStyle`,`__wevuNormalizeStyle`);ensureRuntimeImport(program,`unref`,`__wevuUnref`);ensureRuntimeImport(program,`resolvePropValue`,`__wevuResolvePropValue`)}function unwrapExpression$1(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return unwrapExpression$1(node.expression);return node}function resolveSetupFunction$1(componentOptionsObject){for(const prop of componentOptionsObject.properties){if(t.isObjectMethod(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`setup`))return prop;if(!t.isObjectProperty(prop)||prop.computed||!isStaticObjectKeyMatch(prop.key,`setup`))continue;const value=unwrapExpression$1(prop.value);if(t.isFunctionExpression(value)||t.isArrowFunctionExpression(value))return value}return null}function isComponentMetaObject(node){return node.properties.some(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&isStaticObjectKeyMatch(prop.key,`__weappViteUsingComponent`)&&t.isBooleanLiteral(prop.value,{value:true})})}function isSerializableSeed(node){const normalized=unwrapExpression$1(node);if(t.isStringLiteral(normalized)||t.isNumericLiteral(normalized)||t.isBooleanLiteral(normalized)||t.isNullLiteral(normalized))return true;if(t.isTemplateLiteral(normalized))return normalized.expressions.length===0;if(t.isArrayExpression(normalized))return normalized.elements.every(element=>!!element&&!t.isSpreadElement(element)&&isSerializableSeed(element));if(t.isObjectExpression(normalized)){if(isComponentMetaObject(normalized))return false;return normalized.properties.every(prop=>{return t.isObjectProperty(prop)&&!prop.computed&&!t.isPatternLike(prop.value)&&isSerializableSeed(prop.value)})}return false}function extractSeedExpression(node){const normalized=unwrapExpression$1(node);if(t.isCallExpression(normalized)&&t.isIdentifier(normalized.callee)&&[`ref`,`shallowRef`,`reactive`].includes(normalized.callee.name)){const firstArg=normalized.arguments[0];if(firstArg&&!t.isSpreadElement(firstArg)&&t.isExpression(firstArg)&&isSerializableSeed(firstArg))return t.cloneNode(unwrapExpression$1(firstArg),true);return null}if(!isSerializableSeed(normalized))return null;return t.cloneNode(normalized,true)}function collectSetupInitializers(setupBody){const initializers=/* @__PURE__ */ new Map;for(const statement of setupBody.body){if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init||!t.isExpression(declarator.init))continue;initializers.set(declarator.id.name,declarator.init)}}return initializers}function resolveReturnedObjectExpression(setupBody,initializers){for(let index=setupBody.body.length-1;index>=0;index-=1){const statement=setupBody.body[index];if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const returned=unwrapExpression$1(statement.argument);if(t.isObjectExpression(returned))return returned;if(t.isIdentifier(returned)){const initializer=initializers.get(returned.name);if(initializer){const normalized=unwrapExpression$1(initializer);if(t.isObjectExpression(normalized))return normalized}}}return null}function resolvePropertyName(node){if(t.isIdentifier(node.key)&&!node.computed)return node.key.name;if(t.isStringLiteral(node.key)&&!node.computed)return node.key.value;return null}function injectSetupInitialData(componentOptionsObject){if(getObjectPropertyByKey$2(componentOptionsObject,`data`))return false;const setupFn=resolveSetupFunction$1(componentOptionsObject);if(!setupFn||!t.isBlockStatement(setupFn.body))return false;const initializers=collectSetupInitializers(setupFn.body);const returnedObject=resolveReturnedObjectExpression(setupFn.body,initializers);if(!returnedObject)return false;const seedProperties=[];for(const prop of returnedObject.properties){if(!t.isObjectProperty(prop)||prop.computed)continue;const propertyName=resolvePropertyName(prop);if(!propertyName)continue;let sourceExpression=null;if(prop.shorthand&&t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??null;else if(t.isIdentifier(prop.value))sourceExpression=initializers.get(prop.value.name)??prop.value;else if(t.isExpression(prop.value))sourceExpression=prop.value;if(!sourceExpression)continue;const seedExpression=extractSeedExpression(sourceExpression);if(!seedExpression)continue;seedProperties.push(t.objectProperty(createStaticObjectKey(propertyName),seedExpression))}if(!seedProperties.length)return false;componentOptionsObject.properties.unshift(t.objectMethod(`method`,createStaticObjectKey(`data`),[],t.blockStatement([t.returnStatement(t.objectExpression(seedProperties))])));return true}function resolveImportedLocalName(program,source,importedName){for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||statement.source.value!==source)continue;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported,{name:importedName}))return specifier.local.name}}function createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName){return t.expressionStatement(t.callExpression(t.identifier(useCssVarsLocalName),[t.arrowFunctionExpression([],t.blockStatement([t.expressionStatement(t.callExpression(t.identifier(unrefLocalName),[t.identifier(`undefined`)])),t.returnStatement(t.objectExpression([]))]))]))}function injectStableCssVarsRuntime(program,componentOptionsObject,scope){const runtimeImportPath=resolveWevuInternalImportModuleId(`useCssVars`);const reactivityImportPath=resolveWevuInternalImportModuleId(`unref`);const useCssVarsLocalName=resolveImportedLocalName(program,runtimeImportPath,`useCssVars`)??scope.generateUidIdentifier(`useCssVars`).name;const unrefLocalName=resolveImportedLocalName(program,reactivityImportPath,`unref`)??scope.generateUidIdentifier(`unref`).name;if(!resolveImportedLocalName(program,runtimeImportPath,`useCssVars`))ensureRuntimeImport(program,`useCssVars`,useCssVarsLocalName);if(!resolveImportedLocalName(program,reactivityImportPath,`unref`))ensureRuntimeImport(program,`unref`,unrefLocalName);const registration=createEmptyCssVarsRegistration(useCssVarsLocalName,unrefLocalName);const setupFn=resolveSetupFunction$1(componentOptionsObject);if(setupFn){const body=setupFn.body;if(t.isBlockStatement(body))body.body.unshift(registration);else setupFn.body=t.blockStatement([registration,t.returnStatement(body)]);return true}componentOptionsObject.properties.push(t.objectMethod(`method`,t.identifier(`setup`),[],t.blockStatement([registration,t.returnStatement(t.objectExpression([]))])));return true}function resolveDefaultsTarget(node){if(t.isObjectExpression(node))return node;if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node))return resolveDefaultsTarget(node.expression);if(t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&t.isIdentifier(node.callee.property,{name:`assign`})){const first=node.arguments[0];return first&&t.isExpression(first)?resolveDefaultsTarget(first):void 0}}function applyDefaultsToExpression(expression,defaults,merge){let changed=false;const fallback=resolveDefaultsTarget(expression);for(const[key,value]of Object.entries(defaults)){const effective=resolveStaticObjectProperty(expression,key,void 0);if(effective.kind===`expression`&&effective.property){const normalized=t.objectProperty(t.stringLiteral(key),effective.property.value);changed=merge(t.objectExpression([normalized]),{[key]:value})||changed;effective.property.value=normalized.value}else if(effective.kind===`absent`&&fallback)changed=merge(fallback,{[key]:value})||changed;else if(effective.kind===`unknown`&&fallback)changed=merge(fallback,{[key]:value})||changed}return changed}function mergePlainDefaultsIntoObjectExpression(target,defaults){const entries=Object.entries(defaults);if(!entries.length)return false;let changed=false;const injectedProps=[];for(const[key,value]of entries){if(getObjectPropertyByKey$2(target,key))continue;injectedProps.push(t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)))}if(!injectedProps.length)return false;target.properties.splice(0,0,...injectedProps);changed=true;return changed}function mergeNestedDefaults(optionsObject,key,defaultsValue){if(!isPlainRecord(defaultsValue)){if(defaultsValue===void 0)return false;if(getObjectPropertyByKey$2(optionsObject,key))return false;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}const existing=getObjectPropertyByKey$2(optionsObject,key);if(!existing){optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(defaultsValue)));return true}if(t.isObjectExpression(existing.value))return mergePlainDefaultsIntoObjectExpression(existing.value,defaultsValue);if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){const injected=t.valueToNode(defaultsValue);if(t.isObjectExpression(injected)){injected.properties.push(t.spreadElement(t.cloneNode(existing.value,true)));existing.value=injected;return true}}return false}function applyWevuDefaultsToOptionsObject(optionsObject,defaults){let changed=false;for(const[key,value]of Object.entries(defaults)){if(key===`setData`||key===`options`){changed=mergeNestedDefaults(optionsObject,key,value)||changed;continue}if(value===void 0||getObjectPropertyByKey$2(optionsObject,key))continue;optionsObject.properties.splice(0,0,t.objectProperty(createStaticObjectKey(key),t.valueToNode(value)));changed=true}return changed}function stripVirtualHostFromDefaults(defaults){const next={...defaults};const options=next.options;if(!isPlainRecord(options))return next;if(!hasOwn(options,`virtualHost`))return next;const copiedOptions={...options};delete copiedOptions.virtualHost;if(Object.keys(copiedOptions).length>0)next.options=copiedOptions;else delete next.options;return next}function serializeWevuDefaults(defaults,warn){const warnHandler=resolveWarnHandler(warn);const seen=/* @__PURE__ */ new Set;try{return JSON.stringify(defaults,(_key,value)=>{if(typeof value===`function`||typeof value===`symbol`||typeof value===`bigint`)throw new TypeError(`Wevu defaults 必须可被 JSON 序列化。`);if(value&&typeof value===`object`){if(seen.has(value))throw new Error(`Wevu defaults 不能包含循环引用。`);seen.add(value);if(!Array.isArray(value)&&!isPlainRecord(value))throw new Error(`Wevu defaults 只能是普通对象或数组。`)}return value})}catch(error){warnHandler(`[vue] 序列化 wevu defaults 失败:${error instanceof Error?error.message:String(error)}`);return}}function insertWevuDefaultsCall(program,serializedDefaults){const callStatement=t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.setWevuDefaults),[t.valueToNode(JSON.parse(serializedDefaults))]));let insertIndex=0;while(insertIndex<program.body.length&&t.isImportDeclaration(program.body[insertIndex]))insertIndex+=1;program.body.splice(insertIndex,0,callStatement)}function applyWevuDefaultsToComponentOptions(params){const{componentExpr,parsedWevuDefaults,options}=params;let changed=false;if(options?.isApp&&parsedWevuDefaults.app&&Object.keys(parsedWevuDefaults.app).length>0)changed=applyDefaultsToExpression(componentExpr,parsedWevuDefaults.app,applyWevuDefaultsToOptionsObject)||changed;if(!options?.isApp&&parsedWevuDefaults.component&&Object.keys(parsedWevuDefaults.component).length>0){const componentDefaults=options?.isPage?stripVirtualHostFromDefaults(parsedWevuDefaults.component):parsedWevuDefaults.component;if(Object.keys(componentDefaults).length>0)changed=applyDefaultsToExpression(componentExpr,componentDefaults,applyWevuDefaultsToOptionsObject)||changed}const componentOptionDefaults=parsedWevuDefaults.component?.options;if(options?.isPage&&isPlainRecord(componentOptionDefaults)&&componentOptionDefaults.virtualHost===true)changed=applyDefaultsToExpression(componentExpr,{options:{virtualHost:false}},applyWevuDefaultsToOptionsObject)||changed;return changed}function injectWevuDefaultsForApp(params){const{astProgram,options,serializedWevuDefaults}=params;let changed=false;if(options?.isApp&&serializedWevuDefaults){ensureRuntimeImport(astProgram,WE_VU_RUNTIME_APIS.setWevuDefaults);insertWevuDefaultsCall(astProgram,serializedWevuDefaults);changed=true}return changed}function rewriteComponentExport(params){const{ast,exportPath,componentExpr,isAppFile,skipComponentTransform}=params;const DEFAULT_OPTIONS_IDENTIFIER=`__wevuOptions`;if(isAppFile){ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createApp);exportPath.replaceWith(t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createApp),[componentExpr])));return true}if(skipComponentTransform){exportPath.replaceWith(t.exportDefaultDeclaration(componentExpr));return true}ensureRuntimeImport(ast.program,WE_VU_RUNTIME_APIS.createWevuComponent);exportPath.replaceWithMultiple([t.variableDeclaration(`const`,[t.variableDeclarator(t.identifier(DEFAULT_OPTIONS_IDENTIFIER),componentExpr)]),t.expressionStatement(t.callExpression(t.identifier(WE_VU_RUNTIME_APIS.createWevuComponent),[t.identifier(DEFAULT_OPTIONS_IDENTIFIER)])),t.exportDefaultDeclaration(t.identifier(DEFAULT_OPTIONS_IDENTIFIER))]);return true}function buildInlineMapExpression(inlineExpressions){const entries=inlineExpressions.map(entry=>{const keysExpr=t.arrayExpression(entry.scopeKeys.map(key=>t.stringLiteral(key)));const exprAst=parseBabelExpression(entry.expression)??t.identifier(`undefined`);const{parameterNames}=entry;const fnExpr=t.arrowFunctionExpression([t.identifier(parameterNames.context),t.identifier(parameterNames.scope),t.identifier(parameterNames.event)],exprAst);const entryObjProps=[t.objectProperty(t.identifier(`keys`),keysExpr),t.objectProperty(t.identifier(`fn`),fnExpr)];if(entry.indexBindings?.length){const indexKeysExpr=t.arrayExpression(entry.indexBindings.map(binding=>t.stringLiteral(binding.key)));entryObjProps.push(t.objectProperty(t.identifier(`indexKeys`),indexKeysExpr))}if(entry.scopeResolvers?.length){const resolverMap=new Map(entry.scopeResolvers.map(item=>[item.key,item.expression]));const resolverExpr=t.arrayExpression(entry.scopeKeys.map(key=>{const source=resolverMap.get(key);if(!source)return t.identifier(`undefined`);return parseBabelExpression(source)??t.identifier(`undefined`)}));entryObjProps.push(t.objectProperty(t.identifier(`scopeResolvers`),resolverExpr))}const entryObj=t.objectExpression(entryObjProps);return t.objectProperty(t.stringLiteral(entry.id),entryObj)});return t.objectExpression(entries)}function buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr){const spreadSources=[];for(const prop of componentExpr.properties){if(!t.isSpreadElement(prop)||!t.isExpression(prop.argument))continue;const methodsAccess=t.optionalMemberExpression(t.cloneNode(prop.argument),t.identifier(`methods`),false,true);spreadSources.push(t.logicalExpression(`||`,methodsAccess,t.objectExpression([])))}if(!spreadSources.length)return null;return t.callExpression(t.memberExpression(t.identifier(`Object`),t.identifier(`assign`)),[t.objectExpression([]),...spreadSources,t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])])}function injectInlineExpressions(componentExpr,inlineExpressions){if(!inlineExpressions.length)return false;const inlineMapExpr=buildInlineMapExpression(inlineExpressions);const methodsProp=getObjectPropertyByKey$2(componentExpr,`methods`);if(!methodsProp){const mergedMethods=buildMethodsMergeFromSpreadSources(componentExpr,inlineMapExpr);if(mergedMethods){componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),mergedMethods));return true}componentExpr.properties.push(t.objectProperty(createStaticObjectKey(`methods`),t.objectExpression([t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr)])));return true}if(!t.isObjectExpression(methodsProp.value))return false;const mapProp=getObjectPropertyByKey$2(methodsProp.value,WEVU_INLINE_MAP_KEY);if(!mapProp){methodsProp.value.properties.push(t.objectProperty(createStaticObjectKey(WEVU_INLINE_MAP_KEY),inlineMapExpr));return true}if(t.isObjectExpression(mapProp.value)){mapProp.value.properties.push(...inlineMapExpr.properties);return true}return false}function buildLayoutHostEntry(binding){const props=[t.objectProperty(t.identifier(`key`),t.stringLiteral(binding.key))];if(binding.refName)props.push(t.objectProperty(t.identifier(`refName`),t.stringLiteral(binding.refName)));props.push(t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)));if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectLayoutHosts(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildLayoutHostEntry(binding));const hostsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_LAYOUT_HOSTS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_LAYOUT_HOSTS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,hostsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 layout host 元数据,请手动合并 ${WEVU_LAYOUT_HOSTS_KEY}。`);return false}function injectPropsAliases(optionsObject,propsAliases){const entries=Object.entries(propsAliases??{}).filter(([alias,propName])=>alias&&propName).map(([alias,propName])=>{return t.objectProperty(createStaticObjectKey(alias),t.stringLiteral(propName))});if(!entries.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_ALIASES_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_ALIASES_KEY),t.objectExpression(entries)));return true}function injectPropsDerivedKeys(optionsObject,propsDerivedKeys){const keys=[...new Set(propsDerivedKeys??[])].filter(Boolean);if(!keys.length)return false;if(getObjectPropertyByKey$2(optionsObject,WEVU_PROPS_DERIVED_KEYS_KEY))return false;optionsObject.properties.push(t.objectProperty(createStaticObjectKey(WEVU_PROPS_DERIVED_KEYS_KEY),t.arrayExpression(keys.map(key=>t.stringLiteral(key)))));return true}function buildTemplateRefEntry(binding){const props=[t.objectProperty(t.identifier(`selector`),t.stringLiteral(binding.selector)),t.objectProperty(t.identifier(`inFor`),t.booleanLiteral(binding.inFor))];if(binding.name)props.push(t.objectProperty(t.identifier(`name`),t.stringLiteral(binding.name)));if(binding.expAst){const body=t.blockStatement([t.returnStatement(t.cloneNode(binding.expAst,true))]);props.push(t.objectProperty(t.identifier(`get`),t.functionExpression(null,[],body)))}if(binding.kind)props.push(t.objectProperty(t.identifier(`kind`),t.stringLiteral(binding.kind)));return t.objectExpression(props)}function injectTemplateRefs(optionsObject,bindings,warn){if(!bindings.length)return false;const warnHandler=resolveWarnHandler(warn);const entries=bindings.map(binding=>buildTemplateRefEntry(binding));const refsArray=t.arrayExpression(entries);const key=createStaticObjectKey(WEVU_TEMPLATE_REFS_KEY);const existing=getObjectPropertyByKey$2(optionsObject,WEVU_TEMPLATE_REFS_KEY);if(!existing){optionsObject.properties.push(t.objectProperty(key,refsArray));return true}if(t.isArrayExpression(existing.value)){existing.value.elements.push(...entries);return true}if(t.isIdentifier(existing.value)||t.isMemberExpression(existing.value)){existing.value=t.arrayExpression([...entries,t.spreadElement(t.cloneNode(existing.value,true))]);return true}warnHandler(`无法自动注入 template ref 元数据,请手动合并 ${WEVU_TEMPLATE_REFS_KEY}。`);return false}function hasStaticProperty(target,keyName){for(const prop of target.properties){if(prop.type!==`ObjectProperty`&&prop.type!==`ObjectMethod`||prop.computed)continue;const key=prop.key;if(key.type===`Identifier`&&key.name===keyName)return true;if(key.type===`StringLiteral`&&key.value===keyName)return true}return false}function injectFunctionPropPaths(componentOptionsObject,paths){const uniquePaths=[...new Set(paths)].filter(Boolean);if(!uniquePaths.length)return false;if(hasStaticProperty(componentOptionsObject,WEVU_FUNCTION_PROP_PATHS_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_FUNCTION_PROP_PATHS_KEY),t.arrayExpression(uniquePaths.map(path=>t.stringLiteral(path)))));return true}function createObjectLiteral(value){return t.objectExpression(Object.entries(value).map(([key,item])=>t.objectProperty(t.stringLiteral(key),item&&typeof item===`object`&&!Array.isArray(item)?createObjectLiteral(item):t.valueToNode(item))))}function injectCssModules(componentOptionsObject,modules){if(hasStaticProperty(componentOptionsObject,WEVU_CSS_MODULES_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.stringLiteral(WEVU_CSS_MODULES_KEY),createObjectLiteral(modules)));return true}function createScopedSlotHostPropertyDefinition(typeName,value){return t.objectExpression([t.objectProperty(t.identifier(`type`),typeName===`String`?t.identifier(`String`):t.nullLiteral()),t.objectProperty(t.identifier(`value`),value===null?t.nullLiteral():t.stringLiteral(value))])}function createScopedSlotHostProperties(){return[t.objectProperty(t.identifier(WEVU_SLOT_NAMES_PROP),createScopedSlotHostPropertyDefinition(`null`,null)),t.objectProperty(t.identifier(WEVU_SLOT_OWNER_ID_PROP),createScopedSlotHostPropertyDefinition(`String`,``)),t.objectProperty(t.identifier(WEVU_SLOT_SCOPE_KEY),createScopedSlotHostPropertyDefinition(`null`,null))]}function injectScopedSlotHostProperties(componentOptionsObject){const propertiesProp=getObjectPropertyByKey$2(componentOptionsObject,`properties`);if(!propertiesProp){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(`properties`),t.objectExpression(createScopedSlotHostProperties())));return true}if(!t.isObjectExpression(propertiesProp.value))return false;let changed=false;for(const prop of createScopedSlotHostProperties().reverse()){const key=t.isIdentifier(prop.key)?prop.key.name:void 0;if(!key||getObjectPropertyByKey$2(propertiesProp.value,key))continue;propertiesProp.value.properties.unshift(prop);changed=true}return changed}function injectScopedSlotOwnerRequirement(componentOptionsObject){if(hasStaticProperty(componentOptionsObject,WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY))return false;componentOptionsObject.properties.push(t.objectProperty(t.identifier(WEVU_SCOPED_SLOT_OWNER_REQUIRED_KEY),t.booleanLiteral(true)));return true}function unwrapTypeLikeExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapTypeLikeExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapTypeLikeExpression(node.expression);return node}function isStructuredRuntimeType(node){return t.isIdentifier(node,{name:`Array`})||t.isIdentifier(node,{name:`Object`})}function shouldRelaxStructuredPropType(node){const normalized=unwrapTypeLikeExpression(node);if(isStructuredRuntimeType(normalized))return true;if(!t.isArrayExpression(normalized)||normalized.elements.length===0)return false;return normalized.elements.every(element=>{if(!element||t.isSpreadElement(element)||!t.isExpression(element))return false;return isStructuredRuntimeType(unwrapTypeLikeExpression(element))})}function relaxStructuredTypeOnlyProps(componentOptionsObject){const propsProp=getObjectPropertyByKey$2(componentOptionsObject,`props`);if(!propsProp||!t.isExpression(propsProp.value))return false;const propsValue=unwrapTypeLikeExpression(propsProp.value);if(!t.isObjectExpression(propsValue))return false;let changed=false;for(const prop of propsValue.properties){if(!t.isObjectProperty(prop)||prop.computed||!t.isExpression(prop.value))continue;const definition=unwrapTypeLikeExpression(prop.value);if(!t.isObjectExpression(definition))continue;const typeProp=getObjectPropertyByKey$2(definition,`type`);if(!typeProp||!t.isExpression(typeProp.value))continue;if(!shouldRelaxStructuredPropType(typeProp.value))continue;typeProp.value=t.nullLiteral();changed=true}return changed}function isObjectAssignCall(node){const callee=node.callee;return t.isMemberExpression(callee)&&t.isIdentifier(callee.object,{name:`Object`})&&t.isIdentifier(callee.property,{name:`assign`})}function resolveObjectExpressionFromProgram(program,name){for(let index=program.body.length-1;index>=0;index-=1){const statement=program.body[index];if(!t.isVariableDeclaration(statement))continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id,{name})||!declarator.init||!t.isExpression(declarator.init))continue;const normalized=unwrapTypeLikeExpression(declarator.init);if(t.isObjectExpression(normalized))return normalized;if(t.isCallExpression(normalized)&&isObjectAssignCall(normalized)){const lastArg=normalized.arguments[normalized.arguments.length-1];if(lastArg&&!t.isSpreadElement(lastArg)&&t.isExpression(lastArg)){const lastNormalized=unwrapTypeLikeExpression(lastArg);if(t.isObjectExpression(lastNormalized))return lastNormalized}}}}return null}function hasStaticPropertyWithSpreads(target,keyName,program,visited=/* @__PURE__ */ new Set){if(hasStaticProperty(target,keyName))return true;for(const prop of target.properties){if(!t.isSpreadElement(prop))continue;const spreadArg=prop.argument;if(t.isObjectExpression(spreadArg)&&hasStaticPropertyWithSpreads(spreadArg,keyName,program,visited))return true;if(!t.isIdentifier(spreadArg)||visited.has(spreadArg.name))continue;visited.add(spreadArg.name);const resolved=resolveObjectExpressionFromProgram(program,spreadArg.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,visited))return true}return false}function hasStaticPropertyInComponentExpression(componentExpr,keyName,program){const normalized=unwrapTypeLikeExpression(componentExpr);if(t.isObjectExpression(normalized))return hasStaticPropertyWithSpreads(normalized,keyName,program);if(!t.isCallExpression(normalized)||!isObjectAssignCall(normalized))return false;for(const arg of normalized.arguments){if(t.isSpreadElement(arg)||!t.isExpression(arg))continue;const expr=unwrapTypeLikeExpression(arg);if(t.isObjectExpression(expr)&&hasStaticPropertyWithSpreads(expr,keyName,program))return true;if(t.isIdentifier(expr)){const resolved=resolveObjectExpressionFromProgram(program,expr.name);if(resolved&&hasStaticPropertyWithSpreads(resolved,keyName,program,/* @__PURE__ */ new Set([expr.name])))return true}}return false}function rewriteDefaultExport(ast,state,options,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults){if(!state.defaultExportPath)return false;const warn=resolveWarnHandler(options?.warn);let transformed=false;const exportPath=state.defaultExportPath;const componentExpr=resolveComponentExpression(exportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases);const componentOptionsObject=resolveComponentOptionsObject(componentExpr);const hasPageMarker=componentExpr?hasStaticPropertyInComponentExpression(componentExpr,WEVU_IS_PAGE_KEY,ast.program):false;if(componentOptionsObject&&!options?.isApp&&!hasPageMarker){componentOptionsObject.properties.splice(0,0,t.objectProperty(t.identifier(WEVU_IS_PAGE_KEY),t.booleanLiteral(options?.isPage===true)));transformed=true}if(componentOptionsObject&&enabledPageFeatures.size)transformed=injectWevuPageFeatureFlagsIntoOptionsObject(componentOptionsObject,enabledPageFeatures)||transformed;if(componentOptionsObject&&parsedWevuDefaults)transformed=applyWevuDefaultsToComponentOptions({componentExpr,parsedWevuDefaults,options})||transformed;if(componentExpr&&!options?.isApp&&!options?.skipComponentTransform)state.componentStyleOptions=analyzeComponentStyleOptions(componentExpr,exportPath.scope);if(componentOptionsObject)transformed=injectSetupInitialData(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.relaxStructuredTypeOnlyProps)transformed=relaxStructuredTypeOnlyProps(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.runtimeCapabilities?.required.includes(`scopedSlots`))transformed=injectScopedSlotOwnerRequirement(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.scopedSlotHostProperties)transformed=injectScopedSlotHostProperties(componentOptionsObject)||transformed;if(componentOptionsObject&&options?.cssModules&&Object.keys(options.cssModules).length)transformed=injectCssModules(componentOptionsObject,options.cssModules)||transformed;if(componentOptionsObject&&options?.stabilizeCssVarsRuntime)transformed=injectStableCssVarsRuntime(ast.program,componentOptionsObject,exportPath.scope)||transformed;if(componentOptionsObject){transformed=injectPropsAliases(componentOptionsObject,options?.propsAliases)||transformed;transformed=injectPropsDerivedKeys(componentOptionsObject,options?.propsDerivedKeys)||transformed}if(componentOptionsObject&&!options?.isApp)transformed=injectBindingManifestContract(componentOptionsObject,{manifest:options?.bindingManifest,autoSetDataPick:options?.autoSetDataPick,pageLayout:options?.pageLayout,runtimeBindingManifest:options?.runtimeBindingManifest})||transformed;const classStyleBindings=options?.classStyleBindings??[];if(classStyleBindings.length){if(componentOptionsObject){ensureClassStyleRuntimeImports(ast.program);transformed=injectClassStyleComputed(componentOptionsObject,classStyleBindings,options?.propsAliases,warn)||transformed}else warn(`无法自动注入 class/style 计算属性:组件选项不是对象字面量。`)}const templateRefs=options?.templateRefs??[];if(templateRefs.length){if(componentOptionsObject)transformed=injectTemplateRefs(componentOptionsObject,templateRefs,warn)||transformed;else warn(`无法自动注入 template ref 元数据:组件选项不是对象字面量。`)}const layoutHosts=options?.layoutHosts??[];if(layoutHosts.length){if(componentOptionsObject)transformed=injectLayoutHosts(componentOptionsObject,layoutHosts,warn)||transformed;else warn(`无法自动注入 layout host 元数据:组件选项不是对象字面量。`)}const inlineExpressions=options?.inlineExpressions??[];if(inlineExpressions.length){if(componentOptionsObject){const injected=injectInlineExpressions(componentOptionsObject,inlineExpressions);if(!injected)warn(`无法自动注入内联表达式元数据:methods 不是对象字面量。`);transformed=injected||transformed}else warn(`无法自动注入内联表达式元数据:组件选项不是对象字面量。`)}const functionPropPaths=options?.functionPropPaths??[];if(functionPropPaths.length){if(componentOptionsObject)transformed=injectFunctionPropPaths(componentOptionsObject,functionPropPaths)||transformed;else warn(`无法自动注入函数 prop 元数据:组件选项不是对象字面量。`)}if(componentExpr){if(options?.isApp)transformed=injectWevuDefaultsForApp({astProgram:ast.program,options,serializedWevuDefaults})||transformed;transformed=rewriteComponentExport({ast,exportPath,componentExpr,isAppFile:!!options?.isApp,skipComponentTransform:options?.skipComponentTransform})||transformed}return transformed}function createCapabilityAccumulator(){return{required:/* @__PURE__ */ new Set,conservative:/* @__PURE__ */ new Set}}function addConservativeCapabilities(accumulator,names){for(const name of names){accumulator.required.add(name);accumulator.conservative.add(name)}}function unwrapExpression(node){if(t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTypeCastExpression(node))return unwrapExpression(node.expression);if(t.isParenthesizedExpression(node))return unwrapExpression(node.expression);return node}function resolveStaticExpression(node,context,visited=/* @__PURE__ */ new Set){const normalized=unwrapExpression(node);if(!t.isIdentifier(normalized)||normalized.name===`undefined`)return{value:normalized,context};const binding=context.scope?.getBinding(normalized.name);if(!binding||!binding.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath?.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||visited.has(binding.path.node))return;if(!(binding.referencePaths.length===1||binding.referencePaths.every(reference=>{return context.safeBindingReferences?.has(reference.node)||reference.parentPath.isExportDefaultDeclaration()&&reference.parentPath.node.declaration===reference.node}))||!binding.path.node.init||!t.isExpression(binding.path.node.init))return;visited.add(binding.path.node);return resolveStaticExpression(binding.path.node.init,{scope:binding.path.scope,safeBindingReferences:context.safeBindingReferences},visited)}function resolveProperty(object,key,context,initial={kind:`absent`}){let state=initial;for(const property of object.properties){if(t.isSpreadElement(property)||property.computed){state={kind:`unknown`};continue}if(!isStaticObjectKeyMatch(property.key,key))continue;if(!t.isObjectProperty(property)||!t.isExpression(property.value)){state={kind:`unknown`};continue}state={kind:`value`,value:property.value,context}}return state}function isStaticPrimitive(node){return t.isBooleanLiteral(node)||t.isNullLiteral(node)||t.isNumericLiteral(node)||t.isStringLiteral(node)||t.isTemplateLiteral(node)&&node.expressions.length===0||t.isIdentifier(node,{name:`undefined`})}function applyResolvedProperty(current,next){return next.kind===`absent`?current:next}function resolveInheritedSetData(expression,context,visited){const result=resolveStaticExpression(expression,context);if(!result)return{kind:`unknown`};const{value:resolved,context:resolvedContext}=result;if(!t.isObjectExpression(resolved))return isStaticPrimitive(resolved)||t.isFunction(resolved)?{kind:`absent`}:{kind:`unknown`};if(visited.has(resolved))return{kind:`absent`};visited.add(resolved);let state={kind:`absent`};const inherited=resolveProperty(resolved,`extends`,resolvedContext);if(inherited.kind===`unknown`)state=inherited;else if(inherited.kind===`value`)state=applyResolvedProperty(state,resolveInheritedSetData(inherited.value,inherited.context,visited));const mixins=resolveProperty(resolved,`mixins`,resolvedContext);if(mixins.kind===`unknown`)state=mixins;else if(mixins.kind===`value`){const resolvedMixins=resolveStaticExpression(mixins.value,mixins.context);if(!resolvedMixins||!t.isArrayExpression(resolvedMixins.value))state={kind:`unknown`};else for(const element of resolvedMixins.value.elements){if(!element||t.isSpreadElement(element)||!t.isExpression(element)){state={kind:`unknown`};continue}state=applyResolvedProperty(state,resolveInheritedSetData(element,resolvedMixins.context,visited))}}state=applyResolvedProperty(state,resolveProperty(resolved,`setData`,resolvedContext));visited.delete(resolved);return state}function analyzeHighFrequencyWarning(state,accumulator){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`)return;const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(t.isObjectExpression(value)){const enabled=resolveProperty(value,`enabled`,context);if(enabled.kind===`unknown`){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(enabled.kind===`value`){const resolvedEnabled=resolveStaticExpression(enabled.value,enabled.context);if(!resolvedEnabled){addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`]);return}if(t.isBooleanLiteral(resolvedEnabled.value,{value:false}))return}accumulator.required.add(`setDataHighFrequencyWarning`);return}if(t.isBooleanLiteral(value,{value:true})){accumulator.required.add(`setDataHighFrequencyWarning`);return}if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`setDataHighFrequencyWarning`])}function analyzeSetData(state,accumulator,defaults){if(state.kind===`unknown`){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(state.kind===`absent`){if(defaults)analyzeSetData(defaults,accumulator);return}const defaultValue=defaults?.kind===`value`?resolveStaticExpression(defaults.value,defaults.context):void 0;const defaultObject=defaultValue&&t.isObjectExpression(defaultValue.value)?defaultValue.value:void 0;if(defaultObject&&(t.isIdentifier(state.value)||t.isMemberExpression(state.value))){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const resolved=resolveStaticExpression(state.value,state.context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const{value,context}=resolved;if(!t.isObjectExpression(value)){if(defaultObject)analyzeSetData({kind:`value`,value:defaultObject,context:defaultValue.context},accumulator);if(!isStaticPrimitive(value)&&!t.isArrayExpression(value)&&!t.isFunction(value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}const mergedDefaults=t.isObjectExpression(state.value)?defaultObject:void 0;const strategy=resolveProperty(value,`strategy`,context,mergedDefaults?resolveProperty(mergedDefaults,`strategy`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0);if(strategy.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`]);else if(strategy.kind===`value`){const resolvedStrategy=resolveStaticExpression(strategy.value,strategy.context)?.value;if(t.isStringLiteral(resolvedStrategy,{value:`patch`})||t.isTemplateLiteral(resolvedStrategy)&&resolvedStrategy.expressions.length===0&&resolvedStrategy.quasis[0]?.value.cooked===`patch`)accumulator.required.add(`patchStrategy`);else if(!resolvedStrategy||!isStaticPrimitive(resolvedStrategy)&&!t.isArrayExpression(resolvedStrategy)&&!t.isFunction(resolvedStrategy))addConservativeCapabilities(accumulator,[`patchStrategy`])}analyzeHighFrequencyWarning(resolveProperty(value,`highFrequencyWarning`,context,mergedDefaults?resolveProperty(mergedDefaults,`highFrequencyWarning`,defaultValue.context):defaults?.kind===`unknown`?defaults:void 0),accumulator)}function analyzeRuntimeFactoryOptions(expression,context,accumulator,defaults){const defaultSetDataNode=Boolean(defaults&&Object.prototype.hasOwnProperty.call(defaults,`setData`))?t.valueToNode(defaults?.setData):void 0;const defaultSetData=defaultSetDataNode&&t.isExpression(defaultSetDataNode)?{kind:`value`,value:defaultSetDataNode,context:{}}:void 0;if(!expression){if(defaultSetData)analyzeSetData(defaultSetData,accumulator);return}const resolved=resolveStaticExpression(expression,context);if(!resolved){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}if(!t.isObjectExpression(resolved.value)){if(!isStaticPrimitive(resolved.value)&&!t.isArrayExpression(resolved.value)&&!t.isFunction(resolved.value))addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}analyzeSetData(resolveInheritedSetData(resolved.value,resolved.context,/* @__PURE__ */ new Set),accumulator,defaultSetData)}function analyzeRuntimeDefaults(expression,context,accumulator){if(!expression)return;const resolved=resolveStaticExpression(expression,context);if(!resolved||!t.isObjectExpression(resolved.value)){addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);return}for(const key of[`app`,`component`]){const branch=resolveProperty(resolved.value,key,resolved.context);if(branch.kind===`unknown`)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(branch.kind===`value`)analyzeRuntimeFactoryOptions(branch.value,branch.context,accumulator)}}function finishRuntimeCapabilityAnalysis(accumulator){return createWevuRuntimeCapabilityMetadata(accumulator.required,accumulator.conservative)}const INSTALLER_LOCAL_NAMES={patchStrategy:`__wevuInstallPatchStrategy`,templateRefs:`__wevuInstallTemplateRefs`,inlineEvents:`__wevuInstallInlineEvents`,setDataHighFrequencyWarning:`__wevuInstallSetDataHighFrequencyWarning`,scopedSlots:`__wevuInstallScopedSlots`,layout:`__wevuInstallLayout`,jsxIslands:`__wevuInstallJsxIslands`};const CAPABILITY_BY_INSTALLER=Object.fromEntries(WE_VU_RUNTIME_CAPABILITY_ORDER.map(name=>[WE_VU_RUNTIME_CAPABILITY_INSTALLERS[name],name]));function resolveInstallerCallCapability(statement,importedLocals,namespaceLocals){if(!t.isExpressionStatement(statement)||!t.isCallExpression(statement.expression)||statement.expression.arguments.length)return;const callee=statement.expression.callee;if(t.isIdentifier(callee))return WE_VU_RUNTIME_CAPABILITY_ORDER.find(name=>importedLocals[name]?.includes(callee.name));if(t.isMemberExpression(callee)&&!callee.computed&&t.isIdentifier(callee.object)&&namespaceLocals.has(callee.object.name)&&t.isIdentifier(callee.property))return CAPABILITY_BY_INSTALLER[callee.property.name]}function findLeadingImportEnd(program){let index=0;while(index<program.body.length&&t.isImportDeclaration(program.body[index]))index+=1;return index}function injectWevuRuntimeCapabilityInstallers(program,metadata){if(!metadata?.required.length)return false;const importedLocals={};const namespaceLocals=/* @__PURE__ */ new Set;for(const statement of program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers)if(t.isImportNamespaceSpecifier(specifier))namespaceLocals.add(specifier.local.name);else if(t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&t.isIdentifier(specifier.imported)){const capability=CAPABILITY_BY_INSTALLER[specifier.imported.name];if(capability){const locals=importedLocals[capability]??[];locals.push(specifier.local.name);importedLocals[capability]=locals}}}const existingCalls={};let prefixIndex=findLeadingImportEnd(program);let previousCapabilityIndex=-1;while(prefixIndex<program.body.length){const statement=program.body[prefixIndex];const capability=resolveInstallerCallCapability(statement,importedLocals,namespaceLocals);if(!capability)break;const capabilityIndex=WE_VU_RUNTIME_CAPABILITY_ORDER.indexOf(capability);if(capabilityIndex<previousCapabilityIndex)break;if(!existingCalls[capability])existingCalls[capability]=statement;previousCapabilityIndex=capabilityIndex;prefixIndex+=1}const usedNames=new Set(Object.keys(t.getBindingIdentifiers(program)));const localByCapability={};for(const capability of metadata.required){if(existingCalls[capability])continue;const existingLocal=importedLocals[capability]?.[0];if(existingLocal){localByCapability[capability]=existingLocal;continue}const baseName=INSTALLER_LOCAL_NAMES[capability];let localName=baseName;let suffix=2;while(usedNames.has(localName)){localName=`${baseName}${suffix}`;suffix+=1}usedNames.add(localName);localByCapability[capability]=localName;ensureRuntimeImport(program,WE_VU_RUNTIME_CAPABILITY_INSTALLERS[capability],localName)}let insertIndex=findLeadingImportEnd(program);const requiredCapabilities=new Set(metadata.required);let changed=false;for(const capability of WE_VU_RUNTIME_CAPABILITY_ORDER){const existingCall=existingCalls[capability];if(existingCall){const existingIndex=program.body.indexOf(existingCall);if(existingIndex>=insertIndex)insertIndex=existingIndex+1;continue}if(!requiredCapabilities.has(capability))continue;const localName=localByCapability[capability];program.body.splice(insertIndex,0,t.expressionStatement(t.callExpression(t.identifier(localName),[])));insertIndex+=1;changed=true}return changed}const OPTION_FACTORY_APIS={createApp:true,createWevuComponent:true,defineComponent:true};function addScopedSlotCreatorCapabilities(accumulator){accumulator.required.add(`scopedSlots`);addConservativeCapabilities(accumulator,[`templateRefs`,`inlineEvents`,`layout`])}function analyzeWevuRuntimeCalls(ast){const namedBindings=/* @__PURE__ */ new Map;const namespaceSpecifiers=[];for(const statement of ast.program.body){if(!t.isImportDeclaration(statement)||statement.importKind===`type`||!isWevuRuntimeModuleId(statement.source.value))continue;for(const specifier of statement.specifiers){if(t.isImportNamespaceSpecifier(specifier)||t.isImportDefaultSpecifier(specifier)){namespaceSpecifiers.push(specifier);continue}if(!t.isImportSpecifier(specifier)||specifier.importKind===`type`||!t.isIdentifier(specifier.imported))continue;const importedName=specifier.imported.name;if(importedName===`createWevuScopedSlotComponent`||importedName===`setWevuDefaults`||Object.prototype.hasOwnProperty.call(OPTION_FACTORY_APIS,importedName))namedBindings.set(specifier.local.name,{api:importedName,specifier})}}if(!namedBindings.size&&!namespaceSpecifiers.length)return;const handledCallees=/* @__PURE__ */ new Set;const safeBindingReferences=/* @__PURE__ */ new Set;const accumulator=createCapabilityAccumulator();const calls=[];let programScope;traverse(ast,{Program(path){programScope=path.scope},CallExpression(path){if(!t.isIdentifier(path.node.callee))return;const runtimeBinding=namedBindings.get(path.node.callee.name);const binding=path.scope.getBinding(path.node.callee.name);if(!runtimeBinding||binding?.path.node!==runtimeBinding.specifier)return;handledCallees.add(path.node.callee);const firstArgument=path.node.arguments[0];const argument=firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument)?firstArgument:void 0;if(t.isIdentifier(argument))safeBindingReferences.add(argument);calls.push({api:runtimeBinding.api,argument,argumentUnknown:Boolean(firstArgument&&(t.isSpreadElement(firstArgument)||!t.isExpression(firstArgument))),scope:path.scope})}});for(const{api,argument,argumentUnknown,scope}of calls){const context={scope,safeBindingReferences};if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else if(argumentUnknown)addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);else if(api===`setWevuDefaults`)analyzeRuntimeDefaults(argument,context,accumulator);else analyzeRuntimeFactoryOptions(argument,context,accumulator)}for(const{api,specifier}of namedBindings.values()){if(!(programScope?.getBinding(specifier.local.name))?.referencePaths.some(reference=>!handledCallees.has(reference.node)))continue;if(api===`createWevuScopedSlotComponent`)addScopedSlotCreatorCapabilities(accumulator);else addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`])}for(const specifier of namespaceSpecifiers){const binding=programScope?.getBinding(specifier.local.name);if(!binding?.referenced)continue;addConservativeCapabilities(accumulator,[`patchStrategy`,`setDataHighFrequencyWarning`]);if(binding.referencePaths.some(reference=>{const parent=reference.parentPath;if(!parent.isMemberExpression()||parent.node.object!==reference.node||parent.node.computed||!t.isIdentifier(parent.node.property))return true;return parent.node.property.name===WE_VU_RUNTIME_APIS.createWevuScopedSlotComponent}))addScopedSlotCreatorCapabilities(accumulator)}return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuComponentOptions(params){if(!params.expression)return;const accumulator=createCapabilityAccumulator();analyzeRuntimeFactoryOptions(params.expression,{scope:params.scope},accumulator,params.defaults);return finishRuntimeCapabilityAnalysis(accumulator)}function analyzeWevuDefaults(defaults){if(!defaults)return;const node=t.valueToNode(defaults);if(!t.isExpression(node))return;const accumulator=createCapabilityAccumulator();analyzeRuntimeDefaults(node,{},accumulator);return finishRuntimeCapabilityAnalysis(accumulator)}function runVisitor(visitor,path){if(typeof visitor===`function`)visitor(path)}function transformScript(source,options){const fastResult=tryFastTransformCompiledScriptSetup(source,options);if(fastResult)return fastResult;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const sourceRuntimeCapabilities=analyzeWevuRuntimeCalls(ast);const warn=resolveWarnHandler(options?.warn);const state={transformed:false,defineComponentAliases:/* @__PURE__ */ new Set([WE_VU_RUNTIME_APIS.defineComponent,`_defineComponent`]),defineComponentDecls:/* @__PURE__ */ new Map,useSlotsAliases:/* @__PURE__ */ new Set,usesSlots:false,defaultExportPath:null};const enabledPageFeatures=options?.isPage?collectWevuPageFeatureFlags(ast):/* @__PURE__ */ new Set;const serializedWevuDefaults=options?.wevuDefaults&&Object.keys(options.wevuDefaults).length>0?serializeWevuDefaults(options.wevuDefaults,warn):void 0;const parsedWevuDefaults=serializedWevuDefaults?JSON.parse(serializedWevuDefaults):void 0;const vueSfcVisitors=vueSfcTransformPlugin().visitor;const macroVisitors=createMacroVisitors(ast,state);const importVisitors=createImportVisitors(ast.program,state);const collectVisitors=createCollectVisitors(state);const visitor={...vueSfcVisitors,...macroVisitors,...importVisitors,...collectVisitors,ImportDeclaration(path){runVisitor(macroVisitors.ImportDeclaration,path);if(path.removed)return;const source=path.node.source.value;const canProvideUseSlots=source===`vue`||isWevuRuntimeModuleId(source);for(const specifier of path.node.specifiers)if(canProvideUseSlots&&specifier.type===`ImportSpecifier`&&(specifier.imported.type===`Identifier`&&specifier.imported.name===`useSlots`||specifier.imported.type===`StringLiteral`&&specifier.imported.value===`useSlots`))state.useSlotsAliases.add(specifier.local.name);runVisitor(vueSfcVisitors.ImportDeclaration,path);if(!path.removed)runVisitor(importVisitors.ImportDeclaration,path)},CallExpression(path){if(path.node.callee.type===`Identifier`&&state.useSlotsAliases.has(path.node.callee.name))state.usesSlots=true;runVisitor(vueSfcVisitors.CallExpression,path);if(!path.removed)runVisitor(macroVisitors.CallExpression,path)}};traverse(ast,visitor);const templateRuntimeCapabilities=createWevuRuntimeCapabilityMetadata([...options?.templateRefs?.length||options?.layoutHosts?.length?[`templateRefs`]:[],...options?.inlineExpressions?.length?[`inlineEvents`]:[],...options?.layoutHosts?.length?[`layout`]:[]]);const componentExpression=state.defaultExportPath?resolveComponentExpression(state.defaultExportPath.node.declaration,state.defineComponentDecls,state.defineComponentAliases):null;const defaultDeclaration=state.defaultExportPath?.node.declaration;let componentCapabilityExpression=componentExpression;if(t.isIdentifier(defaultDeclaration))componentCapabilityExpression=defaultDeclaration;else if(t.isCallExpression(defaultDeclaration)&&t.isIdentifier(defaultDeclaration.callee)&&state.defineComponentAliases.has(defaultDeclaration.callee.name)){const firstArgument=defaultDeclaration.arguments[0];if(firstArgument&&!t.isSpreadElement(firstArgument)&&t.isExpression(firstArgument))componentCapabilityExpression=firstArgument}const defaultsBranch=options?.isApp?parsedWevuDefaults?.app:parsedWevuDefaults?.component;const componentRuntimeCapabilities=componentCapabilityExpression?analyzeWevuComponentOptions({expression:componentCapabilityExpression,scope:state.defaultExportPath?.scope,defaults:defaultsBranch}):void 0;const defaultsRuntimeCapabilities=options?.isApp?analyzeWevuDefaults(parsedWevuDefaults):void 0;const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(options?.runtimeCapabilities,templateRuntimeCapabilities,sourceRuntimeCapabilities,componentRuntimeCapabilities,defaultsRuntimeCapabilities);if(options?.templateComponentMeta)state.transformed=pruneTemplateComponentMeta(ast,options.templateComponentMeta)||state.transformed;const rewriteOptions=state.usesSlots&&!options?.scopedSlotHostProperties?{...options,scopedSlotHostProperties:true}:options;state.transformed=rewriteDefaultExport(ast,state,rewriteOptions,enabledPageFeatures,serializedWevuDefaults,parsedWevuDefaults)||state.transformed;state.transformed=injectWevuRuntimeCapabilityInstallers(ast.program,runtimeCapabilities)||state.transformed;if(!state.transformed)return{code:source,transformed:false,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}};const sourceMap=options?.sourceMap!==false;const generated=generate(ast,{compact:options?.minify===true,minified:options?.minify===true,retainLines:options?.minify!==true,sourceMaps:sourceMap,sourceFileName:`inline.ts`},source);return{code:generated.code,map:sourceMap?generated.map:null,transformed:state.transformed,...runtimeCapabilities?{runtimeCapabilities}:{},...state.componentStyleOptions?{componentStyleOptions:state.componentStyleOptions}:{}}}function createJsxDiagnostics(warnings,filename){return warnings.map(warning=>{return{code:`WV1003`,severity:`warning`,message:warning.startsWith(`[JSX 编译]`)?warning:`[JSX 编译] ${warning}`,filename,source:`jsx`}})}const WXML_EXPRESSION_GENERATE_OPTIONS={compact:true,jsescOption:{quotes:`single`,minimal:true}};const escapeText=escapeWxmlText;const escapeAttr=escapeWxmlAttribute;const WHITESPACE_RE=/\s+/g;function normalizeJsxText(value){return value.replace(WHITESPACE_RE,` `)}function printExpression(exp){const normalized=t.cloneNode(exp,true);t.traverseFast(normalized,node=>{if(t.isStringLiteral(node))node.extra=void 0});return generate(normalized,WXML_EXPRESSION_GENERATE_OPTIONS).code}function unwrapTsExpression(exp){return unwrapTypeScriptExpression(exp)}function normalizeInterpolationExpression(exp,context){const cached=context?.interpolationCache.get(exp);if(cached!=null)return cached;let source=printExpression(unwrapTsExpression(exp));if(context?.setupRefBindings?.size){const expression=t.cloneNode(unwrapTsExpression(exp),true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{"MemberExpression|OptionalMemberExpression":{enter(path){const member=path.node;if(!t.isMemberExpression(member)&&!t.isOptionalMemberExpression(member))return;const object=t.isExpression(member.object)?unwrapTsExpression(member.object):member.object;if(!t.isIdentifier(object)||!context.setupRefBindings?.has(object.name)||context.scopeStack.includes(object.name)||path.scope.hasBinding(object.name))return;if(member.loc?.filename&&context.filename&&member.loc.filename!==context.filename)return;if(member.computed?t.isStringLiteral(member.property,{value:`value`}):t.isIdentifier(member.property,{name:`value`}))path.replaceWith(t.cloneNode(object))}}});const statement=file.program.body[0];source=printExpression(statement.expression)}let normalized=normalizeWxmlExpression(source);if(context&&shouldFallbackToRuntimeBinding(source)){const name=`__wv_bind_${context.classStyleBindings.filter(item=>item.type===`bind`).length}`;context.classStyleBindings.push({name,type:`bind`,exp:source,forStack:context.forStack.map(info=>({...info}))});normalized=`${name}${context.forStack.map(info=>`[${info.index??`index`}]`).join(``)}`}context?.interpolationCache.set(exp,normalized);return normalized}function renderMustache(expression,context){return context.mustacheInterpolation===`spaced`?`{{ ${expression} }}`:`{{${expression}}}`}function pushScope(context,names,sourceExpression){const scopedNames=names.filter(Boolean);const sourceLocals=[...context.scopeStack];context.scopeStack.push(...scopedNames);if(scopedNames.length)context.bindingScopeStack.push({locals:scopedNames,sourceExpression,sourceLocals})}function popScope(context,count){for(let i=0;i<count;i+=1)context.scopeStack.pop();if(count>0)context.bindingScopeStack.pop()}function analyzeInlineExpression(exp,context){const localSet=new Set(context.scopeStack);const used=[];const usedSet=/* @__PURE__ */ new Set;const identifierNames=/* @__PURE__ */ new Set;const normalizedExpression=t.cloneNode(exp,true);const file=t.file(t.program([t.expressionStatement(normalizedExpression)]));let programScope;traverse(file,{Program(path){programScope=path.scope},Identifier(path){const name=path.node.name;identifierNames.add(name);if(!localSet.has(name)||!path.isReferencedIdentifier()||path.scope.hasBinding(name)||usedSet.has(name))return;usedSet.add(name);used.push(name)},StringLiteral(path){path.node.extra=void 0}});if(!programScope)throw new Error(`无法为 JSX 内联表达式创建程序作用域。`);return{parameterIdentifiers:createInlineExpressionParameterIdentifiers(programScope,identifierNames),normalizedExpression,scopeKeys:used}}function registerInlineExpression(exp,context){const{normalizedExpression,parameterIdentifiers,scopeKeys}=analyzeInlineExpression(exp,context);const id=createInlineExpressionId(context.inlineExpressionSeed++);context.inlineExpressions.push({id,expression:generate(normalizedExpression,WXML_EXPRESSION_GENERATE_OPTIONS).code,scopeKeys,parameterNames:{context:parameterIdentifiers.context.name,scope:parameterIdentifiers.scope.name,event:parameterIdentifiers.event.name}});return{id,scopeKeys}}function toJsxTagName(name,context){if(t.isJSXIdentifier(name))return name.name;if(t.isJSXNamespacedName(name))return`${name.namespace.name}:${name.name.name}`;context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return`block`}const REF_FACTORIES=/* @__PURE__ */ new Set([`ref`,`shallowRef`,`computed`,`customRef`,`toRef`,`useModel`,`useTemplateRef`]);const REF_OBJECT_FACTORIES=/* @__PURE__ */ new Set([`toRefs`,`storeToRefs`]);function resolveSetupFunction(component){const setup=getObjectPropertyByKey(component,`setup`);if(t.isObjectMethod(setup))return setup;if(t.isObjectProperty(setup)&&(t.isFunctionExpression(setup.value)||t.isArrowFunctionExpression(setup.value)))return setup.value}function collectSetupRefBindings(component,context){const setup=resolveSetupFunction(component);const refs=/* @__PURE__ */ new Set;if(!setup||!t.isBlockStatement(setup.body))return refs;const declarations=setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)?statement.declarations:[]);const stableDeclarations=new Set(setup.body.body.flatMap(statement=>t.isVariableDeclaration(statement)&&statement.kind===`const`?statement.declarations:[]));const locals=new Set(declarations.flatMap(declaration=>Object.keys(t.getBindingIdentifiers(declaration.id))));for(const statement of setup.body.body)if(t.isFunctionDeclaration(statement)&&statement.id)locals.add(statement.id.name);for(const parameter of setup.params)Object.keys(t.getBindingIdentifiers(parameter)).forEach(name=>locals.add(name));function importedApi(expression){if(t.isIdentifier(expression)&&!locals.has(expression.name)){const imported=context.importedBindings?.get(expression.name);return imported&&[`wevu`,`vue`].includes(imported.source)?imported.importedName:void 0}if(t.isMemberExpression(expression)&&!expression.computed&&t.isIdentifier(expression.object)&&t.isIdentifier(expression.property)&&!locals.has(expression.object.name)){const imported=context.importedBindings?.get(expression.object.name);return imported?.importedName===`*`&&[`wevu`,`vue`].includes(imported.source)?expression.property.name:void 0}}function isRef(expression){const value=unwrapTypeScriptExpression(expression);if(t.isIdentifier(value))return refs.has(value.name);if(!t.isCallExpression(value)||!t.isExpression(value.callee))return false;const api=importedApi(value.callee);if(api&&REF_FACTORIES.has(api))return true;const first=value.arguments[0];return(api===`readonly`||api===`shallowReadonly`)&&t.isExpression(first)&&isRef(first)}for(const declaration of declarations){if(!declaration.init||!stableDeclarations.has(declaration))continue;if(t.isIdentifier(declaration.id)&&isRef(declaration.init))refs.add(declaration.id.name);else if(t.isObjectPattern(declaration.id)&&t.isCallExpression(declaration.init)&&t.isExpression(declaration.init.callee)){const api=importedApi(declaration.init.callee);if(api&&REF_OBJECT_FACTORIES.has(api)){for(const property of declaration.id.properties)if(t.isObjectProperty(property)&&t.isIdentifier(property.value))refs.add(property.value.name)}}}return refs}function parseIslandExpression(expression){const statement=parse$3(`const __wevuIsland = (${expression})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!t.isVariableDeclaration(statement))return;const init=statement.declarations[0]?.init;return init&&t.isExpression(init)?init:void 0}function injectIslandComputed(optionsObject,islands){const entries=islands.flatMap(island=>{const expression=parseIslandExpression(island.expression);if(!expression)return[];const normalized=t.callExpression(t.memberExpression(t.identifier(`__wevuNormalizeJsxIsland`),t.identifier(`call`)),[t.thisExpression(),expression,t.stringLiteral(island.id),t.objectExpression([t.objectProperty(t.identifier(`normalizeClass`),t.identifier(`__wevuNormalizeClass`)),t.objectProperty(t.identifier(`normalizeStyle`),t.identifier(`__wevuNormalizeStyle`))])]);return[t.objectProperty(t.stringLiteral(island.id),normalized)]});if(!entries.length)return false;const islandGetter=t.objectMethod(`method`,t.identifier(WEVU_JSX_ISLAND_DATA_KEY),[],t.blockStatement([t.returnStatement(t.objectExpression(entries))]));const computed=optionsObject.properties.find(property=>(t.isObjectProperty(property)||t.isObjectMethod(property))&&toStaticObjectKey(property.key)===`computed`);if(computed&&t.isObjectProperty(computed)&&t.isObjectExpression(computed.value))computed.value.properties.push(islandGetter);else optionsObject.properties.unshift(t.objectProperty(t.identifier(`computed`),t.objectExpression([islandGetter])));return true}function injectDynamicIslandRuntime(source,islands){if(!islands?.length)return source;const ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS);const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const declarations=/* @__PURE__ */ new Map;let injected=false;traverse(ast,{ImportDeclaration(path){if(path.node.source.value!==`wevu`&&path.node.source.value!==`vue`)return;for(const specifier of path.node.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.imported,{name:`defineComponent`}))defineComponentAliases.add(specifier.local.name)},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init))declarations.set(path.node.id.name,path.node.init);if(t.isCallExpression(path.node.init)&&t.isIdentifier(path.node.init.callee)&&defineComponentAliases.has(path.node.init.callee.name)){const first=path.node.init.arguments[0];if(t.isObjectExpression(first))declarations.set(path.node.id.name,first)}},ExportDefaultDeclaration(path){const declaration=path.node.declaration;let optionsObject;if(t.isObjectExpression(declaration))optionsObject=declaration;else if(t.isCallExpression(declaration)&&t.isIdentifier(declaration.callee)&&defineComponentAliases.has(declaration.callee.name)){const first=declaration.arguments[0];if(t.isObjectExpression(first))optionsObject=first}else if(t.isIdentifier(declaration))optionsObject=declarations.get(declaration.name);if(optionsObject)injected=injectIslandComputed(optionsObject,islands)||injected}});if(!injected)return source;ensureRuntimeImport(ast.program,`normalizeJsxIsland`,`__wevuNormalizeJsxIsland`);ensureRuntimeImport(ast.program,`normalizeClass`,`__wevuNormalizeClass`);ensureRuntimeImport(ast.program,`normalizeStyle`,`__wevuNormalizeStyle`);return generate(ast).code}function removeRenderOptionFromObjectExpression(node){const nextProps=node.properties.filter(prop=>{if(t.isObjectMethod(prop))return toStaticObjectKey(prop.key)!==`render`;if(t.isObjectProperty(prop)&&!prop.computed)return toStaticObjectKey(prop.key)!==`render`;return true});const removed=nextProps.length!==node.properties.length;if(removed)node.properties=nextProps;return removed}function resolveReturnedJsxClosureExpression(expression){if(!t.isArrowFunctionExpression(expression)&&!t.isFunctionExpression(expression))return;if(t.isJSXElement(expression.body)||t.isJSXFragment(expression.body))return expression.body;if(!t.isBlockStatement(expression.body))return;const returned=expression.body.body.find(statement=>t.isReturnStatement(statement)&&statement.argument);if(!returned||!t.isReturnStatement(returned))return;return returned.argument&&(t.isJSXElement(returned.argument)||t.isJSXFragment(returned.argument))?returned.argument:void 0}function rewriteSetupRenderClosure(node){const setup=resolveSetupFunction(node);if(!setup||!t.isBlockStatement(setup.body))return false;const localNames=/* @__PURE__ */ new Set;for(const param of setup.params)Object.keys(t.getBindingIdentifiers(param)).forEach(name=>localNames.add(name));for(const statement of setup.body.body)if(t.isVariableDeclaration(statement))for(const declaration of statement.declarations)Object.keys(t.getBindingIdentifiers(declaration.id)).forEach(name=>localNames.add(name));else if(t.isFunctionDeclaration(statement)&&statement.id)localNames.add(statement.id.name);for(const statement of setup.body.body){if(!t.isReturnStatement(statement)||!statement.argument||!t.isExpression(statement.argument))continue;const jsx=resolveReturnedJsxClosureExpression(statement.argument);if(!jsx)continue;const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(jsx,true))]));traverse(file,{ReferencedIdentifier(path){if(localNames.has(path.node.name))captures.add(path.node.name)}});statement.argument=t.objectExpression([...captures].map(name=>t.objectProperty(t.identifier(name),t.identifier(name),false,true)));return true}return false}function stripRenderOptionFromScript(source,filename,warnings){let ast;try{ast=parse$3(source,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return source}const defineComponentAliases=/* @__PURE__ */ new Set([`defineComponent`,`_defineComponent`]);const defineComponentDecls=/* @__PURE__ */ new Map;let hasDefaultExport=false;let removedRender=false;let removedJsonMacroImport=false;traverse(ast,{ImportDeclaration(path){const importSource=path.node.source.value;if(importSource===`wevu`||importSource===`vue`)for(const specifier of path.node.specifiers){if(!t.isImportSpecifier(specifier))continue;if(!t.isIdentifier(specifier.imported,{name:`defineComponent`}))continue;defineComponentAliases.add(specifier.local.name)}if(importSource!==`weapp-vite`)return;const retained=path.node.specifiers.filter(specifier=>{if(!t.isImportSpecifier(specifier))return true;const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:``;return!JSON_MACROS.has(importedName)});if(retained.length===path.node.specifiers.length)return;removedJsonMacroImport=true;if(retained.length===0)path.remove();else path.node.specifiers=retained},VariableDeclarator(path){if(!t.isIdentifier(path.node.id)||!path.node.init)return;if(t.isObjectExpression(path.node.init)){defineComponentDecls.set(path.node.id.name,path.node.init);return}if(!t.isCallExpression(path.node.init))return;const callee=path.node.init.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=path.node.init.arguments[0];if(t.isObjectExpression(first))defineComponentDecls.set(path.node.id.name,first)},ExportDefaultDeclaration(path){hasDefaultExport=true;const declaration=path.node.declaration;if(t.isDeclaration(declaration))return;if(t.isObjectExpression(declaration)){removedRender=removeRenderOptionFromObjectExpression(declaration)||rewriteSetupRenderClosure(declaration)||removedRender;return}if(t.isCallExpression(declaration)){const callee=declaration.callee;if(!t.isIdentifier(callee)||!defineComponentAliases.has(callee.name))return;const first=declaration.arguments[0];if(t.isObjectExpression(first))removedRender=removeRenderOptionFromObjectExpression(first)||rewriteSetupRenderClosure(first)||removedRender;return}if(t.isIdentifier(declaration)){const target=defineComponentDecls.get(declaration.name);if(target)removedRender=removeRenderOptionFromObjectExpression(target)||rewriteSetupRenderClosure(target)||removedRender}}});if(hasDefaultExport&&!removedRender)warnings?.push(`[JSX 编译] 未在 ${filename} 中移除 render 选项,输出脚本可能包含 JSX。`);if(!removedRender&&!removedJsonMacroImport)return source;return generate(ast).code}function resolveRenderExpression(componentExpr,context){if(!t.isObjectExpression(componentExpr)){context.warnings.push(`JSX 编译仅支持对象字面量组件选项。`);return null}const renderExpression=resolveRenderExpressionFromComponentOptions(componentExpr);if(renderExpression)return renderExpression;if(getRenderPropertyFromComponentOptions(componentExpr)){context.warnings.push(`render 不是可执行函数。`);return null}const setup=resolveSetupFunction(componentExpr);if(setup){const body=setup.body;if(t.isBlockStatement(body))for(const statement of body.body){if(!t.isReturnStatement(statement)||!statement.argument)continue;if(t.isArrowFunctionExpression(statement.argument)||t.isFunctionExpression(statement.argument)){context.setupRefBindings=collectSetupRefBindings(componentExpr,context);const renderBody=statement.argument.body;if(t.isExpression(renderBody))return renderBody;const returned=renderBody.body.find(item=>t.isReturnStatement(item)&&item.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument)return returned.argument}}}context.warnings.push(`未找到 render() 或 setup() 返回的 render closure。`);return null}function isCollectableJsxTemplateTag(tag){if(!tag)return false;if(RESERVED_VUE_COMPONENT_TAGS.has(tag))return false;return!isBuiltinComponent(tag)}function analyzeJsxAst(ast,context){const{importedComponents,exportDefaultExpression}=collectJsxImportedComponentsAndDefaultExportFromBabelAst(ast,{isDefineComponentSource(source){return source===`wevu`||source===`vue`},resolveBabelComponentExpression:resolveComponentExpression});let renderExpression=null;let templateTags=/* @__PURE__ */ new Set;if(exportDefaultExpression){renderExpression=resolveRenderExpression(exportDefaultExpression,context);if(renderExpression)templateTags=collectJsxTemplateTagsFromBabelExpression(renderExpression,isCollectableJsxTemplateTag)}return{renderExpression,autoComponentContext:{templateTags,importedComponents}}}const EXTENSIONS=[``,`.tsx`,`.jsx`,`.ts`,`.js`];function resolveFile(source,importer){if(!source.startsWith(`.`))return;const base=path$1.resolve(path$1.dirname(importer),source);for(const extension of EXTENSIONS){const candidate=`${base}${extension}`;try{if(readFileSync(candidate,`utf8`)!==void 0)return candidate}catch{continue}}for(const extension of EXTENSIONS){const candidate=path$1.join(base,`index${extension}`);try{if(readFileSync(candidate,`utf8`)!==void 0)return candidate}catch{continue}}}function expressionFromDeclaration(node){if(!node)return;if(t.isJSXElement(node)||t.isJSXFragment(node))return{expression:node,params:[]};if(t.isArrowFunctionExpression(node)||t.isFunctionExpression(node)){let body;if(t.isBlockStatement(node.body)){const returned=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(returned&&t.isReturnStatement(returned)&&returned.argument&&t.isExpression(returned.argument))body=returned.argument}else body=node.body;if(body)return{expression:body,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}if(t.isFunctionDeclaration(node)){const body=node.body.body.find(statement=>t.isReturnStatement(statement)&&!!statement.argument);if(body&&t.isReturnStatement(body)&&body.argument&&t.isExpression(body.argument))return{expression:body.argument,params:node.params.filter(t.isIdentifier).map(param=>param.name)}}}function collectExports(ast){const locals=/* @__PURE__ */ new Map;const exports=/* @__PURE__ */ new Map;const reexports=/* @__PURE__ */ new Map;for(const statement of ast.program.body){if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init))locals.set(declaration.id.name,declaration.init)}if(t.isFunctionDeclaration(statement)&&statement.id)locals.set(statement.id.name,statement);if(t.isExportNamedDeclaration(statement)){if(statement.declaration){if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id)&&declaration.init&&t.isExpression(declaration.init)){locals.set(declaration.id.name,declaration.init);exports.set(declaration.id.name,declaration.id.name)}}if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id){locals.set(statement.declaration.id.name,statement.declaration);exports.set(statement.declaration.id.name,statement.declaration.id.name)}}for(const specifier of statement.specifiers)if(t.isExportSpecifier(specifier)&&t.isIdentifier(specifier.local)&&t.isIdentifier(specifier.exported)){exports.set(specifier.exported.name,specifier.local.name);if(statement.source)reexports.set(specifier.exported.name,{source:statement.source.value,importedName:specifier.local.name})}}if(t.isExportDefaultDeclaration(statement)&&statement.declaration){if(t.isFunctionDeclaration(statement.declaration)&&statement.declaration.id)locals.set(`default`,statement.declaration);else if(t.isExpression(statement.declaration))locals.set(`default`,statement.declaration)}}return{locals,exports,reexports}}function createJsxModuleResolver(warnings){const cache=/* @__PURE__ */ new Map;const active=/* @__PURE__ */ new Set;const dependencies=/* @__PURE__ */ new Set;function read(filename){const code=readFileSync(filename,`utf8`);const cached=cache.get(filename);if(cached?.code===code)return cached.exports;const collected=collectExports(parse$3(code,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename}));cache.set(filename,{code,exports:collected});return collected}function resolveExport(filename,localName){if(active.has(filename)){warnings?.push(`[JSX 编译] 检测到跨文件 JSX 循环引用:${filename}`);return}active.add(filename);try{const{locals,reexports}=read(filename);const direct=expressionFromDeclaration(locals.get(localName)??null);if(direct)return direct;const forwarded=reexports.get(localName);if(!forwarded)return;const target=resolveFile(forwarded.source,filename);if(target)dependencies.add(target);return target?resolveExport(target,forwarded.importedName):void 0}finally{active.delete(filename)}}function resolveImport(filename,source,importedName){const target=resolveFile(source,filename);if(!target)return;dependencies.add(target);return resolveExport(target,importedName==="default"?`default`:importedName)}return{getDependencies:()=>[...dependencies],resolveExport,resolveImport}}function normalizeSourceFile$1(filename){return filename.replaceAll(`\\`,`/`)}function resolveBindingSourceFile(context,ownerFile){if(!ownerFile||!context.filename||path$1.resolve(ownerFile)===path$1.resolve(context.filename))return;if(!context.bindingManifest.sourceFile)return normalizeSourceFile$1(ownerFile);const relativeOwner=path$1.relative(path$1.dirname(context.filename),ownerFile);return normalizeSourceFile$1(path$1.join(path$1.dirname(context.bindingManifest.sourceFile),relativeOwner))}function recordJsxBinding(context,node,kind,outputPath){const expression=normalizeInterpolationExpression(node,context);const sourceFile=resolveBindingSourceFile(context,node.loc?.filename);const sourceLocation=node.loc&&node.start!=null&&node.end!=null?{start:{offset:node.start,line:node.loc.start.line,column:node.loc.start.column+1},end:{offset:node.end,line:node.loc.end.line,column:node.loc.end.column+1}}:void 0;const scopes=[{kind:`root`,depth:0},...context.bindingScopeStack.map((scope,index)=>({kind:`for`,depth:index+1,locals:[...scope.locals]}))];recordSyntheticBindingExpression(context.bindingManifest,{kind,expression,outputPath,sourceFile,sourceLocation,scopes,scopeDependencies:context.bindingScopeStack.map(scope=>({expression:scope.sourceExpression,locals:scope.sourceLocals}))},context.scopeStack)}const ON_EVENT_RE=/^on[A-Z]/;const CATCH_EVENT_RE=/^catch[A-Z]/;const CAPTURE_BIND_EVENT_RE=/^captureBind[A-Z]/;const CAPTURE_CATCH_EVENT_RE=/^captureCatch[A-Z]/;const MUT_BIND_EVENT_RE=/^mutBind[A-Z]/;const UPPERCASE_STYLE_RE=/[A-Z]/g;function isEventBinding(name){return ON_EVENT_RE.test(name)||CATCH_EVENT_RE.test(name)||CAPTURE_BIND_EVENT_RE.test(name)||CAPTURE_CATCH_EVENT_RE.test(name)||MUT_BIND_EVENT_RE.test(name)}function lowerFirstEventName(name){if(!name)return name;return`${name.charAt(0).toLowerCase()}${name.slice(1)}`}function resolveMappedEventName(rawName,context,isComponent){const resolveEvent=name=>{const eventName=lowerFirstEventName(name);return isComponent?eventName:context.platform.mapEventName(eventName)};if(CAPTURE_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(11));if(CAPTURE_CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(12));if(MUT_BIND_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(7));if(CATCH_EVENT_RE.test(rawName))return resolveEvent(rawName.slice(5));return resolveEvent(rawName.slice(2))}function toEventBindingName(rawName,context,isComponent,tagName){const eventName=resolveMappedEventName(rawName,context,isComponent);if(ON_EVENT_RE.test(rawName)&&!isComponent){const sourceEventName=lowerFirstEventName(rawName.slice(2));const exactBinding=context.platform.eventBindingAlias?.(sourceEventName,tagName);if(exactBinding)return exactBinding}if(CAPTURE_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-bind:${eventName}`);if(CAPTURE_CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`capture-catch:${eventName}`);if(MUT_BIND_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`mut-bind:${eventName}`);if(CATCH_EVENT_RE.test(rawName))return context.platform.eventBindingAttr(`catch:${eventName}`);return context.platform.eventBindingAttr(`bind:${eventName}`)}function readJsxAttributeExpression(value){if(!value)return t.booleanLiteral(true);if(t.isStringLiteral(value))return value;if(!t.isJSXExpressionContainer(value))return null;if(t.isJSXEmptyExpression(value.expression))return null;return unwrapTsExpression(value.expression)}function extractJsxKeyExpression(node,context){for(const attr of node.openingElement.attributes){if(!t.isJSXAttribute(attr)||!t.isJSXIdentifier(attr.name))continue;if(attr.name.name!==`key`)continue;const exp=readJsxAttributeExpression(attr.value);if(!exp)return null;if(t.isStringLiteral(exp))return exp.value;return normalizeInterpolationExpression(exp,context)}return null}function compileEventAttribute(name,value,context,isComponent,tagName){const bindAttr=toEventBindingName(name,context,isComponent,tagName);const eventName=resolveMappedEventName(name,context,isComponent);const eventSuffix=normalizeEventDatasetSuffix(eventName);const exp=readJsxAttributeExpression(value);if(!exp)return[];if(t.isStringLiteral(exp)&&exp.value)return[`${bindAttr}="${escapeAttr(exp.value)}"`];if(t.isIdentifier(exp))return[`${bindAttr}="${escapeAttr(exp.name)}"`];if(t.isMemberExpression(exp)&&!exp.computed&&t.isThisExpression(exp.object)&&t.isIdentifier(exp.property))return[`${bindAttr}="${escapeAttr(exp.property.name)}"`];context.bindingManifest.features.inlineEvents=true;const inline=registerInlineExpression(exp,context);const attrs=[`data-${`wi`}-${eventSuffix}="${inline.id}"`,`${bindAttr}="${WEVU_INLINE_HANDLER}"`];inline.scopeKeys.forEach((scopeKey,index)=>{attrs.push(`data-wv-s${index}="${renderMustache(scopeKey,context)}"`)});return attrs}function compileNormalAttribute(name,value,context,isComponent){const normalizedName=name===`className`?`class`:isComponent?normalizeComponentHostName(name):name;const exp=readJsxAttributeExpression(value);if(!exp)return null;if(t.isStringLiteral(exp))return`${normalizedName}="${escapeAttr(exp.value)}"`;if(t.isBooleanLiteral(exp))return`${normalizedName}="${renderMustache(String(exp.value),context)}"`;if(normalizedName===`class`){const value=resolveStaticClass(exp);if(value!=null)return`class="${escapeAttr(value)}"`}if(normalizedName===`style`){const value=resolveStaticStyle(exp);if(value!=null)return`style="${escapeAttr(value)}"`}recordJsxBinding(context,exp,normalizedName===`class`?`class`:normalizedName===`style`?`style`:isComponent?`component-prop`:`attribute`);if(isComponent&&(t.isArrowFunctionExpression(exp)||t.isFunctionExpression(exp)))context.bindingManifest.features.functionProps=true;const normalizedExp=normalizeInterpolationExpression(exp,context);return`${normalizedName}="${renderMustache(normalizedExp,context)}"`}function compileNamedAttribute(name,value,context,isComponent,tagName){if(name===`key`)return[];if(name===`v-html`){context.warnings.push(`小程序不支持 JSX v-html,请使用 rich-text 组件替代。`);return[]}if(name===`v-if`||name===`v-show`||name===`v-text`||name===`v-for`)return[];if(name===`v-slots`||name===`v-model`||name===`v-models`){context.warnings.push(`JSX ${name} 需要 Wevu runtime 语义,已生成确定性诊断。`);return[]}if(name.startsWith(`v-`)){context.warnings.push(`小程序不支持 JSX 自定义指令 ${name},已移除该指令。`);return[]}if(name===`innerHTML`||name.startsWith(`domProps`)){context.warnings.push(`小程序不支持 JSX DOM property ${name},已移除该属性。`);return[]}if(isEventBinding(name))return compileEventAttribute(name,value,context,isComponent,tagName);const normalAttr=compileNormalAttribute(name,value,context,isComponent);return normalAttr?[normalAttr]:[]}function compileJsxAttributes(attributes,context,options){const isComponent=options?.isComponent===true;const output=[];for(const attr of attributes){if(t.isJSXSpreadAttribute(attr)){const argument=unwrapTsExpression(attr.argument);if(t.isObjectExpression(argument))for(const property of argument.properties)if(t.isObjectProperty(property)&&!property.computed&&(t.isIdentifier(property.key)||t.isStringLiteral(property.key))){const value=property.value;if(t.isExpression(value)){const name=t.isIdentifier(property.key)?property.key.name:property.key.value;output.push(...compileNamedAttribute(name,t.jsxExpressionContainer(value),context,isComponent,options?.tagName))}}else context.warnings.push(`JSX spread attributes 包含无法静态展开的属性,已保留为 dynamic island。`);else context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成确定性诊断。`);continue}if(t.isJSXNamespacedName(attr.name)){const namespace=attr.name.namespace.name;const name=attr.name.name.name;if(namespace.startsWith(`v-`))context.warnings.push(`小程序不支持 JSX 自定义指令 ${namespace}:${name},已移除该指令。`);else context.warnings.push(`小程序不支持 JSX 命名属性 ${namespace}:${name},已移除该属性。`);continue}if(!t.isJSXIdentifier(attr.name)){context.warnings.push(`小程序不支持 JSX 动态属性名,已移除该属性。`);continue}const name=attr.name.name;output.push(...compileNamedAttribute(name,attr.value,context,isComponent,options?.tagName))}return output}function staticObjectKey(node){if(t.isIdentifier(node))return node.name;if(t.isStringLiteral(node))return node.value}function resolveStaticClass(exp){if(t.isStringLiteral(exp)||t.isNumericLiteral(exp))return String(exp.value);if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticClass(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(` `)}if(t.isObjectExpression(exp)){const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed||!t.isBooleanLiteral(property.value))return;const key=staticObjectKey(property.key);if(key==null)return;if(property.value.value)values.push(key)}return values.join(` `)}}function resolveStaticStyle(exp){if(t.isStringLiteral(exp))return exp.value;if(t.isArrayExpression(exp)){const values=exp.elements.map(element=>{if(!element||!t.isExpression(element))return``;return resolveStaticStyle(element)});return values.some(value=>value==null)?void 0:values.filter(Boolean).join(`;`)}if(!t.isObjectExpression(exp))return;const values=[];for(const property of exp.properties){if(!t.isObjectProperty(property)||property.computed)return;const key=staticObjectKey(property.key)?.replace(UPPERCASE_STYLE_RE,char=>`-${char.toLowerCase()}`);if(!key||!t.isStringLiteral(property.value)&&!t.isNumericLiteral(property.value))return;values.push(`${key}:${property.value.value}`)}return values.join(`;`)}function isStaticClassStyleExpression(exp){return resolveStaticClass(exp)!=null||resolveStaticStyle(exp)!=null}const DYNAMIC_ISLAND_TEMPLATE_DEPTH=8;function resolveDynamicIslandTemplateName(depth){return depth===0?WEVU_JSX_ISLAND_TEMPLATE_NAME:`${WEVU_JSX_ISLAND_TEMPLATE_NAME}_${depth}`}function compileListExpression(exp,context){return normalizeInterpolationExpression(exp,context)}function registerDynamicIsland(exp,context,reason){if(context.dynamicIslandMode===`static`){context.warnings.push(`[JSX 编译] static 模式不允许 dynamic island(${reason})。`);return``}const id=`i${context.dynamicIslandSeed??0}`;context.dynamicIslandSeed=(context.dynamicIslandSeed??0)+1;context.bindingManifest.features.jsxIslands=true;recordJsxBinding(context,exp,`text`,WEVU_JSX_ISLAND_DATA_KEY);const expression=normalizeInterpolationExpression(exp);const captures=/* @__PURE__ */ new Set;const file=t.file(t.program([t.expressionStatement(t.cloneNode(exp,true))]));traverse(file,{ReferencedIdentifier(path){if(path.scope.hasBinding(path.node.name))return;if(context.importedBindings?.has(path.node.name))return;captures.add(path.node.name)},ThisExpression(){captures.add(`this`)}});context.dynamicIslands?.push({id,expression,reason,captures:[...captures]});return`<template is="${WEVU_JSX_ISLAND_TEMPLATE_NAME}" data-wv-jsx-island="${id}" data="{{node:${WEVU_JSX_ISLAND_DATA_KEY}.${id},islandId:'${id}'}}" />`}function renderDynamicIslandSupportTemplate(context){const{directives}=context.platform;const bindTap=context.platform.eventBindingAttr(`bind:tap`);const bindInput=context.platform.eventBindingAttr(`bind:input`);const bindChange=context.platform.eventBindingAttr(`bind:change`);const attrs=`id="{{node.props.id}}" class="{{node.props.class}}" style="{{node.props.style}}" hidden="{{node.props.hidden}}"`;const tapAttrs=`${attrs} data-wv-jsx-handler="{{node.events.tap}}" ${bindTap}="${WEVU_JSX_ISLAND_HANDLER}"`;return Array.from({length:DYNAMIC_ISLAND_TEMPLATE_DEPTH},(_,depth)=>{const templateName=resolveDynamicIslandTemplateName(depth);const childTemplateName=resolveDynamicIslandTemplateName(depth+1);const childTemplate=depth+1<DYNAMIC_ISLAND_TEMPLATE_DEPTH?`<block ${directives.forAttr}="{{node.children}}" ${directives.forItemAttr}="child" ${directives.keyAttr}="index"><template is="${childTemplateName}" data="{{node:child,islandId:islandId}}" /></block>`:``;return`<template name="${templateName}"><block ${directives.ifAttr}="{{node.kind=='text'}}">{{node.text}}</block><block ${directives.elifAttr}="{{node.kind=='fragment'}}">${childTemplate}</block><view ${directives.elifAttr}="{{node.tag=='view'}}" ${tapAttrs}>${childTemplate}</view><text ${directives.elifAttr}="{{node.tag=='text'}}" ${tapAttrs}>${childTemplate}</text><button ${directives.elifAttr}="{{node.tag=='button'}}" ${tapAttrs}>${childTemplate}</button><input ${directives.elifAttr}="{{node.tag=='input'}}" ${attrs} value="{{node.props.value}}" data-wv-jsx-handler="{{node.events.input||node.events.change}}" ${bindInput}="${WEVU_JSX_ISLAND_HANDLER}" ${bindChange}="${WEVU_JSX_ISLAND_HANDLER}" /><image ${directives.elifAttr}="{{node.tag=='image'}}" ${tapAttrs} src="{{node.props.src}}" /><block ${directives.elseAttr}>${childTemplate}</block></template>`}).join(``)}function resolveImportedExpression(node,context){if(!context.filename||!context.moduleResolver)return;let localName;let importedName;if(t.isIdentifier(node))localName=node.name;else if(t.isMemberExpression(node)&&!node.computed&&t.isIdentifier(node.object)&&t.isIdentifier(node.property)){localName=node.object.name;importedName=node.property.name}if(!localName)return;const binding=context.importedBindings?.get(localName);if(!binding)return;if(binding.importedName!==`*`&&importedName)return;const resolvedName=importedName??binding.importedName;const key=`${context.filename}:${localName}:${resolvedName}`;if(context.resolvingExports?.has(key)){context.warnings.push(`[JSX 编译] 跨文件 JSX 导出循环引用:${localName}`);return}context.resolvingExports?.add(key);try{return context.moduleResolver.resolveImport(context.filename,binding.source,resolvedName)}finally{context.resolvingExports?.delete(key)}}function compileImportedExpression(node,context){const resolved=resolveImportedExpression(node,context);if(!resolved||resolved.params.length>0){const importedLocal=t.isIdentifier(node)?node.name:t.isMemberExpression(node)&&t.isIdentifier(node.object)?node.object.name:``;if(context.importedBindings?.has(importedLocal)){context.warnings.push(`[JSX 编译] 无法静态展开跨文件 JSX 导出,已生成 dynamic island:${importedLocal||`unknown`}`);return registerDynamicIsland(node,context,`unsupported-import`)}return null}return compileRenderableExpression(resolved.expression,context)}function compileImportedFactoryCall(node,context){if(!t.isIdentifier(node.callee)||!context.filename||!context.moduleResolver)return null;const binding=context.importedBindings?.get(node.callee.name);if(!binding)return null;const resolved=context.moduleResolver.resolveImport(context.filename,binding.source,binding.importedName);if(!resolved||resolved.params.length===0){context.warnings.push(`[JSX 编译] 无法静态展开 JSX 工厂 ${node.callee.name},已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}const replacements=/* @__PURE__ */ new Map;resolved.params.forEach((param,index)=>{const argument=node.arguments[index];if(argument&&t.isExpression(argument))replacements.set(param,argument)});if(replacements.size!==resolved.params.length){context.warnings.push(`[JSX 编译] JSX 工厂 ${node.callee.name} 调用参数不足,已保留运行时表达式。`);return null}const expression=t.cloneNode(resolved.expression,true);const file=t.file(t.program([t.expressionStatement(expression)]));traverse(file,{ReferencedIdentifier(path){const replacement=replacements.get(path.node.name);if(replacement)path.replaceWith(t.cloneNode(replacement,true))}});const output=file.program.body[0];if(!t.isExpressionStatement(output))return null;let expanded=output.expression;if(t.isCallExpression(expanded)&&expanded.arguments.length===0){const callee=expanded.callee;if(t.isArrowFunctionExpression(callee)||t.isFunctionExpression(callee)){const body=callee.body;let capturesThis=false;if(t.isExpression(body)){const file=t.file(t.program([t.expressionStatement(body)]));traverse(file,{ThisExpression(){capturesThis=true}});if(!capturesThis)expanded=body}}}return compileRenderableExpression(expanded,context)}function compileMapExpression(exp,context){const callee=exp.callee;if(!t.isMemberExpression(callee)||!t.isIdentifier(callee.property,{name:`map`}))return null;const callback=exp.arguments[0];if(!callback||!(t.isArrowFunctionExpression(callback)||t.isFunctionExpression(callback))){context.warnings.push(`仅支持 map(fn) 形式的列表渲染。`);return null}recordJsxBinding(context,callee.object,`for`);const listExp=compileListExpression(callee.object,context);const renderTemplateMustache=expression=>renderMustache(expression,context);const itemParam=callback.params[0];const indexParam=callback.params[1];const item=t.isIdentifier(itemParam)?itemParam.name:`item`;const index=t.isIdentifier(indexParam)?indexParam.name:void 0;const addedScope=[item,index].filter(name=>!!name);pushScope(context,addedScope,listExp);let bodyExp=null;if(t.isBlockStatement(callback.body)){for(const statement of callback.body.body)if(t.isReturnStatement(statement)&&statement.argument){bodyExp=unwrapTsExpression(statement.argument);break}}else bodyExp=unwrapTsExpression(callback.body);const body=bodyExp?compileRenderableExpression(bodyExp,context):``;if(!body){popScope(context,addedScope.length);return``}let keyValue=context.platform.keyThisValue;if(bodyExp&&t.isJSXElement(bodyExp)){const extracted=extractJsxKeyExpression(bodyExp,context);if(extracted)keyValue=extracted;else if(index)keyValue=index}else if(index)keyValue=index;popScope(context,addedScope.length);return`<block ${[...context.platform.forAttrs(listExp,renderTemplateMustache,item,index),context.platform.keyAttr(keyValue)].join(` `)}>${body}</block>`}function compileConditionalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.test,`if`);const test=normalizeInterpolationExpression(exp.test,context);const consequent=compileRenderableExpression(exp.consequent,context);const alternate=compileRenderableExpression(exp.alternate,context);if(!alternate)return context.platform.wrapIf(test,consequent,renderTemplateMustache);return`${context.platform.wrapIf(test,consequent,renderTemplateMustache)}${context.platform.wrapElse(alternate)}`}function compileLogicalExpression(exp,context){const renderTemplateMustache=expression=>renderMustache(expression,context);recordJsxBinding(context,exp.left,`if`);if(exp.operator===`&&`){const test=normalizeInterpolationExpression(exp.left,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}if(exp.operator===`||`){const negated=t.unaryExpression(`!`,t.parenthesizedExpression(t.cloneNode(exp.left,true)));const test=normalizeInterpolationExpression(negated,context);const content=compileRenderableExpression(exp.right,context);return context.platform.wrapIf(test,content,renderTemplateMustache)}return renderMustache(normalizeInterpolationExpression(exp,context),context)}function compileRenderableExpression(exp,context){const node=unwrapTsExpression(exp);if(t.isJSXElement(node))return compileJsxElement(node,context);if(t.isJSXFragment(node))return compileJsxFragment(node,context);if(t.isConditionalExpression(node))return compileConditionalExpression(node,context);if(t.isLogicalExpression(node))return compileLogicalExpression(node,context);if(t.isCallExpression(node)){const importedFactory=compileImportedFactoryCall(node,context);if(importedFactory!=null)return importedFactory;const mapped=compileMapExpression(node,context);if(mapped!=null)return mapped;context.warnings.push(`无法证明 JSX 子节点函数调用返回静态文本,已生成 dynamic island。`);return registerDynamicIsland(node,context,`unsupported-call`)}if(t.isArrayExpression(node))return node.elements.map(element=>{if(!element||!t.isExpression(element))return``;return compileRenderableExpression(element,context)}).join(``);if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=compileImportedExpression(node,context);if(imported!=null)return imported}if(t.isNullLiteral(node)||t.isBooleanLiteral(node))return``;recordJsxBinding(context,node,`text`);return renderMustache(normalizeInterpolationExpression(node,context),context)}function compileExpressionContainer(node,context){const exp=node.expression;if(t.isJSXEmptyExpression(exp))return``;return compileRenderableExpression(exp,context)}function compileJsxChildren(children,context){const parts=[];for(const child of children){if(t.isJSXText(child)){const normalized=normalizeJsxText(child.value);if(!normalized.trim())continue;parts.push(escapeText(normalized));continue}if(t.isJSXExpressionContainer(child)){const chunk=compileExpressionContainer(child,context);if(chunk)parts.push(chunk);continue}if(t.isJSXElement(child)){parts.push(compileJsxElement(child,context));continue}if(t.isJSXFragment(child)){parts.push(compileJsxFragment(child,context));continue}if(t.isJSXSpreadChild(child)){parts.push(registerDynamicIsland(child.expression,context,`spread-child`));context.warnings.push(`JSX spread child 无法映射为静态 WXML,已生成 dynamic island。`)}}return parts.join(``)}function compileJsxFragment(node,context){return compileJsxChildren(node.children,context)}function compileJsxElement(node,context){if(t.isJSXMemberExpression(node.openingElement.name)){context.warnings.push(`JSX 成员标签(如 <Foo.Bar />)无法映射为小程序 WXML 组件标签,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}const dynamicSpread=node.openingElement.attributes.find(attr=>{if(!t.isJSXSpreadAttribute(attr))return false;const argument=unwrapTsExpression(attr.argument);return!t.isObjectExpression(argument)||argument.properties.some(property=>!t.isObjectProperty(property)||property.computed||!t.isIdentifier(property.key)&&!t.isStringLiteral(property.key)||!t.isExpression(property.value))});if(dynamicSpread&&t.isJSXSpreadAttribute(dynamicSpread)){context.warnings.push(`动态 JSX spread attributes 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-spread`)}const rawTag=toJsxTagName(node.openingElement.name,context);if(rawTag===`component`){context.warnings.push(`JSX 动态 component 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Teleport`){context.warnings.push(`小程序不支持 JSX <Teleport>,已生成 dynamic island。`);return registerDynamicIsland(node,context,`dynamic-component`)}if(rawTag===`Transition`){context.warnings.push(`JSX <Transition> 需要 Web 动画运行时,当前仅渲染子节点。`);return compileJsxChildren(node.children,context)}if(rawTag===`KeepAlive`){context.warnings.push(`JSX <KeepAlive> 需要运行时缓存管理,当前仅保留标记并渲染子节点。`);return`<block data-keep-alive="true">${compileJsxChildren(node.children,context)}</block>`}const isComponent=!isBuiltinComponent(rawTag);const tag=isComponent?hyphenate(rawTag):rawTag;if(node.children.some(child=>{if(!t.isJSXExpressionContainer(child)||t.isJSXEmptyExpression(child.expression))return false;const expression=unwrapTsExpression(child.expression);return t.isObjectExpression(expression)||t.isFunctionExpression(expression)||t.isArrowFunctionExpression(expression)})){context.warnings.push(`JSX slot 函数或对象 slots 无法映射为静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}if(node.openingElement.attributes.some(attribute=>{if(!t.isJSXAttribute(attribute)||!t.isJSXIdentifier(attribute.name))return false;if(attribute.name.name!==`class`&&attribute.name.name!==`className`&&attribute.name.name!==`style`)return false;const expression=readJsxAttributeExpression(attribute.value);return!!expression&&(t.isArrayExpression(expression)||t.isObjectExpression(expression))&&!isStaticClassStyleExpression(expression)})){context.warnings.push(`动态 JSX class/style 数组或对象需要运行时合并,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const directives=/* @__PURE__ */ new Map;for(const attribute of node.openingElement.attributes){if(!t.isJSXAttribute(attribute))continue;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(!name?.startsWith(`v-`))continue;const expression=readJsxAttributeExpression(attribute.value);if(expression)directives.set(name,expression)}if(directives.has(`v-for`)||directives.has(`v-slots`)||directives.has(`v-model`)||directives.has(`v-models`)){const directive=[`v-for`,`v-slots`,`v-model`,`v-models`].find(name=>directives.has(name));if(directive===`v-model`||directive===`v-models`)context.bindingManifest.features.model=true;context.warnings.push(`JSX ${directive} 无法直接映射当前静态 WXML,已生成 dynamic island。`);return registerDynamicIsland(node,context,`closure`)}const attrs=compileJsxAttributes(node.openingElement.attributes,context,{isComponent,tagName:tag});const showExpression=directives.get(`v-show`);if(showExpression){recordJsxBinding(context,showExpression,`style`);attrs.push(`hidden="${renderMustache(`!(${normalizeInterpolationExpression(showExpression,context)})`,context)}"`)}const attrsSegment=attrs.length?` ${attrs.join(` `)}`:``;const textExpression=directives.get(`v-text`);if(textExpression)recordJsxBinding(context,textExpression,`text`);const content=textExpression?renderMustache(normalizeInterpolationExpression(textExpression,context),context):compileJsxChildren(node.children,context);const element=node.openingElement.selfClosing&&!textExpression?`<${tag}${attrsSegment} />`:`<${tag}${attrsSegment}>${content}</${tag}>`;const ifExpression=directives.get(`v-if`);if(ifExpression){recordJsxBinding(context,ifExpression,`if`);return context.platform.wrapIf(normalizeInterpolationExpression(ifExpression,context),element,expression=>renderMustache(expression,context))}return element}function createJsxCompileContext(options){return{platform:options?.template?.platform??getMiniProgramTemplatePlatform(),mustacheInterpolation:options?.template?.mustacheInterpolation??`compact`,formatWxml:options?.template?.formatWxml??false,warnings:[],bindingManifest:createBindingManifest(options?.bindingManifestSourceFile??``),inlineExpressions:[],classStyleBindings:[],forStack:[],interpolationCache:/* @__PURE__ */ new WeakMap,inlineExpressionSeed:0,scopeStack:[],bindingScopeStack:[],moduleResolver:void 0,importedBindings:/* @__PURE__ */ new Map,resolvingExports:/* @__PURE__ */ new Set,dynamicIslands:[],dynamicIslandSeed:0,dynamicIslandMode:`auto`}}function collectImportedBindings(ast,context){for(const statement of ast.program.body){if(!t.isImportDeclaration(statement))continue;const source=statement.source.value;for(const specifier of statement.specifiers)if(t.isImportSpecifier(specifier)&&t.isIdentifier(specifier.local)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:specifier.imported.value;context.importedBindings?.set(specifier.local.name,{source,importedName})}else if(t.isImportDefaultSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`default`});else if(t.isImportNamespaceSpecifier(specifier)&&t.isIdentifier(specifier.local))context.importedBindings?.set(specifier.local.name,{source,importedName:`*`})}}function compileJsxTemplateAndCollectComponents(source,filename,options){const ast=parse$3(source,{...BABEL_TS_MODULE_PARSER_OPTIONS,sourceFilename:filename});const context=createJsxCompileContext(options);context.filename=filename;context.bindingManifest.sourceFile=options?.bindingManifestSourceFile??filename;context.moduleResolver=createJsxModuleResolver(context.warnings);collectImportedBindings(ast,context);const{renderExpression,autoComponentContext}=analyzeJsxAst(ast,context);let template;if(renderExpression){template=compileRenderableExpression(renderExpression,context);if(context.dynamicIslands?.length)template+=renderDynamicIslandSupportTemplate(context);if(context.formatWxml)template=formatWxml(template)}else context.warnings=context.warnings.map(message=>message===`未识别到默认导出组件。`?`未在 ${filename} 中识别到默认导出组件。`:message);return{template,warnings:context.warnings,bindingManifest:context.bindingManifest,inlineExpressions:context.inlineExpressions,classStyleBindings:context.classStyleBindings,autoComponentContext,dynamicIslands:context.dynamicIslands,dependencies:context.moduleResolver.getDependencies()}}const DEFAULT_VUE_JSX_TRANSFORM_OPTIONS={enableObjectSlots:true,mergeProps:true,optimize:true,resolveType:false,transformOn:true};function readDirectiveExpression(attribute){if(!attribute.value)return t.booleanLiteral(true);if(!t.isJSXExpressionContainer(attribute.value)||t.isJSXEmptyExpression(attribute.value.expression))return;return t.isExpression(attribute.value.expression)?attribute.value.expression:void 0}function createWevuJsxDirectiveCompatibilityPlugin(){return{name:`wevu-jsx-directive-compatibility`,visitor:{JSXElement(path){const attributes=path.node.openingElement.attributes;let ifExpression;let textExpression;path.node.openingElement.attributes=attributes.filter(attribute=>{if(!t.isJSXAttribute(attribute))return true;const name=t.isJSXIdentifier(attribute.name)?attribute.name.name:t.isJSXNamespacedName(attribute.name)?attribute.name.namespace.name:void 0;if(name===`v-if`){ifExpression=readDirectiveExpression(attribute);return false}if(name===`v-text`){textExpression=readDirectiveExpression(attribute);return false}if(name?.startsWith(`v-`)&&![`v-html`,`v-model`,`v-models`,`v-show`,`v-slots`].includes(name))return false;return true});if(textExpression)path.node.children=[t.jsxExpressionContainer(textExpression)];if(ifExpression)path.replaceWith(t.conditionalExpression(ifExpression,path.node,t.nullLiteral()))}}}}function transformVueJsxScript(source,filename,sourceMaps=true,options){const result=transformSync(source,{filename,sourceType:`module`,sourceMaps,plugins:[createWevuJsxDirectiveCompatibilityPlugin,[vueJsxPlugin,{...DEFAULT_VUE_JSX_TRANSFORM_OPTIONS,...options}]],parserOpts:{plugins:[`typescript`,`jsx`]},generatorOpts:{retainLines:!sourceMaps}});return{code:result?.code??source,map:result?.map?{...result.map,file:result.map.file??void 0}:null}}const LEADING_DOT_RE=/^\./;const SETUP_CALL_RE$1=/\bsetup\s*\(/;function normalizeUsingComponentFrom(value){if(!value)return;return typeof value===`string`?value:value.from}function toMiniProgramComponentTag(name){return name.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).toLowerCase()}async function compileJsxFile(source,filename,options){if(options?.isPage&&mayContainPageDeclaration(source))source=stripPageDeclaration(source,filename)?.code??source;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});let scriptSource=source;let scriptMacroConfig;let scriptMacroHash;const scriptLang=path.extname(filename).replace(LEADING_DOT_RE,``)||void 0;if(mayContainJsonMacro(source))try{const extracted=await extractJsonMacroFromScriptSetup(source,filename,scriptLang,{merge:(target,incoming)=>mergeJson(target,incoming,`macro`)});scriptSource=extracted.stripped;scriptMacroConfig=extracted.config;scriptMacroHash=extracted.macroHash}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 ${filename} 失败:${message}`)}const{template:rawTemplate,warnings:templateWarnings,bindingManifest,inlineExpressions,classStyleBindings,autoComponentContext,dynamicIslands,dependencies}=compileJsxTemplateAndCollectComponents(source,filename,options);const autoUsingComponentsMap={};const localComponentAliases=/* @__PURE__ */ new Map;if(options?.autoUsingComponents?.resolveUsingComponentPath&&autoComponentContext.templateTags.size>0)for(const imported of autoComponentContext.importedComponents){if(!autoComponentContext.templateTags.has(imported.localName))continue;let resolved=normalizeUsingComponentFrom(await options.autoUsingComponents.resolveUsingComponentPath(imported.importSource,filename,{localName:imported.localName,importedName:imported.importedName,kind:imported.kind}));if(!resolved&&imported.importSource.startsWith(`/`))resolved=removeExtensionDeep(imported.importSource);if(!resolved)continue;const componentName=imported.importSource.startsWith(`.`)||imported.importSource.startsWith(`/`)?toMiniProgramComponentTag(imported.localName):imported.localName;autoUsingComponentsMap[componentName]=resolved;if(componentName!==imported.localName)localComponentAliases.set(imported.localName,componentName)}const autoImportTagsMap={};if(options?.autoImportTags?.resolveUsingComponent&&autoComponentContext.templateTags.size>0)for(const tag of autoComponentContext.templateTags){if(!isAutoImportCandidateTag(tag))continue;let resolved;try{resolved=await options.autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;const resolvedName=resolved.name||tag;autoImportTagsMap[localComponentAliases.get(resolvedName)??resolvedName]=resolved.from}let compiledTemplateStr=rawTemplate;for(const[from,to]of localComponentAliases)if(compiledTemplateStr)compiledTemplateStr=compiledTemplateStr.replaceAll(`<${from}`,`<${to}`).replaceAll(`</${from}>`,`</${to}>`);if(compiledTemplateStr&&(options?.pageLayout||options?.appShell))compiledTemplateStr=applyCompilerTemplateWrappers({template:compiledTemplateStr,manifest:bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const normalizedScriptSource=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptSource,filename,templateWarnings),dynamicIslands);const vueJsxTransformed=transformVueJsxScript(normalizedScriptSource,filename,options?.sourceMap!==false);const runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest);const transformedScript=transformScript(vueJsxTransformed.code,{skipComponentTransform:options?.skipComponentTransform??options?.isApp,isApp:options?.isApp,isPage:options?.isPage,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,wevuDefaults:options?.wevuDefaults,inlineExpressions,classStyleBindings,bindingManifest:options?.isApp?void 0:bindingManifest,autoSetDataPick:!options?.isApp&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:options?.isApp?void 0:options?.pageLayout,runtimeCapabilities});const diagnostics=templateWarnings.length?createJsxDiagnostics(templateWarnings,filename):void 0;if(diagnostics&&options?.warn)diagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message));let configObj;if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents=existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw)?existingRaw:{};for(const[name,from]of Object.entries(autoImportTagsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoImportTags?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 标签自动引入覆盖为 '${from}'`);usingComponents[name]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){if(Reflect.has(usingComponents,name)&&usingComponents[name]!==from)options?.autoUsingComponents?.warn?.(`[JSX 编译] usingComponents 冲突:${filename} 中 usingComponents['${name}']='${usingComponents[name]}' 将被 JSX 导入组件覆盖为 '${from}'`);usingComponents[name]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptMacroConfig&&Object.keys(scriptMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptMacroConfig,`macro`);const config=mergeCompilerLayoutUsingComponents(configObj&&Object.keys(configObj).length>0?JSON.stringify(configObj,null,2):void 0,options?.pageLayout,options?.appShell);return{script:transformedScript.code,scriptMap:transformedScript.map??vueJsxTransformed.map,template:compiledTemplateStr,diagnostics,bindingManifest,config,meta:{hasScriptSetup:false,hasSetupOption:SETUP_CALL_RE$1.test(normalizedScriptSource),jsonMacroHash:scriptMacroHash,jsxDynamicIslands:dynamicIslands,...transformedScript.componentStyleOptions?{componentStyleOptions:transformedScript.componentStyleOptions}:{},...transformedScript.runtimeCapabilities?{runtimeCapabilities:transformedScript.runtimeCapabilities}:{},jsxDependencies:dependencies}}}const DIRECTIVE_TOKEN_RE=/\/\/\s*#(?:ifdef|ifndef|else|endif)\b[^\r\n]*|\/\*+\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?\*\/|<!--\s*#(?:ifdef|ifndef|else|endif)\b[\s\S]*?-->/g;const SCRIPT_EXT_RE=/\.[cm]?[jt]sx?$/i;const STYLE_EXT_RE=/\.(?:css|less|sass|scss|styl|stylus)$/i;const UNI_APP_RUNTIME_MODULE=`@dcloudio/uni-app`;function resolveRuntimeImport(source){if(source===`vue`||source===UNI_APP_RUNTIME_MODULE)return`wevu`}function evaluateCondition(expression,defines,filename,line){const normalized=expression.replace(/(?:\*\/|-->)\s*$/,``).trim();const tokens=normalized.match(/[A-Z][A-Z0-9_-]*|&&|\|\||[()!]/g)??[];if(!tokens.length||tokens.join(``)!==normalized.replace(/\s/g,``))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);let index=0;const parser={parseAnd(){let value=parser.parsePrimary();while(tokens[index]===`&&`){index+=1;const right=parser.parsePrimary();value=value&&right}return value},parseOr(){let value=parser.parseAnd();while(tokens[index]===`||`){index+=1;const right=parser.parseAnd();value=value||right}return value},parsePrimary(){const token=tokens[index];if(token===`!`){index+=1;return!parser.parsePrimary()}if(token===`(`){index+=1;const value=parser.parseOr();if(tokens[index]!==`)`)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return value}if(!token||!/^[A-Z][A-Z0-9_-]*$/.test(token))throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);index+=1;return defines.has(token)}};const value=parser.parseOr();if(index!==tokens.length)throw new Error(`[uni-app] ${filename}:${line} 包含无效的条件表达式 "${normalized}"`);return value}function transformUniAppConditionalCode(source,options){const defines=new Set(options.target===`h5`?[`H5`,`VUE3`]:[`MP`,`MP-WEIXIN`,`VUE3`]);const frames=[];let active=true;let changed=false;let cursor=0;let line=1;let code=``;for(const match of source.matchAll(DIRECTIVE_TOKEN_RE)){const offset=match.index;const segment=source.slice(cursor,offset);code+=active?segment:segment.replace(/[^\r\n]/g,``);line+=segment.split(`
|
|
26
26
|
`).length-1;const directiveSource=match[0].slice(match[0].indexOf(`#`));const directiveMatch=directiveSource.match(/^#(ifdef|ifndef|else|endif)\b/);if(!directiveMatch)continue;changed=true;const directive=directiveMatch[1];if(directive===`ifdef`||directive===`ifndef`){const condition=evaluateCondition(directiveSource.slice(directiveMatch[0].length),defines,options.filename,line);frames.push({condition,elseSeen:false,parentActive:active});active=active&&(directive===`ifdef`?condition:!condition)}else{const frame=frames[frames.length-1];if(!frame)throw new Error(`[uni-app] ${options.filename}:${line} 存在未配对的 #${directive}`);if(directive===`else`){if(frame.elseSeen)throw new Error(`[uni-app] ${options.filename}:${line} 同一条件块不能出现多个 #else`);frame.elseSeen=true;active=frame.parentActive&&!frame.condition}else{frames.pop();active=frame.parentActive}}code+=match[0].replace(/[^\r\n]/g,``);line+=match[0].split(`
|
|
27
27
|
`).length-1;cursor=offset+match[0].length}const trailing=source.slice(cursor);code+=active?trailing:trailing.replace(/[^\r\n]/g,``);if(frames.length)throw new Error(`[uni-app] ${options.filename} 存在未闭合的条件编译块`);return{changed,code}}function normalizeAuxiliaryWxsScripts(source){const wxsBlocks=[];const withoutScripts=source.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,(block,attributes,content)=>{const src=attributes.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];const moduleName=attributes.match(/\bmodule\s*=\s*["']([^"']+)["']/i)?.[1];if(!(/\blang\s*=\s*["']wxs["']/i.test(attributes)||src?.endsWith(`.wxs`))||!moduleName)return block;wxsBlocks.push(src?`<wxs module="${moduleName}" src="${src}" />`:`<wxs module="${moduleName}">${content}</wxs>`);return block.replace(/[^\r\n]/g,``)});if(!wxsBlocks.length)return source;return withoutScripts.replace(/<template\b[^>]*>/i,match=>`${match}\n${wxsBlocks.join(`
|
|
28
28
|
`)}`)}function analyzeScript(source,filename){if(!source.trim())return{source,importSources:[],importEnd:0,usesFreeUni:false,virtualHostTrueRanges:[]};const isJsx=/\.[cm]?[jt]sx$/i.test(filename);const ast=parse$3(source,{sourceType:`module`,plugins:[`typescript`,`decorators-legacy`,...isJsx?[`jsx`]:[]]});const importSources=[];let importEnd=0;let usesFreeUni=false;const virtualHostTrueRanges=[];traverse(ast,{ImportDeclaration(path){const sourceNode=path.node.source;if(typeof path.node.end===`number`)importEnd=Math.max(importEnd,path.node.end);const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportAllDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ExportNamedDeclaration(path){const sourceNode=path.node.source;const replacement=t.isStringLiteral(sourceNode)?resolveRuntimeImport(sourceNode.value):void 0;if(replacement)importSources.push({start:sourceNode.start,end:sourceNode.end,replacement})},ReferencedIdentifier(path){if(path.node.name===`uni`&&!path.scope.hasBinding(`uni`))usesFreeUni=true},ObjectProperty(path){const key=path.node.key;if(!(!path.node.computed&&(t.isIdentifier(key,{name:`virtualHost`})||t.isStringLiteral(key,{value:`virtualHost`})))||!t.isBooleanLiteral(path.node.value,{value:true})||!path.parentPath?.isObjectExpression())return;const optionsProperty=path.parentPath.parentPath;if(!optionsProperty?.isObjectProperty()||optionsProperty.node.computed||!(t.isIdentifier(optionsProperty.node.key,{name:`options`})||t.isStringLiteral(optionsProperty.node.key,{value:`options`})))return;const{start,end}=path.node.value;if(typeof start===`number`&&typeof end===`number`)virtualHostTrueRanges.push({start,end})}});return{source,importSources,importEnd,usesFreeUni,virtualHostTrueRanges}}function renderScript(analysis,injectUni,disableVirtualHost){const output=new MagicString(analysis.source);for(const source of analysis.importSources)output.overwrite(source.start,source.end,JSON.stringify(source.replacement));if(injectUni){const insertion=analysis.importEnd>0?analysis.importEnd:0;output.prepend(`import { createUniAppHost as __wevuCreateUniAppHost } from 'wevu/internal-runtime'\n`);output.appendLeft(insertion,`${insertion>0?`
|
|
29
|
-
`:``}const uni = __wevuCreateUniAppHost(wx)\n`)}if(disableVirtualHost)for(const range of analysis.virtualHostTrueRanges)output.overwrite(range.start,range.end,`false`);return output.toString()}function transformVueSfc(source,filename,target){const normalizedSource=normalizeAuxiliaryWxsScripts(source);const{descriptor,errors}=parse$1(normalizedSource,{filename});if(errors.length){const error=errors[0];throw new Error(`[uni-app] 解析 ${filename} 失败:${error.message}`)}const blocks=[descriptor.script,descriptor.scriptSetup].filter(Boolean);const analyses=blocks.map(block=>{const lang=block.lang??`js`;return analyzeScript(block.content,`${filename}.${lang}`)});const injectIndex=analyses.findIndex(analysis=>analysis.usesFreeUni);const output=new MagicString(normalizedSource);for(let index=blocks.length-1;index>=0;index-=1){const block=blocks[index];const analysis=analyses[index];const code=renderScript(analysis,index===injectIndex,target===`mp-weixin`);output.overwrite(block.loc.start.offset,block.loc.end.offset,code)}return output.toString()}function transformUniAppSource(source,options){const conditional=transformUniAppConditionalCode(source,options);const filename=options.filename.split(`?`,1)[0];const blockType=options.blockType??(filename.endsWith(`.vue`)?`sfc`:SCRIPT_EXT_RE.test(filename)?`script`:STYLE_EXT_RE.test(filename)?`style`:void 0);if(blockType===`sfc`){const code=transformVueSfc(conditional.code,filename,options.target);return{changed:conditional.changed||code!==source,code}}if(blockType===`script`){const analysis=analyzeScript(conditional.code,filename);const code=renderScript(analysis,analysis.usesFreeUni,options.target===`mp-weixin`&&filename.endsWith(`.vue`));return{changed:conditional.changed||code!==source,code}}if(blockType===`style`||blockType===`template`)return conditional;return{changed:false,code:source}}function isUniAppCompatibilityFile(filename,srcRoot,include){const clean=filename.split(`?`,1)[0];const relative=path.relative(srcRoot,clean);if(relative===``||!relative.startsWith(`..`)&&!path.isAbsolute(relative))return true;const normalized=clean.replace(/\\/g,`/`);return include.some(packageName=>{const packagePath=packageName.replace(/^\/+|\/+$/g,``);return normalized.includes(`/node_modules/${packagePath}/`)})}function transformNestedWxssVars(source){return source}function normalizeStyleError(error){return error instanceof Error?error.message:String(error)}function hasSlottedScopeSelector(source,slottedScopeId){let found=false;const processor=selectorParser(selectors=>{selectors.walkAttributes(attribute=>{if(attribute.attribute===slottedScopeId)found=true})});postcss.parse(source).walkRules(rule=>{if(!found)processor.processSync(rule.selector)});return found}function transformVueDeepSelectors(source){const root=postcss.parse(source);const processor=selectorParser(selectors=>{selectors.walkTags(tag=>{const mapped=DEFAULT_HTML_TO_WXML_TAG_MAP[tag.value.toLowerCase()];if(mapped&&mapped!==tag.value.toLowerCase())tag.replaceWith(selectorParser.className({value:tag.value.toLowerCase()}))});selectors.walkPseudos(pseudo=>{if(![`:deep`,`::v-deep`].includes(pseudo.value))return;const replacement=pseudo.nodes?.[0]?.nodes.map(node=>node.clone())??[];replacement.length?pseudo.replaceWith(...replacement):pseudo.remove()})});root.walkRules(rule=>{rule.selector=processor.processSync(rule.selector).replace(/\s{2,}/g,` `).trim()});return root.toString()}async function compileVueStyleToWxss(styleBlock,options){const filename=options.filename??`style-${options.id}.${styleBlock.lang||`css`}`;const moduleName=typeof styleBlock.module===`string`?styleBlock.module:typeof options.modules===`string`?options.modules:`$style`;const modules=Boolean(options.modules||styleBlock.module);const result=await compileStyleAsync({filename,id:`data-v-${options.id}`,source:styleBlock.content,scoped:options.transformScoped!==false&&Boolean(options.scoped||styleBlock.scoped),modules,modulesOptions:modules?{generateScopedName:name=>`${name}_${options.id}`}:void 0,preprocessLang:styleBlock.lang,preprocessOptions:options.preprocessOptions});if(result.errors.length)throw new Error(`SFC 样式编译失败(${filename}):${result.errors.map(normalizeStyleError).join(`; `)}`);return{code:options.preserveDeepSelectors?result.code:transformVueDeepSelectors(result.code),map:result.map?JSON.stringify(result.map):void 0,scopedId:options.scoped||styleBlock.scoped?`data-v-${options.id}`:void 0,usesSlotted:hasSlottedScopeSelector(result.code,`data-v-${options.id}-s`),modules:result.modules?{[moduleName]:result.modules}:void 0,dependencies:[...result.dependencies]}}const CLASS_LIKE_TEMPLATE_ATTR_RE=/(?:^|[\s<])(?:[\w-]*class[\w-]*|v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[^\s>]+)/g;const VUE_DYNAMIC_CLASS_LIKE_BINDING_RE=/(?:^|[\s<])(?:v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=/;function hashPayload$1(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function collectTemplateTailwindCandidates(content){const candidates=/* @__PURE__ */ new Set;for(const match of content.matchAll(CLASS_LIKE_TEMPLATE_ATTR_RE))candidates.add(match[0].trim());return Array.from(candidates).sort()}function normalizeTailwindContentPayload(payload){const scriptLiterals=VUE_DYNAMIC_CLASS_LIKE_BINDING_RE.test(payload.template)?payload.scriptLiterals:payload.hasScriptTailwindClassHint?payload.scriptCallLiterals:[];return{...payload,template:collectTemplateTailwindCandidates(payload.template),scriptLiterals,scriptCallLiterals:[]}}function buildTailwindContentPayload(template,scriptContent,scriptSetupContent){return{template,scriptLiterals:[...collectScriptStringLiterals(scriptContent),...collectScriptStringLiterals(scriptSetupContent)],scriptCallLiterals:[...collectScriptCallStringLiterals(scriptContent),...collectScriptCallStringLiterals(scriptSetupContent)],hasScriptTailwindClassHint:mayContainScriptCallOrModuleSyntax(`${scriptContent}\n${scriptSetupContent}`)}}function hashTailwindContentPayload(payload){return hashPayload$1(normalizeTailwindContentPayload(payload))}function hashTailwindTemplateContentPayload(payload){return hashPayload$1({template:normalizeTailwindContentPayload(payload).template})}function hashTailwindScriptContentPayload(payload){return hashPayload$1({scriptLiterals:normalizeTailwindContentPayload(payload).scriptLiterals})}const signaturePayloadCache=/* @__PURE__ */ new Map;function serializeAttrs(attrs){return Object.fromEntries(Object.entries(attrs).sort(([a],[b])=>a.localeCompare(b)))}function serializeBlock(block){if(!block)return null;return{type:block.type,attrs:serializeAttrs(block.attrs),content:block.content}}function buildRawVueSfcPayload(descriptor){const configBlocks=[];const templateBlocks=[];for(const block of descriptor.customBlocks){const serialized=serializeBlock(block);if(block.type===`json`||block.type===`config`)configBlocks.push(serialized);else templateBlocks.push(serialized)}return{script:{script:serializeBlock(descriptor.script),scriptSetup:serializeBlock(descriptor.scriptSetup)},template:{template:serializeBlock(descriptor.template),customBlocks:templateBlocks},style:{styles:descriptor.styles.map(style=>serializeBlock(style))},config:{customBlocks:configBlocks},hasTemplate:Boolean(descriptor.template?.content.trim())}}function normalizeScriptBlock(block,filename){if(!block)return{block:null,macroSources:[]};try{const split=splitJsonMacroCallsFromCode(block.content,filename);return{block:{...block,content:split.stripped},macroSources:split.macroSources}}catch{return{block,macroSources:[]}}}function normalizeVueSfcPayload(raw,filename){const script=normalizeScriptBlock(raw.script.script,filename);const scriptSetup=normalizeScriptBlock(raw.script.scriptSetup,filename);const scriptPayload={script:script.block,scriptSetup:scriptSetup.block};return{...raw,script:scriptPayload,config:{...raw.config,macroSources:[...script.macroSources,...scriptSetup.macroSources]},tailwindContent:buildTailwindContentPayload(raw.template.template?.content??``,script.block?.content??``,scriptSetup.block?.content??``)}}function buildVueSfcSignaturePayloadWithTs(source,filename){const{descriptor,errors}=parse$1(source,{filename});if(errors.length)return;return normalizeVueSfcPayload(buildRawVueSfcPayload(descriptor),filename)}function resolveVueSfcSignaturePayload(source,filename){const cacheKey=`${filename}\0${source}`;if(signaturePayloadCache.has(cacheKey))return signaturePayloadCache.get(cacheKey);const payload=buildVueSfcSignaturePayloadWithTs(source,filename);signaturePayloadCache.set(cacheKey,payload);return payload}const VUE_SFC_BLOCK_TYPES=[`script`,`template`,`style`,`config`];const hmrSignaturesCache=/* @__PURE__ */ new WeakMap;function hashPayload(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function resolveVueSfcHmrSignatures(source,filename){const payload=resolveVueSfcSignaturePayload(source,filename);if(!payload)return{};const cached=hmrSignaturesCache.get(payload);if(cached)return cached;const blockSignatures={script:hashPayload(payload.script),template:hashPayload(payload.template),style:hashPayload(payload.style),config:hashPayload(payload.config)};const signatures={blockSignatures,nonJsonSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.style]),scriptSignature:blockSignatures.script,styleIndependentSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.config]),tailwindContentSignature:hashTailwindContentPayload(payload.tailwindContent),tailwindTemplateContentSignature:hashTailwindTemplateContentPayload(payload.tailwindContent),tailwindScriptContentSignature:hashTailwindScriptContentPayload(payload.tailwindContent),hasTemplate:payload.hasTemplate};hmrSignaturesCache.set(payload,signatures);return signatures}function classifyVueSfcBlockChanges(previous,current){return VUE_SFC_BLOCK_TYPES.filter(type=>previous[type]!==current[type])}function resolveVueSfcNonJsonSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).nonJsonSignature}function resolveVueSfcScriptSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).blockSignatures?.script}function resolveVueSfcStyleIndependentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).styleIndependentSignature}function resolveVueSfcTailwindContentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).tailwindContentSignature}function resolveVueSfcHasTemplate(source,filename){return resolveVueSfcHmrSignatures(source,filename).hasTemplate}const SOURCE_ROOT_RE=/(?:^|\/)src\/(.+)$/;function normalizeScopedIdInput(filename){const normalized=filename.replace(/\\/g,`/`);return normalized.match(SOURCE_ROOT_RE)?.[1]??normalized.replace(/^.*?\/(pages|components|layouts)\//,`$1/`)}function generateScopedId(filename){const input=normalizeScopedIdInput(filename);let hash=2166136261;for(let index=0;index<input.length;index+=1){hash^=input.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function normalizeResolvedUsingComponent(result){if(!result)return;if(typeof result===`string`)return{from:result};return result}function isWevuSfcComponent(result){return result?.sourceType===`wevu-sfc`||Boolean(result?.resolvedId?.endsWith(`.vue`))||Boolean(result?.from?.endsWith(`.vue`))}function isVueSfcSource(source){return source.endsWith(`.vue`)}function kebabToCamel(name){return name.replace(/-([a-z0-9])/g,(_,character)=>character.toUpperCase())}function capitalize(name){return name?`${name.charAt(0).toUpperCase()}${name.slice(1)}`:name}function extractStringPropertyFromObject(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if(!(t.isIdentifier(key)?key.name===keyName:t.isStringLiteral(key)?key.value===keyName:false)||!t.isStringLiteral(property.value))continue;return property.value.value}}function extractStaticComponentMeta(scriptSetupContent){let ast;try{ast=parse$3(scriptSetupContent,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return{isMiniProgramComponent:false}}let componentName;let isMiniProgramComponent=false;traverse(ast,{CallExpression(path){const callee=path.node.callee;const arg=path.node.arguments[0];if(!t.isObjectExpression(arg))return;if(t.isIdentifier(callee,{name:`defineOptions`})){componentName??=extractStringPropertyFromObject(arg,`name`);return}if(!t.isIdentifier(callee,{name:`defineComponentJson`}))return;for(const property of arg.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if((t.isIdentifier(key)?key.name===`component`:t.isStringLiteral(key)?key.value===`component`:false)&&t.isBooleanLiteral(property.value)&&property.value.value){isMiniProgramComponent=true;return}}}});return{componentName,isMiniProgramComponent}}function readVueSfcScriptSetupContent(source,resolvedId){const{descriptor,errors}=parse$1(source,{filename:resolvedId});if(errors.length>0||!descriptor.scriptSetup?.content)return;return descriptor.scriptSetup.content}async function resolveVueSfcStaticComponentMeta(resolvedId,options){if(!resolvedId?.endsWith(`.vue`))return{isMiniProgramComponent:false};const cached=options?.cache?.get(resolvedId);if(cached)return await cached;const task=(async()=>{try{const scriptSetupContent=readVueSfcScriptSetupContent(await readFile$1(resolvedId,`utf8`),resolvedId);return scriptSetupContent?extractStaticComponentMeta(scriptSetupContent):{isMiniProgramComponent:false}}catch(error){const message=error instanceof Error?error.message:String(error);options?.warn?.(`[Vue 编译] 解析 ${resolvedId} 的静态组件元信息失败:${message}`);return{isMiniProgramComponent:false}}})();options?.cache?.set(resolvedId,task);return await task}function registerComponentName(result,tag,componentName){if(!componentName)return;result.componentNameMap[tag]=componentName;result.componentNameMap[normalizeTemplateTagName(tag)]=componentName}function registerMiniProgramComponentTag(result,tag,isComponent){if(!isComponent)return;result.miniProgramComponentTags.add(tag);result.miniProgramComponentTags.add(normalizeTemplateTagName(tag))}function createComponentSourceInfo(){return{autoUsingComponentsMap:{},autoImportTagsMap:{},autoComponentMeta:{},wevuComponentTags:/* @__PURE__ */ new Set,miniProgramComponentTags:/* @__PURE__ */ new Set,componentNameMap:{}}}function mergeComponentSourceInfo(target,source){Object.assign(target.autoUsingComponentsMap,source.autoUsingComponentsMap);Object.assign(target.autoImportTagsMap,source.autoImportTagsMap);Object.assign(target.autoComponentMeta,source.autoComponentMeta);Object.assign(target.componentNameMap,source.componentNameMap);for(const tag of source.wevuComponentTags)target.wevuComponentTags.add(tag);for(const tag of source.miniProgramComponentTags)target.miniProgramComponentTags.add(tag)}function collectTemplateComponentTagInfo(template,filename,warn){const warnHandler=resolveWarnHandler(warn);const autoImportTags=collectVueTemplateTags(template,{filename,warnLabel:`组件标签`,warn:message=>warnHandler(message),shouldCollect:isAutoImportCandidateTag});const templateTags=collectVueTemplateTags(template,{filename,warnLabel:`脚本导入组件标签`,warn:message=>warnHandler(message),shouldCollect:()=>true});const componentNames=/* @__PURE__ */ new Set;const tagsByComponentName=/* @__PURE__ */ new Map;for(const tag of templateTags){const camelName=kebabToCamel(tag);for(const componentName of[tag,camelName,capitalize(camelName)]){componentNames.add(componentName);const matchedTags=tagsByComponentName.get(componentName)??/* @__PURE__ */ new Set;matchedTags.add(tag);tagsByComponentName.set(componentName,matchedTags)}}return{autoImportTags,componentNames,tagsByComponentName}}async function resolveScriptComponentRegistrations(options){const{pending,filename,compileOptions,autoUsingComponents,result}=options;const resolvedComponents=await Promise.all(pending.map(async({localName,importSource,importedName,kind,templateTags})=>{let resolved=autoUsingComponents?.resolveUsingComponentPath?normalizeResolvedUsingComponent(await autoUsingComponents.resolveUsingComponentPath(importSource,filename,{localName,importedName,kind})):void 0;if(!resolved?.from&&importSource.startsWith(`/`))resolved={from:removeExtensionDeep(importSource),resolvedId:importSource};if(!resolved?.resolvedId&&isVueSfcSource(importSource)&&importSource.startsWith(`.`))resolved={...resolved??{},resolvedId:path.resolve(path.dirname(filename),importSource)};const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoUsingComponents?.warn??compileOptions?.warn});return{localName,importSource,resolved,componentMeta,templateTags}}));for(const{localName,importSource,resolved,componentMeta,templateTags}of resolvedComponents){if(resolved?.from){for(const tag of templateTags)result.autoUsingComponentsMap[tag]=resolved.from;result.autoComponentMeta[localName]=resolved.from}if(isVueSfcSource(importSource)||isWevuSfcComponent(resolved)){result.wevuComponentTags.add(localName);result.wevuComponentTags.add(normalizeTemplateTagName(localName))}registerComponentName(result,localName,componentMeta.componentName);for(const tag of templateTags)registerComponentName(result,tag,componentMeta.componentName);registerMiniProgramComponentTag(result,localName,componentMeta.isMiniProgramComponent);for(const tag of templateTags)registerMiniProgramComponentTag(result,tag,componentMeta.isMiniProgramComponent)}}async function collectScriptSetupUsingComponents(options){const{descriptor,descriptorForCompile,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,result}=options;if(!descriptor.scriptSetup||!descriptor.template)return;if(!templateComponentNames?.size)return;try{const setupAst=parse$3(descriptorForCompile.scriptSetup.content,BABEL_TS_MODULE_PARSER_OPTIONS);const pending=[];traverse(setupAst,{ImportDeclaration(path){if(path.node.importKind===`type`)return;if(!t.isStringLiteral(path.node.source))return;const importSource=path.node.source.value;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!(`local`in specifier)||!t.isIdentifier(specifier.local))continue;const localName=specifier.local.name;if(!templateComponentNames.has(localName))continue;const templateTags=[...templateTagsByComponentName?.get(localName)??[localName]];if(t.isImportDefaultSpecifier(specifier))pending.push({localName,importSource,importedName:`default`,kind:`default`,templateTags});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;pending.push({localName,importSource,importedName,kind:`named`,templateTags})}}}});await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents,result})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 <script setup> 导入失败:${message}`)}}function getExportDefaultObject(scriptAst){let options;traverse(scriptAst,{ExportDefaultDeclaration(path){const declaration=path.node.declaration;if(t.isObjectExpression(declaration))options=declaration;else if(t.isCallExpression(declaration)&&t.isObjectExpression(declaration.arguments[0]))options=declaration.arguments[0];path.stop()}});return options}function getObjectProperty(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property)||property.computed)continue;if(t.isIdentifier(property.key)?property.key.name===keyName:t.isStringLiteral(property.key)&&property.key.value===keyName)return property}}function getComponentRegistrationName(property){if(t.isIdentifier(property.key))return property.key.name;return t.isStringLiteral(property.key)?property.key.value:void 0}async function collectOptionsApiUsingComponents(options){const{descriptor,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,result}=options;if(!descriptor.script||!descriptor.template||!templateComponentNames?.size)return;try{const ast=parse$3(descriptor.script.content,BABEL_TS_MODULE_PARSER_OPTIONS);const imports=/* @__PURE__ */ new Map;traverse(ast,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!t.isIdentifier(specifier.local))continue;if(t.isImportDefaultSpecifier(specifier))imports.set(specifier.local.name,{importSource:path.node.source.value,importedName:`default`,kind:`default`});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;imports.set(specifier.local.name,{importSource:path.node.source.value,importedName,kind:`named`})}}}});const componentOptions=getExportDefaultObject(ast);const componentsProperty=componentOptions&&getObjectProperty(componentOptions,`components`);if(!componentsProperty||!t.isObjectExpression(componentsProperty.value))return;const pending=[];for(const property of componentsProperty.value.properties){if(!t.isObjectProperty(property)||!t.isIdentifier(property.value))continue;const registrationName=getComponentRegistrationName(property);const imported=imports.get(property.value.name);if(!registrationName||!imported||!templateComponentNames.has(registrationName))continue;pending.push({localName:property.value.name,...imported,templateTags:[...templateTagsByComponentName?.get(registrationName)??[registrationName]]})}await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents,result})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 Options API 局部组件失败:${message}`)}}async function collectAutoImportWevuComponents(options){const{descriptor,filename,compileOptions,autoImportTags,templateAutoImportTags,warn,result}=options;if(!autoImportTags||!descriptor.template)return;const resolvedTags=await Promise.all([...templateAutoImportTags??[]].map(async tag=>{let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoImportTags.warn??warn});return{tag,resolved,componentMeta}}));for(const{tag,resolved,componentMeta}of resolvedTags){if(!resolved?.from)continue;result.autoImportTagsMap[resolved.name||tag]=resolved.from;if(isWevuSfcComponent(resolved)){result.wevuComponentTags.add(tag);if(resolved.name)result.wevuComponentTags.add(resolved.name)}registerComponentName(result,tag,componentMeta.componentName);const isMiniProgramComponent=componentMeta.isMiniProgramComponent;registerMiniProgramComponentTag(result,tag,isMiniProgramComponent);if(resolved.name){registerComponentName(result,resolved.name,componentMeta.componentName);registerMiniProgramComponentTag(result,resolved.name,isMiniProgramComponent)}}}async function collectComponentSourceInfo(options){const result=createComponentSourceInfo();const templateComponentTagInfo=options.descriptor.template?collectTemplateComponentTagInfo(options.descriptor.template.content,options.filename,options.autoUsingComponents?.warn??options.autoImportTags?.warn??options.compileOptions?.warn):void 0;const scriptImportResult=createComponentSourceInfo();const autoImportResult=createComponentSourceInfo();await Promise.all([collectScriptSetupUsingComponents({descriptor:options.descriptor,descriptorForCompile:options.descriptorForCompile,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,result:scriptImportResult}),collectOptionsApiUsingComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,result:scriptImportResult}),collectAutoImportWevuComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoImportTags:options.autoImportTags,templateAutoImportTags:templateComponentTagInfo?.autoImportTags,warn:options.compileOptions?.warn,result:autoImportResult})]);mergeComponentSourceInfo(result,scriptImportResult);mergeComponentSourceInfo(result,autoImportResult);return result}function normalizeConfigLang(lang){if(!lang)return`json`;const lower=lang.toLowerCase();if(lower===`txt`)return`json`;return lower}function isJsonLikeLang(lang){return lang===`json`||lang===`jsonc`||lang===`json5`}function resolveJsLikeLang(lang){if(lang===`ts`||lang===`tsx`||lang===`cts`||lang===`mts`)return`ts`;return`js`}async function evaluateJsLikeConfig(source,filename,lang){const dir=path.dirname(filename);const extension=resolveJsLikeLang(lang)===`ts`?`ts`:`js`;const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.config.${unique}`);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.${unique}.${extension}`);const rewritten=rewriteJsLikeImportsForTempDir(source,dir,tempDir);await writeFile(tempFile,rewritten,`utf8`);try{const{mod}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});let resolved=mod?.default??mod;if(typeof resolved===`function`)resolved=resolved();if(resolved&&typeof resolved.then===`function`)resolved=await resolved;if(resolved&&typeof resolved===`object`)return resolved;throw new Error(`配置块必须导出对象或返回对象的函数。`)}finally{try{await remove(tempDir)}catch{}}})}async function compileConfigBlocks(blocks,filename,options){const jsonBlocks=blocks.filter(block=>block.type===`json`);if(!jsonBlocks.length)return;let accumulator={};for(const block of jsonBlocks){const lang=normalizeConfigLang(block.lang);try{if(isJsonLikeLang(lang)){const parsed=parse$2(block.content,void 0,true);if(options?.merge){const merged=options.merge(accumulator,parsed);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,parsed);continue}const evaluated=await evaluateJsLikeConfig(block.content,filename,lang);if(!evaluated||typeof evaluated!==`object`)continue;if(options?.merge){const merged=options.merge(accumulator,evaluated);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,evaluated)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 <json> 块失败(${lang}):${filename}: ${message}`)}}if(Reflect.has(accumulator,`$schema`))delete accumulator.$schema;return JSON.stringify(accumulator,null,2)}function collectTemplateAutoImportTags(template,filename,warn){const warnHandler=resolveWarnHandler(warn);return collectVueTemplateTags(template,{filename,warnLabel:`自动导入标签`,warn:message=>warnHandler(message),shouldCollect:isAutoImportCandidateTag})}function normalizeUsingComponents(config){const raw=config.usingComponents;if(!raw||typeof raw!==`object`||Array.isArray(raw))return;const usingComponents={};for(const[name,from]of Object.entries(raw))usingComponents[normalizeTemplateTagName(name)]=from;config.usingComponents=usingComponents}async function compileConfigPhase(params){const{descriptor,filename,autoUsingComponentsMap,autoImportTagsMap:precomputedAutoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults,mergeJson,scriptSetupMacroConfig,result,warn}=params;let configObj;if(descriptor.customBlocks.some(b=>b.type===`json`)){const configResult=await compileConfigBlocks(descriptor.customBlocks,filename,{merge:(target,source)=>mergeJson(target,source,`json-block`)});if(configResult)try{configObj=JSON.parse(configResult)}catch{configObj={}}}const autoImportTagsMap=precomputedAutoImportTagsMap?{...precomputedAutoImportTagsMap}:{};if(!precomputedAutoImportTagsMap&&autoImportTags&&descriptor.template){const tags=collectTemplateAutoImportTags(descriptor.template.content,filename,autoImportTags.warn??warn);for(const tag of tags){let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;autoImportTagsMap[resolved.name||tag]=resolved.from}}if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents={};if(existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw))for(const[name,from]of Object.entries(existingRaw))usingComponents[normalizeTemplateTagName(name)]=from;for(const[name,from]of Object.entries(autoImportTagsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoImportTags?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被模板标签自动引入覆盖为 '${from}'`);usingComponents[normalizedName]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoUsingComponents?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被 <script setup> 导入覆盖为 '${from}'`);usingComponents[normalizedName]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(result.componentGenerics&&Object.keys(result.componentGenerics).length>0){const existing=configObj?.componentGenerics;const componentGenerics=existing&&typeof existing===`object`&&!Array.isArray(existing)?existing:{};for(const[key,value]of Object.entries(result.componentGenerics))componentGenerics[key]=value;configObj=mergeJson(configObj??{},{componentGenerics},`component-generics`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptSetupMacroConfig&&Object.keys(scriptSetupMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptSetupMacroConfig,`macro`);if(configObj)normalizeUsingComponents(configObj);if(configObj&&Object.keys(configObj).length>0)result.config=JSON.stringify(configObj,null,2)}function finalizeResult(result,options){if(!result.script||result.script.trim()===``)result.script=`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from '${RUNTIME_IMPORT_PATH}';\n${WE_VU_RUNTIME_APIS.createWevuComponent}({});\n`;if(result.meta&&options.scriptSetupMacroHash)result.meta.jsonMacroHash=options.scriptSetupMacroHash;if(result.meta&&options.defineOptionsHash)result.meta.defineOptionsHash=options.defineOptionsHash}function isEncodedSourceMapLike(value){return Boolean(value&&typeof value===`object`&&`version`in value&&`mappings`in value&&`names`in value&&`sources`in value)}function composeSourceMaps(transformedMap,originalMap){if(isEncodedSourceMapLike(transformedMap)&&isEncodedSourceMapLike(originalMap))return remapping([transformedMap,originalMap],()=>null);if(isEncodedSourceMapLike(transformedMap))return transformedMap;if(isEncodedSourceMapLike(originalMap))return originalMap;return null}function composeSourceMapForSource(transformedMap,originalMap,sourceFile){if(!isEncodedSourceMapLike(transformedMap))return null;if(!isEncodedSourceMapLike(originalMap))return transformedMap;const transformedMapInput=transformedMap;const sourceIndex=transformedMap.sources.indexOf(sourceFile);if(sourceIndex<0)return transformedMap;const resolvedSourceFile=new TraceMap(transformedMapInput).resolvedSources[sourceIndex];return remapping(transformedMapInput,(file,context)=>{if(context.depth!==1||file!==resolvedSourceFile)return null;context.source=``;return originalMap})}function getErrorMessage(error){if(error instanceof Error)return error.message;return typeof error===`string`?error:``}const BEHAVIOR_NOT_DEFINED_RE=/\bBehavior is not defined\b/;function shouldFallbackToRawDefineOptions(error){const message=getErrorMessage(error);return BEHAVIOR_NOT_DEFINED_RE.test(message)}function normalizeScriptSetupLang(lang){if(!lang)return`ts`;const lower=lang.toLowerCase();if(lower===`txt`)return`ts`;return lower}function resolveScriptSetupExtension(lang){const normalized=normalizeScriptSetupLang(lang);if(normalized===`ts`||normalized===`tsx`||normalized===`cts`||normalized===`mts`)return`ts`;return`js`}const IDENTIFIER_LIKE_KEY_RE=/^[A-Z_$][\w$]*$/i;const OBJECT_TO_STRING=Object.prototype.toString;function isIdentifierLikeKey(key){return IDENTIFIER_LIKE_KEY_RE.test(key)}function resolveRuntimeMarkerReference(value,scopeValues){if(value[WEAPP_I18N_RUNTIME_MARKER]!==true)return;const pending=Object.entries(scopeValues).filter(([name])=>isIdentifierLikeKey(name));const visited=/* @__PURE__ */ new WeakSet;for(let index=0;index<pending.length;index+=1){const[reference,candidate]=pending[index];if(candidate===value)return reference;if(!candidate||typeof candidate!==`object`||visited.has(candidate))continue;visited.add(candidate);for(const[key,member]of Object.entries(candidate))if(member&&typeof member===`object`){const accessor=isIdentifierLikeKey(key)?`.${key}`:`[${JSON.stringify(key)}]`;pending.push([`${reference}${accessor}`,member])}}}function getObjectTag(value){return OBJECT_TO_STRING.call(value)}const SERIALIZABLE_NATIVE_FUNCTIONS=/* @__PURE__ */ new Map([[String,`String`],[Number,`Number`],[Boolean,`Boolean`],[Object,`Object`],[Array,`Array`],[Function,`Function`],[Date,`Date`],[RegExp,`RegExp`],[Map,`Map`],[Set,`Set`],[WeakMap,`WeakMap`],[WeakSet,`WeakSet`],[Promise,`Promise`]]);function isParsableFunctionExpressionSource(source){try{parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);return true}catch{return false}}function tryConvertObjectMethodSourceToFunctionExpression(source){try{const statement=parse$3(`({ ${source} })`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement)||!t.isObjectExpression(statement.expression))return null;const firstProperty=statement.expression.properties[0];if(!firstProperty)return null;if(t.isObjectMethod(firstProperty)){const functionName=t.isIdentifier(firstProperty.key)?t.identifier(firstProperty.key.name):null;const functionExpression=t.functionExpression(functionName,firstProperty.params,firstProperty.body,firstProperty.generator,firstProperty.async);return generate(functionExpression).code}if(t.isObjectProperty(firstProperty)&&(t.isFunctionExpression(firstProperty.value)||t.isArrowFunctionExpression(firstProperty.value)))return generate(firstProperty.value).code}catch{}return null}function normalizeFunctionSourceToExpression(source){if(isParsableFunctionExpressionSource(source))return source;const converted=tryConvertObjectMethodSourceToFunctionExpression(source);if(converted&&isParsableFunctionExpressionSource(converted))return converted;throw new Error(`defineOptions 的参数中包含无法序列化的函数值。`)}function parseExpressionFromSource(source){const statement=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);return statement.expression}function rewriteFunctionSourceWithScopeValues(source,scopeValues){if(!Object.keys(scopeValues).length)return source;const wrappedAst=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);traverse(wrappedAst,{Identifier(path){if(!path.isReferencedIdentifier())return;if(path.scope.hasBinding(path.node.name))return;if(!hasOwn(scopeValues,path.node.name))return;try{const replacement=serializeStaticValueToExpression(scopeValues[path.node.name],/* @__PURE__ */ new WeakSet,{});path.replaceWith(parseExpressionFromSource(replacement))}catch{}}});const statement=wrappedAst.program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);const expression=statement.expression;return generate(expression).code}function serializeStaticValueToExpression(value,seen=/* @__PURE__ */ new WeakSet,scopeValues={}){if(value===null)return`null`;if(value===void 0)return`undefined`;const valueType=typeof value;if(valueType===`string`)return JSON.stringify(value);if(valueType===`boolean`)return value?`true`:`false`;if(valueType===`number`){if(Number.isNaN(value))return`Number.NaN`;if(value===Number.POSITIVE_INFINITY)return`Number.POSITIVE_INFINITY`;if(value===Number.NEGATIVE_INFINITY)return`Number.NEGATIVE_INFINITY`;if(Object.is(value,-0))return`-0`;return String(value)}if(valueType===`bigint`)return`${String(value)}n`;if(valueType===`symbol`)throw new Error(`defineOptions 的参数中不支持 Symbol 值。`);if(valueType===`function`){const source=Function.prototype.toString.call(value);if(source.includes(`[native code]`)){const nativeLiteral=SERIALIZABLE_NATIVE_FUNCTIONS.get(value);if(nativeLiteral)return nativeLiteral;throw new Error(`defineOptions 的参数中不支持原生函数值。`)}return`(${normalizeFunctionSourceToExpression(rewriteFunctionSourceWithScopeValues(normalizeFunctionSourceToExpression(source),scopeValues))})`}if(getObjectTag(value)===`[object Date]`)return`new Date(${JSON.stringify(value.toISOString())})`;if(getObjectTag(value)===`[object RegExp]`)return value.toString();if(Array.isArray(value))return`[${value.map(item=>serializeStaticValueToExpression(item,seen,scopeValues)).join(`, `)}]`;if(value&&typeof value===`object`){const runtimeReference=resolveRuntimeMarkerReference(value,scopeValues);if(runtimeReference)return runtimeReference;if(seen.has(value))throw new Error(`defineOptions 的参数中不支持循环引用。`);seen.add(value);const proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new Error(`defineOptions 的参数仅支持普通对象。`);const objectValue=value;return`{ ${Object.keys(objectValue).map(key=>{return`${isIdentifierLikeKey(key)?key:JSON.stringify(key)}: ${serializeStaticValueToExpression(objectValue[key],seen,scopeValues)}`}).join(`, `)} }`}throw new Error(`defineOptions 的参数中包含不支持的值类型:${valueType}`)}function resolveStaticDefineOptionsValues(statements){const values=[];for(const statement of statements){const arg=statement.argPath?.node;if(!arg||!t.isExpression(arg))return;let value;try{value=resolveStaticLiteralValue(arg)}catch{return}if(!value||typeof value!==`object`||Array.isArray(value))return;values.push(value)}return values}function collectDefineOptionsStatements(content,filename){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const statements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;if(path.node.arguments.length!==1)throw new Error(`defineOptions() 在 ${filename} 中必须且只能传 1 个参数。`);statements.push({statementPath:path.parentPath,callPath:path,argPath:path.get(`arguments.0`)})}});return{statements}}function evaluateStaticExpression(source){return vm.runInNewContext(`(${source})`,{})}function collectStaticTopLevelScopeValues(content){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const scopeValues={};for(const statement of ast.program.body){if(!t.isVariableDeclaration(statement)||statement.kind!==`const`)continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init)continue;try{scopeValues[declarator.id.name]=evaluateStaticExpression(declarator.init.end!=null&&declarator.init.start!=null?content.slice(declarator.init.start,declarator.init.end):``)}catch{}}}return scopeValues}function collectKeptBindingNames(keptStatementPaths){const names=/* @__PURE__ */ new Set;for(const statementPath of keptStatementPaths){if(statementPath.isImportDeclaration()){if(statementPath.node.importKind===`type`)continue;for(const specifier of statementPath.get(`specifiers`))if(specifier.isImportSpecifier()||specifier.isImportDefaultSpecifier()||specifier.isImportNamespaceSpecifier()){if(specifier.isImportSpecifier()&&specifier.node.importKind===`type`)continue;const local=specifier.node.local;if(t.isIdentifier(local))names.add(local.name)}continue}if(statementPath.isVariableDeclaration()){for(const declarator of statementPath.get(`declarations`)){const id=declarator.get(`id`);if(id.isIdentifier())names.add(id.node.name)}continue}if(statementPath.isFunctionDeclaration()||statementPath.isClassDeclaration()){const id=statementPath.node.id;if(t.isIdentifier(id))names.add(id.name)}}return[...names]}async function evaluateDefineOptionsValues(params){const{content,filename,lang,statements}=params;const ms=new MagicString(content);const dir=path.dirname(filename);const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.define-options.${unique}`);const programPath=statements[0]?.statementPath.parentPath;if(!programPath)return{values:[],dependencies:[],scopeValues:{}};const bodyPaths=programPath?.get(`body`)??[];const macroStatementPaths=statements.map(item=>item.statementPath);const{keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatementPaths);const keptBindingNames=collectKeptBindingNames(keptStatementPaths);for(const statementPath of keptStatementPaths){if(!statementPath.isImportDeclaration())continue;const sourceNode=statementPath.node.source;if(!sourceNode||!t.isStringLiteral(sourceNode))continue;const originalSource=sourceNode.value;if(!originalSource.startsWith(`.`))continue;const next=rewriteRelativeImportSource(originalSource,dir,tempDir);if(typeof sourceNode.start===`number`&&typeof sourceNode.end===`number`)ms.overwrite(sourceNode.start,sourceNode.end,JSON.stringify(next))}for(const statementPath of macroStatementPaths){const calleePath=statementPath.get(`expression`).get(`callee`);if(calleePath?.isIdentifier()&&typeof calleePath.node.start===`number`&&typeof calleePath.node.end===`number`)ms.overwrite(calleePath.node.start,calleePath.node.end,`__weapp_defineOptions`)}for(const statementPath of bodyPaths){if(keptStatementPaths.has(statementPath))continue;const start=statementPath.node.start;const end=statementPath.node.end;if(typeof start===`number`&&typeof end===`number`)ms.remove(start,end)}const extension=resolveScriptSetupExtension(lang);const header=`
|
|
29
|
+
`:``}const uni = __wevuCreateUniAppHost(wx)\n`)}if(disableVirtualHost)for(const range of analysis.virtualHostTrueRanges)output.overwrite(range.start,range.end,`false`);return output.toString()}function transformVueSfc(source,filename,target){const normalizedSource=normalizeAuxiliaryWxsScripts(source);const{descriptor,errors}=parse$1(normalizedSource,{filename});if(errors.length){const error=errors[0];throw new Error(`[uni-app] 解析 ${filename} 失败:${error.message}`)}const blocks=[descriptor.script,descriptor.scriptSetup].filter(Boolean);const analyses=blocks.map(block=>{const lang=block.lang??`js`;return analyzeScript(block.content,`${filename}.${lang}`)});const injectIndex=analyses.findIndex(analysis=>analysis.usesFreeUni);const output=new MagicString(normalizedSource);for(let index=blocks.length-1;index>=0;index-=1){const block=blocks[index];const analysis=analyses[index];const code=renderScript(analysis,index===injectIndex,target===`mp-weixin`);output.overwrite(block.loc.start.offset,block.loc.end.offset,code)}return output.toString()}function transformUniAppSource(source,options){const conditional=transformUniAppConditionalCode(source,options);const filename=options.filename.split(`?`,1)[0];const blockType=options.blockType??(filename.endsWith(`.vue`)?`sfc`:SCRIPT_EXT_RE.test(filename)?`script`:STYLE_EXT_RE.test(filename)?`style`:void 0);if(blockType===`sfc`){const code=transformVueSfc(conditional.code,filename,options.target);return{changed:conditional.changed||code!==source,code}}if(blockType===`script`){const analysis=analyzeScript(conditional.code,filename);const code=renderScript(analysis,analysis.usesFreeUni,options.target===`mp-weixin`&&filename.endsWith(`.vue`));return{changed:conditional.changed||code!==source,code}}if(blockType===`style`||blockType===`template`)return conditional;return{changed:false,code:source}}function isUniAppCompatibilityFile(filename,srcRoot,include){const clean=filename.split(`?`,1)[0];const relative=path.relative(srcRoot,clean);if(relative===``||!relative.startsWith(`..`)&&!path.isAbsolute(relative))return true;const normalized=clean.replace(/\\/g,`/`);return include.some(packageName=>{const packagePath=packageName.replace(/^\/+|\/+$/g,``);return normalized.includes(`/node_modules/${packagePath}/`)})}function transformNestedWxssVars(source){return source}function normalizeStyleError(error){return error instanceof Error?error.message:String(error)}function hasSlottedScopeSelector(source,slottedScopeId){let found=false;const processor=selectorParser(selectors=>{selectors.walkAttributes(attribute=>{if(attribute.attribute===slottedScopeId)found=true})});postcss.parse(source).walkRules(rule=>{if(!found)processor.processSync(rule.selector)});return found}function transformVueDeepSelectors(source){const root=postcss.parse(source);const processor=selectorParser(selectors=>{selectors.walkTags(tag=>{const mapped=DEFAULT_HTML_TO_WXML_TAG_MAP[tag.value.toLowerCase()];if(mapped&&mapped!==tag.value.toLowerCase())tag.replaceWith(selectorParser.className({value:tag.value.toLowerCase()}))});selectors.walkPseudos(pseudo=>{if(![`:deep`,`::v-deep`].includes(pseudo.value))return;const replacement=pseudo.nodes?.[0]?.nodes.map(node=>node.clone())??[];replacement.length?pseudo.replaceWith(...replacement):pseudo.remove()})});root.walkRules(rule=>{rule.selector=processor.processSync(rule.selector).replace(/\s{2,}/g,` `).trim()});return root.toString()}async function compileVueStyleToWxss(styleBlock,options){const filename=options.filename??`style-${options.id}.${styleBlock.lang||`css`}`;const moduleName=typeof styleBlock.module===`string`?styleBlock.module:typeof options.modules===`string`?options.modules:`$style`;const modules=Boolean(options.modules||styleBlock.module);const result=await compileStyleAsync({filename,id:`data-v-${options.id}`,source:styleBlock.content,scoped:options.transformScoped!==false&&Boolean(options.scoped||styleBlock.scoped),modules,modulesOptions:modules?{generateScopedName:name=>`${name}_${options.id}`}:void 0,preprocessLang:styleBlock.lang,preprocessOptions:options.preprocessOptions});if(result.errors.length)throw new Error(`SFC 样式编译失败(${filename}):${result.errors.map(normalizeStyleError).join(`; `)}`);return{code:options.preserveDeepSelectors?result.code:transformVueDeepSelectors(result.code),map:result.map?JSON.stringify(result.map):void 0,scopedId:options.scoped||styleBlock.scoped?`data-v-${options.id}`:void 0,usesSlotted:hasSlottedScopeSelector(result.code,`data-v-${options.id}-s`),modules:result.modules?{[moduleName]:result.modules}:void 0,dependencies:[...result.dependencies]}}const CLASS_LIKE_TEMPLATE_ATTR_RE=/(?:^|[\s<])(?:[\w-]*class[\w-]*|v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[^\s>]+)/g;const VUE_DYNAMIC_CLASS_LIKE_BINDING_RE=/(?:^|[\s<])(?:v-bind(?::[\w-]*class[\w-]*)?|:[\w-]*class[\w-]*)(?:\.[\w-]+)*\s*=/;function hashPayload$1(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function collectTemplateTailwindCandidates(content){const candidates=/* @__PURE__ */ new Set;for(const match of content.matchAll(CLASS_LIKE_TEMPLATE_ATTR_RE))candidates.add(match[0].trim());return Array.from(candidates).sort()}function normalizeTailwindContentPayload(payload){const scriptLiterals=VUE_DYNAMIC_CLASS_LIKE_BINDING_RE.test(payload.template)?payload.scriptLiterals:payload.hasScriptTailwindClassHint?payload.scriptCallLiterals:[];return{...payload,template:collectTemplateTailwindCandidates(payload.template),scriptLiterals,scriptCallLiterals:[]}}function buildTailwindContentPayload(template,scriptContent,scriptSetupContent){return{template,scriptLiterals:[...collectScriptStringLiterals(scriptContent),...collectScriptStringLiterals(scriptSetupContent)],scriptCallLiterals:[...collectScriptCallStringLiterals(scriptContent),...collectScriptCallStringLiterals(scriptSetupContent)],hasScriptTailwindClassHint:mayContainScriptCallOrModuleSyntax(`${scriptContent}\n${scriptSetupContent}`)}}function hashTailwindContentPayload(payload){return hashPayload$1(normalizeTailwindContentPayload(payload))}function hashTailwindTemplateContentPayload(payload){return hashPayload$1({template:normalizeTailwindContentPayload(payload).template})}function hashTailwindScriptContentPayload(payload){return hashPayload$1({scriptLiterals:normalizeTailwindContentPayload(payload).scriptLiterals})}const signaturePayloadCache=/* @__PURE__ */ new Map;function serializeAttrs(attrs){return Object.fromEntries(Object.entries(attrs).sort(([a],[b])=>a.localeCompare(b)))}function serializeBlock(block){if(!block)return null;return{type:block.type,attrs:serializeAttrs(block.attrs),content:block.content}}function buildRawVueSfcPayload(descriptor){const configBlocks=[];const templateBlocks=[];for(const block of descriptor.customBlocks){const serialized=serializeBlock(block);if(block.type===`json`||block.type===`config`)configBlocks.push(serialized);else templateBlocks.push(serialized)}return{script:{script:serializeBlock(descriptor.script),scriptSetup:serializeBlock(descriptor.scriptSetup)},template:{template:serializeBlock(descriptor.template),customBlocks:templateBlocks},style:{styles:descriptor.styles.map(style=>serializeBlock(style))},config:{customBlocks:configBlocks},hasTemplate:Boolean(descriptor.template?.content.trim())}}function normalizeScriptBlock(block,filename){if(!block)return{block:null,macroSources:[]};try{const split=splitJsonMacroCallsFromCode(block.content,filename);return{block:{...block,content:split.stripped},macroSources:split.macroSources}}catch{return{block,macroSources:[]}}}function normalizeVueSfcPayload(raw,filename){const script=normalizeScriptBlock(raw.script.script,filename);const scriptSetup=normalizeScriptBlock(raw.script.scriptSetup,filename);const scriptPayload={script:script.block,scriptSetup:scriptSetup.block};return{...raw,script:scriptPayload,config:{...raw.config,macroSources:[...script.macroSources,...scriptSetup.macroSources]},tailwindContent:buildTailwindContentPayload(raw.template.template?.content??``,script.block?.content??``,scriptSetup.block?.content??``)}}function buildVueSfcSignaturePayloadWithTs(source,filename){const{descriptor,errors}=parse$1(source,{filename});if(errors.length)return;return normalizeVueSfcPayload(buildRawVueSfcPayload(descriptor),filename)}function resolveVueSfcSignaturePayload(source,filename){const cacheKey=`${filename}\0${source}`;if(signaturePayloadCache.has(cacheKey))return signaturePayloadCache.get(cacheKey);const payload=buildVueSfcSignaturePayloadWithTs(source,filename);signaturePayloadCache.set(cacheKey,payload);return payload}const VUE_SFC_BLOCK_TYPES=[`script`,`template`,`style`,`config`];const hmrSignaturesCache=/* @__PURE__ */ new WeakMap;function hashPayload(payload){return createHash(`sha256`).update(JSON.stringify(payload)).digest(`hex`).slice(0,16)}function resolveVueSfcHmrSignatures(source,filename){const payload=resolveVueSfcSignaturePayload(source,filename);if(!payload)return{};const cached=hmrSignaturesCache.get(payload);if(cached)return cached;const blockSignatures={script:hashPayload(payload.script),template:hashPayload(payload.template),style:hashPayload(payload.style),config:hashPayload(payload.config)};const tailwindContentSignature=hashTailwindContentPayload(payload.tailwindContent);const tailwindTemplateContentSignature=hashTailwindTemplateContentPayload(payload.tailwindContent);const tailwindScriptContentSignature=hashTailwindScriptContentPayload(payload.tailwindContent);const signatures={blockSignatures,contentSignatures:{tailwindcss:tailwindContentSignature},nonJsonSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.style]),scriptSignature:blockSignatures.script,styleIndependentSignature:hashPayload([blockSignatures.script,blockSignatures.template,blockSignatures.config]),scriptContentSignatures:{tailwindcss:tailwindScriptContentSignature},tailwindContentSignature,tailwindScriptContentSignature,tailwindTemplateContentSignature,templateContentSignatures:{tailwindcss:tailwindTemplateContentSignature},hasTemplate:payload.hasTemplate};hmrSignaturesCache.set(payload,signatures);return signatures}function classifyVueSfcBlockChanges(previous,current){return VUE_SFC_BLOCK_TYPES.filter(type=>previous[type]!==current[type])}function resolveVueSfcNonJsonSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).nonJsonSignature}function resolveVueSfcScriptSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).blockSignatures?.script}function resolveVueSfcStyleIndependentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).styleIndependentSignature}function resolveVueSfcTailwindContentSignature(source,filename){return resolveVueSfcHmrSignatures(source,filename).tailwindContentSignature}function resolveVueSfcHasTemplate(source,filename){return resolveVueSfcHmrSignatures(source,filename).hasTemplate}const SOURCE_ROOT_RE=/(?:^|\/)src\/(.+)$/;function normalizeScopedIdInput(filename){const normalized=filename.replace(/\\/g,`/`);return normalized.match(SOURCE_ROOT_RE)?.[1]??normalized.replace(/^.*?\/(pages|components|layouts)\//,`$1/`)}function generateScopedId(filename){const input=normalizeScopedIdInput(filename);let hash=2166136261;for(let index=0;index<input.length;index+=1){hash^=input.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function normalizeResolvedUsingComponent(result){if(!result)return;if(typeof result===`string`)return{from:result};return result}function isWevuSfcComponent(result){return result?.sourceType===`wevu-sfc`||Boolean(result?.resolvedId?.endsWith(`.vue`))||Boolean(result?.from?.endsWith(`.vue`))}function isVueSfcSource(source){return source.endsWith(`.vue`)}function kebabToCamel(name){return name.replace(/-([a-z0-9])/g,(_,character)=>character.toUpperCase())}function capitalize(name){return name?`${name.charAt(0).toUpperCase()}${name.slice(1)}`:name}function extractStringPropertyFromObject(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if(!(t.isIdentifier(key)?key.name===keyName:t.isStringLiteral(key)?key.value===keyName:false)||!t.isStringLiteral(property.value))continue;return property.value.value}}function extractStaticComponentMeta(scriptSetupContent){let ast;try{ast=parse$3(scriptSetupContent,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return{isMiniProgramComponent:false}}let componentName;let isMiniProgramComponent=false;traverse(ast,{CallExpression(path){const callee=path.node.callee;const arg=path.node.arguments[0];if(!t.isObjectExpression(arg))return;if(t.isIdentifier(callee,{name:`defineOptions`})){componentName??=extractStringPropertyFromObject(arg,`name`);return}if(!t.isIdentifier(callee,{name:`defineComponentJson`}))return;for(const property of arg.properties){if(!t.isObjectProperty(property))continue;const key=property.key;if((t.isIdentifier(key)?key.name===`component`:t.isStringLiteral(key)?key.value===`component`:false)&&t.isBooleanLiteral(property.value)&&property.value.value){isMiniProgramComponent=true;return}}}});return{componentName,isMiniProgramComponent}}function readVueSfcScriptSetupContent(source,resolvedId){const{descriptor,errors}=parse$1(source,{filename:resolvedId});if(errors.length>0||!descriptor.scriptSetup?.content)return;return descriptor.scriptSetup.content}async function resolveVueSfcStaticComponentMeta(resolvedId,options){if(!resolvedId?.endsWith(`.vue`))return{isMiniProgramComponent:false};const cached=options?.cache?.get(resolvedId);if(cached)return await cached;const task=(async()=>{try{const scriptSetupContent=readVueSfcScriptSetupContent(await readFile$1(resolvedId,`utf8`),resolvedId);return scriptSetupContent?extractStaticComponentMeta(scriptSetupContent):{isMiniProgramComponent:false}}catch(error){const message=error instanceof Error?error.message:String(error);options?.warn?.(`[Vue 编译] 解析 ${resolvedId} 的静态组件元信息失败:${message}`);return{isMiniProgramComponent:false}}})();options?.cache?.set(resolvedId,task);return await task}function registerComponentName(result,tag,componentName){if(!componentName)return;result.componentNameMap[tag]=componentName;result.componentNameMap[normalizeTemplateTagName(tag)]=componentName}function registerMiniProgramComponentTag(result,tag,isComponent){if(!isComponent)return;result.miniProgramComponentTags.add(tag);result.miniProgramComponentTags.add(normalizeTemplateTagName(tag))}function createComponentSourceInfo(){return{autoUsingComponentsMap:{},autoImportTagsMap:{},autoComponentMeta:{},wevuComponentTags:/* @__PURE__ */ new Set,miniProgramComponentTags:/* @__PURE__ */ new Set,componentNameMap:{}}}function mergeComponentSourceInfo(target,source){Object.assign(target.autoUsingComponentsMap,source.autoUsingComponentsMap);Object.assign(target.autoImportTagsMap,source.autoImportTagsMap);Object.assign(target.autoComponentMeta,source.autoComponentMeta);Object.assign(target.componentNameMap,source.componentNameMap);for(const tag of source.wevuComponentTags)target.wevuComponentTags.add(tag);for(const tag of source.miniProgramComponentTags)target.miniProgramComponentTags.add(tag)}function collectTemplateComponentTagInfo(template,filename,warn){const warnHandler=resolveWarnHandler(warn);const analysis=analyzeVueTemplateTags(template);if(analysis.errorMessage!==void 0)for(const warnLabel of[`组件标签`,`脚本导入组件标签`])warnVueTemplateTagAnalysis(analysis.errorMessage,{filename,warnLabel,warn:warnHandler});const autoImportTags=/* @__PURE__ */ new Set;const componentNames=/* @__PURE__ */ new Set;const tagsByComponentName=/* @__PURE__ */ new Map;for(const tag of analysis.tags){if(isAutoImportCandidateTag(tag))autoImportTags.add(tag);const camelName=kebabToCamel(tag);for(const componentName of[tag,camelName,capitalize(camelName)]){componentNames.add(componentName);const matchedTags=tagsByComponentName.get(componentName)??/* @__PURE__ */ new Set;matchedTags.add(tag);tagsByComponentName.set(componentName,matchedTags)}}return{autoImportTags,componentNames,tagsByComponentName}}async function resolveScriptComponentRegistrations(options){const{pending,filename,compileOptions,autoUsingComponents,result}=options;const resolvedComponents=await Promise.all(pending.map(async({localName,importSource,importedName,kind,templateTags})=>{let resolved=autoUsingComponents?.resolveUsingComponentPath?normalizeResolvedUsingComponent(await autoUsingComponents.resolveUsingComponentPath(importSource,filename,{localName,importedName,kind})):void 0;if(!resolved?.from&&importSource.startsWith(`/`))resolved={from:removeExtensionDeep(importSource),resolvedId:importSource};if(!resolved?.resolvedId&&isVueSfcSource(importSource)&&importSource.startsWith(`.`))resolved={...resolved??{},resolvedId:path.resolve(path.dirname(filename),importSource)};const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoUsingComponents?.warn??compileOptions?.warn});return{localName,importSource,resolved,componentMeta,templateTags}}));for(const{localName,importSource,resolved,componentMeta,templateTags}of resolvedComponents){if(resolved?.from){for(const tag of templateTags)result.autoUsingComponentsMap[tag]=resolved.from;result.autoComponentMeta[localName]=resolved.from}if(isVueSfcSource(importSource)||isWevuSfcComponent(resolved)){result.wevuComponentTags.add(localName);result.wevuComponentTags.add(normalizeTemplateTagName(localName))}registerComponentName(result,localName,componentMeta.componentName);for(const tag of templateTags)registerComponentName(result,tag,componentMeta.componentName);registerMiniProgramComponentTag(result,localName,componentMeta.isMiniProgramComponent);for(const tag of templateTags)registerMiniProgramComponentTag(result,tag,componentMeta.isMiniProgramComponent)}}async function collectScriptSetupUsingComponents(options){const{descriptor,descriptorForCompile,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,result}=options;if(!descriptor.scriptSetup||!descriptor.template)return;if(!templateComponentNames?.size)return;try{const setupAst=parse$3(descriptorForCompile.scriptSetup.content,BABEL_TS_MODULE_PARSER_OPTIONS);const pending=[];traverse(setupAst,{ImportDeclaration(path){if(path.node.importKind===`type`)return;if(!t.isStringLiteral(path.node.source))return;const importSource=path.node.source.value;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!(`local`in specifier)||!t.isIdentifier(specifier.local))continue;const localName=specifier.local.name;if(!templateComponentNames.has(localName))continue;const templateTags=[...templateTagsByComponentName?.get(localName)??[localName]];if(t.isImportDefaultSpecifier(specifier))pending.push({localName,importSource,importedName:`default`,kind:`default`,templateTags});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;pending.push({localName,importSource,importedName,kind:`named`,templateTags})}}}});await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents,result})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 <script setup> 导入失败:${message}`)}}function getExportDefaultObject(scriptAst){let options;traverse(scriptAst,{ExportDefaultDeclaration(path){const declaration=path.node.declaration;if(t.isObjectExpression(declaration))options=declaration;else if(t.isCallExpression(declaration)&&t.isObjectExpression(declaration.arguments[0]))options=declaration.arguments[0];path.stop()}});return options}function getObjectProperty(node,keyName){for(const property of node.properties){if(!t.isObjectProperty(property)||property.computed)continue;if(t.isIdentifier(property.key)?property.key.name===keyName:t.isStringLiteral(property.key)&&property.key.value===keyName)return property}}function getComponentRegistrationName(property){if(t.isIdentifier(property.key))return property.key.name;return t.isStringLiteral(property.key)?property.key.value:void 0}async function collectOptionsApiUsingComponents(options){const{descriptor,filename,compileOptions,autoUsingComponents,templateComponentNames,templateTagsByComponentName,result}=options;if(!descriptor.script||!descriptor.template||!templateComponentNames?.size)return;try{const ast=parse$3(descriptor.script.content,BABEL_TS_MODULE_PARSER_OPTIONS);const imports=/* @__PURE__ */ new Map;traverse(ast,{ImportDeclaration(path){if(path.node.importKind===`type`||!t.isStringLiteral(path.node.source))return;for(const specifier of path.node.specifiers){if(`importKind`in specifier&&specifier.importKind===`type`)continue;if(!t.isIdentifier(specifier.local))continue;if(t.isImportDefaultSpecifier(specifier))imports.set(specifier.local.name,{importSource:path.node.source.value,importedName:`default`,kind:`default`});else if(t.isImportSpecifier(specifier)){const importedName=t.isIdentifier(specifier.imported)?specifier.imported.name:t.isStringLiteral(specifier.imported)?specifier.imported.value:void 0;imports.set(specifier.local.name,{importSource:path.node.source.value,importedName,kind:`named`})}}}});const componentOptions=getExportDefaultObject(ast);const componentsProperty=componentOptions&&getObjectProperty(componentOptions,`components`);if(!componentsProperty||!t.isObjectExpression(componentsProperty.value))return;const pending=[];for(const property of componentsProperty.value.properties){if(!t.isObjectProperty(property)||!t.isIdentifier(property.value))continue;const registrationName=getComponentRegistrationName(property);const imported=imports.get(property.value.name);if(!registrationName||!imported||!templateComponentNames.has(registrationName))continue;pending.push({localName:property.value.name,...imported,templateTags:[...templateTagsByComponentName?.get(registrationName)??[registrationName]]})}await resolveScriptComponentRegistrations({pending,filename,compileOptions,autoUsingComponents,result})}catch(error){const message=error instanceof Error?error.message:String(error);autoUsingComponents?.warn?.(`[Vue 编译] 解析 ${filename} 的 Options API 局部组件失败:${message}`)}}async function collectAutoImportWevuComponents(options){const{descriptor,filename,compileOptions,autoImportTags,templateAutoImportTags,warn,result}=options;if(!autoImportTags||!descriptor.template)return;const resolvedTags=await Promise.all([...templateAutoImportTags??[]].map(async tag=>{let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}const componentMeta=await resolveVueSfcStaticComponentMeta(resolved?.resolvedId,{cache:compileOptions?.componentMetaCache,warn:autoImportTags.warn??warn});return{tag,resolved,componentMeta}}));for(const{tag,resolved,componentMeta}of resolvedTags){if(!resolved?.from)continue;result.autoImportTagsMap[resolved.name||tag]=resolved.from;if(isWevuSfcComponent(resolved)){result.wevuComponentTags.add(tag);if(resolved.name)result.wevuComponentTags.add(resolved.name)}registerComponentName(result,tag,componentMeta.componentName);const isMiniProgramComponent=componentMeta.isMiniProgramComponent;registerMiniProgramComponentTag(result,tag,isMiniProgramComponent);if(resolved.name){registerComponentName(result,resolved.name,componentMeta.componentName);registerMiniProgramComponentTag(result,resolved.name,isMiniProgramComponent)}}}async function collectComponentSourceInfo(options){const result=createComponentSourceInfo();const templateComponentTagInfo=options.descriptor.template?collectTemplateComponentTagInfo(options.descriptor.template.content,options.filename,options.autoUsingComponents?.warn??options.autoImportTags?.warn??options.compileOptions?.warn):void 0;const scriptImportResult=createComponentSourceInfo();const autoImportResult=createComponentSourceInfo();await Promise.all([collectScriptSetupUsingComponents({descriptor:options.descriptor,descriptorForCompile:options.descriptorForCompile,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,result:scriptImportResult}),collectOptionsApiUsingComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoUsingComponents:options.autoUsingComponents,templateComponentNames:templateComponentTagInfo?.componentNames,templateTagsByComponentName:templateComponentTagInfo?.tagsByComponentName,result:scriptImportResult}),collectAutoImportWevuComponents({descriptor:options.descriptor,filename:options.filename,compileOptions:options.compileOptions,autoImportTags:options.autoImportTags,templateAutoImportTags:templateComponentTagInfo?.autoImportTags,warn:options.compileOptions?.warn,result:autoImportResult})]);mergeComponentSourceInfo(result,scriptImportResult);mergeComponentSourceInfo(result,autoImportResult);return result}function normalizeConfigLang(lang){if(!lang)return`json`;const lower=lang.toLowerCase();if(lower===`txt`)return`json`;return lower}function isJsonLikeLang(lang){return lang===`json`||lang===`jsonc`||lang===`json5`}function resolveJsLikeLang(lang){if(lang===`ts`||lang===`tsx`||lang===`cts`||lang===`mts`)return`ts`;return`js`}async function evaluateJsLikeConfig(source,filename,lang){const dir=path.dirname(filename);const extension=resolveJsLikeLang(lang)===`ts`?`ts`:`js`;const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.config.${unique}`);return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.${unique}.${extension}`);const rewritten=rewriteJsLikeImportsForTempDir(source,dir,tempDir);await writeFile(tempFile,rewritten,`utf8`);try{const{mod}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});let resolved=mod?.default??mod;if(typeof resolved===`function`)resolved=resolved();if(resolved&&typeof resolved.then===`function`)resolved=await resolved;if(resolved&&typeof resolved===`object`)return resolved;throw new Error(`配置块必须导出对象或返回对象的函数。`)}finally{try{await remove(tempDir)}catch{}}})}async function compileConfigBlocks(blocks,filename,options){const jsonBlocks=blocks.filter(block=>block.type===`json`);if(!jsonBlocks.length)return;let accumulator={};for(const block of jsonBlocks){const lang=normalizeConfigLang(block.lang);try{if(isJsonLikeLang(lang)){const parsed=parse$2(block.content,void 0,true);if(options?.merge){const merged=options.merge(accumulator,parsed);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,parsed);continue}const evaluated=await evaluateJsLikeConfig(block.content,filename,lang);if(!evaluated||typeof evaluated!==`object`)continue;if(options?.merge){const merged=options.merge(accumulator,evaluated);if(merged&&typeof merged===`object`&&!Array.isArray(merged))accumulator=merged}else recursive(accumulator,evaluated)}catch(error){const message=error instanceof Error?error.message:String(error);throw new Error(`解析 <json> 块失败(${lang}):${filename}: ${message}`)}}if(Reflect.has(accumulator,`$schema`))delete accumulator.$schema;return JSON.stringify(accumulator,null,2)}function collectTemplateAutoImportTags(template,filename,warn){const warnHandler=resolveWarnHandler(warn);return collectVueTemplateTags(template,{filename,warnLabel:`自动导入标签`,warn:message=>warnHandler(message),shouldCollect:isAutoImportCandidateTag})}function normalizeUsingComponents(config){const raw=config.usingComponents;if(!raw||typeof raw!==`object`||Array.isArray(raw))return;const usingComponents={};for(const[name,from]of Object.entries(raw))usingComponents[normalizeTemplateTagName(name)]=from;config.usingComponents=usingComponents}async function compileConfigPhase(params){const{descriptor,filename,autoUsingComponentsMap,autoImportTagsMap:precomputedAutoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults,mergeJson,scriptSetupMacroConfig,result,warn}=params;let configObj;if(descriptor.customBlocks.some(b=>b.type===`json`)){const configResult=await compileConfigBlocks(descriptor.customBlocks,filename,{merge:(target,source)=>mergeJson(target,source,`json-block`)});if(configResult)try{configObj=JSON.parse(configResult)}catch{configObj={}}}const autoImportTagsMap=precomputedAutoImportTagsMap?{...precomputedAutoImportTagsMap}:{};if(!precomputedAutoImportTagsMap&&autoImportTags&&descriptor.template){const tags=collectTemplateAutoImportTags(descriptor.template.content,filename,autoImportTags.warn??warn);for(const tag of tags){let resolved;try{resolved=await autoImportTags.resolveUsingComponent(tag,filename)}catch{resolved=void 0}if(!resolved?.from)continue;autoImportTagsMap[resolved.name||tag]=resolved.from}}if(Object.keys(autoUsingComponentsMap).length>0||Object.keys(autoImportTagsMap).length>0){const existingRaw=configObj?.usingComponents;const usingComponents={};if(existingRaw&&typeof existingRaw===`object`&&!Array.isArray(existingRaw))for(const[name,from]of Object.entries(existingRaw))usingComponents[normalizeTemplateTagName(name)]=from;for(const[name,from]of Object.entries(autoImportTagsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoImportTags?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被模板标签自动引入覆盖为 '${from}'`);usingComponents[normalizedName]=from}for(const[name,from]of Object.entries(autoUsingComponentsMap)){const normalizedName=normalizeTemplateTagName(name);if(Reflect.has(usingComponents,normalizedName)&&usingComponents[normalizedName]!==from)autoUsingComponents?.warn?.(`[Vue 编译] usingComponents 冲突:${filename} 中 <json>.usingComponents['${normalizedName}']='${usingComponents[normalizedName]}' 将被 <script setup> 导入覆盖为 '${from}'`);usingComponents[normalizedName]=from}configObj=mergeJson(configObj??{},{usingComponents},`auto-using-components`)}if(result.componentGenerics&&Object.keys(result.componentGenerics).length>0){const existing=configObj?.componentGenerics;const componentGenerics=existing&&typeof existing===`object`&&!Array.isArray(existing)?existing:{};for(const[key,value]of Object.entries(result.componentGenerics))componentGenerics[key]=value;configObj=mergeJson(configObj??{},{componentGenerics},`component-generics`)}if(jsonDefaults&&Object.keys(jsonDefaults).length>0)configObj=mergeJson(configObj??{},jsonDefaults,`defaults`);if(scriptSetupMacroConfig&&Object.keys(scriptSetupMacroConfig).length>0)configObj=mergeJson(configObj??{},scriptSetupMacroConfig,`macro`);if(configObj)normalizeUsingComponents(configObj);if(configObj&&Object.keys(configObj).length>0)result.config=JSON.stringify(configObj,null,2)}function finalizeResult(result,options){if(!result.script||result.script.trim()===``)result.script=`import { ${WE_VU_RUNTIME_APIS.createWevuComponent} } from '${RUNTIME_IMPORT_PATH}';\n${WE_VU_RUNTIME_APIS.createWevuComponent}({});\n`;if(result.meta&&options.scriptSetupMacroHash)result.meta.jsonMacroHash=options.scriptSetupMacroHash;if(result.meta&&options.defineOptionsHash)result.meta.defineOptionsHash=options.defineOptionsHash}function getErrorMessage(error){if(error instanceof Error)return error.message;return typeof error===`string`?error:``}const BEHAVIOR_NOT_DEFINED_RE=/\bBehavior is not defined\b/;function shouldFallbackToRawDefineOptions(error){const message=getErrorMessage(error);return BEHAVIOR_NOT_DEFINED_RE.test(message)}function normalizeScriptSetupLang(lang){if(!lang)return`ts`;const lower=lang.toLowerCase();if(lower===`txt`)return`ts`;return lower}function resolveScriptSetupExtension(lang){const normalized=normalizeScriptSetupLang(lang);if(normalized===`ts`||normalized===`tsx`||normalized===`cts`||normalized===`mts`)return`ts`;return`js`}const IDENTIFIER_LIKE_KEY_RE=/^[A-Z_$][\w$]*$/i;const OBJECT_TO_STRING=Object.prototype.toString;function isIdentifierLikeKey(key){return IDENTIFIER_LIKE_KEY_RE.test(key)}function resolveRuntimeMarkerReference(value,scopeValues){if(value[WEAPP_I18N_RUNTIME_MARKER]!==true)return;const pending=Object.entries(scopeValues).filter(([name])=>isIdentifierLikeKey(name));const visited=/* @__PURE__ */ new WeakSet;for(let index=0;index<pending.length;index+=1){const[reference,candidate]=pending[index];if(candidate===value)return reference;if(!candidate||typeof candidate!==`object`||visited.has(candidate))continue;visited.add(candidate);for(const[key,member]of Object.entries(candidate))if(member&&typeof member===`object`){const accessor=isIdentifierLikeKey(key)?`.${key}`:`[${JSON.stringify(key)}]`;pending.push([`${reference}${accessor}`,member])}}}function getObjectTag(value){return OBJECT_TO_STRING.call(value)}const SERIALIZABLE_NATIVE_FUNCTIONS=/* @__PURE__ */ new Map([[String,`String`],[Number,`Number`],[Boolean,`Boolean`],[Object,`Object`],[Array,`Array`],[Function,`Function`],[Date,`Date`],[RegExp,`RegExp`],[Map,`Map`],[Set,`Set`],[WeakMap,`WeakMap`],[WeakSet,`WeakSet`],[Promise,`Promise`]]);function isParsableFunctionExpressionSource(source){try{parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);return true}catch{return false}}function tryConvertObjectMethodSourceToFunctionExpression(source){try{const statement=parse$3(`({ ${source} })`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement)||!t.isObjectExpression(statement.expression))return null;const firstProperty=statement.expression.properties[0];if(!firstProperty)return null;if(t.isObjectMethod(firstProperty)){const functionName=t.isIdentifier(firstProperty.key)?t.identifier(firstProperty.key.name):null;const functionExpression=t.functionExpression(functionName,firstProperty.params,firstProperty.body,firstProperty.generator,firstProperty.async);return generate(functionExpression).code}if(t.isObjectProperty(firstProperty)&&(t.isFunctionExpression(firstProperty.value)||t.isArrowFunctionExpression(firstProperty.value)))return generate(firstProperty.value).code}catch{}return null}function normalizeFunctionSourceToExpression(source){if(isParsableFunctionExpressionSource(source))return source;const converted=tryConvertObjectMethodSourceToFunctionExpression(source);if(converted&&isParsableFunctionExpressionSource(converted))return converted;throw new Error(`defineOptions 的参数中包含无法序列化的函数值。`)}function parseExpressionFromSource(source){const statement=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS).program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);return statement.expression}function rewriteFunctionSourceWithScopeValues(source,scopeValues){if(!Object.keys(scopeValues).length)return source;const wrappedAst=parse$3(`(${source})`,BABEL_TS_MODULE_PARSER_OPTIONS);traverse(wrappedAst,{Identifier(path){if(!path.isReferencedIdentifier())return;if(path.scope.hasBinding(path.node.name))return;if(!hasOwn(scopeValues,path.node.name))return;try{const replacement=serializeStaticValueToExpression(scopeValues[path.node.name],/* @__PURE__ */ new WeakSet,{});path.replaceWith(parseExpressionFromSource(replacement))}catch{}}});const statement=wrappedAst.program.body[0];if(!statement||!t.isExpressionStatement(statement))throw new Error(`defineOptions 的函数源码解析失败。`);const expression=statement.expression;return generate(expression).code}function serializeStaticValueToExpression(value,seen=/* @__PURE__ */ new WeakSet,scopeValues={}){if(value===null)return`null`;if(value===void 0)return`undefined`;const valueType=typeof value;if(valueType===`string`)return JSON.stringify(value);if(valueType===`boolean`)return value?`true`:`false`;if(valueType===`number`){if(Number.isNaN(value))return`Number.NaN`;if(value===Number.POSITIVE_INFINITY)return`Number.POSITIVE_INFINITY`;if(value===Number.NEGATIVE_INFINITY)return`Number.NEGATIVE_INFINITY`;if(Object.is(value,-0))return`-0`;return String(value)}if(valueType===`bigint`)return`${String(value)}n`;if(valueType===`symbol`)throw new Error(`defineOptions 的参数中不支持 Symbol 值。`);if(valueType===`function`){const source=Function.prototype.toString.call(value);if(source.includes(`[native code]`)){const nativeLiteral=SERIALIZABLE_NATIVE_FUNCTIONS.get(value);if(nativeLiteral)return nativeLiteral;throw new Error(`defineOptions 的参数中不支持原生函数值。`)}return`(${normalizeFunctionSourceToExpression(rewriteFunctionSourceWithScopeValues(normalizeFunctionSourceToExpression(source),scopeValues))})`}if(getObjectTag(value)===`[object Date]`)return`new Date(${JSON.stringify(value.toISOString())})`;if(getObjectTag(value)===`[object RegExp]`)return value.toString();if(Array.isArray(value))return`[${value.map(item=>serializeStaticValueToExpression(item,seen,scopeValues)).join(`, `)}]`;if(value&&typeof value===`object`){const runtimeReference=resolveRuntimeMarkerReference(value,scopeValues);if(runtimeReference)return runtimeReference;if(seen.has(value))throw new Error(`defineOptions 的参数中不支持循环引用。`);seen.add(value);const proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new Error(`defineOptions 的参数仅支持普通对象。`);const objectValue=value;return`{ ${Object.keys(objectValue).map(key=>{return`${isIdentifierLikeKey(key)?key:JSON.stringify(key)}: ${serializeStaticValueToExpression(objectValue[key],seen,scopeValues)}`}).join(`, `)} }`}throw new Error(`defineOptions 的参数中包含不支持的值类型:${valueType}`)}function resolveStaticDefineOptionsValues(statements){const values=[];for(const statement of statements){const arg=statement.argPath?.node;if(!arg||!t.isExpression(arg))return;let value;try{value=resolveStaticLiteralValue(arg)}catch{return}if(!value||typeof value!==`object`||Array.isArray(value))return;values.push(value)}return values}function collectDefineOptionsStatements(content,filename){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const statements=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;if(path.node.arguments.length!==1)throw new Error(`defineOptions() 在 ${filename} 中必须且只能传 1 个参数。`);statements.push({statementPath:path.parentPath,callPath:path,argPath:path.get(`arguments.0`)})}});return{statements}}function evaluateStaticExpression(source){return vm.runInNewContext(`(${source})`,{})}function collectStaticTopLevelScopeValues(content){const ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS);const scopeValues={};for(const statement of ast.program.body){if(!t.isVariableDeclaration(statement)||statement.kind!==`const`)continue;for(const declarator of statement.declarations){if(!t.isIdentifier(declarator.id)||!declarator.init)continue;try{scopeValues[declarator.id.name]=evaluateStaticExpression(declarator.init.end!=null&&declarator.init.start!=null?content.slice(declarator.init.start,declarator.init.end):``)}catch{}}}return scopeValues}function collectKeptBindingNames(keptStatementPaths){const names=/* @__PURE__ */ new Set;for(const statementPath of keptStatementPaths){if(statementPath.isImportDeclaration()){if(statementPath.node.importKind===`type`)continue;for(const specifier of statementPath.get(`specifiers`))if(specifier.isImportSpecifier()||specifier.isImportDefaultSpecifier()||specifier.isImportNamespaceSpecifier()){if(specifier.isImportSpecifier()&&specifier.node.importKind===`type`)continue;const local=specifier.node.local;if(t.isIdentifier(local))names.add(local.name)}continue}if(statementPath.isVariableDeclaration()){for(const declarator of statementPath.get(`declarations`)){const id=declarator.get(`id`);if(id.isIdentifier())names.add(id.node.name)}continue}if(statementPath.isFunctionDeclaration()||statementPath.isClassDeclaration()){const id=statementPath.node.id;if(t.isIdentifier(id))names.add(id.name)}}return[...names]}async function evaluateDefineOptionsValues(params){const{content,filename,lang,statements}=params;const ms=new MagicString(content);const dir=path.dirname(filename);const tempRoot=resolveWevuConfigTempDir(dir);const basename=path.basename(filename,path.extname(filename));const unique=`${Date.now()}-${Math.random().toString(16).slice(2)}`;const tempDir=path.join(tempRoot,`${basename}.define-options.${unique}`);const programPath=statements[0]?.statementPath.parentPath;if(!programPath)return{values:[],dependencies:[],scopeValues:{}};const bodyPaths=programPath?.get(`body`)??[];const macroStatementPaths=statements.map(item=>item.statementPath);const{keptStatementPaths}=collectKeptStatementPaths(programPath,macroStatementPaths);const keptBindingNames=collectKeptBindingNames(keptStatementPaths);for(const statementPath of keptStatementPaths){if(!statementPath.isImportDeclaration())continue;const sourceNode=statementPath.node.source;if(!sourceNode||!t.isStringLiteral(sourceNode))continue;const originalSource=sourceNode.value;if(!originalSource.startsWith(`.`))continue;const next=rewriteRelativeImportSource(originalSource,dir,tempDir);if(typeof sourceNode.start===`number`&&typeof sourceNode.end===`number`)ms.overwrite(sourceNode.start,sourceNode.end,JSON.stringify(next))}for(const statementPath of macroStatementPaths){const calleePath=statementPath.get(`expression`).get(`callee`);if(calleePath?.isIdentifier()&&typeof calleePath.node.start===`number`&&typeof calleePath.node.end===`number`)ms.overwrite(calleePath.node.start,calleePath.node.end,`__weapp_defineOptions`)}for(const statementPath of bodyPaths){if(keptStatementPaths.has(statementPath))continue;const start=statementPath.node.start;const end=statementPath.node.end;if(typeof start===`number`&&typeof end===`number`)ms.remove(start,end)}const extension=resolveScriptSetupExtension(lang);const header=`
|
|
30
30
|
const __weapp_define_options_values = []
|
|
31
31
|
const __weapp_define_scope_values = {}
|
|
32
32
|
const __weapp_defineOptions = (value) => (__weapp_define_options_values.push(value), value)
|
|
@@ -34,8 +34,8 @@ const __weapp_defineOptions = (value) => (__weapp_define_options_values.push(val
|
|
|
34
34
|
`);const evalSource=`${header+ms.toString()+(scopeFooter?`\n${scopeFooter}\n`:`
|
|
35
35
|
`)}export const __weapp_define_scope = __weapp_define_scope_values\n
|
|
36
36
|
export const __weapp_define_options = __weapp_define_options_values
|
|
37
|
-
`;return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.define-options.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const exported=mod?.__weapp_define_options??mod;return{values:Array.isArray(exported)?exported:[exported],dependencies,scopeValues:mod?.__weapp_define_scope??{}}}finally{try{await remove(tempDir)}catch{}}})}async function resolveDefineOptionsValue(raw){let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`defineOptions 的参数最终必须解析为对象。`);return next}async function inlineScriptSetupDefineOptionsArgs(content,filename,lang,sourceMap){const{statements}=collectDefineOptionsStatements(content,filename);if(!statements.length)return{code:content,dependencies:[]};let values=[];let dependencies=[];let scopeValues={};const staticValues=resolveStaticDefineOptionsValues(statements);if(staticValues)values=staticValues;else{scopeValues=collectStaticTopLevelScopeValues(content);try{const evaluated=await evaluateDefineOptionsValues({content,filename,lang,statements});values=evaluated.values;dependencies=evaluated.dependencies;scopeValues={...scopeValues,...evaluated.scopeValues}}catch(error){if(shouldFallbackToRawDefineOptions(error))return{code:content,dependencies:[]};throw error}}const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);for(let index=0;index<statements.length;index+=1){const argNode=statements[index].argPath?.node;if(!argNode||typeof argNode.start!==`number`||typeof argNode.end!==`number`)continue;const value=await resolveDefineOptionsValue(values[index]);const literal=serializeStaticValueToExpression(value,/* @__PURE__ */ new WeakSet,scopeValues);ms.overwrite(argNode.start,argNode.end,literal)}const code=sourceMap?ms.slice(0,content.length):ms.toString();
|
|
38
|
-
`)).digest(`hex`).slice(0,12)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0){const error=errors[0];throw new Error(`解析 ${filename} 失败:${error.message}`)}let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(options?.isPage===true&&(scriptResolvedId||scriptSetupResolvedId||mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=stripPageCompileTimeMacrosFromSfcDescriptor(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId});if(stripped){const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsHash;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},options?.sourceMap!==false&&(usesExternalScriptCompileSource||!scriptSetupForMap.src)?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0){const error=nextErrors[0];throw new Error(`解析 ${filename} 失败:${error.message}`)}assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsHash=extractDefineOptionsHash(scriptSetup.content)}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,options?.sourceMap!==false&&(usesExternalScriptCompileSource||!compileScriptSetup.src)?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0){const error=nextErrors[0];throw new Error(`解析 ${filename} 失败:${error.message}`)}assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile){if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearBindingManifestLocations(manifest);return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearBindingManifestLocations(manifest);return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={}){if(!scriptSetupCode)return;const result=detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;const EXPORT_DEFAULT_RE=/\bexport\s+default\b/;function hasDefaultExport(scriptCode){if(!EXPORT_DEFAULT_RE.test(scriptCode))return false;try{const ast=parseJsLike(scriptCode);let found=false;traverse(ast,{ExportDefaultDeclaration(path){found=true;path.stop()}});return found}catch{return EXPORT_DEFAULT_RE.test(scriptCode)}}function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(scriptCode){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=parseJsLike(scriptCode);traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(scriptCode);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap){const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start});if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode))scriptCode+=`
|
|
37
|
+
`;return await withTempDirLock(tempRoot,async()=>{await ensureDir(tempDir);const tempFile=path.join(tempDir,`${basename}.define-options.${unique}.${extension}`);await writeFile(tempFile,evalSource,`utf8`);try{const{mod,dependencies}=await bundleRequire({filepath:tempFile,cwd:dir,tsconfig:false});const exported=mod?.__weapp_define_options??mod;return{values:Array.isArray(exported)?exported:[exported],dependencies,scopeValues:mod?.__weapp_define_scope??{}}}finally{try{await remove(tempDir)}catch{}}})}async function resolveDefineOptionsValue(raw){let next=raw;if(typeof next===`function`)next=next();if(next&&typeof next.then===`function`)next=await next;if(!next||typeof next!==`object`||Array.isArray(next))throw new Error(`defineOptions 的参数最终必须解析为对象。`);return next}async function inlineScriptSetupDefineOptionsArgs(content,filename,lang,sourceMap){const{statements}=collectDefineOptionsStatements(content,filename);if(!statements.length)return{code:content,dependencies:[]};let values=[];let dependencies=[];let scopeValues={};const staticValues=resolveStaticDefineOptionsValues(statements);if(staticValues)values=staticValues;else{scopeValues=collectStaticTopLevelScopeValues(content);try{const evaluated=await evaluateDefineOptionsValues({content,filename,lang,statements});values=evaluated.values;dependencies=evaluated.dependencies;scopeValues={...scopeValues,...evaluated.scopeValues}}catch(error){if(shouldFallbackToRawDefineOptions(error))return{code:content,dependencies:[]};throw error}}const ms=sourceMap?new MagicString(sourceMap.source,{offset:sourceMap.offset}):new MagicString(content);for(let index=0;index<statements.length;index+=1){const argNode=statements[index].argPath?.node;if(!argNode||typeof argNode.start!==`number`||typeof argNode.end!==`number`)continue;const value=await resolveDefineOptionsValue(values[index]);const literal=serializeStaticValueToExpression(value,/* @__PURE__ */ new WeakSet,scopeValues);ms.overwrite(argNode.start,argNode.end,literal)}const code=sourceMap?ms.slice(0,content.length):ms.toString();const result={code,dependencies:dependencies.filter(Boolean)};if(!sourceMap||code===content)return result;const sourceFile=sourceMap.sourceFile;let map;return{...result,get map(){return map??=ms.generateMap({hires:true,includeContent:true,source:sourceFile})}}}const SETUP_CALL_RE=/\bsetup\s*\(/;const DEFINE_OPTIONS_CALL_RE=/\bdefineOptions\s*\(/;const APP_VUE_FILE_RE=/[\\/]app\.vue$/;const TEMPLATE_BLOCK_RE=/<template\b[\s\S]*?<\/template>/g;const TEMPLATE_IMPORT_META_RE=/\bimport\.meta\b/g;const TEMPLATE_IMPORT_META_PLACEHOLDER=`__im_meta__`;function createIdentitySourceMap(source,originalSource,filename){const sourceMap=new MagicString(source).generateMap({hires:true,includeContent:false,source:filename});sourceMap.sourcesContent=[originalSource];return sourceMap}function resolveSfcScriptLangLabel(lang){return typeof lang===`string`&&lang.length>0?lang:`(default)`}function assertMatchingSfcScriptLang(descriptor,filename){const scriptLang=descriptor.script?.lang;const scriptSetupLang=descriptor.scriptSetup?.lang;if(!descriptor.script||!descriptor.scriptSetup||scriptLang===scriptSetupLang)return;throw new Error(`解析 ${filename} 失败:同一个 SFC 中 <script> 与 <script setup> 的 lang 必须一致,当前分别为 ${resolveSfcScriptLangLabel(scriptLang)} 与 ${resolveSfcScriptLangLabel(scriptSetupLang)}`)}function resolveSourcePosition(source,offset){let line=1;let lineStart=0;for(let index=0;index<offset;index+=1){const char=source.charCodeAt(index);if(char===10||char===8232||char===8233){line+=1;lineStart=index+1}else if(char===13){line+=1;if(source.charCodeAt(index+1)===10)index+=1;lineStart=index+1}}return{column:offset-lineStart+1,line,offset}}function replaceScriptSetupContent(descriptor,content){const scriptSetup=descriptor.scriptSetup;const startOffset=scriptSetup.loc.start.offset;const endOffset=scriptSetup.loc.end.offset;const nextSource=descriptor.source.slice(0,startOffset)+content+descriptor.source.slice(endOffset);const delta=content.length-(endOffset-startOffset);const updateBlock=block=>{if(!block)return null;const isSetup=block===scriptSetup;const nextStart=isSetup?startOffset:block.loc.start.offset>=endOffset?block.loc.start.offset+delta:block.loc.start.offset;const nextEnd=isSetup?startOffset+content.length:block.loc.end.offset>=endOffset?block.loc.end.offset+delta:block.loc.end.offset;return{...block,content:isSetup?content:block.content,loc:{source:isSetup?content:block.loc.source,start:resolveSourcePosition(nextSource,nextStart),end:resolveSourcePosition(nextSource,nextEnd)}}};return{...descriptor,source:nextSource,script:updateBlock(descriptor.script),scriptSetup:updateBlock(descriptor.scriptSetup)}}function extractDefineOptionsHash(content){let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});if(!macroSources.length)return;return createHash(`sha256`).update(macroSources.join(`
|
|
38
|
+
`)).digest(`hex`).slice(0,12)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(options?.isPage===true&&(scriptResolvedId||scriptSetupResolvedId||mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=stripPageCompileTimeMacrosFromSfcDescriptor(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId});if(stripped){const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsHash;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsHash=extractDefineOptionsHash(scriptSetup.content)}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile){if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearBindingManifestLocations(manifest);return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearBindingManifestLocations(manifest);return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={}){if(!scriptSetupCode)return;const result=detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;const EXPORT_DEFAULT_RE=/\bexport\s+default\b/;function hasDefaultExport(scriptCode){if(!EXPORT_DEFAULT_RE.test(scriptCode))return false;try{const ast=parseJsLike(scriptCode);let found=false;traverse(ast,{ExportDefaultDeclaration(path){found=true;path.stop()}});return found}catch{return EXPORT_DEFAULT_RE.test(scriptCode)}}function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(scriptCode){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=parseJsLike(scriptCode);traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(scriptCode);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap){const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start});if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode))scriptCode+=`
|
|
39
39
|
export default {}`}else scriptCode=`export default {}`;if(scriptCode){const scriptLang=descriptor.script?.lang??descriptor.scriptSetup?.lang;const isJsxScript=scriptLang===`jsx`||scriptLang===`tsx`;let jsxTemplate;if(isJsxScript){jsxTemplate=compileJsxTemplateAndCollectComponents(scriptCode,filename,options);const externalScriptBlock=descriptor.script?.src?descriptor.script:descriptor.scriptSetup?.src?descriptor.scriptSetup:void 0;remapJsxBindingManifestLocations(jsxTemplate.bindingManifest,scriptMap,externalScriptBlock?.content??originalSource,externalScriptBlock?.src);if(jsxTemplate.template&&(options?.pageLayout||options?.appShell))jsxTemplate.template=applyCompilerTemplateWrappers({template:jsxTemplate.template,manifest:jsxTemplate.bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const reportJsxWarnings=!descriptor.template||Boolean(jsxTemplate.template);scriptCode=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptCode,filename,reportJsxWarnings?jsxTemplate.warnings:void 0),jsxTemplate.dynamicIslands);if(reportJsxWarnings&&jsxTemplate.warnings.length){jsxDiagnostics=createJsxDiagnostics(jsxTemplate.warnings,filename);if(options?.warn)jsxDiagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message))}}const jsxTransformed=isJsxScript?transformVueJsxScript(scriptCode,filename,options?.sourceMap!==false):{code:scriptCode,map:null};const bindingManifest=jsxTemplate?.template?jsxTemplate.bindingManifest:templateCompiled?.bindingManifest;const effectiveInlineExpressions=jsxTemplate?.template?jsxTemplate.inlineExpressions:templateCompiled?.inlineExpressions;const runtimeCapabilities=bindingManifest?createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest):templateCompiled?.runtimeCapabilities;const transformed=transformScript(jsxTransformed.code,{isTypeScript:descriptor.script?.lang===`ts`||descriptor.script?.lang===`tsx`||descriptor.scriptSetup?.lang===`ts`||descriptor.scriptSetup?.lang===`tsx`,skipComponentTransform:options?.skipComponentTransform??isAppFile,isApp:isAppFile,isPage:options?.isPage===true,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,templateComponentMeta:Object.keys(autoComponentMeta).length?autoComponentMeta:void 0,wevuDefaults:options?.wevuDefaults,classStyleRuntime:templateCompiled?.classStyleRuntime,classStyleBindings:templateCompiled?.classStyleBindings,templateRefs:templateCompiled?.templateRefs,layoutHosts:templateCompiled?.layoutHosts,inlineExpressions:effectiveInlineExpressions,bindingManifest:isAppFile?void 0:bindingManifest,autoSetDataPick:!isAppFile&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:isAppFile?void 0:options?.pageLayout,runtimeCapabilities,functionPropPaths:templateCompiled?.functionPropPaths,propsAliases,propsDerivedKeys,cssModules:precomputedScriptPhaseInfo?.cssModules,stabilizeCssVarsRuntime:options?.stabilizeCssVarsRuntime,relaxStructuredTypeOnlyProps,scopedSlotHostProperties:!isAppFile&&options?.isPage!==true&&Boolean(templateCompiled?.hasSlotOutlet||templateCompiled?.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length>0)});return{script:transformed.code,scriptMap:composeSourceMaps(transformed.map??jsxTransformed.map,scriptMap),template:jsxTemplate?.template,diagnostics:jsxDiagnostics,bindingManifest,inlineExpressions:jsxTemplate?.inlineExpressions,runtimeCapabilities:transformed.runtimeCapabilities,componentStyleOptions:transformed.componentStyleOptions,autoUsingComponentsMap,autoComponentMeta}}return{script:scriptCode,scriptMap:null,autoUsingComponentsMap,autoComponentMeta}}async function compileStylePhase(descriptor,filename,result,options){if(descriptor.styles.length===0)return{usesSlotted:false};const scopedId=generateScopedId(filename);const compiledStyles=await Promise.all(descriptor.styles.map(async styleBlock=>{return await compileVueStyleToWxss(styleBlock,{id:scopedId,filename,scoped:styleBlock.scoped,modules:styleBlock.module,preprocessOptions:options?.preprocessOptions?.[styleBlock.lang||`css`],preserveDeepSelectors:options?.preserveDeepSelectors,transformScoped:options?.transformScoped})}));result.style=compiledStyles.map(s=>s.code.trim()).filter(Boolean).join(`
|
|
40
40
|
|
|
41
|
-
`);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;if(templateCompiled.diagnostics.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(templateCompiled.diagnostics,templateResolvedId,descriptor.template.content);else for(const diagnostic of templateCompiled.diagnostics)diagnostic.loc=void 0}else remapTemplateDiagnostics(templateCompiled.diagnostics,descriptor.template.loc.start,source);result.diagnostics=templateCompiled.diagnostics}if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags});const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content):void 0;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length&&options?.warn)for(const diagnostic of templateCompiled.diagnostics)options.warn(diagnostic.message);if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};
|
|
41
|
+
`);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;if(templateCompiled.diagnostics.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(templateCompiled.diagnostics,templateResolvedId,descriptor.template.content);else for(const diagnostic of templateCompiled.diagnostics)diagnostic.loc=void 0}else remapTemplateDiagnostics(templateCompiled.diagnostics,descriptor.template.loc.start,source);result.diagnostics=templateCompiled.diagnostics}if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags});const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content):void 0;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};
|