@wevu/compiler 7.10.0 → 7.10.1-dev.20261112.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +5 -1
- package/dist/index.mjs +2 -2
- package/package.json +16 -8
package/dist/index.d.mts
CHANGED
|
@@ -4,7 +4,7 @@ import "@vue/compiler-core";
|
|
|
4
4
|
import { parse } from "@vue/compiler-dom";
|
|
5
5
|
import { LRUCache } from "lru-cache";
|
|
6
6
|
import MagicString from "magic-string";
|
|
7
|
-
import { SFCBlock, SFCDescriptor, SFCParseResult, SFCStyleBlock } from "vue/compiler-sfc";
|
|
7
|
+
import { SFCBlock, SFCDescriptor, SFCParseOptions, SFCParseResult, SFCStyleBlock } from "vue/compiler-sfc";
|
|
8
8
|
import * as t from "@weapp-vite/ast/babelTypes";
|
|
9
9
|
import { Expression, File } from "@weapp-vite/ast/babelTypes";
|
|
10
10
|
import { MpPlatform } from "@weapp-core/shared";
|
|
@@ -260,6 +260,10 @@ interface ReadAndParseSfcOptions {
|
|
|
260
260
|
*/
|
|
261
261
|
resolveSrc?: ResolveSfcBlockSrcOptions;
|
|
262
262
|
}
|
|
263
|
+
/**
|
|
264
|
+
* 解析 SFC,并在 Vue 完成块归属与校验后恢复外部脚本来源。
|
|
265
|
+
*/
|
|
266
|
+
export declare function parseVueSfc(source: string, options?: Omit<SFCParseOptions, 'compiler'>): SFCParseResult;
|
|
263
267
|
/**
|
|
264
268
|
* 预处理 `<script setup src>`,避免编译器丢失 src。
|
|
265
269
|
*/
|
package/dist/index.mjs
CHANGED
|
@@ -11,7 +11,7 @@ return transformNormalElement(node,context,transformNode);const{conditionKind,co
|
|
|
11
11
|
/* istanbul ignore next */
|
|
12
12
|
return renderMustache$1(``,context)}function transformNode(node,context){switch(node.type){case NodeTypes.ELEMENT:if(context.rawScriptModules?.byStart.has(node.loc.start.offset))return context.rawScriptModules.byStart.get(node.loc.start.offset).placeholder;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:
|
|
13
13
|
/* istanbul ignore next */
|
|
14
|
-
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};const compatibleWechatPlatform={...defaultMiniProgramPlatform,nativeSlotContext:false};function getDefaultMiniProgramTemplatePlatform(){return TEMPLATE_PRESET_PLATFORMS[getMiniProgramTemplatePreset()]}const getDefaultMiniProgramPlatform=getDefaultMiniProgramTemplatePlatform;const defaultMiniProgramTemplatePlatform=getDefaultMiniProgramTemplatePlatform();const wechatPlatform=defaultMiniProgramPlatform;function getMiniProgramTemplatePlatform(platform){const preset=getMiniProgramTemplatePreset(platform);if(platform&&platform!==`weapp`&&preset===`wechat`)return compatibleWechatPlatform;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})}}}function collectTemplateSourceTags(root,filename,htmlTagToWxmlMap){const tags=[];const visit=nodes=>{for(const node of nodes)if(node.type===NodeTypes.ELEMENT){tags.push({tag:node.tag,resolvedTag:resolveTemplateTagName(node.tag,{htmlTagToWxmlMap}),filename,loc:{start:{...node.loc.start},end:{...node.loc.end}}});if(node.tag!==`wxs`)visit(node.children)}};visit(root.children);return tags}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,scripts}=parseTemplateWithScriptModules(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`)},options?.platform?.name??`weapp`);const sourceTags=collectTemplateSourceTags(ast,filename,htmlTagToWxmlMap);const context={source:template,rawScriptModules:scripts,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,scriptSetupPropConflicts:options?.scriptSetupPropConflicts,htmlTagToWxmlMap,htmlTagToWxmlTagClass:options?.htmlTagToWxmlTagClass??true,scopedSlotsCompiler:options?.scopedSlotsCompiler??`auto`,scopedSlotsRequireProps,nativeSlotContext:options?.nativeSlotContext===true,nativeSlotContextTags:options?.nativeSlotContextTags,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:[],nativeDeclarationStack:[],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,context.platform.name)}\n${wxml}`}if(context.formatWxml)wxml=formatWxml(wxml);wxml=scripts.restore(wxml);for(const asset of context.scopedSlotComponents)asset.template=scripts.restore(asset.template);retainScopedSlotOwnerBindings(context.bindingManifest,context.scopedSlotComponents);const result={code:wxml,diagnostics,bindingManifest:context.bindingManifest,sourceTags};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=`
|
|
14
|
+
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};const compatibleWechatPlatform={...defaultMiniProgramPlatform,nativeSlotContext:false};function getDefaultMiniProgramTemplatePlatform(){return TEMPLATE_PRESET_PLATFORMS[getMiniProgramTemplatePreset()]}const getDefaultMiniProgramPlatform=getDefaultMiniProgramTemplatePlatform;const defaultMiniProgramTemplatePlatform=getDefaultMiniProgramTemplatePlatform();const wechatPlatform=defaultMiniProgramPlatform;function getMiniProgramTemplatePlatform(platform){const preset=getMiniProgramTemplatePreset(platform);if(platform&&platform!==`weapp`&&preset===`wechat`)return compatibleWechatPlatform;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})}}}function collectTemplateSourceTags(root,filename,htmlTagToWxmlMap){const tags=[];const visit=nodes=>{for(const node of nodes)if(node.type===NodeTypes.ELEMENT){tags.push({tag:node.tag,resolvedTag:resolveTemplateTagName(node.tag,{htmlTagToWxmlMap}),filename,loc:{start:{...node.loc.start},end:{...node.loc.end}}});if(node.tag!==`wxs`)visit(node.children)}};visit(root.children);return tags}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,scripts}=parseTemplateWithScriptModules(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`)},options?.platform?.name??`weapp`);const sourceTags=collectTemplateSourceTags(ast,filename,htmlTagToWxmlMap);const context={source:template,rawScriptModules:scripts,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,scriptSetupPropConflicts:options?.scriptSetupPropConflicts,htmlTagToWxmlMap,htmlTagToWxmlTagClass:options?.htmlTagToWxmlTagClass??true,scopedSlotsCompiler:options?.scopedSlotsCompiler??`auto`,scopedSlotsRequireProps,nativeSlotContext:options?.nativeSlotContext===true,nativeSlotContextTags:options?.nativeSlotContextTags,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:[],nativeDeclarationStack:[],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,context.platform.name)}\n${wxml}`}if(context.formatWxml)wxml=formatWxml(wxml);wxml=scripts.restore(wxml);for(const asset of context.scopedSlotComponents)asset.template=scripts.restore(asset.template);retainScopedSlotOwnerBindings(context.bindingManifest,context.scopedSlotComponents);const result={code:wxml,diagnostics,bindingManifest:context.bindingManifest,sourceTags};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){const expression=serializeFallbackLayoutValue(currentLayout?.props?.[key],key);const encoded=platform.name===`wechat`&&platform.nativeSlotContext!==false?expression.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`):escapeWxmlAttribute(expression);attrs.push(`${toKebabCase(key)}="{{${encoded}}}"`)}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
15
|
const __weapp_json_macro_values = []
|
|
16
16
|
const __weapp_defineAppJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
17
17
|
const __weapp_definePageJson = (config) => (__weapp_json_macro_values.push(config), config)
|
|
@@ -39,4 +39,4 @@ export const __weapp_define_options = __weapp_define_options_values
|
|
|
39
39
|
`)).digest(`hex`).slice(0,12)}function extractDefineOptionsHash(content,analysis){if(analysis)return hashDefineOptionsSources(analysis.defineOptionsStatements.map(({start,end})=>content.slice(start,end)));let ast;try{ast=parse$3(content,BABEL_TS_MODULE_PARSER_OPTIONS)}catch{return}const macroSources=[];traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineOptions`}))return;if(!(path.parentPath?.isExpressionStatement()&&path.parentPath.parentPath?.isProgram()))return;const statement=path.parentPath?.node;if(statement&&typeof statement.start===`number`&&typeof statement.end===`number`)macroSources.push(content.slice(statement.start,statement.end))}});return hashDefineOptionsSources(macroSources)}function preprocessTemplateImportMeta(source){return source.replace(TEMPLATE_BLOCK_RE,block=>block.replace(TEMPLATE_IMPORT_META_RE,TEMPLATE_IMPORT_META_PLACEHOLDER))}function restoreTemplateImportMeta(content){return content.replace(new RegExp(TEMPLATE_IMPORT_META_PLACEHOLDER,`g`),`import.meta`)}function restoreTemplateImportMetaInDescriptor(descriptor){if(!descriptor.template?.content?.includes(TEMPLATE_IMPORT_META_PLACEHOLDER))return descriptor;return{...descriptor,template:{...descriptor.template,content:restoreTemplateImportMeta(descriptor.template.content)}}}async function parseSfc(source,filename,ignoreEmpty,preprocessedSource=preprocessTemplateImportMeta(source)){const parsed=await readAndParseSfc(filename,{source,preprocessedSource,checkMtime:false,ignoreEmpty});return{...parsed,descriptor:restoreTemplateImportMetaInDescriptor(parsed.descriptor)}}function resolvePreprocessSourceMap(sourceMap,transforms){if(transforms)for(const transform of transforms)sourceMap=composeSourceMaps(transform.map,sourceMap);return sourceMap}function hasSharedNativeAnalysis(descriptor,defineOptionsSource,isAppFile){return[descriptor.script,descriptor.scriptSetup,defineOptionsSource].filter(Boolean).length>1||process.env.WEAPP_VITE_NATIVE===`1`&&Boolean(process.env.WEAPP_VITE_NATIVE_AST_PATH?.trim())&&!isAppFile&&!descriptor.scriptSetup&&Boolean(descriptor.script&&mayShareNativeOptionsAnalysis(descriptor.script.content,descriptor.template))}async function parseVueFile(source,filename,options){const normalizedInputSource=normalizeLineEndings(source);let scriptPreprocessMap=null;let deferredPreprocessMaps;if(options?.sourceMap!==false&&normalizedInputSource!==source)scriptPreprocessMap=createIdentitySourceMap(normalizedInputSource,source,filename);const normalizedSource=normalizedInputSource;const parserSource=preprocessTemplateImportMeta(normalizedSource);if(options?.sourceMap!==false&&parserSource!==normalizedSource)scriptPreprocessMap=composeSourceMaps(createIdentitySourceMap(parserSource,normalizedSource,filename),scriptPreprocessMap);let descriptorForCompileSource=normalizedSource;const parsedSfc=await parseSfc(normalizedSource,filename,true,parserSource);const descriptor=parsedSfc.descriptor;const{errors}=parsedSfc;if(errors.length>0)throw createSfcParseError(errors[0],{filename,source,sourceMap:scriptPreprocessMap});let resolvedDescriptor=descriptor;let sfcSrcDeps;let templateResolvedId;let scriptResolvedId;let scriptSetupResolvedId;if(options?.sfcSrc){const resolved=await resolveSfcBlockSrc(descriptor,filename,options.sfcSrc);resolvedDescriptor=resolved.descriptor;templateResolvedId=resolved.templateResolvedId;scriptResolvedId=resolved.scriptResolvedId;scriptSetupResolvedId=resolved.scriptSetupResolvedId;if(resolved.deps.length)sfcSrcDeps=resolved.deps}let routeConfig;let pageMeta;let descriptorForCompile=resolvedDescriptor;let usesExternalScriptCompileSource=false;if(scriptResolvedId||scriptSetupResolvedId||options?.isPage===true&&(mayContainPageDeclaration(normalizedSource)||mayContainPageMeta(normalizedSource))){const stripped=prepareSfcScriptCompile(normalizedSource,filename,resolvedDescriptor,options?.sourceMap!==false,{scriptResolvedId,scriptSetupResolvedId},options?.isPage===true);if(stripped){routeConfig=stripped.routeConfig;pageMeta=stripped.pageMeta;const mainSourcePreprocessMap=scriptPreprocessMap;resolvedDescriptor=stripped.descriptor;usesExternalScriptCompileSource=Boolean(stripped.descriptorForCompile);descriptorForCompile=stripped.descriptorForCompile??stripped.descriptor;descriptorForCompileSource=stripped.descriptorForCompile?.source??stripped.code;const usesExternalNormalScriptCompileSource=Boolean(resolvedDescriptor.script?.src&&!resolvedDescriptor.scriptSetup);if(usesExternalScriptCompileSource)scriptPreprocessMap=composeSourceMapForSource(stripped.scriptMap,mainSourcePreprocessMap,filename);else if(usesExternalNormalScriptCompileSource)scriptPreprocessMap=null;else scriptPreprocessMap=composeSourceMaps(stripped.map,mainSourcePreprocessMap)}}assertMatchingSfcScriptLang(resolvedDescriptor,filename);const meta={routeConfig,pageMeta,hasScriptSetup:!!resolvedDescriptor.scriptSetup,hasSetupOption:!!resolvedDescriptor.script&&SETUP_CALL_RE.test(resolvedDescriptor.script.content),sfcSrcDeps,sfcSrcCompilationDeps:[templateResolvedId,scriptResolvedId,scriptSetupResolvedId].filter(id=>Boolean(id))};let scriptSetupMacroConfig;let scriptSetupMacroHash;let defineOptionsSource;const jsonKind=options?.json?.kind??(options?.isApp?`app`:options?.isPage?`page`:`component`);const jsonDefaults=options?.json?.defaults?.[jsonKind];const mergeJson=createJsonMerger(options?.json?.mergeStrategy,{filename,kind:jsonKind,routeConfig,pageMeta});const scriptSetup=resolvedDescriptor.scriptSetup;if(scriptSetup?.content){const scriptSetupForMap=usesExternalScriptCompileSource?descriptorForCompile.scriptSetup:scriptSetup;if(mayContainJsonMacro(scriptSetup.content)){const extracted=await extractJsonMacroFromScriptSetupWithSourceMap(scriptSetup.content,filename,scriptSetup.lang,{merge:(target,source)=>mergeJson(target,source,`macro`),preambleContent:resolvedDescriptor.script?.content},usesExternalScriptCompileSource||!scriptSetupForMap.src?{source:descriptorForCompileSource,sourceFile:filename,offset:scriptSetupForMap.loc.start.offset}:void 0);if(extracted.stripped!==scriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(extracted);else scriptPreprocessMap=composeSourceMaps(extracted.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,extracted.stripped);descriptorForCompileSource=descriptorForCompile.source}else if(scriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...descriptorForCompile.scriptSetup,content:extracted.stripped}};else{const setupLoc=scriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+extracted.stripped+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}scriptSetupMacroConfig=extracted.config;scriptSetupMacroHash=extracted.macroHash}if(DEFINE_OPTIONS_CALL_RE.test(scriptSetup.content))defineOptionsSource=scriptSetup}const compileScriptSetup=descriptorForCompile.scriptSetup;if(compileScriptSetup?.content&&DEFINE_OPTIONS_CALL_RE.test(compileScriptSetup.content)){const inlined=await inlineScriptSetupDefineOptionsArgs(compileScriptSetup.content,filename,compileScriptSetup.lang,usesExternalScriptCompileSource||!compileScriptSetup.src?{source:descriptorForCompileSource,sourceFile:filename,offset:compileScriptSetup.loc.start.offset}:void 0);if(inlined.code!==compileScriptSetup.content){if(options?.sourceMap===false)(deferredPreprocessMaps??=[]).push(inlined);else scriptPreprocessMap=composeSourceMaps(inlined.map,scriptPreprocessMap);if(usesExternalScriptCompileSource){descriptorForCompile=replaceScriptSetupContent(descriptorForCompile,inlined.code);descriptorForCompileSource=descriptorForCompile.source}else if(compileScriptSetup.src)descriptorForCompile={...descriptorForCompile,scriptSetup:{...compileScriptSetup,content:inlined.code}};else{const setupLoc=compileScriptSetup.loc;const startOffset=setupLoc.start.offset;const endOffset=setupLoc.end.offset;const nextSource=descriptorForCompileSource.slice(0,startOffset)+inlined.code+descriptorForCompileSource.slice(endOffset);const{descriptor:nextDescriptor,errors:nextErrors}=await parseSfc(nextSource,filename,false);if(nextErrors.length>0)throw createSfcParseError(nextErrors[0],{filename,source,sourceMap:resolvePreprocessSourceMap(scriptPreprocessMap,deferredPreprocessMaps)});assertMatchingSfcScriptLang(nextDescriptor,filename);if(options?.sfcSrc){const resolvedNext=await resolveSfcBlockSrc(nextDescriptor,filename,options.sfcSrc);descriptorForCompile=resolvedNext.descriptor;if(resolvedNext.deps.length){sfcSrcDeps=[.../* @__PURE__ */ new Set([...sfcSrcDeps??[],...resolvedNext.deps])];meta.sfcSrcDeps=sfcSrcDeps}}else descriptorForCompile=nextDescriptor;descriptorForCompileSource=nextSource}}}const isAppFile=APP_VUE_FILE_RE.test(filename);const nativeAnalysis=hasSharedNativeAnalysis(descriptorForCompile,defineOptionsSource,isAppFile)?analyzeNativeScriptBlocks(descriptorForCompile,filename,defineOptionsSource):void 0;const defineOptionsHash=defineOptionsSource?extractDefineOptionsHash(defineOptionsSource.content,nativeAnalysis?.defineOptions):void 0;return{descriptor:resolvedDescriptor,descriptorForCompile,scriptPreprocessMap,templateResolvedId,meta,scriptSetupMacroConfig,scriptSetupMacroHash,defineOptionsHash,jsonKind,jsonDefaults,mergeJson,isAppFile,nativeScriptAnalysis:nativeAnalysis?.scripts}}function createModuleFacts(id,ast){let scope;traverse(ast,{Program(path){scope=path.scope;path.stop()}});return{id,ast,scope}}function unwrap(node){return t.isTSAsExpression(node)||t.isTSSatisfiesExpression(node)||t.isTSNonNullExpression(node)||t.isTSTypeAssertion(node)||t.isTypeCastExpression(node)||t.isParenthesizedExpression(node)?unwrap(node.expression):node}function staticName(node,computed=false){node=unwrap(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return String(node.value);if(!computed&&t.isIdentifier(node))return node.name;if(t.isTemplateLiteral(node)&&!node.expressions.length)return node.quasis[0]?.value.cooked??node.quasis[0]?.value.raw}function isImportedCall(node,module,importedName,sources){if(!t.isCallExpression(node)||!t.isIdentifier(node.callee))return false;const importPath=module.scope.getBinding(node.callee.name)?.path;const declaration=importPath?.parentPath;return Boolean(importPath?.isImportSpecifier()&&importPath.node.importKind!==`type`&&t.isIdentifier(importPath.node.imported,{name:importedName})&&declaration?.isImportDeclaration()&&declaration.node.importKind!==`type`&&sources.includes(declaration.node.source.value))}function createPropsModuleResolver(reader,root){const modules=/* @__PURE__ */ new Map([[root.id,Promise.resolve(root)]]);const load=id=>{let task=modules.get(id);if(!task){task=(async()=>{const source=await reader.load(id);if(!source||source.descriptor||source.invalid)return;try{source.ast??=parseJsLike(source.source);return createModuleFacts(id,source.ast)}catch{return}})();modules.set(id,task)}return task};const resolveExport=async(source,importer,name,visiting=/* @__PURE__ */ new Set)=>{const id=await reader.resolve(source,importer);if(!id)return;const key=`${id}\0${name}`;if(visiting.has(key))return;const next=new Set(visiting).add(key);const module=await load(id);if(!module)return;for(const statement of module.ast.program.body){if(name==="default"&&t.isExportDefaultDeclaration(statement))return{node:statement.declaration,module};if(!t.isExportNamedDeclaration(statement)||statement.exportKind===`type`)continue;if(t.isVariableDeclaration(statement.declaration)){for(const declaration of statement.declaration.declarations)if(t.isIdentifier(declaration.id,{name}))return{node:declaration.id,module}}for(const specifier of statement.specifiers){if(!t.isExportSpecifier(specifier)||specifier.exportKind===`type`||staticName(specifier.exported)!==name)continue;const local=staticName(specifier.local);if(statement.source)return local?resolveExport(statement.source.value,module.id,local,next):void 0;return{node:specifier.local,module}}}};const resolveImport=async(node,module)=>{node=unwrap(node);let local;let member;if(t.isIdentifier(node))local=node.name;else if(t.isMemberExpression(node)&&t.isIdentifier(node.object)){local=node.object.name;member=staticName(node.property,node.computed);if(!member)return}const binding=local&&module.scope.getBinding(local);if(!binding||!binding.path.parentPath?.isImportDeclaration()||binding.path.parentPath.node.importKind===`type`)return;const declaration=binding.path.parentPath.node;const specifier=binding.path.node;const name=t.isImportDefaultSpecifier(specifier)&&member===void 0?`default`:t.isImportSpecifier(specifier)&&specifier.importKind!==`type`&&member===void 0?staticName(specifier.imported):t.isImportNamespaceSpecifier(specifier)?member:void 0;return name?resolveExport(declaration.source.value,module.id,name):void 0};return{resolveImport}}function isObjectCall(node,scope,name){return t.isCallExpression(node)&&t.isMemberExpression(node.callee)&&!node.callee.computed&&t.isIdentifier(node.callee.object,{name:`Object`})&&!scope.getBinding(`Object`)&&t.isIdentifier(node.callee.property,{name})}function isGeneratedSetupReturn(reference,setup){const property=reference.parentPath;const object=property?.parentPath;const declaration=object?.parentPath;return Boolean(setup&&property?.isObjectProperty()&&property.node.value===reference.node&&object?.isObjectExpression()&&declaration?.isVariableDeclarator()&&t.isIdentifier(declaration.node.id,{name:`__returned__`})&&declaration.findParent(parent=>parent.node===setup))}function isSafeReference(reference,ownership,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(ownership.props&&unwrap(current.node)===unwrap(ownership.props)||isGeneratedSetupReturn(current,ownership.setup))return true;if(current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isSpreadElement()&&(parent.parentPath.isObjectExpression()||parent.parentPath.isArrayExpression()))return true;if(parent?.isCallExpression())return isObjectCall(parent.node,parent.scope,`freeze`)&&parent.node.arguments.length===1||isObjectCall(parent.node,parent.scope,`assign`)&&parent.node.arguments.indexOf(current.node)>0;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafePropsBinding(parent.scope.getBinding(parent.node.id.name),ownership,visiting);return false}function isSafePropsBinding(binding,ownership,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeReference(reference,ownership,next))}const absent={kind:`absent`};const unknown={kind:`unknown`};function isSafeOptionReference(reference,allowed,visiting){let current=reference;while(current.parentPath&&unwrap(current.parentPath.node)===unwrap(current.node))current=current.parentPath;if(allowed.has(unwrap(current.node))||current.findParent(parent=>t.isTSType(parent.node)))return true;const parent=current.parentPath;if(parent?.isVariableDeclarator()&&t.isIdentifier(parent.node.id)&&parent.node.init===current.node)return isSafeOptionBinding(parent.scope.getBinding(parent.node.id.name),allowed,visiting);return false}function isSafeOptionBinding(binding,allowed,visiting=/* @__PURE__ */ new Set){if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||binding.path.parentPath.parentPath?.isExportNamedDeclaration()||visiting.has(binding.path.node))return false;const next=new Set(visiting).add(binding.path.node);return binding.referencePaths.every(reference=>isSafeOptionReference(reference,allowed,next))}function isComponentFactory(node,module){if(!t.isIdentifier(node.callee))return false;const binding=module.scope.getBinding(node.callee.name);return binding?.path.isImportSpecifier()&&t.isIdentifier(binding.path.node.imported,{name:`defineComponent`})&&binding.path.parentPath.isImportDeclaration()&&[`vue`,`wevu`,`wevu/internal-runtime`,`virtual:weapp-vite/runtime`].includes(binding.path.parentPath.node.source.value)}function isSafeMergeOperand(input,module,visiting){const node=unwrap(input);if(visiting.has(node))return false;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&Boolean(binding?.path.isVariableDeclarator()&&binding.path.node.init&&isSafeMergeOperand(binding.path.node.init,module,next))}if(t.isObjectExpression(node))return node.properties.every(property=>{if(t.isSpreadElement(property))return isSafeMergeOperand(property.argument,module,next);const key=staticName(property.key,property.computed);return key!==void 0&&key!==`__proto__`&&(t.isObjectProperty(property)||property.kind===`method`)});if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return isSafeMergeOperand(node.arguments[0],module,next);if(isObjectCall(node,module.scope,`assign`))return node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next))}return false}function findCompiledOption(input,name,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return unknown;const next=new Set(visiting).add(node);if(t.isIdentifier(node)){const binding=module.scope.getBinding(node.name);return isSafeOptionBinding(binding,next)&&binding?.path.isVariableDeclarator()&&binding.path.node.init?findCompiledOption(binding.path.node.init,name,module,next):unknown}if(t.isObjectExpression(node)){for(const property of[...node.properties].reverse()){if(t.isSpreadElement(property)){const inherited=findCompiledOption(property.argument,name,module,next);if(inherited.kind!==`absent`)return inherited;continue}const key=staticName(property.key,property.computed);if(key===void 0||key===`__proto__`)return unknown;if(key===name)return t.isObjectProperty(property)||property.kind===`method`?{kind:`value`,node:t.isObjectProperty(property)?property.value:property}:unknown}return absent}if(t.isCallExpression(node)){if(isComponentFactory(node,module)&&node.arguments.length===1&&t.isExpression(node.arguments[0]))return findCompiledOption(node.arguments[0],name,module,next);if(isObjectCall(node,module.scope,`assign`)){if(!node.arguments.every(argument=>t.isExpression(argument)&&isSafeMergeOperand(argument,module,next)))return unknown;for(const argument of[...node.arguments].reverse()){const option=t.isExpression(argument)?findCompiledOption(argument,name,module,next):unknown;if(option.kind!==`absent`)return option}return absent}}return unknown}function excludePropsObjectAliases(keys,setup){if(!setup||!(t.isObjectMethod(setup)||t.isFunctionExpression(setup)||t.isArrowFunctionExpression(setup))||!t.isIdentifier(setup.params[0])||!t.isBlockStatement(setup.body))return keys;const aliases=/* @__PURE__ */ new Set;for(const statement of setup.body.body)if(t.isVariableDeclaration(statement)){for(const declaration of statement.declarations)if(t.isIdentifier(declaration.id)&&t.isIdentifier(declaration.init,{name:setup.params[0].name}))aliases.add(declaration.id.name)}return keys.filter(key=>!aliases.has(key))}function constantInitializer(node,module){if(!t.isIdentifier(node))return;const binding=module.scope.getBinding(node.name);if(!binding?.constant||!binding.path.isVariableDeclarator()||!binding.path.parentPath.isVariableDeclaration()||binding.path.parentPath.node.kind!==`const`||!binding.path.node.init)return;return{binding,node:binding.path.node.init}}function createPropsShapeAnalyzer(modules,ownership){async function primitive(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);if(t.isStringLiteral(node)||t.isNumericLiteral(node))return node.value;if(t.isTemplateLiteral(node)&&!node.expressions.length)return staticName(node,true);const local=constantInitializer(node,module);if(local)return primitive(local.node,module,next);const imported=await modules.resolveImport(node,module);return imported?primitive(imported.node,imported.module,next):void 0}async function analyze(input,module,visiting=/* @__PURE__ */ new Set){const node=unwrap(input);if(visiting.has(node))return;const next=new Set(visiting).add(node);const local=constantInitializer(node,module);if(local){const value=await analyze(local.node,module,next);return value&&(value.frozen||isSafePropsBinding(local.binding,ownership))?value:void 0}if(t.isIdentifier(node)||t.isMemberExpression(node)){const imported=await modules.resolveImport(node,module);const value=imported&&await analyze(imported.node,imported.module,next);return value?.frozen?value:void 0}if(t.isCallExpression(node)&&isImportedCall(node,module,`mergeModels`,[`vue`])){if(node.arguments.length!==2||!node.arguments.every(t.isExpression))return;const[left,right]=await Promise.all(node.arguments.map(argument=>analyze(argument,module,next)));if(!left||!right)return;const names=new Set(left.names);right.names.forEach(name=>names.add(name));return{kind:left.kind===`array`&&right.kind===`array`?`array`:`object`,names,frozen:false}}if(isObjectCall(node,module.scope,`freeze`)&&node.arguments.length===1&&t.isExpression(node.arguments[0])){const value=await analyze(node.arguments[0],module,next);return value&&{...value,frozen:true}}if(isObjectCall(node,module.scope,`assign`)){const first=node.arguments[0]&&unwrap(node.arguments[0]);if(!t.isObjectExpression(first)||first.properties.length)return;const names=/* @__PURE__ */ new Set;for(const argument of node.arguments.slice(1)){if(!t.isExpression(argument))return;const value=await analyze(argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name))}return{kind:`object`,names,frozen:false}}if(t.isObjectExpression(node)){const names=/* @__PURE__ */ new Set;for(const property of node.properties){if(t.isSpreadElement(property)){const value=await analyze(property.argument,module,next);if(!value||value.kind!==`object`)return;value.names.forEach(name=>names.add(name));continue}if(!t.isObjectProperty(property))return;const key=property.computed?await primitive(property.key,module,next):staticName(property.key);if(key===void 0||key===`__proto__`)return;names.add(String(key))}return{kind:`object`,names,frozen:false}}if(t.isArrayExpression(node)){const names=/* @__PURE__ */ new Set;for(const element of node.elements){if(!element)return;if(t.isSpreadElement(element)){const value=await analyze(element.argument,module,next);if(!value||value.kind!==`array`)return;value.names.forEach(name=>names.add(name))}else{const value=await primitive(element,module,next);if(typeof value!==`string`)return;names.add(value)}}return{kind:`array`,names,frozen:false}}}return{analyze}}async function resolveSetupPropConflicts(options){const dependencies=/* @__PURE__ */ new Set;if(!/\bprops\b/.test(options.script))return{dependencies:[]};let setupKeys=Object.entries(options.bindings??{}).filter(([,kind])=>typeof kind===`string`&&(kind.startsWith(`setup-`)||kind===`literal-const`)).map(([key])=>key);if(!setupKeys.length)return{dependencies:[]};const root=createModuleFacts(normalizeSourceId(options.filename),options.getScriptAst());const exported=root.ast.program.body.find(statement=>t.isExportDefaultDeclaration(statement));if(!exported||!t.isExportDefaultDeclaration(exported))return{conflicts:setupKeys,dependencies:[]};const props=findCompiledOption(exported.declaration,`props`,root);const setup=findCompiledOption(exported.declaration,`setup`,root);const setupNode=setup.kind===`value`?setup.node:void 0;setupKeys=excludePropsObjectAliases(setupKeys,setupNode);if(props.kind!==`value`)return{conflicts:props.kind===`unknown`?setupKeys:void 0,dependencies:[]};const reader=createAnalysisSourceReader({source:options.source,trackLogicalPaths:true},dependencies);const modules=createPropsModuleResolver(reader,root);const shape=await createPropsShapeAnalyzer(modules,{props:props.node,setup:setupNode}).analyze(props.node,root);dependencies.delete(root.id);return{conflicts:shape?setupKeys.filter(key=>shape.names.has(key)):setupKeys,dependencies:[...dependencies]}}function createSourceLineStarts(source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);return lineStarts}function clearBindingManifestLocations(manifest){for(const binding of manifest.bindings)if(!binding.sourceFile)binding.sourceLocation=void 0}function normalizeSourceFile(filename){return filename.replaceAll(`\\`,`/`).replace(/^\.\//,``)}function sourceFilesMatch(left,right){const normalizedLeft=normalizeSourceFile(left);const normalizedRight=normalizeSourceFile(right);return normalizedLeft===normalizedRight||normalizedLeft.endsWith(`/${normalizedRight}`)||normalizedRight.endsWith(`/${normalizedLeft}`)}function resolveMappedSource(sourceMap,originalSource,fallbackSource){if(!isEncodedSourceMapLike(sourceMap))return{content:fallbackSource,sourceFile:originalSource,hasMappedContent:false};const normalizedOriginal=normalizeSourceFile(originalSource);const sourceIndex=sourceMap.sources.findIndex(candidate=>{return sourceFilesMatch(candidate,normalizedOriginal)});const sourceFile=sourceIndex>=0?sourceMap.sources[sourceIndex]:originalSource;const mappedContent=sourceIndex>=0?sourceMap.sourcesContent?.[sourceIndex]:void 0;return{content:mappedContent??fallbackSource,sourceFile,hasMappedContent:mappedContent!=null}}function remapJsxBindingManifestLocations(manifest,sourceMap,source,sourceFile){if(sourceFile)manifest.sourceFile=sourceFile;if(!source||!sourceMap){clearBindingManifestLocations(manifest);return}let traceMap;try{traceMap=new TraceMap(sourceMap)}catch{clearBindingManifestLocations(manifest);return}const lineStartsCache=/* @__PURE__ */ new Map;const remap=(line,column)=>{let original;try{original=originalPositionFor(traceMap,{line,column:Math.max(0,column-1)})}catch{return}if(original.source==null||original.line==null||original.column==null)return;const mapped=resolveMappedSource(sourceMap,original.source,source);const ownedSourceFile=sourceFile??(sourceFilesMatch(mapped.sourceFile,manifest.sourceFile)?manifest.sourceFile:mapped.sourceFile);if(!mapped.hasMappedContent&&!sourceFilesMatch(ownedSourceFile,manifest.sourceFile))return;const content=sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?source:mapped.content;let lineStarts=lineStartsCache.get(content);if(!lineStarts){lineStarts=createSourceLineStarts(content);lineStartsCache.set(content,lineStarts)}return{position:{offset:(lineStarts[original.line-1]??0)+original.column,line:original.line,column:original.column+1},sourceFile:sourceFilesMatch(ownedSourceFile,manifest.sourceFile)?void 0:normalizeSourceFile(ownedSourceFile)}};for(const binding of manifest.bindings){const location=binding.sourceLocation;if(!location)continue;if(binding.sourceFile&&!sourceFilesMatch(binding.sourceFile,manifest.sourceFile))continue;const start=remap(location.start.line,location.start.column);const end=remap(location.end.line,location.end.column);if(!start||!end||start.sourceFile!==end.sourceFile){binding.sourceLocation=void 0;continue}binding.sourceFile=start.sourceFile;binding.sourceLocation={start:start.position,end:end.position}}}const RESERVED_SCRIPT_SETUP_PROPS=/* @__PURE__ */ new Set([`id`,`class`,`slot`]);const RESERVED_PROPS_WARNING=`defineProps 中声明 id/class/slot 可能无法在小程序 properties 中正确取值,请改用其他 prop 名称。`;function getStaticKeyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function getTypePropertyName(key){if(t.isIdentifier(key))return key.name;if(t.isStringLiteral(key))return key.value}function isReservedScriptSetupProp(name){return name!=null&&RESERVED_SCRIPT_SETUP_PROPS.has(name)}function runtimePropsContainReservedName(node){if(t.isObjectExpression(node))return node.properties.some(prop=>t.isObjectProperty(prop)&&!prop.computed&&isReservedScriptSetupProp(getStaticKeyName(prop.key)));if(t.isArrayExpression(node))return node.elements.some(element=>t.isStringLiteral(element)&&isReservedScriptSetupProp(element.value));return false}function createTypeScope(ast){const scope=/* @__PURE__ */ new Map;traverse(ast,{TSInterfaceDeclaration(path){scope.set(path.node.id.name,path.node.body)},TSTypeAliasDeclaration(path){scope.set(path.node.id.name,path.node.typeAnnotation)}});return scope}function typePropsContainReservedName(typeNode,scope,seen=/* @__PURE__ */ new Set){if(!typeNode)return false;if(t.isTSTypeLiteral(typeNode))return typeNode.members.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSInterfaceBody(typeNode))return typeNode.body.some(member=>{return t.isTSPropertySignature(member)&&!member.computed&&isReservedScriptSetupProp(getTypePropertyName(member.key))});if(t.isTSIntersectionType(typeNode))return typeNode.types.some(item=>typePropsContainReservedName(item,scope,seen));if(t.isTSTypeReference(typeNode)&&t.isIdentifier(typeNode.typeName)){const typeName=typeNode.typeName.name;if(seen.has(typeName))return false;const resolved=scope.get(typeName);if(!resolved)return false;seen.add(typeName);return typePropsContainReservedName(resolved,scope,seen)}return false}function getDefinePropsLocation(node){const start=node.loc?.start;if(!start)return;return{line:start.line,column:start.column}}function resolveSourceLocation(location,scriptSetupStart){if(!location)return;if(!scriptSetupStart)return location;return{line:scriptSetupStart.line+location.line-1,column:location.line===1?scriptSetupStart.column+location.column:location.column}}function createReservedPropsWarning(location,filename){if(!location||!filename)return RESERVED_PROPS_WARNING;return`${filename}:${location.line}:${location.column+1} ${RESERVED_PROPS_WARNING}`}function detectDefinePropsReservedName(scriptSetupCode){let result;try{const ast=parseJsLike(scriptSetupCode);const typeScope=createTypeScope(ast);traverse(ast,{CallExpression(path){const callee=path.node.callee;if(!t.isIdentifier(callee,{name:`defineProps`}))return;if(runtimePropsContainReservedName(path.node.arguments[0])){result={location:getDefinePropsLocation(path.node)};path.stop();return}const typeParam=(path.node.typeParameters??path.node.typeArguments)?.params?.[0];if(typePropsContainReservedName(typeParam,typeScope)){result={location:getDefinePropsLocation(path.node)};path.stop()}}})}catch{return}return result}function warnReservedScriptSetupProps(scriptSetupCode,warn,context={},diagnostic){if(!scriptSetupCode)return;const offset=diagnostic?.warningOffset;const lines=offset===void 0?void 0:scriptSetupCode.slice(0,offset).split(/\r\n|[\r\n\u2028\u2029]/);const result=diagnostic?lines&&{location:{line:lines.length,column:lines.at(-1).length}}:detectDefinePropsReservedName(scriptSetupCode);if(!result)return;const location=resolveSourceLocation(result.location,context.scriptSetupStart);warn?.(createReservedPropsWarning(location,context.filename))}const TYPE_ONLY_DEFINE_PROPS_RE=/\bdefineProps\s*</;function resolveScriptSetupPropsAliases(bindings){const aliases=bindings?.__propsAliases;if(!aliases||typeof aliases!==`object`)return;const resolved={};for(const[alias,propName]of Object.entries(aliases))if(typeof propName===`string`&&propName.length>0)resolved[alias]=propName;return Object.keys(resolved).length?resolved:void 0}function resolveScriptSetupPropsDerivedKeys(bindings){const keys=/* @__PURE__ */ new Set;for(const[key,bindingType]of Object.entries(bindings??{})){if(key.startsWith(`__`)||bindingType!==`props`&&bindingType!==`props-aliased`)continue;keys.add(key)}return keys.size?[...keys]:void 0}function bindingsMayContainProps(bindings,scriptCode){for(const[key,bindingType]of Object.entries(bindings??{}))if(key===`__propsAliases`||bindingType===`props`||bindingType===`props-aliased`)return true;return scriptCode.includes(`__props`)||scriptCode.includes(`props:`)}function hasPrecomputedScriptPhaseInfo(info,key){return Boolean(info)&&Object.prototype.hasOwnProperty.call(info,key)}function collectScriptSetupReturnInfo(getScriptAst){const keys=/* @__PURE__ */ new Set;const propsObjectAliases=/* @__PURE__ */ new Set([`__props`]);const propsRefsAliases=/* @__PURE__ */ new Set;const destructuredPropsKeys=/* @__PURE__ */ new Set;const addObjectPatternKeys=pattern=>{for(const property of pattern.properties){if(!t.isObjectProperty(property))continue;if(t.isIdentifier(property.value))destructuredPropsKeys.add(property.value.name);else if(t.isAssignmentPattern(property.value)&&t.isIdentifier(property.value.left))destructuredPropsKeys.add(property.value.left.name)}};try{const ast=getScriptAst();traverse(ast,{VariableDeclarator(path){const init=path.node.init;if(t.isIdentifier(path.node.id)&&t.isIdentifier(init)&&propsObjectAliases.has(init.name)){propsObjectAliases.add(path.node.id.name);return}if(t.isIdentifier(path.node.id)&&t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name)){propsRefsAliases.add(path.node.id.name);return}if(!t.isObjectPattern(path.node.id))return;if(t.isIdentifier(init)&&propsObjectAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isIdentifier(init)&&propsRefsAliases.has(init.name)){addObjectPatternKeys(path.node.id);return}if(t.isCallExpression(init)&&t.isIdentifier(init.callee,{name:`toRefs`})&&init.arguments.length===1&&t.isIdentifier(init.arguments[0])&&propsObjectAliases.has(init.arguments[0].name))addObjectPatternKeys(path.node.id)},ObjectProperty(path){const objectPath=path.parentPath;if(!objectPath.isObjectExpression()||!objectPath.parentPath.isVariableDeclarator()||!t.isIdentifier(objectPath.parentPath.node.id,{name:`__returned__`}))return;const prop=path.node;if(prop.computed)return;if(t.isIdentifier(prop.key))keys.add(prop.key.name);else if(t.isStringLiteral(prop.key))keys.add(prop.key.value)}})}catch{return{returnedKeys:keys,destructuredPropsKeys}}return{returnedKeys:keys,destructuredPropsKeys}}function resolveEffectivePropsDerivedKeys(bindings,scriptCode,getScriptAst=()=>parseJsLike(scriptCode)){if(!bindingsMayContainProps(bindings,scriptCode))return;const directKeys=resolveScriptSetupPropsDerivedKeys(bindings)??[];const{returnedKeys,destructuredPropsKeys}=collectScriptSetupReturnInfo(getScriptAst);const aliases=resolveScriptSetupPropsAliases(bindings)??{};const propsKeys=new Set(Object.entries(bindings??{}).filter(([key,bindingType])=>key&&!key.startsWith(`__`)&&bindingType===`props`).map(([key])=>key));const keys=/* @__PURE__ */ new Set;for(const key of directKeys)keys.add(key);for(const key of destructuredPropsKeys)keys.add(key);for(const[alias,propName]of Object.entries(aliases)){if(!returnedKeys.has(alias))keys.add(alias);if(propsKeys.has(propName)&&!returnedKeys.has(propName))keys.add(propName)}for(const key of propsKeys)if(!returnedKeys.has(key))keys.add(key);return keys.size?[...keys]:void 0}async function compileScriptPhase(descriptor,descriptorForCompile,filename,options,_autoUsingComponents,templateCompiled,isAppFile,componentSourceInfo,precompiledScript,precomputedScriptPhaseInfo,originalSource,scriptPreprocessMap,nativeScriptAnalysis){const autoUsingComponentsMap={...componentSourceInfo?.autoUsingComponentsMap??{}};const autoComponentMeta={...componentSourceInfo?.autoComponentMeta??{}};const relaxStructuredTypeOnlyProps=Boolean(descriptor.scriptSetup?.content&&TYPE_ONLY_DEFINE_PROPS_RE.test(descriptor.scriptSetup.content));let scriptCode;let scriptMap=null;let propsAliases=options?.template?.propsAliases;let propsDerivedKeys;let jsxDiagnostics;if(descriptor.script||descriptor.scriptSetup){const scriptCompiled=precompiledScript??compileScript(descriptorForCompile,{id:generateScopedId(filename),isProd:false});warnReservedScriptSetupProps(descriptorForCompile.scriptSetup?.content,options?.warn,{filename,scriptSetupStart:descriptorForCompile.scriptSetup?.loc.start},nativeScriptAnalysis?.scriptSetup?.reservedPropsDiagnostic);if(!propsAliases&&hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsAliases`))propsAliases=precomputedScriptPhaseInfo.propsAliases;propsAliases??=resolveScriptSetupPropsAliases(scriptCompiled.bindings);scriptCode=scriptCompiled.content;propsDerivedKeys=hasPrecomputedScriptPhaseInfo(precomputedScriptPhaseInfo,`propsDerivedKeys`)?precomputedScriptPhaseInfo.propsDerivedKeys:resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCode);const compiledScriptMap=options?.sourceMap!==false&&scriptCompiled.map&&typeof scriptCompiled.map===`object`?scriptCompiled.map:null;scriptMap=compiledScriptMap?composeSourceMaps(compiledScriptMap,scriptPreprocessMap):null;if(scriptCode.includes(`defineAppJson`)||scriptCode.includes(`definePageJson`)||scriptCode.includes(`defineComponentJson`))scriptCode=stripJsonMacroCallsFromCode(scriptCode,filename);const defaultExportAnalysis=scriptCode===descriptorForCompile.script?.content?nativeScriptAnalysis?.script:void 0;if(!isAppFile&&!descriptor.scriptSetup&&!hasDefaultExport(scriptCode,defaultExportAnalysis))scriptCode+=`
|
|
40
40
|
export default {}`}else scriptCode=`export default {}`;if(scriptCode){const scriptLang=descriptor.script?.lang??descriptor.scriptSetup?.lang;const isJsxScript=scriptLang===`jsx`||scriptLang===`tsx`;let jsxTemplate;if(isJsxScript){jsxTemplate=compileJsxTemplateAndCollectComponents(scriptCode,filename,options);const externalScriptBlock=descriptor.script?.src?descriptor.script:descriptor.scriptSetup?.src?descriptor.scriptSetup:void 0;remapJsxBindingManifestLocations(jsxTemplate.bindingManifest,scriptMap,externalScriptBlock?.content??originalSource,externalScriptBlock?.src);if(jsxTemplate.template&&(options?.pageLayout||options?.appShell))jsxTemplate.template=applyCompilerTemplateWrappers({template:jsxTemplate.template,manifest:jsxTemplate.bindingManifest,platform:options?.template?.platform??getMiniProgramTemplatePlatform(),pageLayout:options?.pageLayout,appShell:options?.appShell});const reportJsxWarnings=!descriptor.template||Boolean(jsxTemplate.template);scriptCode=injectDynamicIslandRuntime(stripRenderOptionFromScript(scriptCode,filename,reportJsxWarnings?jsxTemplate.warnings:void 0),jsxTemplate.dynamicIslands);if(reportJsxWarnings&&jsxTemplate.warnings.length){jsxDiagnostics=createJsxDiagnostics(jsxTemplate.warnings,filename);if(options?.warn)jsxDiagnostics.forEach(diagnostic=>options.warn?.(diagnostic.message))}}const jsxTransformed=isJsxScript?(await import(`./vueJsxTransform-C4lhnLbg.mjs`)).transformVueJsxScript(scriptCode,filename,options?.sourceMap!==false):{code:scriptCode,map:null};const bindingManifest=jsxTemplate?.template?jsxTemplate.bindingManifest:templateCompiled?.bindingManifest;const effectiveInlineExpressions=jsxTemplate?.template?jsxTemplate.inlineExpressions:templateCompiled?.inlineExpressions;const templateRuntimeCapabilities=bindingManifest?createWevuRuntimeCapabilityMetadataFromBindingManifest(bindingManifest):templateCompiled?.runtimeCapabilities;const nativeSlotContext=!isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true});const runtimeCapabilities=mergeWevuRuntimeCapabilityMetadata(templateRuntimeCapabilities,nativeSlotContext?createWevuRuntimeCapabilityMetadata([`scopedSlots`]):void 0);const transformed=transformScript(jsxTransformed.code,{isTypeScript:descriptor.script?.lang===`ts`||descriptor.script?.lang===`tsx`||descriptor.scriptSetup?.lang===`ts`||descriptor.scriptSetup?.lang===`tsx`,skipComponentTransform:options?.skipComponentTransform??isAppFile,isApp:isAppFile,isPage:options?.isPage===true,minify:options?.minify,sourceMap:options?.sourceMap,warn:options?.warn,templateComponentMeta:Object.keys(autoComponentMeta).length?autoComponentMeta:void 0,wevuDefaults:options?.wevuDefaults,classStyleRuntime:templateCompiled?.classStyleRuntime,classStyleBindings:templateCompiled?.classStyleBindings,templateRefs:templateCompiled?.templateRefs,layoutHosts:templateCompiled?.layoutHosts,inlineExpressions:effectiveInlineExpressions,bindingManifest:isAppFile?void 0:bindingManifest,autoSetDataPick:!isAppFile&&options?.autoSetDataPick,runtimeBindingManifest:options?.runtimeBindingManifest,pageLayout:isAppFile?void 0:options?.pageLayout,runtimeCapabilities,functionPropPaths:templateCompiled?.functionPropPaths,propsAliases,propsDerivedKeys,cssModules:precomputedScriptPhaseInfo?.cssModules,stabilizeCssVarsRuntime:options?.stabilizeCssVarsRuntime,relaxStructuredTypeOnlyProps,nativeSlotContext,scopedSlotHostProperties:!isAppFile&&options?.isPage!==true&&Boolean(templateCompiled?.hasSlotOutlet||templateCompiled?.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length>0)});return{script:transformed.code,scriptMap:composeSourceMaps(transformed.map??jsxTransformed.map,scriptMap),template:jsxTemplate?.template,diagnostics:jsxDiagnostics,bindingManifest,inlineExpressions:jsxTemplate?.inlineExpressions,runtimeCapabilities:transformed.runtimeCapabilities,componentStyleOptions:transformed.componentStyleOptions,autoUsingComponentsMap,autoComponentMeta}}return{script:scriptCode,scriptMap:null,autoUsingComponentsMap,autoComponentMeta}}async function compileStylePhase(descriptor,filename,result,options){if(descriptor.styles.length===0)return{usesSlotted:false};const scopedId=generateScopedId(filename);const compiledStyles=await Promise.all(descriptor.styles.map(async styleBlock=>{return await compileVueStyleToWxss(styleBlock,{id:scopedId,filename,scoped:styleBlock.scoped,modules:styleBlock.module,preprocessOptions:options?.preprocessOptions?.[styleBlock.lang||`css`],preserveDeepSelectors:options?.preserveDeepSelectors,transformScoped:options?.transformScoped})}));result.style=compiledStyles.map(s=>s.code.trim()).filter(Boolean).join(`
|
|
41
41
|
|
|
42
|
-
`);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;const located=[...templateCompiled.diagnostics,...templateCompiled.sourceTags??[]];if(located.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(located,templateResolvedId,descriptor.template.content);else for(const diagnostic of located)diagnostic.loc=void 0}else remapTemplateDiagnostics(located,descriptor.template.loc.start,source)}result.meta??={};result.meta.templateTags=templateCompiled.sourceTags;if(templateCompiled.diagnostics.length)result.diagnostics=templateCompiled.diagnostics;if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis});if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo});options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const propsAnalysis=scriptCompiled?await resolveSetupPropConflicts({script:scriptCompiled.content,bindings:scriptCompiled.bindings,getScriptAst:getCompiledScriptAst,filename,source:options?.sfcSrc}):void 0;const scriptSetupPropConflicts=propsAnalysis?.conflicts;if(propsAnalysis?.dependencies.length)result.meta.propsAnalysisDeps=propsAnalysis.dependencies;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,pathExists,preprocessScriptSetupSrc,preprocessScriptSrc,readAndParseSfc,readFile,refreshVueFileJsonConfig,resolveClassStyleWxsLocation,resolveJsLikeLang,resolveSfcBlockSrc,resolveVueSfcHasTemplate,resolveVueSfcHmrSignatures,resolveVueSfcNonJsonSignature,resolveVueSfcScriptSignature,resolveVueSfcStyleIndependentSignature,resolveVueSfcTailwindContentSignature,resolveWevuInternalImportModuleId,restoreScriptSetupSrc,restoreScriptSrc,stripJsonMacroCallsFromCode,stripPageDeclaration,swanPlatform,transformNestedWxssVars,transformScript,transformScript as transformSfcScript,transformUniAppConditionalCode,transformUniAppSource,transformVueDeepSelectors,ttPlatform,wechatPlatform};
|
|
42
|
+
`);if(!compiledStyles.some(s=>s.modules))return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)};const modulesMap={};compiledStyles.forEach(compiled=>{if(compiled.modules)Object.assign(modulesMap,compiled.modules)});result.cssModules=modulesMap;return{usesSlotted:compiledStyles.some(style=>style.usesSlotted)}}function remapTemplateDiagnostics(diagnostics,base,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const remap=position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}};for(const diagnostic of diagnostics)if(diagnostic.loc)diagnostic.loc={start:remap(diagnostic.loc.start),end:remap(diagnostic.loc.end)}}function ownExternalTemplateDiagnostics(diagnostics,filename,source){const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);const own=position=>{let low=0;let high=lineStarts.length;while(low+1<high){const middle=low+high>>1;if(lineStarts[middle]<=position.offset)low=middle;else high=middle}const line=low+1;return{offset:position.offset,line,column:position.offset-lineStarts[line-1]+1}};for(const diagnostic of diagnostics){diagnostic.filename=filename;if(diagnostic.loc)diagnostic.loc={start:own(diagnostic.loc.start),end:own(diagnostic.loc.end)}}}function updateTemplateBindingManifests(templateCompiled,sourceFile,remap,runtimeBindingManifest){const updateManifest=manifest=>{manifest.sourceFile=sourceFile;if(!remap)return;for(const binding of manifest.bindings)if(binding.sourceLocation)binding.sourceLocation={start:remap(binding.sourceLocation.start),end:remap(binding.sourceLocation.end)}};updateManifest(templateCompiled.bindingManifest);for(const asset of templateCompiled.scopedSlotComponents??[]){const previousManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));updateManifest(asset.bindingManifest);const nextManifest=JSON.stringify(createRuntimeBindingManifest(asset.bindingManifest,runtimeBindingManifest));asset.script=asset.script.replace(previousManifest,nextManifest)}}function compileTemplatePhase(descriptor,filename,source,templateResolvedId,options,result,bindingManifestSourceFile){if(!descriptor.template)return;const templateCompiled=compileVueTemplateToWxml(descriptor.template.content,filename,options);const manifestSourceFile=descriptor.template.src||bindingManifestSourceFile||templateResolvedId||filename;const runtimeBindingManifest=options?.runtimeBindingManifest??`compact`;if(descriptor.template.src)updateTemplateBindingManifests(templateCompiled,manifestSourceFile,void 0,runtimeBindingManifest);else{const base=descriptor.template.loc.start;const lineStarts=[0];for(const match of source.matchAll(/\r\n?|\n/g))lineStarts.push(match.index+match[0].length);updateTemplateBindingManifests(templateCompiled,manifestSourceFile,position=>{const line=base.line+position.line-1;const column=position.line===1?base.column+position.column-1:position.column;return{offset:Math.min(source.length,(lineStarts[line-1]??base.offset+position.offset)+column-1),line,column}},runtimeBindingManifest)}result.bindingManifest=templateCompiled.bindingManifest;result.template=templateCompiled.code;const located=[...templateCompiled.diagnostics,...templateCompiled.sourceTags??[]];if(located.length){if(descriptor.template.src){if(templateResolvedId)ownExternalTemplateDiagnostics(located,templateResolvedId,descriptor.template.content);else for(const diagnostic of located)diagnostic.loc=void 0}else remapTemplateDiagnostics(located,descriptor.template.loc.start,source)}result.meta??={};result.meta.templateTags=templateCompiled.sourceTags;if(templateCompiled.diagnostics.length)result.diagnostics=templateCompiled.diagnostics;if(templateCompiled.scopedSlotComponents?.length)result.scopedSlotComponents=templateCompiled.scopedSlotComponents;if(templateCompiled.slotFallbackWrapperComponent)result.slotFallbackWrapperComponent=templateCompiled.slotFallbackWrapperComponent;if(templateCompiled.componentGenerics&&Object.keys(templateCompiled.componentGenerics).length)result.componentGenerics=templateCompiled.componentGenerics;if(templateCompiled.classStyleWxs)result.classStyleWxs=true;return templateCompiled}function createTemplateRegistrationSignature(descriptor,compiledTemplate){const serialize=block=>block&&{attrs:Object.fromEntries(Object.entries(block.attrs).sort(([a],[b])=>a.localeCompare(b))),content:block.content,type:block.type};return createHash(`sha256`).update(JSON.stringify([serialize(descriptor.template),descriptor.customBlocks.filter(block=>block.type!==`json`&&block.type!==`config`).map(serialize),compiledTemplate])).digest(`hex`)}async function refreshVueFileJsonConfig(source,filename,cachedResult,options){const jsonConfigCache=cachedResult.meta?.jsonConfigCache;if(!jsonConfigCache)return;const parsed=await parseVueFile(source,filename,options);const meta={...cachedResult.meta,routeConfig:parsed.meta.routeConfig,pageMeta:parsed.meta.pageMeta,hasScriptSetup:parsed.meta.hasScriptSetup,hasSetupOption:parsed.meta.hasSetupOption,sfcSrcDeps:parsed.meta.sfcSrcDeps,sfcSrcCompilationDeps:parsed.meta.sfcSrcCompilationDeps};const result={...cachedResult,meta};delete result.config;await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:{...jsonConfigCache.autoUsingComponentsMap},autoImportTagsMap:jsonConfigCache.autoImportTagsMap?{...jsonConfigCache.autoImportTagsMap}:void 0,autoUsingComponents:options?.autoUsingComponents,autoImportTags:options?.autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});if(parsed.scriptSetupMacroHash)meta.jsonMacroHash=parsed.scriptSetupMacroHash;else delete meta.jsonMacroHash;return result}async function compileVueFile(source,filename,options){const parsed=await parseVueFile(source,filename,options);const sfcId=generateScopedId(filename);const result={meta:{...parsed.meta,styleBlocks:parsed.descriptor.styles,cssVars:parsed.descriptor.cssVars}};const autoUsingComponents=options?.autoUsingComponents?.enabled&&(parsed.descriptor.scriptSetup||parsed.descriptor.script)&&parsed.descriptor.template&&options.autoUsingComponents.resolveUsingComponentPath?options.autoUsingComponents:void 0;const autoImportTags=options?.autoImportTags?.enabled&&parsed.descriptor.template&&options.autoImportTags.resolveUsingComponent?options.autoImportTags:void 0;const componentSourceInfo=await collectComponentSourceInfo({descriptor:parsed.descriptor,descriptorForCompile:parsed.descriptorForCompile,filename,compileOptions:options,autoUsingComponents,autoImportTags,nativeScriptAnalysis:parsed.nativeScriptAnalysis});if(!parsed.isAppFile&&usesNativeDeclarationContext({platform:options?.template?.platform??getMiniProgramTemplatePlatform(),scopedSlotsRequireProps:options?.template?.scopedSlotsRequireProps??options?.template?.scopedSlotsCompiler!==`augmented`,nativeSlotContext:options?.template?.nativeSlotContext===true})){const participation=await analyzeNativeSlotContext({descriptor:parsed.descriptor,filename,options,components:componentSourceInfo});options={...options,template:{...options?.template,nativeSlotContext:participation.required,nativeSlotContextTags:participation.tags}};result.meta.nativeSlotContextDeps=participation.dependencies}const scriptCompiled=parsed.descriptor.script||parsed.descriptor.scriptSetup?compileScript(parsed.descriptorForCompile,{id:sfcId,isProd:false}):void 0;let compiledScriptAst;const getCompiledScriptAst=()=>compiledScriptAst??=parseJsLike(scriptCompiled.content);const propsAliases=scriptCompiled?resolveScriptSetupPropsAliases(scriptCompiled.bindings):void 0;const propsDerivedKeys=scriptCompiled?resolveEffectivePropsDerivedKeys(scriptCompiled.bindings,scriptCompiled.content,getCompiledScriptAst):void 0;const propsAnalysis=scriptCompiled?await resolveSetupPropConflicts({script:scriptCompiled.content,bindings:scriptCompiled.bindings,getScriptAst:getCompiledScriptAst,filename,source:options?.sfcSrc}):void 0;const scriptSetupPropConflicts=propsAnalysis?.conflicts;if(propsAnalysis?.dependencies.length)result.meta.propsAnalysisDeps=propsAnalysis.dependencies;const styleCompiled=await compileStylePhase(parsed.descriptor,filename,result,options?.style);const hasCssVarsRuntime=parsed.descriptor.cssVars.length>0||options?.stabilizeCssVarsRuntime===true;const scopedId=parsed.descriptor.styles.some(style=>style.scoped)?`data-v-${sfcId}`:void 0;const baseTemplateOptions=parsed.isAppFile?{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopedSlotsRequireProps:true,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime}:{...options?.template,isPage:options?.isPage,runtimeBindingManifest:options?.runtimeBindingManifest,propsAliases,propsDerivedKeys,scriptSetupBindings:scriptCompiled?.bindings,scriptSetupPropConflicts,scopeId:scopedId,slottedScopeId:scopedId&&styleCompiled.usesSlotted?`${scopedId}-s`:void 0,cssVars:hasCssVarsRuntime};const templateOptions=componentSourceInfo.wevuComponentTags.size?{...baseTemplateOptions,wevuComponentTags:componentSourceInfo.wevuComponentTags,componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags}:{...baseTemplateOptions,wevuComponentTags:[],componentNameMap:componentSourceInfo.componentNameMap,miniProgramComponentTags:componentSourceInfo.miniProgramComponentTags};const templateCompiled=compileTemplatePhase(parsed.descriptor,filename,source,parsed.templateResolvedId,templateOptions,result,options?.bindingManifestSourceFile);if(templateCompiled?.diagnostics.length){let fatalDiagnostic;for(const diagnostic of templateCompiled.diagnostics){options?.warn?.(diagnostic.message);if(diagnostic.severity===`error`)fatalDiagnostic??=diagnostic}if(fatalDiagnostic)throw new CompilerDiagnosticError(fatalDiagnostic)}if(templateCompiled&&result.template&&(options?.pageLayout||options?.appShell)){result.template=applyCompilerTemplateWrappers({template:result.template,manifest:templateCompiled.bindingManifest,platform:templateOptions.platform??getMiniProgramTemplatePlatform(),pageLayout:options.pageLayout,appShell:options.appShell});templateCompiled.code=result.template;templateCompiled.runtimeCapabilities=createWevuRuntimeCapabilityMetadataFromBindingManifest(templateCompiled.bindingManifest)}const scriptPhase=await compileScriptPhase(parsed.descriptor,parsed.descriptorForCompile,filename,options,autoUsingComponents,templateCompiled,parsed.isAppFile,componentSourceInfo,scriptCompiled,{propsAliases,propsDerivedKeys,cssModules:result.cssModules},source,parsed.scriptPreprocessMap,parsed.nativeScriptAnalysis);result.script=scriptPhase.script;result.scriptMap=scriptPhase.scriptMap;if(scriptPhase.componentStyleOptions)result.meta.componentStyleOptions=scriptPhase.componentStyleOptions;if(scriptPhase.runtimeCapabilities)result.meta.runtimeCapabilities=scriptPhase.runtimeCapabilities;if(scriptPhase.template)result.template=scriptPhase.template;if(scriptPhase.bindingManifest)result.bindingManifest=scriptPhase.bindingManifest;if(scriptPhase.diagnostics?.length)result.diagnostics=[...result.diagnostics??[],...scriptPhase.diagnostics];await compileConfigPhase({descriptor:parsed.descriptor,filename,autoUsingComponentsMap:scriptPhase.autoUsingComponentsMap,autoImportTagsMap:componentSourceInfo.autoImportTagsMap,autoUsingComponents,autoImportTags,jsonDefaults:parsed.jsonDefaults,mergeJson:parsed.mergeJson,scriptSetupMacroConfig:parsed.scriptSetupMacroConfig,result,warn:options?.warn});result.config=mergeCompilerLayoutUsingComponents(result.config,options?.pageLayout,options?.appShell);result.meta.jsonConfigCache={autoUsingComponentsMap:{...scriptPhase.autoUsingComponentsMap},autoImportTagsMap:componentSourceInfo.autoImportTagsMap?{...componentSourceInfo.autoImportTagsMap}:void 0};finalizeResult(result,{scriptSetupMacroHash:parsed.scriptSetupMacroHash,defineOptionsHash:parsed.defineOptionsHash});result.meta.templateRegistrationSignature=createTemplateRegistrationSignature(parsed.descriptor,result.template);return result}export{CLASS_STYLE_WXS_FILE,CLASS_STYLE_WXS_MODULE,CompilerDiagnosticError,RESERVED_VUE_COMPONENT_TAGS,VUE_COMPONENT_TAG_RE,VUE_SFC_BLOCK_TYPES,WE_VU_COMPILER_REACTIVITY_MODULE_ID,WE_VU_COMPILER_RUNTIME_MODULE_ID,WE_VU_COMPILER_TEMPLATE_MODULE_ID,WE_VU_INTERNAL_REACTIVITY_APIS,WE_VU_INTERNAL_REACTIVITY_MODULE_ID,WE_VU_INTERNAL_RUNTIME_MODULE_ID,WE_VU_INTERNAL_TEMPLATE_APIS,WE_VU_INTERNAL_TEMPLATE_MODULE_ID,WE_VU_MODULE_ID,WE_VU_PAGE_HOOK_TO_FEATURE,WE_VU_RUNTIME_APIS,WE_VU_RUNTIME_MODULE_IDS,alipayPlatform,buildClassStyleComputedCode,buildClassStyleWxsTag,builtinComponentsSet,classifyVueSfcBlockChanges,clearFileCaches,collectPageMetaCallsFromPrograms,collectTargetOptionsObjectsFromCode,collectVueTemplateTags,collectWevuFeaturesFromCodeReachableImports,collectWevuPageFeatureFlags,collectWevuPageFeatureFlagsFromCode,compileConfigBlocks,compileJsxFile,compileVueFile as compileSfc,compileVueFile,compileVueStyleToWxss as compileStyle,compileVueStyleToWxss,compileVueTemplateToWxml as compileTemplate,compileVueTemplateToWxml,createJsonMerger,createPageEntryMatcher,createRuntimeBindingManifest,defaultMiniProgramPlatform,defaultMiniProgramTemplatePlatform,defaultPlatform,evaluateJsLikeConfig,extractJsonMacroFromScriptSetup,extractPageDeclaration,extractPageDeclarationWithDependencies,generateScopedId,getClassStyleWxsSource,getDefaultMiniProgramPlatform,getDefaultMiniProgramTemplatePlatform,getMiniProgramTemplatePlatform,getSfcCheckMtime,injectWevuPageFeatureFlagsIntoOptionsObject,injectWevuPageFeaturesInJs,injectWevuPageFeaturesInJsWithResolver,invalidateFileCache,isAutoImportCandidateTag,isBuiltinComponent,isInvalidate,isJsonLikeLang,isUniAppCompatibilityFile,isWevuPageFeatureModuleId,isWevuRuntimeModuleId,loadCache,mayContainJsonMacro,mayContainPageDeclaration,mayContainPageMeta,mergeJsonWithStrategy,mtimeCache,normalizeConfigLang,parseVueSfc,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};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wevu/compiler",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "7.10.
|
|
4
|
+
"version": "7.10.1-dev.20261112.1",
|
|
5
5
|
"description": "wevu 编译器基础包,面向小程序模板的编译与转换",
|
|
6
6
|
"author": "ice breaker <1324318532@qq.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -66,10 +66,10 @@
|
|
|
66
66
|
"@vue/babel-plugin-jsx": "3.0.0",
|
|
67
67
|
"@vue/compiler-core": "^3.5.45",
|
|
68
68
|
"@vue/compiler-dom": "^3.5.45",
|
|
69
|
-
"@weapp-core/constants": "0.5.4",
|
|
70
|
-
"@weapp-core/shared": "3.4.3",
|
|
71
|
-
"@weapp-vite/ast": "7.10.
|
|
72
|
-
"@weapp-vite/wxml": "0.0.1",
|
|
69
|
+
"@weapp-core/constants": "0.5.4-dev.20261112.1",
|
|
70
|
+
"@weapp-core/shared": "3.4.3-dev.20261112.1",
|
|
71
|
+
"@weapp-vite/ast": "7.10.1-dev.20261112.1",
|
|
72
|
+
"@weapp-vite/wxml": "0.0.1-dev.20261112.1",
|
|
73
73
|
"comment-json": "^5.0.0",
|
|
74
74
|
"lru-cache": "^11.5.3",
|
|
75
75
|
"magic-string": "^1.4.5",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
"pathe": "^2.0.3",
|
|
78
78
|
"postcss": "^8.5.32",
|
|
79
79
|
"postcss-selector-parser": "^7.2.0",
|
|
80
|
-
"rolldown-require": "2.1.3",
|
|
80
|
+
"rolldown-require": "2.1.3-dev.20261112.1",
|
|
81
81
|
"vue": "^3.5.45"
|
|
82
82
|
},
|
|
83
83
|
"tsd": {
|
|
@@ -88,7 +88,15 @@
|
|
|
88
88
|
},
|
|
89
89
|
"publishConfig": {
|
|
90
90
|
"access": "public",
|
|
91
|
-
"registry": "https://registry.npmjs.org"
|
|
91
|
+
"registry": "https://registry.npmjs.org/",
|
|
92
|
+
"tag": "snapshot-nightly"
|
|
93
|
+
},
|
|
94
|
+
"repoctlSnapshot": {
|
|
95
|
+
"kind": "nightly",
|
|
96
|
+
"commit": "7e9d81a1105c2849fc2c54f20b964a3df43b0ae9",
|
|
97
|
+
"buildId": "43217073815-1",
|
|
98
|
+
"identityKey": "d14e19009b26a30a2228b6b0735a8bc2a56457ca594394d0cbaf788e157385bd",
|
|
99
|
+
"tag": "snapshot-nightly"
|
|
92
100
|
},
|
|
93
101
|
"scripts": {
|
|
94
102
|
"dev": "tsdown -w",
|
|
@@ -102,4 +110,4 @@
|
|
|
102
110
|
"lint": "eslint .",
|
|
103
111
|
"lint:fix": "eslint . --fix"
|
|
104
112
|
}
|
|
105
|
-
}
|
|
113
|
+
}
|