wevu 6.19.0 → 6.19.2
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/dev/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/defineProperty.mjs +1 -1
- package/dist/dev/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/toPrimitive.mjs +1 -1
- package/dist/dev/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/toPropertyKey.mjs +1 -1
- package/dist/dev/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/typeof.mjs +1 -1
- package/dist/dev/index.mjs +0 -1
- package/dist/dev/package.mjs +1 -1
- package/dist/dev/reactivity/core.mjs +1 -1
- package/dist/dev/reactivity/reactive/patch.mjs +2 -1
- package/dist/dev/reactivity/reactive/patch.mjs.map +1 -1
- package/dist/dev/reactivity/reactive.mjs +2 -1
- package/dist/dev/reactivity/reactive.mjs.map +1 -1
- package/dist/dev/reactivity/ref.mjs +1 -1
- package/dist/dev/router/createRouter.mjs +6 -3
- package/dist/dev/router/createRouter.mjs.map +1 -1
- package/dist/dev/router/navigationTarget.mjs +2 -1
- package/dist/dev/router/navigationTarget.mjs.map +1 -1
- package/dist/dev/router/resolve.mjs +9 -2
- package/dist/dev/router/resolve.mjs.map +1 -1
- package/dist/dev/routerInternal/location.mjs +3 -1
- package/dist/dev/routerInternal/location.mjs.map +1 -1
- package/dist/dev/routerInternal/records.mjs +2 -1
- package/dist/dev/routerInternal/records.mjs.map +1 -1
- package/dist/dev/runtime/app/mount.mjs +2 -1
- package/dist/dev/runtime/app/mount.mjs.map +1 -1
- package/dist/dev/runtime/define/scopedSlotOptions.mjs +6 -3
- package/dist/dev/runtime/define/scopedSlotOptions.mjs.map +1 -1
- package/dist/dev/runtime/define.mjs +6 -4
- package/dist/dev/runtime/define.mjs.map +1 -1
- package/dist/dev/runtime/layoutBridge.mjs.map +1 -1
- package/dist/dev/runtime/platform.mjs +4 -2
- package/dist/dev/runtime/platform.mjs.map +1 -1
- package/dist/dev/runtime/register/app.mjs +3 -1
- package/dist/dev/runtime/register/app.mjs.map +1 -1
- package/dist/dev/runtime/register/component/lifecycle/platform.mjs +2 -1
- package/dist/dev/runtime/register/component/lifecycle/platform.mjs.map +1 -1
- package/dist/dev/runtime/register/component/methods.mjs +3 -1
- package/dist/dev/runtime/register/component/methods.mjs.map +1 -1
- package/dist/dev/runtime/register/component.mjs +35 -34
- package/dist/dev/runtime/register/component.mjs.map +1 -1
- package/dist/dev/runtime/register/runtimeInstance/setupContext.mjs +4 -2
- package/dist/dev/runtime/register/runtimeInstance/setupContext.mjs.map +1 -1
- package/dist/dev/runtime/register/runtimeInstance/setupPhase.mjs +4 -2
- package/dist/dev/runtime/register/runtimeInstance/setupPhase.mjs.map +1 -1
- package/dist/dev/runtime/register/runtimeInstance.mjs +6 -3
- package/dist/dev/runtime/register/runtimeInstance.mjs.map +1 -1
- package/dist/dev/runtime/register/snapshot.mjs +2 -1
- package/dist/dev/runtime/register/snapshot.mjs.map +1 -1
- package/dist/dev/runtime/templateRefs/helpers.mjs +13 -8
- package/dist/dev/runtime/templateRefs/helpers.mjs.map +1 -1
- package/dist/dev/runtime/templateRefs.mjs +4 -3
- package/dist/dev/runtime/templateRefs.mjs.map +1 -1
- package/dist/dev/runtime/vueCompat/model.mjs +2 -1
- package/dist/dev/runtime/vueCompat/model.mjs.map +1 -1
- package/dist/dev/store/define/optionsStyle.mjs +17 -15
- package/dist/dev/store/define/optionsStyle.mjs.map +1 -1
- package/dist/dev/store/define/setupStyle.mjs +17 -15
- package/dist/dev/store/define/setupStyle.mjs.map +1 -1
- package/dist/dev/vue-demi.mjs +0 -158
- package/dist/dev/vue-demi.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/reactivity/core.mjs +1 -1
- package/dist/reactivity/reactive/patch.mjs +1 -1
- package/dist/reactivity/reactive.mjs +1 -1
- package/dist/reactivity/ref.mjs +1 -1
- package/dist/reactivity/watch/helpers.mjs +1 -1
- package/dist/router/createRouter.mjs +1 -1
- package/dist/router/navigationTarget.mjs +1 -1
- package/dist/router/resolve.mjs +1 -1
- package/dist/routerInternal/location.mjs +1 -1
- package/dist/routerInternal/records.mjs +1 -1
- package/dist/runtime/app/mount.mjs +1 -1
- package/dist/runtime/define/scopedSlotOptions.mjs +1 -1
- package/dist/runtime/define.mjs +1 -1
- package/dist/runtime/platform.mjs +1 -1
- package/dist/runtime/register/app.mjs +1 -1
- package/dist/runtime/register/component/lifecycle/platform.mjs +1 -1
- package/dist/runtime/register/component/methods.mjs +1 -1
- package/dist/runtime/register/component/props.mjs +1 -1
- package/dist/runtime/register/component.mjs +1 -1
- package/dist/runtime/register/runtimeInstance/setupPhase.mjs +1 -1
- package/dist/runtime/register/runtimeInstance.mjs +1 -1
- package/dist/runtime/register/snapshot.mjs +1 -1
- package/dist/runtime/templateRefs/helpers.mjs +1 -1
- package/dist/runtime/vueCompat/model.mjs +1 -1
- package/dist/store/storeToRefs.mjs +1 -1
- package/dist/vue-demi.d.mts +1 -3
- package/dist/vue-demi.mjs +1 -1
- package/package.json +6 -6
- package/dist/_virtual/_rolldown/runtime.mjs +0 -1
- package/dist/dev/_virtual/_rolldown/runtime.mjs +0 -36
- /package/dist/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/defineProperty.mjs +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/toPrimitive.mjs +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/toPropertyKey.mjs +0 -0
- /package/dist/_virtual/{_@oxc-project_runtime@0.139.0 → _@oxc-project_runtime@0.143.0}/helpers/esm/typeof.mjs +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../src/runtime/app/mount.ts"],"sourcesContent":["import type { MutationRecord, WatchOptions, WatchStopHandle } from '../../reactivity'\nimport type {\n AppConfig,\n ComputedDefinitions,\n CreateAppOptions,\n ExtractComputed,\n MethodDefinitions,\n MiniProgramAdapter,\n RuntimeInstance,\n SetDataDebugInfo,\n} from '../types'\nimport {\n WEVU_ATTRS_KEY,\n WEVU_PROPS_DERIVED_KEYS_KEY,\n WEVU_PROPS_KEY,\n WEVU_SETUP_STATE_KEY,\n} from '@weapp-core/constants'\nimport { addMutationRecorder, effect, isReactive, prelinkReactiveTree, reactive, removeMutationRecorder, shallowReactive, stop, toRaw, touchReactive, watch } from '../../reactivity'\nimport { clearPatchIndices } from '../../reactivity/reactive'\nimport { queueJob } from '../../scheduler'\nimport { hasOwn } from '../../utils'\nimport { createBindModel } from '../bindModel'\nimport { hasTrackableSetupBinding, touchSetupBinding } from '../setupTracking'\nimport { createRuntimeContext } from './context'\nimport { createDiagnosticsLogger } from './diagnostics'\nimport { createSetDataScheduler } from './setData/scheduler'\nimport { resolveSetDataOptions } from './setDataOptions'\n\nfunction createWatchStopHandle(cleanup: () => void, baseHandle?: WatchStopHandle): WatchStopHandle {\n const stopHandle = (() => {\n cleanup()\n }) as WatchStopHandle\n stopHandle.stop = () => stopHandle()\n stopHandle.pause = () => {\n baseHandle?.pause?.()\n }\n stopHandle.resume = () => {\n baseHandle?.resume?.()\n }\n return stopHandle\n}\n\ntype RuntimeInstanceWithSetupMethodsVersion<\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> = RuntimeInstance<D, C, M> & {\n __wevu_touchSetupMethodsVersion?: () => void\n __wevu_flushSetupSnapshotSync?: () => void\n __wevu_cloneLatestSnapshot?: () => Record<string, any>\n __wevu_trackSetupReactiveKey?: (key: string) => void\n}\n\nfunction resolveDataOption<D extends object>(data: CreateAppOptions<D, any, any>['data']): D {\n if (typeof data === 'function') {\n return data()\n }\n return (data ?? {}) as D\n}\n\nexport function createRuntimeMount<D extends object, C extends ComputedDefinitions, M extends MethodDefinitions>(options: {\n data: CreateAppOptions<D, C, M>['data']\n resolvedComputed: C\n resolvedMethods: M\n appConfig: AppConfig\n setDataOptions: CreateAppOptions<D, C, M>['setData']\n}) {\n const {\n data,\n resolvedComputed,\n resolvedMethods,\n appConfig,\n setDataOptions,\n } = options\n\n return (adapter?: MiniProgramAdapter): RuntimeInstance<D, C, M> => {\n const rawState = resolveDataOption(data)\n const adapterInitialProps = (adapter as any)?.__wevu_initialProps\n // 预置 props 容器,确保编译器生成的 this.__wevuProps 回退表达式\n // 在 computed 首次求值阶段即可建立响应式依赖。\n if (rawState && typeof rawState === 'object' && !hasOwn(rawState as object, WEVU_PROPS_KEY)) {\n try {\n Object.defineProperty(rawState as object, WEVU_PROPS_KEY, {\n value: shallowReactive(Object.create(null)),\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n // 若 data 返回对象不可扩展,则跳过预置,后续由 mount 阶段兜底注入。\n }\n }\n const rawProps = rawState && typeof rawState === 'object'\n ? (rawState as any)[WEVU_PROPS_KEY]\n : undefined\n if (rawProps && typeof rawProps === 'object' && adapterInitialProps && typeof adapterInitialProps === 'object') {\n Object.assign(rawProps, adapterInitialProps)\n }\n const state = reactive(rawState)\n const setupState = reactive(Object.create(null))\n const adapterSnapshotOmitKeys = (adapter as any)?.__wevu_snapshotOmitKeys\n const deferInitialSnapshot = Boolean((adapter as any)?.__wevu_deferInitialSnapshot)\n const adapterInitialSnapshot = (adapter as any)?.__wevu_initialSnapshot\n const adapterInitialState = (adapter as any)?.__wevu_initialState\n const snapshotOmitKeys = new Set<string>(\n adapterSnapshotOmitKeys instanceof Set\n ? adapterSnapshotOmitKeys\n : Array.isArray(adapterSnapshotOmitKeys)\n ? adapterSnapshotOmitKeys\n : [],\n )\n if (rawState && typeof rawState === 'object' && !hasOwn(rawState as object, WEVU_SETUP_STATE_KEY)) {\n try {\n Object.defineProperty(rawState as object, WEVU_SETUP_STATE_KEY, {\n value: setupState,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n // 若 data 返回对象不可扩展,则跳过预置,后续由注册阶段兜底注入。\n }\n }\n if (rawState && typeof rawState === 'object' && adapterInitialState && typeof adapterInitialState === 'object') {\n for (const [key, value] of Object.entries(adapterInitialState as Record<string, unknown>)) {\n if (snapshotOmitKeys.has(key)) {\n continue\n }\n ;(rawState as Record<string, unknown>)[key] = value\n }\n }\n const computedDefs = resolvedComputed\n const methodDefs = resolvedMethods\n\n let mounted = true\n const stopHandles: WatchStopHandle[] = []\n const trackedSetupReactiveKeys = new Set<string>()\n Object.keys(state as any).forEach((key) => {\n const value = (state as any)[key]\n if (hasTrackableSetupBinding(value)) {\n trackedSetupReactiveKeys.add(key)\n }\n })\n\n const {\n includeComputed,\n setDataStrategy,\n maxPatchKeys,\n maxPayloadBytes,\n mergeSiblingThreshold,\n mergeSiblingMaxInflationRatio,\n mergeSiblingMaxParentBytes,\n mergeSiblingSkipArray,\n computedCompare,\n computedCompareMaxDepth,\n computedCompareMaxKeys,\n prelinkMaxDepth,\n prelinkMaxKeys,\n debug,\n diagnostics,\n loopWarning,\n debugWhen,\n debugSampleRate,\n elevateTopKeyThreshold,\n toPlainMaxDepth,\n toPlainMaxKeys,\n includeFunctions,\n functionPaths,\n shouldIncludeKey,\n } = resolveSetDataOptions(setDataOptions)\n const diagnosticsLogger = createDiagnosticsLogger(diagnostics)\n const loopWarningLogger = diagnostics === 'off' && loopWarning\n ? createDiagnosticsLogger('fallback')\n : undefined\n const mergedDebug = (debug || diagnosticsLogger || loopWarningLogger)\n ? (info: SetDataDebugInfo) => {\n if (typeof debug === 'function') {\n debug(info)\n }\n diagnosticsLogger?.(info)\n if (info.reason === 'loopWarning') {\n loopWarningLogger?.(info)\n }\n }\n : undefined\n const mergedDebugWhen = diagnostics === 'always'\n ? 'always'\n : debugWhen\n\n const {\n boundMethods,\n computedRefs,\n computedSetters,\n dirtyComputedKeys,\n computedProxy,\n publicInstance,\n touchSetupMethodsVersion,\n } = createRuntimeContext({\n state,\n setupState: setupState as Record<string, any>,\n computedDefs,\n methodDefs,\n appConfig,\n includeComputed,\n setDataStrategy,\n })\n\n const currentAdapter = adapter ?? { setData: () => {} }\n const targetLabel = (currentAdapter as any).__wevu_targetLabel as string | undefined\n const stateRootRaw = toRaw(state as any) as object\n let tracker: ReturnType<typeof effect> | undefined\n const scheduler = createSetDataScheduler({\n state: state as any,\n setupState: setupState as any,\n snapshotOmitKeys,\n computedRefs,\n dirtyComputedKeys,\n includeComputed,\n setDataStrategy,\n computedCompare,\n computedCompareMaxDepth,\n computedCompareMaxKeys,\n currentAdapter,\n shouldIncludeKey,\n maxPatchKeys,\n maxPayloadBytes,\n mergeSiblingThreshold,\n mergeSiblingMaxInflationRatio,\n mergeSiblingMaxParentBytes,\n mergeSiblingSkipArray,\n elevateTopKeyThreshold,\n toPlainMaxDepth,\n toPlainMaxKeys,\n includeFunctions,\n functionPaths,\n debug: mergedDebug,\n debugWhen: mergedDebugWhen,\n debugSampleRate,\n loopWarning,\n targetLabel,\n runTracker: () => tracker?.(),\n isMounted: () => mounted,\n initialSnapshot: adapterInitialSnapshot && typeof adapterInitialSnapshot === 'object'\n ? adapterInitialSnapshot\n : undefined,\n initialState: adapterInitialState && typeof adapterInitialState === 'object'\n ? adapterInitialState\n : undefined,\n })\n const job = () => scheduler.job(stateRootRaw)\n const mutationRecorder = (record: MutationRecord) => scheduler.mutationRecorder(record, stateRootRaw)\n\n tracker = effect(\n () => {\n // 通过根版本信号跟踪任意状态变化\n touchReactive(state as any)\n // __wevuProps / __wevuAttrs 是非枚举属性,需显式跟踪,\n // 否则 props/attrs 更新不会触发 setData 调度。\n const runtimeProps = (state as any)[WEVU_PROPS_KEY]\n if (isReactive(runtimeProps)) {\n touchReactive(runtimeProps as any)\n }\n const runtimeAttrs = (state as any)[WEVU_ATTRS_KEY]\n if (isReactive(runtimeAttrs)) {\n touchReactive(runtimeAttrs as any)\n }\n // 在 setup 返回的 ref/computedRef 变更不会提升 reactive 根版本:\n // 仅跟踪这些明确注册过的键,避免每轮 flush 扫描整份 state。\n trackedSetupReactiveKeys.forEach((key) => {\n const v = (setupState as any)[key] ?? (state as any)[key]\n // setup 返回的组合式对象常常是“普通对象 + 内含 refs/reactive”,\n // 这里递归触达内部响应式源,确保异步更新也能继续驱动 setData。\n touchSetupBinding(v)\n })\n },\n {\n lazy: true,\n scheduler: () => queueJob(job),\n },\n )\n\n if (!deferInitialSnapshot) {\n job()\n }\n\n stopHandles.push(createWatchStopHandle(() => stop(tracker)))\n if (setDataStrategy === 'patch') {\n prelinkReactiveTree(state as any, { shouldIncludeTopKey: shouldIncludeKey, maxDepth: prelinkMaxDepth, maxKeys: prelinkMaxKeys })\n addMutationRecorder(mutationRecorder)\n stopHandles.push(createWatchStopHandle(() => removeMutationRecorder(mutationRecorder)))\n stopHandles.push(createWatchStopHandle(() => clearPatchIndices(state as any)))\n }\n\n function registerWatch<T>(\n source: (() => T) | Record<string, any>,\n cb: (value: T, oldValue: T) => void,\n watchOptions?: WatchOptions,\n ): WatchStopHandle {\n const stopHandle = watch(source as any, (value: T, oldValue: T) => cb(value, oldValue), watchOptions)\n stopHandles.push(stopHandle)\n return createWatchStopHandle(() => {\n stopHandle()\n const index = stopHandles.indexOf(stopHandle)\n if (index >= 0) {\n stopHandles.splice(index, 1)\n }\n }, stopHandle)\n }\n\n const bindModel = createBindModel(\n publicInstance as any,\n state as any,\n computedRefs,\n computedSetters,\n setupState as Record<string, any>,\n )\n\n const unmount = () => {\n if (!mounted) {\n return\n }\n mounted = false\n stopHandles.forEach((handle) => {\n try {\n handle()\n }\n catch {\n // 卸载阶段忽略 stop 抛错,确保其余清理继续\n }\n })\n stopHandles.length = 0\n }\n\n const runtimeInstance: RuntimeInstance<D, C, M> = {\n get state() {\n return state\n },\n get setupState() {\n return setupState as Record<string, any>\n },\n get proxy() {\n return publicInstance\n },\n get methods() {\n return boundMethods\n },\n get computed() {\n return computedProxy as Readonly<ExtractComputed<C>>\n },\n get adapter() {\n return currentAdapter\n },\n bindModel,\n watch: registerWatch,\n snapshot: () => scheduler.snapshot(),\n unmount,\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_touchSetupMethodsVersion', {\n value: touchSetupMethodsVersion,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_touchSetupMethodsVersion = touchSetupMethodsVersion\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_flushSetupSnapshotSync', {\n value: job,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_flushSetupSnapshotSync = job\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_cloneLatestSnapshot', {\n value: scheduler.cloneLatestSnapshot,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_cloneLatestSnapshot = scheduler.cloneLatestSnapshot\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_trackSetupReactiveKey', {\n value: (key: string) => {\n trackedSetupReactiveKeys.add(key)\n },\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_trackSetupReactiveKey = (key: string) => {\n trackedSetupReactiveKeys.add(key)\n }\n }\n\n try {\n Object.defineProperty(runtimeInstance, WEVU_PROPS_DERIVED_KEYS_KEY, {\n value: snapshotOmitKeys,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as any)[WEVU_PROPS_DERIVED_KEYS_KEY] = snapshotOmitKeys\n }\n\n return runtimeInstance\n }\n}\n"],"mappings":";;;;;;;;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gCAAgC,QAAgB;IACpH,yBAAyB,IAAI,GAAG;GAClC;EACF;EAEA,IAAI;GACF,OAAO,eAAe,iBAAiB,6BAA6B;IAClE,OAAO;IACP,cAAc;IACd,YAAY;IACZ,UAAU;GACZ,CAAC;EACH,mBACM;GACH,AAAC,gBAAwB,+BAA+B;EAC3D;EAEA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../src/runtime/app/mount.ts"],"sourcesContent":["import type { MutationRecord, WatchOptions, WatchStopHandle } from '../../reactivity'\nimport type {\n AppConfig,\n ComputedDefinitions,\n CreateAppOptions,\n ExtractComputed,\n MethodDefinitions,\n MiniProgramAdapter,\n RuntimeInstance,\n SetDataDebugInfo,\n} from '../types'\nimport {\n WEVU_ATTRS_KEY,\n WEVU_PROPS_DERIVED_KEYS_KEY,\n WEVU_PROPS_KEY,\n WEVU_SETUP_STATE_KEY,\n} from '@weapp-core/constants'\nimport { addMutationRecorder, effect, isReactive, prelinkReactiveTree, reactive, removeMutationRecorder, shallowReactive, stop, toRaw, touchReactive, watch } from '../../reactivity'\nimport { clearPatchIndices } from '../../reactivity/reactive'\nimport { queueJob } from '../../scheduler'\nimport { hasOwn } from '../../utils'\nimport { createBindModel } from '../bindModel'\nimport { hasTrackableSetupBinding, touchSetupBinding } from '../setupTracking'\nimport { createRuntimeContext } from './context'\nimport { createDiagnosticsLogger } from './diagnostics'\nimport { createSetDataScheduler } from './setData/scheduler'\nimport { resolveSetDataOptions } from './setDataOptions'\n\nfunction createWatchStopHandle(cleanup: () => void, baseHandle?: WatchStopHandle): WatchStopHandle {\n const stopHandle = (() => {\n cleanup()\n }) as WatchStopHandle\n stopHandle.stop = () => stopHandle()\n stopHandle.pause = () => {\n baseHandle?.pause?.()\n }\n stopHandle.resume = () => {\n baseHandle?.resume?.()\n }\n return stopHandle\n}\n\ntype RuntimeInstanceWithSetupMethodsVersion<\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> = RuntimeInstance<D, C, M> & {\n __wevu_touchSetupMethodsVersion?: () => void\n __wevu_flushSetupSnapshotSync?: () => void\n __wevu_cloneLatestSnapshot?: () => Record<string, any>\n __wevu_trackSetupReactiveKey?: (key: string) => void\n}\n\nfunction resolveDataOption<D extends object>(data: CreateAppOptions<D, any, any>['data']): D {\n if (typeof data === 'function') {\n return data()\n }\n return (data ?? {}) as D\n}\n\nexport function createRuntimeMount<D extends object, C extends ComputedDefinitions, M extends MethodDefinitions>(options: {\n data: CreateAppOptions<D, C, M>['data']\n resolvedComputed: C\n resolvedMethods: M\n appConfig: AppConfig\n setDataOptions: CreateAppOptions<D, C, M>['setData']\n}) {\n const {\n data,\n resolvedComputed,\n resolvedMethods,\n appConfig,\n setDataOptions,\n } = options\n\n return (adapter?: MiniProgramAdapter): RuntimeInstance<D, C, M> => {\n const rawState = resolveDataOption(data)\n const adapterInitialProps = (adapter as any)?.__wevu_initialProps\n // 预置 props 容器,确保编译器生成的 this.__wevuProps 回退表达式\n // 在 computed 首次求值阶段即可建立响应式依赖。\n if (rawState && typeof rawState === 'object' && !hasOwn(rawState as object, WEVU_PROPS_KEY)) {\n try {\n Object.defineProperty(rawState as object, WEVU_PROPS_KEY, {\n value: shallowReactive(Object.create(null)),\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n // 若 data 返回对象不可扩展,则跳过预置,后续由 mount 阶段兜底注入。\n }\n }\n const rawProps = rawState && typeof rawState === 'object'\n ? (rawState as any)[WEVU_PROPS_KEY]\n : undefined\n if (rawProps && typeof rawProps === 'object' && adapterInitialProps && typeof adapterInitialProps === 'object') {\n Object.assign(rawProps, adapterInitialProps)\n }\n const state = reactive(rawState)\n const setupState = reactive(Object.create(null))\n const adapterSnapshotOmitKeys = (adapter as any)?.__wevu_snapshotOmitKeys\n const deferInitialSnapshot = Boolean((adapter as any)?.__wevu_deferInitialSnapshot)\n const adapterInitialSnapshot = (adapter as any)?.__wevu_initialSnapshot\n const adapterInitialState = (adapter as any)?.__wevu_initialState\n const snapshotOmitKeys = new Set<string>(\n adapterSnapshotOmitKeys instanceof Set\n ? adapterSnapshotOmitKeys\n : Array.isArray(adapterSnapshotOmitKeys)\n ? adapterSnapshotOmitKeys\n : [],\n )\n if (rawState && typeof rawState === 'object' && !hasOwn(rawState as object, WEVU_SETUP_STATE_KEY)) {\n try {\n Object.defineProperty(rawState as object, WEVU_SETUP_STATE_KEY, {\n value: setupState,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n // 若 data 返回对象不可扩展,则跳过预置,后续由注册阶段兜底注入。\n }\n }\n if (rawState && typeof rawState === 'object' && adapterInitialState && typeof adapterInitialState === 'object') {\n for (const [key, value] of Object.entries(adapterInitialState as Record<string, unknown>)) {\n if (snapshotOmitKeys.has(key)) {\n continue\n }\n ;(rawState as Record<string, unknown>)[key] = value\n }\n }\n const computedDefs = resolvedComputed\n const methodDefs = resolvedMethods\n\n let mounted = true\n const stopHandles: WatchStopHandle[] = []\n const trackedSetupReactiveKeys = new Set<string>()\n Object.keys(state as any).forEach((key) => {\n const value = (state as any)[key]\n if (hasTrackableSetupBinding(value)) {\n trackedSetupReactiveKeys.add(key)\n }\n })\n\n const {\n includeComputed,\n setDataStrategy,\n maxPatchKeys,\n maxPayloadBytes,\n mergeSiblingThreshold,\n mergeSiblingMaxInflationRatio,\n mergeSiblingMaxParentBytes,\n mergeSiblingSkipArray,\n computedCompare,\n computedCompareMaxDepth,\n computedCompareMaxKeys,\n prelinkMaxDepth,\n prelinkMaxKeys,\n debug,\n diagnostics,\n loopWarning,\n debugWhen,\n debugSampleRate,\n elevateTopKeyThreshold,\n toPlainMaxDepth,\n toPlainMaxKeys,\n includeFunctions,\n functionPaths,\n shouldIncludeKey,\n } = resolveSetDataOptions(setDataOptions)\n const diagnosticsLogger = createDiagnosticsLogger(diagnostics)\n const loopWarningLogger = diagnostics === 'off' && loopWarning\n ? createDiagnosticsLogger('fallback')\n : undefined\n const mergedDebug = (debug || diagnosticsLogger || loopWarningLogger)\n ? (info: SetDataDebugInfo) => {\n if (typeof debug === 'function') {\n debug(info)\n }\n diagnosticsLogger?.(info)\n if (info.reason === 'loopWarning') {\n loopWarningLogger?.(info)\n }\n }\n : undefined\n const mergedDebugWhen = diagnostics === 'always'\n ? 'always'\n : debugWhen\n\n const {\n boundMethods,\n computedRefs,\n computedSetters,\n dirtyComputedKeys,\n computedProxy,\n publicInstance,\n touchSetupMethodsVersion,\n } = createRuntimeContext({\n state,\n setupState: setupState as Record<string, any>,\n computedDefs,\n methodDefs,\n appConfig,\n includeComputed,\n setDataStrategy,\n })\n\n const currentAdapter = adapter ?? { setData: () => {} }\n const targetLabel = (currentAdapter as any).__wevu_targetLabel as string | undefined\n const stateRootRaw = toRaw(state as any) as object\n let tracker: ReturnType<typeof effect> | undefined\n const scheduler = createSetDataScheduler({\n state: state as any,\n setupState: setupState as any,\n snapshotOmitKeys,\n computedRefs,\n dirtyComputedKeys,\n includeComputed,\n setDataStrategy,\n computedCompare,\n computedCompareMaxDepth,\n computedCompareMaxKeys,\n currentAdapter,\n shouldIncludeKey,\n maxPatchKeys,\n maxPayloadBytes,\n mergeSiblingThreshold,\n mergeSiblingMaxInflationRatio,\n mergeSiblingMaxParentBytes,\n mergeSiblingSkipArray,\n elevateTopKeyThreshold,\n toPlainMaxDepth,\n toPlainMaxKeys,\n includeFunctions,\n functionPaths,\n debug: mergedDebug,\n debugWhen: mergedDebugWhen,\n debugSampleRate,\n loopWarning,\n targetLabel,\n runTracker: () => tracker?.(),\n isMounted: () => mounted,\n initialSnapshot: adapterInitialSnapshot && typeof adapterInitialSnapshot === 'object'\n ? adapterInitialSnapshot\n : undefined,\n initialState: adapterInitialState && typeof adapterInitialState === 'object'\n ? adapterInitialState\n : undefined,\n })\n const job = () => scheduler.job(stateRootRaw)\n const mutationRecorder = (record: MutationRecord) => scheduler.mutationRecorder(record, stateRootRaw)\n\n tracker = effect(\n () => {\n // 通过根版本信号跟踪任意状态变化\n touchReactive(state as any)\n // __wevuProps / __wevuAttrs 是非枚举属性,需显式跟踪,\n // 否则 props/attrs 更新不会触发 setData 调度。\n const runtimeProps = (state as any)[WEVU_PROPS_KEY]\n if (isReactive(runtimeProps)) {\n touchReactive(runtimeProps as any)\n }\n const runtimeAttrs = (state as any)[WEVU_ATTRS_KEY]\n if (isReactive(runtimeAttrs)) {\n touchReactive(runtimeAttrs as any)\n }\n // 在 setup 返回的 ref/computedRef 变更不会提升 reactive 根版本:\n // 仅跟踪这些明确注册过的键,避免每轮 flush 扫描整份 state。\n trackedSetupReactiveKeys.forEach((key) => {\n const v = (setupState as any)[key] ?? (state as any)[key]\n // setup 返回的组合式对象常常是“普通对象 + 内含 refs/reactive”,\n // 这里递归触达内部响应式源,确保异步更新也能继续驱动 setData。\n touchSetupBinding(v)\n })\n },\n {\n lazy: true,\n scheduler: () => queueJob(job),\n },\n )\n\n if (!deferInitialSnapshot) {\n job()\n }\n\n stopHandles.push(createWatchStopHandle(() => stop(tracker)))\n if (setDataStrategy === 'patch') {\n prelinkReactiveTree(state as any, { shouldIncludeTopKey: shouldIncludeKey, maxDepth: prelinkMaxDepth, maxKeys: prelinkMaxKeys })\n addMutationRecorder(mutationRecorder)\n stopHandles.push(createWatchStopHandle(() => removeMutationRecorder(mutationRecorder)))\n stopHandles.push(createWatchStopHandle(() => clearPatchIndices(state as any)))\n }\n\n function registerWatch<T>(\n source: (() => T) | Record<string, any>,\n cb: (value: T, oldValue: T) => void,\n watchOptions?: WatchOptions,\n ): WatchStopHandle {\n const stopHandle = watch(source as any, (value: T, oldValue: T) => cb(value, oldValue), watchOptions)\n stopHandles.push(stopHandle)\n return createWatchStopHandle(() => {\n stopHandle()\n const index = stopHandles.indexOf(stopHandle)\n if (index >= 0) {\n stopHandles.splice(index, 1)\n }\n }, stopHandle)\n }\n\n const bindModel = createBindModel(\n publicInstance as any,\n state as any,\n computedRefs,\n computedSetters,\n setupState as Record<string, any>,\n )\n\n const unmount = () => {\n if (!mounted) {\n return\n }\n mounted = false\n stopHandles.forEach((handle) => {\n try {\n handle()\n }\n catch {\n // 卸载阶段忽略 stop 抛错,确保其余清理继续\n }\n })\n stopHandles.length = 0\n }\n\n const runtimeInstance: RuntimeInstance<D, C, M> = {\n get state() {\n return state\n },\n get setupState() {\n return setupState as Record<string, any>\n },\n get proxy() {\n return publicInstance\n },\n get methods() {\n return boundMethods\n },\n get computed() {\n return computedProxy as Readonly<ExtractComputed<C>>\n },\n get adapter() {\n return currentAdapter\n },\n bindModel,\n watch: registerWatch,\n snapshot: () => scheduler.snapshot(),\n unmount,\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_touchSetupMethodsVersion', {\n value: touchSetupMethodsVersion,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_touchSetupMethodsVersion = touchSetupMethodsVersion\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_flushSetupSnapshotSync', {\n value: job,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_flushSetupSnapshotSync = job\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_cloneLatestSnapshot', {\n value: scheduler.cloneLatestSnapshot,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_cloneLatestSnapshot = scheduler.cloneLatestSnapshot\n }\n\n try {\n Object.defineProperty(runtimeInstance, '__wevu_trackSetupReactiveKey', {\n value: (key: string) => {\n trackedSetupReactiveKeys.add(key)\n },\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as RuntimeInstanceWithSetupMethodsVersion<D, C, M>).__wevu_trackSetupReactiveKey = (key: string) => {\n trackedSetupReactiveKeys.add(key)\n }\n }\n\n try {\n Object.defineProperty(runtimeInstance, WEVU_PROPS_DERIVED_KEYS_KEY, {\n value: snapshotOmitKeys,\n configurable: true,\n enumerable: false,\n writable: false,\n })\n }\n catch {\n ;(runtimeInstance as any)[WEVU_PROPS_DERIVED_KEYS_KEY] = snapshotOmitKeys\n }\n\n return runtimeInstance\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,SAAS,sBAAsB,SAAqB,YAA+C;CACjG,MAAM,oBAAoB;EACxB,QAAQ;CACV;CACA,WAAW,aAAa,WAAW;CACnC,WAAW,cAAc;;EACvB,gFAAY,oFAAQ;CACtB;CACA,WAAW,eAAe;;EACxB,iFAAY,uFAAS;CACvB;CACA,OAAO;AACT;AAaA,SAAS,kBAAoC,MAAgD;CAC3F,IAAI,OAAO,SAAS,YAClB,OAAO,KAAK;CAEd,OAAQ,0CAAQ,CAAC;AACnB;AAEA,SAAgB,mBAAiG,SAM9G;CACD,MAAM,EACJ,MACA,kBACA,iBACA,WACA,mBACE;CAEJ,QAAQ,YAA2D;EACjE,MAAM,WAAW,kBAAkB,IAAI;EACvC,MAAM,wEAAuB,QAAiB;EAG9C,IAAI,YAAY,OAAO,aAAa,YAAY,CAAC,OAAO,UAAoB,cAAc,GACxF,IAAI;GACF,OAAO,eAAe,UAAoB,gBAAgB;IACxD,OAAO,gBAAgB,OAAO,OAAO,IAAI,CAAC;IAC1C,cAAc;IACd,YAAY;IACZ,UAAU;GACZ,CAAC;EACH,kBACM,CAEN;EAEF,MAAM,WAAW,YAAY,OAAO,aAAa,WAC5C,SAAiB,kBAClB;EACJ,IAAI,YAAY,OAAO,aAAa,YAAY,uBAAuB,OAAO,wBAAwB,UACpG,OAAO,OAAO,UAAU,mBAAmB;EAE7C,MAAM,QAAQ,SAAS,QAAQ;EAC/B,MAAM,aAAa,SAAS,OAAO,OAAO,IAAI,CAAC;EAC/C,MAAM,4EAA2B,QAAiB;EAClD,MAAM,uBAAuB,0DAAS,QAAiB,2BAA2B;EAClF,MAAM,2EAA0B,QAAiB;EAC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,mBACM;GACH,AAAC,gBAAoE,6BAA6B,UAAU;EAC/G;EAEA,IAAI;GACF,OAAO,eAAe,iBAAiB,gCAAgC;IACrE,QAAQ,QAAgB;KACtB,yBAAyB,IAAI,GAAG;IAClC;IACA,cAAc;IACd,YAAY;IACZ,UAAU;GACZ,CAAC;EACH,mBACM;GACH,AAAC,gBAAoE,gCAAgC,QAAgB;IACpH,yBAAyB,IAAI,GAAG;GAClC;EACF;EAEA,IAAI;GACF,OAAO,eAAe,iBAAiB,6BAA6B;IAClE,OAAO;IACP,cAAc;IACd,YAAY;IACZ,UAAU;GACZ,CAAC;EACH,mBACM;GACH,AAAC,gBAAwB,+BAA+B;EAC3D;EAEA,OAAO;CACT;AACF"}
|
|
@@ -27,7 +27,8 @@ function decodeWxmlEntities(value) {
|
|
|
27
27
|
}
|
|
28
28
|
function parseInlineArgs(event) {
|
|
29
29
|
var _ref, _event$currentTarget$, _event$currentTarget, _event$target;
|
|
30
|
-
const
|
|
30
|
+
const dataset = (_ref = (_event$currentTarget$ = event === null || event === void 0 || (_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 ? void 0 : _event$currentTarget.dataset) !== null && _event$currentTarget$ !== void 0 ? _event$currentTarget$ : event === null || event === void 0 || (_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.dataset) !== null && _ref !== void 0 ? _ref : {};
|
|
31
|
+
const argsRaw = resolveDatasetEventValue(dataset, "wvArgs", event);
|
|
31
32
|
let args = [];
|
|
32
33
|
if (Array.isArray(argsRaw)) args = argsRaw;
|
|
33
34
|
else if (typeof argsRaw === "string") try {
|
|
@@ -288,10 +289,12 @@ function createScopedSlotOptions(overrides) {
|
|
|
288
289
|
methods: { [WEVU_OWNER_HANDLER](event) {
|
|
289
290
|
var _wevu, _ref4, _event$currentTarget$2, _event$currentTarget2, _event$target2;
|
|
290
291
|
const owner = this[WEVU_SLOT_OWNER_PROXY_KEY];
|
|
291
|
-
const
|
|
292
|
+
const inlineMap = (_wevu = this.__wevu) === null || _wevu === void 0 || (_wevu = _wevu.methods) === null || _wevu === void 0 ? void 0 : _wevu[WEVU_INLINE_MAP_KEY];
|
|
293
|
+
const result = runInlineExpression(owner, void 0, event, inlineMap);
|
|
292
294
|
if (result !== void 0) return result;
|
|
293
295
|
if (!owner) return;
|
|
294
|
-
const
|
|
296
|
+
const dataset = (_ref4 = (_event$currentTarget$2 = event === null || event === void 0 || (_event$currentTarget2 = event.currentTarget) === null || _event$currentTarget2 === void 0 ? void 0 : _event$currentTarget2.dataset) !== null && _event$currentTarget$2 !== void 0 ? _event$currentTarget$2 : event === null || event === void 0 || (_event$target2 = event.target) === null || _event$target2 === void 0 ? void 0 : _event$target2.dataset) !== null && _ref4 !== void 0 ? _ref4 : {};
|
|
297
|
+
const handlerName = resolveDatasetEventValue(dataset, "wvHandler", event);
|
|
295
298
|
if (typeof handlerName !== "string" || !handlerName) return;
|
|
296
299
|
const handler = owner === null || owner === void 0 ? void 0 : owner[handlerName];
|
|
297
300
|
if (typeof handler !== "function") return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scopedSlotOptions.mjs","names":[],"sources":["../../../../src/runtime/define/scopedSlotOptions.ts"],"sourcesContent":["import type { InlineExpressionMap } from '../register/inline'\nimport type { TemplateRefBinding } from '../templateRefs'\nimport type { ComputedDefinitions } from '../types'\nimport {\n WEVU_INLINE_HANDLER,\n WEVU_INLINE_MAP_KEY,\n WEVU_OWNER_HANDLER,\n WEVU_PROPS_DERIVED_KEYS_KEY,\n WEVU_PUBLIC_RUNTIME_KEY,\n WEVU_SLOT_FUNCTION_TOKEN,\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_OWNER_KEY,\n WEVU_SLOT_OWNER_PROXY_KEY,\n WEVU_SLOT_PROPS_DATA_KEY,\n WEVU_SLOT_PROPS_KEY,\n WEVU_SLOT_SCOPE_KEY,\n WEVU_TEMPLATE_REFS_KEY,\n} from '@weapp-core/constants'\nimport { hasOwn } from '../../utils'\nimport { cloneSnapshotValue, isDeepEqualValue } from '../app/setData/snapshot'\nimport { resolveDatasetEventValue, runInlineExpression } from '../register/inline'\nimport { getOwnerProxy, getOwnerSnapshot, getOwnerTarget, subscribeOwner } from '../scopedSlots'\nimport { clearTemplateRefs, scheduleTemplateRefUpdate } from '../templateRefs'\n\nconst SCOPED_SLOT_SNAPSHOT_OMIT_KEYS = [\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_OWNER_PROXY_KEY,\n WEVU_SLOT_OWNER_KEY,\n WEVU_SLOT_PROPS_DATA_KEY,\n WEVU_SLOT_PROPS_KEY,\n WEVU_SLOT_SCOPE_KEY,\n]\n\nconst AMP_RE = /&/g\nconst QUOT_RE = /"/g\nconst NUM_QUOT_RE = /"/g\nconst APOS_RE = /'/g\nconst NUM_APOS_RE = /'/g\nconst LT_RE = /</g\nconst GT_RE = />/g\n\nfunction decodeWxmlEntities(value: string) {\n return value\n .replace(AMP_RE, '&')\n .replace(QUOT_RE, '\"')\n .replace(NUM_QUOT_RE, '\"')\n .replace(APOS_RE, '\\'')\n .replace(NUM_APOS_RE, '\\'')\n .replace(LT_RE, '<')\n .replace(GT_RE, '>')\n}\n\nfunction parseInlineArgs(event: any) {\n const dataset = event?.currentTarget?.dataset ?? event?.target?.dataset ?? {}\n const argsRaw = resolveDatasetEventValue(dataset, 'wvArgs', event)\n let args: any[] = []\n if (Array.isArray(argsRaw)) {\n args = argsRaw\n }\n else if (typeof argsRaw === 'string') {\n try {\n args = JSON.parse(argsRaw)\n }\n catch {\n try {\n args = JSON.parse(decodeWxmlEntities(argsRaw))\n }\n catch {\n args = []\n }\n }\n }\n if (!Array.isArray(args)) {\n args = []\n }\n return args.map((item: any) => item === '$event' ? event : item)\n}\n\nfunction normalizeSlotBindings(value: unknown): Record<string, any> {\n if (!value || typeof value !== 'object') {\n return {}\n }\n if (Array.isArray(value)) {\n const result: Record<string, any> = {}\n for (let i = 0; i < value.length; i += 2) {\n const key = value[i]\n if (typeof key === 'string' && key) {\n result[key] = value[i + 1]\n }\n }\n return result\n }\n return value as Record<string, any>\n}\n\nfunction isSlotFunctionDescriptor(value: unknown): value is [string, string, unknown[], unknown[]] {\n return Array.isArray(value)\n && value[0] === WEVU_SLOT_FUNCTION_TOKEN\n && typeof value[1] === 'string'\n}\n\nfunction createSlotFunctionProxy(instance: any, descriptor: [string, string, unknown[], unknown[]]) {\n return (...args: unknown[]) => {\n const owner = instance?.selectOwnerComponent?.()\n const handler = owner?.[WEVU_INLINE_HANDLER]\n if (typeof handler !== 'function') {\n return undefined\n }\n const dataset: Record<string, unknown> = {\n wd: 1,\n wi: descriptor[1],\n }\n const scopeBindings = Array.isArray(descriptor[2]) ? descriptor[2] : []\n const indexBindings = Array.isArray(descriptor[3]) ? descriptor[3] : []\n scopeBindings.forEach((value, index) => dataset[`wvS${index}`] = value)\n indexBindings.forEach((value, index) => dataset[`wvI${index}`] = value)\n const event = {\n type: 'wv-slot-function',\n detail: args,\n currentTarget: { dataset },\n target: { dataset },\n }\n return handler.call(owner, event)\n }\n}\n\nfunction resolveRuntimeSlotBindings(instance: any, bindings: Record<string, any>) {\n return Object.fromEntries(Object.entries(bindings).map(([key, value]) => [\n key,\n isSlotFunctionDescriptor(value) ? createSlotFunctionProxy(instance, value) : value,\n ]))\n}\n\nfunction resolveComputedContext(instance: any) {\n return instance?.__wevu?.proxy\n ?? instance?.[WEVU_PUBLIC_RUNTIME_KEY]?.proxy\n ?? instance\n}\n\nfunction collectComputedPayload(instance: any, computed?: ComputedDefinitions) {\n if (!computed || Object.keys(computed).length === 0) {\n return undefined\n }\n\n const context = resolveComputedContext(instance)\n const payload: Record<string, any> = {}\n for (const [key, definition] of Object.entries(computed)) {\n try {\n let value: any\n if (typeof definition === 'function') {\n value = definition.call(context)\n }\n else if (typeof (definition as any)?.get === 'function') {\n value = (definition as any).get.call(context)\n }\n if (value !== undefined) {\n payload[key] = value\n }\n }\n catch {\n }\n }\n return payload\n}\n\nfunction flushOwnerProxyBindings(instance: any) {\n instance?.__wevu?.__wevu_flushSetupSnapshotSync?.()\n}\n\nfunction flushScopedSlotComputedBindings(\n instance: any,\n computed?: ComputedDefinitions,\n options?: { force?: boolean },\n) {\n flushOwnerProxyBindings(instance)\n const payload = collectComputedPayload(instance, computed)\n if (!payload || typeof instance?.setData !== 'function') {\n return\n }\n const hasPrevious = hasOwn(instance, '__wvScopedSlotComputedSnapshot')\n const previous = instance.__wvScopedSlotComputedSnapshot ?? {}\n const next: Record<string, any> = {}\n const changed: Record<string, any> = {}\n for (const [key, value] of Object.entries(payload)) {\n next[key] = cloneSnapshotValue(value)\n if (options?.force || !hasPrevious || !hasOwn(previous, key) || !isDeepEqualValue(previous[key], value, 20, { keys: 10_000 })) {\n changed[key] = value\n }\n }\n for (const key of Object.keys(previous)) {\n if (!hasOwn(payload, key)) {\n changed[key] = null\n }\n }\n instance.__wvScopedSlotComputedSnapshot = next\n if (Object.keys(changed).length > 0) {\n instance.setData(changed)\n }\n}\n\nfunction syncSlotPropsData(\n instance: any,\n override?: { [WEVU_SLOT_SCOPE_KEY]?: unknown, [WEVU_SLOT_PROPS_KEY]?: unknown },\n) {\n const scopeSource = hasOwn(override ?? {}, WEVU_SLOT_SCOPE_KEY)\n ? (override as any)[WEVU_SLOT_SCOPE_KEY]\n : instance?.properties?.[WEVU_SLOT_SCOPE_KEY]\n const propsSource = hasOwn(override ?? {}, WEVU_SLOT_PROPS_KEY)\n ? (override as any)[WEVU_SLOT_PROPS_KEY]\n : instance?.properties?.[WEVU_SLOT_PROPS_KEY]\n const scope = normalizeSlotBindings(scopeSource)\n const slotProps = normalizeSlotBindings(propsSource)\n const snapshot = { ...scope, ...slotProps }\n const snapshotChanged = !hasOwn(instance, '__wvSlotPropsSnapshot')\n || !isDeepEqualValue(\n instance.__wvSlotPropsSnapshot ?? {},\n snapshot,\n 20,\n { keys: 10_000 },\n )\n const merged = snapshotChanged || !instance[WEVU_SLOT_PROPS_DATA_KEY]\n ? resolveRuntimeSlotBindings(instance, snapshot)\n : instance[WEVU_SLOT_PROPS_DATA_KEY]\n if (snapshotChanged) {\n instance.__wvSlotPropsSnapshot = cloneSnapshotValue(snapshot)\n }\n instance[WEVU_SLOT_PROPS_DATA_KEY] = merged\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_PROPS_DATA_KEY] = merged\n }\n return { merged, snapshot, snapshotChanged }\n}\n\nfunction mergeSlotProps(\n instance: any,\n computed?: ComputedDefinitions,\n override?: { [WEVU_SLOT_SCOPE_KEY]?: unknown, [WEVU_SLOT_PROPS_KEY]?: unknown },\n) {\n const { snapshot, snapshotChanged } = syncSlotPropsData(instance, override)\n if (snapshotChanged && typeof instance?.setData === 'function') {\n instance.setData({ [WEVU_SLOT_PROPS_DATA_KEY]: snapshot })\n }\n if (snapshotChanged) {\n flushScopedSlotComputedBindings(instance, computed)\n }\n}\n\nfunction setOwnerProxy(instance: any, proxy: any) {\n if (instance[WEVU_SLOT_OWNER_PROXY_KEY] === proxy) {\n return false\n }\n instance[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n const data = instance?.data\n if (data && typeof data === 'object') {\n try {\n Object.defineProperty(data, WEVU_SLOT_OWNER_PROXY_KEY, {\n value: proxy,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n }\n catch {\n data[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n }\n }\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n }\n return true\n}\n\nfunction updateOwnerBindings(instance: any, snapshot: Record<string, any>, proxy: any, computed?: ComputedDefinitions) {\n const proxyChanged = setOwnerProxy(instance, proxy)\n const { snapshotChanged: slotPropsChanged } = syncSlotPropsData(instance)\n const nextOwnerSnapshot = snapshot || {}\n const ownerChanged = !hasOwn(instance, '__wvOwnerSnapshot')\n || !isDeepEqualValue(\n instance.__wvOwnerSnapshot ?? {},\n nextOwnerSnapshot,\n 20,\n { keys: 10_000 },\n )\n if (ownerChanged) {\n instance.__wvOwnerSnapshot = cloneSnapshotValue(nextOwnerSnapshot)\n instance[WEVU_SLOT_OWNER_KEY] = nextOwnerSnapshot\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_OWNER_KEY] = nextOwnerSnapshot\n }\n }\n if (ownerChanged && typeof instance?.setData === 'function') {\n instance.setData({ [WEVU_SLOT_OWNER_KEY]: nextOwnerSnapshot })\n }\n if (ownerChanged || proxyChanged || slotPropsChanged) {\n flushScopedSlotComputedBindings(instance, computed)\n }\n}\n\nfunction bindOwner(instance: any, ownerId: string, computed?: ComputedDefinitions) {\n if (!ownerId) {\n if (typeof instance?.__wvOwnerUnsub === 'function') {\n instance.__wvOwnerUnsub()\n }\n instance.__wvOwnerUnsub = undefined\n instance.__wvOwnerBoundId = ''\n setOwnerProxy(instance, undefined)\n return\n }\n\n const updateOwner = (snapshot: Record<string, any>, proxy: any) => {\n updateOwnerBindings(instance, snapshot, proxy, computed)\n }\n if (instance.__wvOwnerBoundId !== ownerId) {\n if (typeof instance.__wvOwnerUnsub === 'function') {\n instance.__wvOwnerUnsub()\n }\n instance.__wvOwnerBoundId = ownerId\n instance.__wvOwnerUnsub = subscribeOwner(ownerId, updateOwner)\n }\n const snapshot = getOwnerSnapshot(ownerId)\n if (snapshot) {\n updateOwner(snapshot, getOwnerProxy(ownerId))\n }\n}\n\nfunction resolveBoundOwnerId(instance: any) {\n return instance?.properties?.[WEVU_SLOT_OWNER_ID_PROP]\n ?? instance?.properties?.[WEVU_SLOT_OWNER_ID_KEY]\n ?? ''\n}\n\nfunction syncScopedSlotBindings(instance: any, computed?: ComputedDefinitions) {\n mergeSlotProps(instance, computed)\n const ownerId = resolveBoundOwnerId(instance)\n if (!ownerId) {\n return\n }\n bindOwner(instance, ownerId, computed)\n}\n\nfunction createScopedSlotData() {\n const data = {\n [WEVU_SLOT_OWNER_KEY]: {},\n [WEVU_SLOT_PROPS_DATA_KEY]: {},\n }\n Object.defineProperty(data, WEVU_SLOT_OWNER_PROXY_KEY, {\n value: undefined,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n return data\n}\n\nexport function createScopedSlotOptions(\n overrides?: {\n computed?: ComputedDefinitions\n inlineMap?: InlineExpressionMap\n templateRefs?: TemplateRefBinding[]\n },\n) {\n const scopedSlotComputed = overrides?.computed\n const templateRefs = overrides?.templateRefs\n const resolveTemplateRefOwner = (instance: any) => {\n const ownerId = resolveBoundOwnerId(instance)\n return ownerId ? getOwnerTarget(ownerId) : undefined\n }\n const baseOptions = {\n options: {\n virtualHost: true,\n },\n setData: {\n omit: SCOPED_SLOT_SNAPSHOT_OMIT_KEYS,\n },\n [WEVU_PROPS_DERIVED_KEYS_KEY]: SCOPED_SLOT_SNAPSHOT_OMIT_KEYS,\n properties: {\n [WEVU_SLOT_OWNER_ID_PROP]: {\n type: String,\n value: '',\n observer(this: any, next: string) {\n bindOwner(this, next || '', scopedSlotComputed)\n },\n },\n [WEVU_SLOT_OWNER_ID_KEY]: {\n type: String,\n value: '',\n observer(this: any, next: string) {\n bindOwner(this, next || '', scopedSlotComputed)\n },\n },\n [WEVU_SLOT_PROPS_KEY]: {\n type: null,\n value: null,\n observer(this: any, next: unknown) {\n mergeSlotProps(this, scopedSlotComputed, { [WEVU_SLOT_PROPS_KEY]: next })\n },\n },\n [WEVU_SLOT_SCOPE_KEY]: {\n type: null,\n value: null,\n observer(this: any, next: unknown) {\n mergeSlotProps(this, scopedSlotComputed, { [WEVU_SLOT_SCOPE_KEY]: next })\n },\n },\n },\n data: createScopedSlotData,\n lifetimes: {\n attached(this: any) {\n syncScopedSlotBindings(this, scopedSlotComputed)\n },\n ready(this: any) {\n syncScopedSlotBindings(this, scopedSlotComputed)\n flushScopedSlotComputedBindings(this, scopedSlotComputed, { force: true })\n const owner = resolveTemplateRefOwner(this)\n if (owner) {\n scheduleTemplateRefUpdate(this, undefined, owner)\n }\n },\n detached(this: any) {\n const owner = resolveTemplateRefOwner(this)\n if (owner) {\n clearTemplateRefs(this, owner)\n }\n if (typeof this.__wvOwnerUnsub === 'function') {\n this.__wvOwnerUnsub()\n }\n this.__wvOwnerUnsub = undefined\n this.__wvOwnerBoundId = ''\n setOwnerProxy(this, undefined)\n },\n },\n methods: {\n [WEVU_OWNER_HANDLER](this: any, event: any) {\n const owner = this[WEVU_SLOT_OWNER_PROXY_KEY]\n const inlineMap = (this as any).__wevu?.methods?.[WEVU_INLINE_MAP_KEY]\n const result = runInlineExpression(owner, undefined, event, inlineMap)\n if (result !== undefined) {\n return result\n }\n if (!owner) {\n return undefined\n }\n const dataset = event?.currentTarget?.dataset ?? event?.target?.dataset ?? {}\n const handlerName = resolveDatasetEventValue(dataset, 'wvHandler', event)\n if (typeof handlerName !== 'string' || !handlerName) {\n return undefined\n }\n const handler = owner?.[handlerName]\n if (typeof handler !== 'function') {\n return undefined\n }\n const args = parseInlineArgs(event)\n return handler.apply(owner, args)\n },\n },\n }\n\n if (overrides?.computed && Object.keys(overrides.computed).length > 0) {\n ;(baseOptions as any).computed = overrides.computed\n }\n if (overrides?.inlineMap && Object.keys(overrides.inlineMap).length > 0) {\n ;(baseOptions as any).methods = {\n ...(baseOptions as any).methods,\n [WEVU_INLINE_MAP_KEY]: overrides.inlineMap,\n }\n }\n if (templateRefs?.length) {\n ;(baseOptions as any)[WEVU_TEMPLATE_REFS_KEY] = templateRefs\n }\n\n return baseOptions\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,iCAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,SAAS;AACf,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,QAAQ;AACd,MAAM,QAAQ;AAEd,SAAS,mBAAmB,OAAe;CACzC,O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AAC,oBAA+B,OAAY;;GAC1C,MAAM,QAAQ,KAAK;GAEnB,MAAM,SAAS,oBAAoB,OAAO,QAAW,gBADlC,KAAa,uDAAQ,uDAAU,oBACmB;GACrE,IAAI,WAAW,QACb,OAAO;GAET,IAAI,CAAC,OACH;GAGF,MAAM,cAAc,2HADJ,MAAO,6FAAe,0IAAW,MAAO,wEAAQ,gDAAW,CAAC,GACtB,aAAa,KAAK;GACxE,IAAI,OAAO,gBAAgB,YAAY,CAAC,aACtC;GAEF,MAAM,wDAAU,MAAQ;GACxB,IAAI,OAAO,YAAY,YACrB;GAEF,MAAM,OAAO,gBAAgB,KAAK;GAClC,OAAO,QAAQ,MAAM,OAAO,IAAI;EAClC,EACF;CACF;CAEA,2DAAI,UAAW,aAAY,OAAO,KAAK,UAAU,QAAQ,CAAC,CAAC,SAAS,GACjE,AAAC,YAAoB,WAAW,UAAU;CAE7C,2DAAI,UAAW,cAAa,OAAO,KAAK,UAAU,SAAS,CAAC,CAAC,SAAS,GACnE,AAAC,YAAoB,UAAU;EAC9B,GAAI,YAAoB;GACvB,sBAAsB,UAAU;CACnC;CAEF,gEAAI,aAAc,QACf,AAAC,YAAoB,0BAA0B;CAGlD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"scopedSlotOptions.mjs","names":[],"sources":["../../../../src/runtime/define/scopedSlotOptions.ts"],"sourcesContent":["import type { InlineExpressionMap } from '../register/inline'\nimport type { TemplateRefBinding } from '../templateRefs'\nimport type { ComputedDefinitions } from '../types'\nimport {\n WEVU_INLINE_HANDLER,\n WEVU_INLINE_MAP_KEY,\n WEVU_OWNER_HANDLER,\n WEVU_PROPS_DERIVED_KEYS_KEY,\n WEVU_PUBLIC_RUNTIME_KEY,\n WEVU_SLOT_FUNCTION_TOKEN,\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_OWNER_KEY,\n WEVU_SLOT_OWNER_PROXY_KEY,\n WEVU_SLOT_PROPS_DATA_KEY,\n WEVU_SLOT_PROPS_KEY,\n WEVU_SLOT_SCOPE_KEY,\n WEVU_TEMPLATE_REFS_KEY,\n} from '@weapp-core/constants'\nimport { hasOwn } from '../../utils'\nimport { cloneSnapshotValue, isDeepEqualValue } from '../app/setData/snapshot'\nimport { resolveDatasetEventValue, runInlineExpression } from '../register/inline'\nimport { getOwnerProxy, getOwnerSnapshot, getOwnerTarget, subscribeOwner } from '../scopedSlots'\nimport { clearTemplateRefs, scheduleTemplateRefUpdate } from '../templateRefs'\n\nconst SCOPED_SLOT_SNAPSHOT_OMIT_KEYS = [\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_OWNER_PROXY_KEY,\n WEVU_SLOT_OWNER_KEY,\n WEVU_SLOT_PROPS_DATA_KEY,\n WEVU_SLOT_PROPS_KEY,\n WEVU_SLOT_SCOPE_KEY,\n]\n\nconst AMP_RE = /&/g\nconst QUOT_RE = /"/g\nconst NUM_QUOT_RE = /"/g\nconst APOS_RE = /'/g\nconst NUM_APOS_RE = /'/g\nconst LT_RE = /</g\nconst GT_RE = />/g\n\nfunction decodeWxmlEntities(value: string) {\n return value\n .replace(AMP_RE, '&')\n .replace(QUOT_RE, '\"')\n .replace(NUM_QUOT_RE, '\"')\n .replace(APOS_RE, '\\'')\n .replace(NUM_APOS_RE, '\\'')\n .replace(LT_RE, '<')\n .replace(GT_RE, '>')\n}\n\nfunction parseInlineArgs(event: any) {\n const dataset = event?.currentTarget?.dataset ?? event?.target?.dataset ?? {}\n const argsRaw = resolveDatasetEventValue(dataset, 'wvArgs', event)\n let args: any[] = []\n if (Array.isArray(argsRaw)) {\n args = argsRaw\n }\n else if (typeof argsRaw === 'string') {\n try {\n args = JSON.parse(argsRaw)\n }\n catch {\n try {\n args = JSON.parse(decodeWxmlEntities(argsRaw))\n }\n catch {\n args = []\n }\n }\n }\n if (!Array.isArray(args)) {\n args = []\n }\n return args.map((item: any) => item === '$event' ? event : item)\n}\n\nfunction normalizeSlotBindings(value: unknown): Record<string, any> {\n if (!value || typeof value !== 'object') {\n return {}\n }\n if (Array.isArray(value)) {\n const result: Record<string, any> = {}\n for (let i = 0; i < value.length; i += 2) {\n const key = value[i]\n if (typeof key === 'string' && key) {\n result[key] = value[i + 1]\n }\n }\n return result\n }\n return value as Record<string, any>\n}\n\nfunction isSlotFunctionDescriptor(value: unknown): value is [string, string, unknown[], unknown[]] {\n return Array.isArray(value)\n && value[0] === WEVU_SLOT_FUNCTION_TOKEN\n && typeof value[1] === 'string'\n}\n\nfunction createSlotFunctionProxy(instance: any, descriptor: [string, string, unknown[], unknown[]]) {\n return (...args: unknown[]) => {\n const owner = instance?.selectOwnerComponent?.()\n const handler = owner?.[WEVU_INLINE_HANDLER]\n if (typeof handler !== 'function') {\n return undefined\n }\n const dataset: Record<string, unknown> = {\n wd: 1,\n wi: descriptor[1],\n }\n const scopeBindings = Array.isArray(descriptor[2]) ? descriptor[2] : []\n const indexBindings = Array.isArray(descriptor[3]) ? descriptor[3] : []\n scopeBindings.forEach((value, index) => dataset[`wvS${index}`] = value)\n indexBindings.forEach((value, index) => dataset[`wvI${index}`] = value)\n const event = {\n type: 'wv-slot-function',\n detail: args,\n currentTarget: { dataset },\n target: { dataset },\n }\n return handler.call(owner, event)\n }\n}\n\nfunction resolveRuntimeSlotBindings(instance: any, bindings: Record<string, any>) {\n return Object.fromEntries(Object.entries(bindings).map(([key, value]) => [\n key,\n isSlotFunctionDescriptor(value) ? createSlotFunctionProxy(instance, value) : value,\n ]))\n}\n\nfunction resolveComputedContext(instance: any) {\n return instance?.__wevu?.proxy\n ?? instance?.[WEVU_PUBLIC_RUNTIME_KEY]?.proxy\n ?? instance\n}\n\nfunction collectComputedPayload(instance: any, computed?: ComputedDefinitions) {\n if (!computed || Object.keys(computed).length === 0) {\n return undefined\n }\n\n const context = resolveComputedContext(instance)\n const payload: Record<string, any> = {}\n for (const [key, definition] of Object.entries(computed)) {\n try {\n let value: any\n if (typeof definition === 'function') {\n value = definition.call(context)\n }\n else if (typeof (definition as any)?.get === 'function') {\n value = (definition as any).get.call(context)\n }\n if (value !== undefined) {\n payload[key] = value\n }\n }\n catch {\n }\n }\n return payload\n}\n\nfunction flushOwnerProxyBindings(instance: any) {\n instance?.__wevu?.__wevu_flushSetupSnapshotSync?.()\n}\n\nfunction flushScopedSlotComputedBindings(\n instance: any,\n computed?: ComputedDefinitions,\n options?: { force?: boolean },\n) {\n flushOwnerProxyBindings(instance)\n const payload = collectComputedPayload(instance, computed)\n if (!payload || typeof instance?.setData !== 'function') {\n return\n }\n const hasPrevious = hasOwn(instance, '__wvScopedSlotComputedSnapshot')\n const previous = instance.__wvScopedSlotComputedSnapshot ?? {}\n const next: Record<string, any> = {}\n const changed: Record<string, any> = {}\n for (const [key, value] of Object.entries(payload)) {\n next[key] = cloneSnapshotValue(value)\n if (options?.force || !hasPrevious || !hasOwn(previous, key) || !isDeepEqualValue(previous[key], value, 20, { keys: 10_000 })) {\n changed[key] = value\n }\n }\n for (const key of Object.keys(previous)) {\n if (!hasOwn(payload, key)) {\n changed[key] = null\n }\n }\n instance.__wvScopedSlotComputedSnapshot = next\n if (Object.keys(changed).length > 0) {\n instance.setData(changed)\n }\n}\n\nfunction syncSlotPropsData(\n instance: any,\n override?: { [WEVU_SLOT_SCOPE_KEY]?: unknown, [WEVU_SLOT_PROPS_KEY]?: unknown },\n) {\n const scopeSource = hasOwn(override ?? {}, WEVU_SLOT_SCOPE_KEY)\n ? (override as any)[WEVU_SLOT_SCOPE_KEY]\n : instance?.properties?.[WEVU_SLOT_SCOPE_KEY]\n const propsSource = hasOwn(override ?? {}, WEVU_SLOT_PROPS_KEY)\n ? (override as any)[WEVU_SLOT_PROPS_KEY]\n : instance?.properties?.[WEVU_SLOT_PROPS_KEY]\n const scope = normalizeSlotBindings(scopeSource)\n const slotProps = normalizeSlotBindings(propsSource)\n const snapshot = { ...scope, ...slotProps }\n const snapshotChanged = !hasOwn(instance, '__wvSlotPropsSnapshot')\n || !isDeepEqualValue(\n instance.__wvSlotPropsSnapshot ?? {},\n snapshot,\n 20,\n { keys: 10_000 },\n )\n const merged = snapshotChanged || !instance[WEVU_SLOT_PROPS_DATA_KEY]\n ? resolveRuntimeSlotBindings(instance, snapshot)\n : instance[WEVU_SLOT_PROPS_DATA_KEY]\n if (snapshotChanged) {\n instance.__wvSlotPropsSnapshot = cloneSnapshotValue(snapshot)\n }\n instance[WEVU_SLOT_PROPS_DATA_KEY] = merged\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_PROPS_DATA_KEY] = merged\n }\n return { merged, snapshot, snapshotChanged }\n}\n\nfunction mergeSlotProps(\n instance: any,\n computed?: ComputedDefinitions,\n override?: { [WEVU_SLOT_SCOPE_KEY]?: unknown, [WEVU_SLOT_PROPS_KEY]?: unknown },\n) {\n const { snapshot, snapshotChanged } = syncSlotPropsData(instance, override)\n if (snapshotChanged && typeof instance?.setData === 'function') {\n instance.setData({ [WEVU_SLOT_PROPS_DATA_KEY]: snapshot })\n }\n if (snapshotChanged) {\n flushScopedSlotComputedBindings(instance, computed)\n }\n}\n\nfunction setOwnerProxy(instance: any, proxy: any) {\n if (instance[WEVU_SLOT_OWNER_PROXY_KEY] === proxy) {\n return false\n }\n instance[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n const data = instance?.data\n if (data && typeof data === 'object') {\n try {\n Object.defineProperty(data, WEVU_SLOT_OWNER_PROXY_KEY, {\n value: proxy,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n }\n catch {\n data[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n }\n }\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_OWNER_PROXY_KEY] = proxy\n }\n return true\n}\n\nfunction updateOwnerBindings(instance: any, snapshot: Record<string, any>, proxy: any, computed?: ComputedDefinitions) {\n const proxyChanged = setOwnerProxy(instance, proxy)\n const { snapshotChanged: slotPropsChanged } = syncSlotPropsData(instance)\n const nextOwnerSnapshot = snapshot || {}\n const ownerChanged = !hasOwn(instance, '__wvOwnerSnapshot')\n || !isDeepEqualValue(\n instance.__wvOwnerSnapshot ?? {},\n nextOwnerSnapshot,\n 20,\n { keys: 10_000 },\n )\n if (ownerChanged) {\n instance.__wvOwnerSnapshot = cloneSnapshotValue(nextOwnerSnapshot)\n instance[WEVU_SLOT_OWNER_KEY] = nextOwnerSnapshot\n const runtimeState = instance?.__wevu?.state\n if (runtimeState && typeof runtimeState === 'object') {\n runtimeState[WEVU_SLOT_OWNER_KEY] = nextOwnerSnapshot\n }\n }\n if (ownerChanged && typeof instance?.setData === 'function') {\n instance.setData({ [WEVU_SLOT_OWNER_KEY]: nextOwnerSnapshot })\n }\n if (ownerChanged || proxyChanged || slotPropsChanged) {\n flushScopedSlotComputedBindings(instance, computed)\n }\n}\n\nfunction bindOwner(instance: any, ownerId: string, computed?: ComputedDefinitions) {\n if (!ownerId) {\n if (typeof instance?.__wvOwnerUnsub === 'function') {\n instance.__wvOwnerUnsub()\n }\n instance.__wvOwnerUnsub = undefined\n instance.__wvOwnerBoundId = ''\n setOwnerProxy(instance, undefined)\n return\n }\n\n const updateOwner = (snapshot: Record<string, any>, proxy: any) => {\n updateOwnerBindings(instance, snapshot, proxy, computed)\n }\n if (instance.__wvOwnerBoundId !== ownerId) {\n if (typeof instance.__wvOwnerUnsub === 'function') {\n instance.__wvOwnerUnsub()\n }\n instance.__wvOwnerBoundId = ownerId\n instance.__wvOwnerUnsub = subscribeOwner(ownerId, updateOwner)\n }\n const snapshot = getOwnerSnapshot(ownerId)\n if (snapshot) {\n updateOwner(snapshot, getOwnerProxy(ownerId))\n }\n}\n\nfunction resolveBoundOwnerId(instance: any) {\n return instance?.properties?.[WEVU_SLOT_OWNER_ID_PROP]\n ?? instance?.properties?.[WEVU_SLOT_OWNER_ID_KEY]\n ?? ''\n}\n\nfunction syncScopedSlotBindings(instance: any, computed?: ComputedDefinitions) {\n mergeSlotProps(instance, computed)\n const ownerId = resolveBoundOwnerId(instance)\n if (!ownerId) {\n return\n }\n bindOwner(instance, ownerId, computed)\n}\n\nfunction createScopedSlotData() {\n const data = {\n [WEVU_SLOT_OWNER_KEY]: {},\n [WEVU_SLOT_PROPS_DATA_KEY]: {},\n }\n Object.defineProperty(data, WEVU_SLOT_OWNER_PROXY_KEY, {\n value: undefined,\n configurable: true,\n enumerable: false,\n writable: true,\n })\n return data\n}\n\nexport function createScopedSlotOptions(\n overrides?: {\n computed?: ComputedDefinitions\n inlineMap?: InlineExpressionMap\n templateRefs?: TemplateRefBinding[]\n },\n) {\n const scopedSlotComputed = overrides?.computed\n const templateRefs = overrides?.templateRefs\n const resolveTemplateRefOwner = (instance: any) => {\n const ownerId = resolveBoundOwnerId(instance)\n return ownerId ? getOwnerTarget(ownerId) : undefined\n }\n const baseOptions = {\n options: {\n virtualHost: true,\n },\n setData: {\n omit: SCOPED_SLOT_SNAPSHOT_OMIT_KEYS,\n },\n [WEVU_PROPS_DERIVED_KEYS_KEY]: SCOPED_SLOT_SNAPSHOT_OMIT_KEYS,\n properties: {\n [WEVU_SLOT_OWNER_ID_PROP]: {\n type: String,\n value: '',\n observer(this: any, next: string) {\n bindOwner(this, next || '', scopedSlotComputed)\n },\n },\n [WEVU_SLOT_OWNER_ID_KEY]: {\n type: String,\n value: '',\n observer(this: any, next: string) {\n bindOwner(this, next || '', scopedSlotComputed)\n },\n },\n [WEVU_SLOT_PROPS_KEY]: {\n type: null,\n value: null,\n observer(this: any, next: unknown) {\n mergeSlotProps(this, scopedSlotComputed, { [WEVU_SLOT_PROPS_KEY]: next })\n },\n },\n [WEVU_SLOT_SCOPE_KEY]: {\n type: null,\n value: null,\n observer(this: any, next: unknown) {\n mergeSlotProps(this, scopedSlotComputed, { [WEVU_SLOT_SCOPE_KEY]: next })\n },\n },\n },\n data: createScopedSlotData,\n lifetimes: {\n attached(this: any) {\n syncScopedSlotBindings(this, scopedSlotComputed)\n },\n ready(this: any) {\n syncScopedSlotBindings(this, scopedSlotComputed)\n flushScopedSlotComputedBindings(this, scopedSlotComputed, { force: true })\n const owner = resolveTemplateRefOwner(this)\n if (owner) {\n scheduleTemplateRefUpdate(this, undefined, owner)\n }\n },\n detached(this: any) {\n const owner = resolveTemplateRefOwner(this)\n if (owner) {\n clearTemplateRefs(this, owner)\n }\n if (typeof this.__wvOwnerUnsub === 'function') {\n this.__wvOwnerUnsub()\n }\n this.__wvOwnerUnsub = undefined\n this.__wvOwnerBoundId = ''\n setOwnerProxy(this, undefined)\n },\n },\n methods: {\n [WEVU_OWNER_HANDLER](this: any, event: any) {\n const owner = this[WEVU_SLOT_OWNER_PROXY_KEY]\n const inlineMap = (this as any).__wevu?.methods?.[WEVU_INLINE_MAP_KEY]\n const result = runInlineExpression(owner, undefined, event, inlineMap)\n if (result !== undefined) {\n return result\n }\n if (!owner) {\n return undefined\n }\n const dataset = event?.currentTarget?.dataset ?? event?.target?.dataset ?? {}\n const handlerName = resolveDatasetEventValue(dataset, 'wvHandler', event)\n if (typeof handlerName !== 'string' || !handlerName) {\n return undefined\n }\n const handler = owner?.[handlerName]\n if (typeof handler !== 'function') {\n return undefined\n }\n const args = parseInlineArgs(event)\n return handler.apply(owner, args)\n },\n },\n }\n\n if (overrides?.computed && Object.keys(overrides.computed).length > 0) {\n ;(baseOptions as any).computed = overrides.computed\n }\n if (overrides?.inlineMap && Object.keys(overrides.inlineMap).length > 0) {\n ;(baseOptions as any).methods = {\n ...(baseOptions as any).methods,\n [WEVU_INLINE_MAP_KEY]: overrides.inlineMap,\n }\n }\n if (templateRefs?.length) {\n ;(baseOptions as any)[WEVU_TEMPLATE_REFS_KEY] = templateRefs\n }\n\n return baseOptions\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,iCAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,SAAS;AACf,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,M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BAAmB,YACjC,KAAK,eAAe;IAEtB,KAAK,iBAAiB;IACtB,KAAK,mBAAmB;IACxB,cAAc,MAAM,MAAS;GAC/B;EACF;EACA,SAAS,EACP,CAAC,oBAA+B,OAAY;;GAC1C,MAAM,QAAQ,KAAK;GACnB,MAAM,qBAAa,KAAa,uDAAQ,uDAAU;GAClD,MAAM,SAAS,oBAAoB,OAAO,QAAW,OAAO,SAAS;GACrE,IAAI,WAAW,QACb,OAAO;GAET,IAAI,CAAC,OACH;GAEF,MAAM,4GAAU,MAAO,6FAAe,0IAAW,MAAO,wEAAQ,gDAAW,CAAC;GAC5E,MAAM,cAAc,yBAAyB,SAAS,aAAa,KAAK;GACxE,IAAI,OAAO,gBAAgB,YAAY,CAAC,aACtC;GAEF,MAAM,wDAAU,MAAQ;GACxB,IAAI,OAAO,YAAY,YACrB;GAEF,MAAM,OAAO,gBAAgB,KAAK;GAClC,OAAO,QAAQ,MAAM,OAAO,IAAI;EAClC,EACF;CACF;CAEA,2DAAI,UAAW,aAAY,OAAO,KAAK,UAAU,QAAQ,CAAC,CAAC,SAAS,GACjE,AAAC,YAAoB,WAAW,UAAU;CAE7C,2DAAI,UAAW,cAAa,OAAO,KAAK,UAAU,SAAS,CAAC,CAAC,SAAS,GACnE,AAAC,YAAoB,UAAU;EAC9B,GAAI,YAAoB;GACvB,sBAAsB,UAAU;CACnC;CAEF,gEAAI,aAAc,QACf,AAAC,YAAoB,0BAA0B;CAGlD,OAAO;AACT"}
|
|
@@ -86,10 +86,11 @@ function defineComponent(options) {
|
|
|
86
86
|
return result;
|
|
87
87
|
}) : void 0;
|
|
88
88
|
const nativeData = typeof resolvedData === "function" ? resolvedData() : resolvedData;
|
|
89
|
-
const
|
|
89
|
+
const seededNativeData = shouldDeclareNativeSlotOwnerId(resolvedSetData) ? {
|
|
90
90
|
...nativeData && typeof nativeData === "object" ? nativeData : {},
|
|
91
91
|
[WEVU_SLOT_OWNER_ID_KEY]: shouldSeedNativeSlotOwnerId(mpOptions, resolvedSetData) ? (nativeData === null || nativeData === void 0 ? void 0 : nativeData[WEVU_SLOT_OWNER_ID_KEY]) || allocateOwnerId() : (nativeData === null || nativeData === void 0 ? void 0 : nativeData[WEVU_SLOT_OWNER_ID_KEY]) || ""
|
|
92
|
-
} : nativeData
|
|
92
|
+
} : nativeData;
|
|
93
|
+
const nativeInitialData = resolveNativeInitialData(seededNativeData, computed, resolvedSetData);
|
|
93
94
|
const mpOptionsWithProps = nativeInitialData !== void 0 ? {
|
|
94
95
|
...normalizedMpOptions,
|
|
95
96
|
data: nativeInitialData
|
|
@@ -119,11 +120,12 @@ function createWevuComponent(options) {
|
|
|
119
120
|
var _allowNullPropInput;
|
|
120
121
|
ensureScopedSlotComponentGlobal();
|
|
121
122
|
const { properties, props, ...restOptions } = options;
|
|
122
|
-
|
|
123
|
+
const baseOptions = {
|
|
123
124
|
...restOptions,
|
|
124
125
|
allowNullPropInput: (_allowNullPropInput = restOptions.allowNullPropInput) !== null && _allowNullPropInput !== void 0 ? _allowNullPropInput : true,
|
|
125
126
|
__wevu_allowNullPropInput: true
|
|
126
|
-
}
|
|
127
|
+
};
|
|
128
|
+
defineComponent(normalizeProps(baseOptions, props, properties));
|
|
127
129
|
}
|
|
128
130
|
/**
|
|
129
131
|
* scoped slot 兼容组件入口(编译产物内部使用)。
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.mjs","names":[],"sources":["../../../src/runtime/define.ts"],"sourcesContent":["import type { InlineExpressionMap } from './register/inline'\nimport type { TemplateRefBinding } from './templateRefs'\nimport type {\n ComponentPropsOptions,\n ComponentPublicInstance,\n ComputedDefinitions,\n DefineComponent,\n DefineComponentOptions,\n InferProps,\n MethodDefinitions,\n MiniProgramComponentPropertyOption,\n MiniProgramComponentRawOptions,\n ShallowUnwrapRef,\n} from './types'\nimport {\n WEVU_FUNCTION_PROP_PATHS_KEY,\n WEVU_SCOPED_SLOT_CREATOR_KEY,\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_SCOPE_KEY,\n} from '@weapp-core/constants'\nimport { hasOwn } from '../utils'\nimport { createApp } from './app'\nimport { applyWevuComponentDefaults, INTERNAL_DEFAULTS_SCOPE_KEY } from './defaults'\nimport { resolveNativeInitialData } from './define/initialComputed'\nimport { resolveVueComponentOptions } from './define/options'\nimport { applyOptionsApiProvide, resolveOptionsApiInjections } from './define/optionsApi'\nimport { normalizeProps } from './define/props'\nimport { createScopedSlotOptions } from './define/scopedSlotOptions'\nimport { applySetupResult } from './define/setupResult'\nimport { getScopedSlotHostGlobalObject } from './platform'\nimport { registerComponent, runSetupFunction } from './register'\nimport { allocateOwnerId } from './scopedSlots'\n\nlet scopedSlotCreator: (() => void) | undefined\n\nfunction ensureScopedSlotComponentGlobal() {\n const globalObject = getScopedSlotHostGlobalObject()\n if (!globalObject) {\n return\n }\n const globalRecord = globalObject as Record<string, any>\n if (scopedSlotCreator && globalRecord[WEVU_SCOPED_SLOT_CREATOR_KEY] !== scopedSlotCreator) {\n globalRecord[WEVU_SCOPED_SLOT_CREATOR_KEY] = scopedSlotCreator\n }\n}\n\nfunction resolveInitialDataContext(properties: unknown, methods: MethodDefinitions | undefined) {\n const context: Record<string, unknown> = { ...(methods ?? {}) }\n if (!properties || typeof properties !== 'object') {\n return context\n }\n for (const [name, definition] of Object.entries(properties)) {\n if (definition && typeof definition === 'object' && hasOwn(definition, 'value')) {\n context[name] = (definition as Record<string, unknown>).value\n }\n }\n return context\n}\n\nfunction shouldSeedNativeSlotOwnerId(\n mpOptions: Record<string, any>,\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n return Boolean((mpOptions as any).__wevu_isPage)\n && Array.isArray(setData?.pick)\n && setData.pick.includes(WEVU_SLOT_OWNER_ID_KEY)\n}\n\nfunction shouldDeclareNativeSlotOwnerId(\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n return Array.isArray(setData?.pick)\n && setData.pick.includes(WEVU_SLOT_OWNER_ID_KEY)\n}\n\nfunction hasScopedSlotHostProperties(mpOptions: Record<string, any>) {\n const properties = mpOptions.properties\n return Boolean(\n properties\n && typeof properties === 'object'\n && (\n WEVU_SLOT_OWNER_ID_PROP in properties\n || WEVU_SLOT_SCOPE_KEY in properties\n ),\n )\n}\n\nfunction resolveScopedSlotHostSetData(\n mpOptions: Record<string, any>,\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n if (setData?.strategy !== 'patch' || !hasScopedSlotHostProperties(mpOptions)) {\n return setData\n }\n return {\n ...setData,\n strategy: 'diff' as const,\n }\n}\n\n/**\n * defineComponent 返回的组件定义描述,用于手动注册或高级用法。\n */\nexport interface ComponentDefinition<\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> {\n /**\n * 内部 runtime app(高级能力使用),不对外暴露正式 API。\n * @internal\n */\n __wevu_runtime: import('./types').RuntimeApp<D, C, M>\n\n /**\n * 内部选项快照(高级能力使用),包含 data/computed/methods 等。\n * @internal\n */\n __wevu_options: {\n data: () => D\n computed: C\n methods: M\n setData: import('./types').SetDataSnapshotOptions | undefined\n watch: Record<string, any> | undefined\n setup: ((props: any, ctx: any) => any) | undefined\n mpOptions: MiniProgramComponentRawOptions\n }\n}\n\ntype SetupBindings<S> = Exclude<S, void> extends never ? Record<string, never> : Exclude<S, void>\ntype ResolveProps<P> = P extends ComponentPropsOptions ? InferProps<P> : P\n\nexport interface WevuComponentConstructor<\n Props,\n RawBindings,\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> {\n new (): ComponentPublicInstance<D, C, M, Props> & ShallowUnwrapRef<RawBindings>\n}\n\nexport type WevuDefinedComponent<\n PropsOrPropOptions,\n RawBindings,\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> = DefineComponent<PropsOrPropOptions, RawBindings, D, C, M> & ComponentDefinition<D, C, M>\nexport interface SetupContextWithTypeProps<TypeProps> {\n props: TypeProps\n [key: string]: any\n}\nexport type SetupFunctionWithTypeProps<\n TypeProps,\n> = (\n props: TypeProps,\n ctx: SetupContextWithTypeProps<TypeProps>,\n) => Record<string, any> | void\nexport interface DefineComponentTypePropsOptions<TypeProps> {\n __typeProps: TypeProps\n setup?: SetupFunctionWithTypeProps<TypeProps>\n [key: string]: any\n}\nexport interface DefineComponentWithTypeProps<TypeProps> {\n new (): { $props: TypeProps } & Record<string, any>\n}\n\n/**\n * 按 Vue 3 风格定义一个小程序组件/页面。\n *\n * - 统一注册为 `Component()`\n *\n * @param options 组件定义项\n * @returns 可手动注册的组件定义\n *\n * @example\n * ```ts\n * defineComponent({\n * data: () => ({ count: 0 }),\n * setup() {\n * onMounted(() => console.log('已挂载'))\n * }\n * })\n * ```\n *\n * @example\n * ```ts\n * defineComponent({\n * setup() {\n * onPageScroll(() => {})\n * }\n * })\n * ```\n */\n// @ts-expect-error -- TS2589:__typeProps 签名的重载实例化深度过高。\nexport function defineComponent<\n TypeProps = any,\n>(\n options: DefineComponentTypePropsOptions<TypeProps>,\n): DefineComponentWithTypeProps<TypeProps>\nexport function defineComponent<\n P extends ComponentPropsOptions = ComponentPropsOptions,\n D extends object = Record<string, any>,\n C extends ComputedDefinitions = ComputedDefinitions,\n M extends MethodDefinitions = MethodDefinitions,\n S extends Record<string, any> | void = Record<string, any> | void,\n>(\n options: DefineComponentOptions<P, D, C, M, S>,\n): WevuComponentConstructor<ResolveProps<P>, SetupBindings<S>, D, C, M> & ComponentDefinition<D, C, M>\nexport function defineComponent(\n options: DefineComponentOptions<any, any, any, any, any>,\n): WevuComponentConstructor<Record<string, any>, Record<string, any>, Record<string, any>, ComputedDefinitions, MethodDefinitions>\n & ComponentDefinition<any, any, any> {\n ensureScopedSlotComponentGlobal()\n const resolvedOptions = resolveVueComponentOptions(applyWevuComponentDefaults(options))\n const {\n __typeProps: _typeProps,\n data,\n computed,\n methods,\n setData,\n watch,\n setup,\n props,\n inject: injectOptions,\n provide: provideOptions,\n allowFunctionProps,\n ...mpOptions\n } = resolvedOptions\n\n const rawFunctionPropPaths = (mpOptions as any)[WEVU_FUNCTION_PROP_PATHS_KEY]\n const functionPropPaths: string[] = Array.isArray(rawFunctionPropPaths)\n ? [...new Set(rawFunctionPropPaths.filter((path: unknown): path is string => typeof path === 'string' && path.length > 0))]\n : []\n delete (mpOptions as any)[WEVU_FUNCTION_PROP_PATHS_KEY]\n\n const rawResolvedSetData = allowFunctionProps === true\n ? {\n ...(setData ?? {}),\n includeFunctions: true,\n functionPaths: functionPropPaths,\n }\n : allowFunctionProps === false\n ? setData\n : functionPropPaths.length\n ? {\n ...(setData ?? {}),\n functionPaths: functionPropPaths,\n }\n : setData\n const resolvedSetData = resolveScopedSlotHostSetData(mpOptions, rawResolvedSetData)\n const setupFunctionPropKeys = new Set(\n functionPropPaths\n .filter(path => !path.includes('.')),\n )\n\n const normalizedMpOptions = normalizeProps(mpOptions, props)\n const initialDataContext = resolveInitialDataContext(normalizedMpOptions.properties, methods)\n const resolvedData = typeof data === 'function'\n ? () => data.call(initialDataContext)\n : data\n\n const runtimeApp = createApp({\n data: resolvedData,\n computed,\n methods,\n setData: resolvedSetData,\n [INTERNAL_DEFAULTS_SCOPE_KEY]: 'component',\n } as any)\n\n const hasOptionsApiContext = injectOptions != null || provideOptions != null\n const setupWrapper = typeof setup === 'function' || hasOptionsApiContext\n ? ((props, ctx) => {\n const publicInstance = (ctx as any)?.proxy ?? (ctx as any)?.instance ?? Object.create(null)\n const injected = resolveOptionsApiInjections(injectOptions, publicInstance)\n if (provideOptions != null) {\n applyOptionsApiProvide(provideOptions, publicInstance)\n }\n const setupResult = typeof setup === 'function'\n ? runSetupFunction(setup as any, props as Record<string, any>, ctx as any) as Record<string, any> | void\n : undefined\n const result = {\n ...injected,\n ...(setupResult ?? {}),\n }\n if (ctx && Object.keys(result).length) {\n applySetupResult((ctx as any).runtime, (ctx as any).instance, result, {\n includeFunctionsInState: allowFunctionProps === true,\n functionPropPaths: allowFunctionProps === false ? undefined : setupFunctionPropKeys,\n })\n }\n return result\n }) satisfies DefineComponentOptions<ComponentPropsOptions, any, any, any, any>['setup']\n : undefined\n\n const nativeData = typeof resolvedData === 'function'\n ? resolvedData()\n : resolvedData\n const shouldDeclareOwnerId = shouldDeclareNativeSlotOwnerId(resolvedSetData)\n const seededNativeData = shouldDeclareOwnerId\n ? {\n ...(nativeData && typeof nativeData === 'object' ? nativeData : {}),\n [WEVU_SLOT_OWNER_ID_KEY]: shouldSeedNativeSlotOwnerId(mpOptions, resolvedSetData)\n ? (nativeData as any)?.[WEVU_SLOT_OWNER_ID_KEY] || allocateOwnerId()\n : (nativeData as any)?.[WEVU_SLOT_OWNER_ID_KEY] || '',\n }\n : nativeData\n const nativeInitialData = resolveNativeInitialData(seededNativeData, computed as ComputedDefinitions, resolvedSetData)\n const mpOptionsWithProps = nativeInitialData !== undefined\n ? {\n ...normalizedMpOptions,\n data: nativeInitialData,\n }\n : normalizedMpOptions\n\n const componentOptions = {\n data: resolvedData as () => Record<string, any>,\n computed: computed as ComputedDefinitions,\n methods: methods as MethodDefinitions,\n setData: resolvedSetData,\n watch,\n setup: setupWrapper,\n mpOptions: mpOptionsWithProps,\n }\n\n registerComponent(runtimeApp as any, methods ?? {}, watch as any, setupWrapper as any, mpOptionsWithProps as any)\n\n // 返回组件定义,便于外部自行注册\n const definition: ComponentDefinition<any, any, any> = {\n __wevu_runtime: runtimeApp as any,\n __wevu_options: componentOptions as ComponentDefinition<any, any, any>['__wevu_options'],\n }\n\n return definition as unknown as WevuComponentConstructor<\n ResolveProps<ComponentPropsOptions>,\n Record<string, any>,\n Record<string, any>,\n ComputedDefinitions,\n MethodDefinitions\n > & ComponentDefinition<any, any, any>\n}\n\n/**\n * 从 Vue SFC 选项创建 wevu 组件,供 weapp-vite 编译产物直接调用的兼容入口。\n *\n * @param options 组件选项,可能包含小程序特有的 properties\n * @internal\n */\nexport function createWevuComponent<\n P extends ComponentPropsOptions = ComponentPropsOptions,\n D extends object = Record<string, any>,\n C extends ComputedDefinitions = ComputedDefinitions,\n M extends MethodDefinitions = MethodDefinitions,\n>(\n options: DefineComponentOptions<P, D, C, M> & { properties?: MiniProgramComponentPropertyOption },\n): void {\n ensureScopedSlotComponentGlobal()\n const {\n properties,\n props,\n ...restOptions\n } = options\n\n const baseOptions = {\n ...restOptions,\n allowNullPropInput: (restOptions as any).allowNullPropInput ?? true,\n __wevu_allowNullPropInput: true,\n }\n\n // 将 properties 合并到 mpOptions,保持小程序属性定义\n const finalOptions = normalizeProps(baseOptions, props, properties)\n\n defineComponent(finalOptions)\n}\n\n/**\n * scoped slot 兼容组件入口(编译产物内部使用)。\n * @internal\n */\nexport function createWevuScopedSlotComponent(\n overrides?: {\n computed?: ComputedDefinitions\n inlineMap?: InlineExpressionMap\n templateRefs?: TemplateRefBinding[]\n },\n): void {\n const baseOptions = createScopedSlotOptions(overrides)\n createWevuComponent(baseOptions as any)\n}\n\nscopedSlotCreator = createWevuScopedSlotComponent\nensureScopedSlotComponentGlobal()\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,IAAI;AAEJ,SAAS,kCAAkC;CACzC,MAAM,eAAe,8BAA8B;CACnD,IAAI,CAAC,cACH;CAEF,MAAM,eAAe;CACrB,IAAI,qBAAqB,aAAa,kCAAkC,mBACtE,aAAa,gCAAgC;AAEjD;AAEA,SAAS,0BAA0B,YAAqB,SAAwC;CAC9F,MAAM,UAAmC,EAAE,GAAI,mDAAW,CAAC,EAAG;CAC9D,IAAI,CAAC,cAAc,OAAO,eAAe,UACvC,OAAO;CAET,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,UAAU,GACxD,IAAI,cAAc,OAAO,eAAe,YAAY,OAAO,YAAY,OAAO,GAC5E,QAAQ,QAAS,WAAuC;CAG5D,OAAO;AACT;AAEA,SAAS,4BACP,WACA,SACA;CACA,OAAO,QAAS,UAAkB,aAAa,KAC1C,MAAM,0DAAQ,QAAS,IAAI,KAC3B,QAAQ,KAAK,SAAS,sBAAsB;AACnD;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B,eAAe;EANlC,GAAG;EACH,2CAAqB,YAAoB,uFAAsB;EAC/D,2BAA2B;CAIiB,GAAG,OAAO,UAE7B,CAAC;AAC9B;;;;;AAMA,SAAgB,8BACd,WAKM;CAEN,oBADoB,wBAAwB,SACd,CAAQ;AACxC;AAEA,oBAAoB;AACpB,gCAAgC"}
|
|
1
|
+
{"version":3,"file":"define.mjs","names":[],"sources":["../../../src/runtime/define.ts"],"sourcesContent":["import type { InlineExpressionMap } from './register/inline'\nimport type { TemplateRefBinding } from './templateRefs'\nimport type {\n ComponentPropsOptions,\n ComponentPublicInstance,\n ComputedDefinitions,\n DefineComponent,\n DefineComponentOptions,\n InferProps,\n MethodDefinitions,\n MiniProgramComponentPropertyOption,\n MiniProgramComponentRawOptions,\n ShallowUnwrapRef,\n} from './types'\nimport {\n WEVU_FUNCTION_PROP_PATHS_KEY,\n WEVU_SCOPED_SLOT_CREATOR_KEY,\n WEVU_SLOT_OWNER_ID_KEY,\n WEVU_SLOT_OWNER_ID_PROP,\n WEVU_SLOT_SCOPE_KEY,\n} from '@weapp-core/constants'\nimport { hasOwn } from '../utils'\nimport { createApp } from './app'\nimport { applyWevuComponentDefaults, INTERNAL_DEFAULTS_SCOPE_KEY } from './defaults'\nimport { resolveNativeInitialData } from './define/initialComputed'\nimport { resolveVueComponentOptions } from './define/options'\nimport { applyOptionsApiProvide, resolveOptionsApiInjections } from './define/optionsApi'\nimport { normalizeProps } from './define/props'\nimport { createScopedSlotOptions } from './define/scopedSlotOptions'\nimport { applySetupResult } from './define/setupResult'\nimport { getScopedSlotHostGlobalObject } from './platform'\nimport { registerComponent, runSetupFunction } from './register'\nimport { allocateOwnerId } from './scopedSlots'\n\nlet scopedSlotCreator: (() => void) | undefined\n\nfunction ensureScopedSlotComponentGlobal() {\n const globalObject = getScopedSlotHostGlobalObject()\n if (!globalObject) {\n return\n }\n const globalRecord = globalObject as Record<string, any>\n if (scopedSlotCreator && globalRecord[WEVU_SCOPED_SLOT_CREATOR_KEY] !== scopedSlotCreator) {\n globalRecord[WEVU_SCOPED_SLOT_CREATOR_KEY] = scopedSlotCreator\n }\n}\n\nfunction resolveInitialDataContext(properties: unknown, methods: MethodDefinitions | undefined) {\n const context: Record<string, unknown> = { ...(methods ?? {}) }\n if (!properties || typeof properties !== 'object') {\n return context\n }\n for (const [name, definition] of Object.entries(properties)) {\n if (definition && typeof definition === 'object' && hasOwn(definition, 'value')) {\n context[name] = (definition as Record<string, unknown>).value\n }\n }\n return context\n}\n\nfunction shouldSeedNativeSlotOwnerId(\n mpOptions: Record<string, any>,\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n return Boolean((mpOptions as any).__wevu_isPage)\n && Array.isArray(setData?.pick)\n && setData.pick.includes(WEVU_SLOT_OWNER_ID_KEY)\n}\n\nfunction shouldDeclareNativeSlotOwnerId(\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n return Array.isArray(setData?.pick)\n && setData.pick.includes(WEVU_SLOT_OWNER_ID_KEY)\n}\n\nfunction hasScopedSlotHostProperties(mpOptions: Record<string, any>) {\n const properties = mpOptions.properties\n return Boolean(\n properties\n && typeof properties === 'object'\n && (\n WEVU_SLOT_OWNER_ID_PROP in properties\n || WEVU_SLOT_SCOPE_KEY in properties\n ),\n )\n}\n\nfunction resolveScopedSlotHostSetData(\n mpOptions: Record<string, any>,\n setData: DefineComponentOptions<any, any, any, any, any>['setData'],\n) {\n if (setData?.strategy !== 'patch' || !hasScopedSlotHostProperties(mpOptions)) {\n return setData\n }\n return {\n ...setData,\n strategy: 'diff' as const,\n }\n}\n\n/**\n * defineComponent 返回的组件定义描述,用于手动注册或高级用法。\n */\nexport interface ComponentDefinition<\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> {\n /**\n * 内部 runtime app(高级能力使用),不对外暴露正式 API。\n * @internal\n */\n __wevu_runtime: import('./types').RuntimeApp<D, C, M>\n\n /**\n * 内部选项快照(高级能力使用),包含 data/computed/methods 等。\n * @internal\n */\n __wevu_options: {\n data: () => D\n computed: C\n methods: M\n setData: import('./types').SetDataSnapshotOptions | undefined\n watch: Record<string, any> | undefined\n setup: ((props: any, ctx: any) => any) | undefined\n mpOptions: MiniProgramComponentRawOptions\n }\n}\n\ntype SetupBindings<S> = Exclude<S, void> extends never ? Record<string, never> : Exclude<S, void>\ntype ResolveProps<P> = P extends ComponentPropsOptions ? InferProps<P> : P\n\nexport interface WevuComponentConstructor<\n Props,\n RawBindings,\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> {\n new (): ComponentPublicInstance<D, C, M, Props> & ShallowUnwrapRef<RawBindings>\n}\n\nexport type WevuDefinedComponent<\n PropsOrPropOptions,\n RawBindings,\n D extends object,\n C extends ComputedDefinitions,\n M extends MethodDefinitions,\n> = DefineComponent<PropsOrPropOptions, RawBindings, D, C, M> & ComponentDefinition<D, C, M>\nexport interface SetupContextWithTypeProps<TypeProps> {\n props: TypeProps\n [key: string]: any\n}\nexport type SetupFunctionWithTypeProps<\n TypeProps,\n> = (\n props: TypeProps,\n ctx: SetupContextWithTypeProps<TypeProps>,\n) => Record<string, any> | void\nexport interface DefineComponentTypePropsOptions<TypeProps> {\n __typeProps: TypeProps\n setup?: SetupFunctionWithTypeProps<TypeProps>\n [key: string]: any\n}\nexport interface DefineComponentWithTypeProps<TypeProps> {\n new (): { $props: TypeProps } & Record<string, any>\n}\n\n/**\n * 按 Vue 3 风格定义一个小程序组件/页面。\n *\n * - 统一注册为 `Component()`\n *\n * @param options 组件定义项\n * @returns 可手动注册的组件定义\n *\n * @example\n * ```ts\n * defineComponent({\n * data: () => ({ count: 0 }),\n * setup() {\n * onMounted(() => console.log('已挂载'))\n * }\n * })\n * ```\n *\n * @example\n * ```ts\n * defineComponent({\n * setup() {\n * onPageScroll(() => {})\n * }\n * })\n * ```\n */\n// @ts-expect-error -- TS2589:__typeProps 签名的重载实例化深度过高。\nexport function defineComponent<\n TypeProps = any,\n>(\n options: DefineComponentTypePropsOptions<TypeProps>,\n): DefineComponentWithTypeProps<TypeProps>\nexport function defineComponent<\n P extends ComponentPropsOptions = ComponentPropsOptions,\n D extends object = Record<string, any>,\n C extends ComputedDefinitions = ComputedDefinitions,\n M extends MethodDefinitions = MethodDefinitions,\n S extends Record<string, any> | void = Record<string, any> | void,\n>(\n options: DefineComponentOptions<P, D, C, M, S>,\n): WevuComponentConstructor<ResolveProps<P>, SetupBindings<S>, D, C, M> & ComponentDefinition<D, C, M>\nexport function defineComponent(\n options: DefineComponentOptions<any, any, any, any, any>,\n): WevuComponentConstructor<Record<string, any>, Record<string, any>, Record<string, any>, ComputedDefinitions, MethodDefinitions>\n & ComponentDefinition<any, any, any> {\n ensureScopedSlotComponentGlobal()\n const resolvedOptions = resolveVueComponentOptions(applyWevuComponentDefaults(options))\n const {\n __typeProps: _typeProps,\n data,\n computed,\n methods,\n setData,\n watch,\n setup,\n props,\n inject: injectOptions,\n provide: provideOptions,\n allowFunctionProps,\n ...mpOptions\n } = resolvedOptions\n\n const rawFunctionPropPaths = (mpOptions as any)[WEVU_FUNCTION_PROP_PATHS_KEY]\n const functionPropPaths: string[] = Array.isArray(rawFunctionPropPaths)\n ? [...new Set(rawFunctionPropPaths.filter((path: unknown): path is string => typeof path === 'string' && path.length > 0))]\n : []\n delete (mpOptions as any)[WEVU_FUNCTION_PROP_PATHS_KEY]\n\n const rawResolvedSetData = allowFunctionProps === true\n ? {\n ...(setData ?? {}),\n includeFunctions: true,\n functionPaths: functionPropPaths,\n }\n : allowFunctionProps === false\n ? setData\n : functionPropPaths.length\n ? {\n ...(setData ?? {}),\n functionPaths: functionPropPaths,\n }\n : setData\n const resolvedSetData = resolveScopedSlotHostSetData(mpOptions, rawResolvedSetData)\n const setupFunctionPropKeys = new Set(\n functionPropPaths\n .filter(path => !path.includes('.')),\n )\n\n const normalizedMpOptions = normalizeProps(mpOptions, props)\n const initialDataContext = resolveInitialDataContext(normalizedMpOptions.properties, methods)\n const resolvedData = typeof data === 'function'\n ? () => data.call(initialDataContext)\n : data\n\n const runtimeApp = createApp({\n data: resolvedData,\n computed,\n methods,\n setData: resolvedSetData,\n [INTERNAL_DEFAULTS_SCOPE_KEY]: 'component',\n } as any)\n\n const hasOptionsApiContext = injectOptions != null || provideOptions != null\n const setupWrapper = typeof setup === 'function' || hasOptionsApiContext\n ? ((props, ctx) => {\n const publicInstance = (ctx as any)?.proxy ?? (ctx as any)?.instance ?? Object.create(null)\n const injected = resolveOptionsApiInjections(injectOptions, publicInstance)\n if (provideOptions != null) {\n applyOptionsApiProvide(provideOptions, publicInstance)\n }\n const setupResult = typeof setup === 'function'\n ? runSetupFunction(setup as any, props as Record<string, any>, ctx as any) as Record<string, any> | void\n : undefined\n const result = {\n ...injected,\n ...(setupResult ?? {}),\n }\n if (ctx && Object.keys(result).length) {\n applySetupResult((ctx as any).runtime, (ctx as any).instance, result, {\n includeFunctionsInState: allowFunctionProps === true,\n functionPropPaths: allowFunctionProps === false ? undefined : setupFunctionPropKeys,\n })\n }\n return result\n }) satisfies DefineComponentOptions<ComponentPropsOptions, any, any, any, any>['setup']\n : undefined\n\n const nativeData = typeof resolvedData === 'function'\n ? resolvedData()\n : resolvedData\n const shouldDeclareOwnerId = shouldDeclareNativeSlotOwnerId(resolvedSetData)\n const seededNativeData = shouldDeclareOwnerId\n ? {\n ...(nativeData && typeof nativeData === 'object' ? nativeData : {}),\n [WEVU_SLOT_OWNER_ID_KEY]: shouldSeedNativeSlotOwnerId(mpOptions, resolvedSetData)\n ? (nativeData as any)?.[WEVU_SLOT_OWNER_ID_KEY] || allocateOwnerId()\n : (nativeData as any)?.[WEVU_SLOT_OWNER_ID_KEY] || '',\n }\n : nativeData\n const nativeInitialData = resolveNativeInitialData(seededNativeData, computed as ComputedDefinitions, resolvedSetData)\n const mpOptionsWithProps = nativeInitialData !== undefined\n ? {\n ...normalizedMpOptions,\n data: nativeInitialData,\n }\n : normalizedMpOptions\n\n const componentOptions = {\n data: resolvedData as () => Record<string, any>,\n computed: computed as ComputedDefinitions,\n methods: methods as MethodDefinitions,\n setData: resolvedSetData,\n watch,\n setup: setupWrapper,\n mpOptions: mpOptionsWithProps,\n }\n\n registerComponent(runtimeApp as any, methods ?? {}, watch as any, setupWrapper as any, mpOptionsWithProps as any)\n\n // 返回组件定义,便于外部自行注册\n const definition: ComponentDefinition<any, any, any> = {\n __wevu_runtime: runtimeApp as any,\n __wevu_options: componentOptions as ComponentDefinition<any, any, any>['__wevu_options'],\n }\n\n return definition as unknown as WevuComponentConstructor<\n ResolveProps<ComponentPropsOptions>,\n Record<string, any>,\n Record<string, any>,\n ComputedDefinitions,\n MethodDefinitions\n > & ComponentDefinition<any, any, any>\n}\n\n/**\n * 从 Vue SFC 选项创建 wevu 组件,供 weapp-vite 编译产物直接调用的兼容入口。\n *\n * @param options 组件选项,可能包含小程序特有的 properties\n * @internal\n */\nexport function createWevuComponent<\n P extends ComponentPropsOptions = ComponentPropsOptions,\n D extends object = Record<string, any>,\n C extends ComputedDefinitions = ComputedDefinitions,\n M extends MethodDefinitions = MethodDefinitions,\n>(\n options: DefineComponentOptions<P, D, C, M> & { properties?: MiniProgramComponentPropertyOption },\n): void {\n ensureScopedSlotComponentGlobal()\n const {\n properties,\n props,\n ...restOptions\n } = options\n\n const baseOptions = {\n ...restOptions,\n allowNullPropInput: (restOptions as any).allowNullPropInput ?? true,\n __wevu_allowNullPropInput: true,\n }\n\n // 将 properties 合并到 mpOptions,保持小程序属性定义\n const finalOptions = normalizeProps(baseOptions, props, properties)\n\n defineComponent(finalOptions)\n}\n\n/**\n * scoped slot 兼容组件入口(编译产物内部使用)。\n * @internal\n */\nexport function createWevuScopedSlotComponent(\n overrides?: {\n computed?: ComputedDefinitions\n inlineMap?: InlineExpressionMap\n templateRefs?: TemplateRefBinding[]\n },\n): void {\n const baseOptions = createScopedSlotOptions(overrides)\n createWevuComponent(baseOptions as any)\n}\n\nscopedSlotCreator = createWevuScopedSlotComponent\nensureScopedSlotComponentGlobal()\n"],"mappings":";;;;;;;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C,aAAa,IACb;CAEJ,MAAM,mBADuB,+BAA+B,eAChB,IACxC;EACE,GAAI,cAAc,OAAO,eAAe,WAAW,aAAa,CAAC;GAChE,yBAAyB,4BAA4B,WAAW,eAAe,6DAC3E,WAAqB,4BAA2B,gBAAgB,6DAChE,WAAqB,4BAA2B;CACvD,IACA;CACJ,MAAM,oBAAoB,yBAAyB,kBAAkB,UAAiC,eAAe;CACrH,MAAM,qBAAqB,sBAAsB,SAC7C;EACE,GAAG;EACH,MAAM;CACR,IACA;CAEJ,MAAM,mBAAmB;EACvB,MAAM;EACI;EACD;EACT,SAAS;EACT;EACA,OAAO;EACP,WAAW;CACb;CAEA,kBAAkB,YAAmB,mDAAW,CAAC,GAAG,OAAc,cAAqB,kBAAyB;CAQhH,OAAO;EAJL,gBAAgB;EAChB,gBAAgB;CAGF;AAOlB;;;;;;;AAQA,SAAgB,oBAMd,SACM;;CACN,gCAAgC;CAChC,MAAM,EACJ,YACA,OACA,GAAG,gBACD;CAEJ,MAAM,cAAc;EAClB,GAAG;EACH,2CAAqB,YAAoB,uFAAsB;EAC/D,2BAA2B;CAC7B;CAKA,gBAFqB,eAAe,aAAa,OAAO,UAE7B,CAAC;AAC9B;;;;;AAMA,SAAgB,8BACd,WAKM;CAEN,oBADoB,wBAAwB,SACd,CAAQ;AACxC;AAEA,oBAAoB;AACpB,gCAAgC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"layoutBridge.mjs","names":[],"sources":["../../../src/runtime/layoutBridge.ts"],"sourcesContent":["import type { Ref } from '../reactivity'\nimport {\n WEVU_LAYOUT_BRIDGE_PAGE_KEYS,\n WEVU_NATIVE_INSTANCE_KEY,\n WEVU_PUBLIC_RUNTIME_KEY,\n} from '@weapp-core/constants'\nimport { isRef } from '../reactivity'\nimport { getCurrentInstance, getCurrentSetupContext, onAttached, onDetached } from './hooks'\nimport { getCurrentMiniProgramPages } from './platform'\nimport { getTemplateRefMap } from './templateRefs/helpers'\n\ntype LayoutBridgeContext = Record<string, any>\ntype LayoutBridgeComponentResolver = (selector: string) => any\ntype LayoutHostMap = Record<string, unknown>\nexport type LayoutBridgeInstance<T = LayoutBridgeContext> = T & {\n selectComponent?: LayoutBridgeComponentResolver\n}\nexport interface LayoutHostBinding {\n key: string\n refName?: string\n selector: string\n kind?: 'component'\n}\ninterface LayoutHostResolveOptions<T = any> {\n context?: T\n fallbackContext?: T\n interval?: number\n retries?: number\n}\n\n/**\n * @description 对 layout host key 去重并过滤空字符串。\n */\nfunction normalizeLayoutHostKeys(keys: string | string[]) {\n return Array.from(new Set(Array.isArray(keys) ? keys : [keys]))\n .filter((key): key is string => typeof key === 'string' && key.length > 0)\n}\n\n/**\n * @description 解析小程序页面实例的稳定身份 key。\n */\nfunction resolvePageIdentityKeys(page?: Record<string, any>): string[] {\n if (!page || typeof page !== 'object') {\n return []\n }\n\n const keys: string[] = []\n const route = typeof page.route === 'string' ? page.route.replace(/^\\/+/, '') : ''\n if (route) {\n keys.push(`route:${route}`)\n }\n for (const [prefix, field] of [\n ['webview', '__wxWebviewId__'],\n ['exparser', '__wxExparserNodeId__'],\n ] as const) {\n const value = page[field]\n if (typeof value === 'number' || typeof value === 'string') {\n keys.push(`${prefix}:${String(value)}`)\n }\n }\n\n return Array.from(new Set(keys))\n}\n\n/**\n * @description 创建小程序 layout host 注册表。\n */\nfunction createLayoutHostRegistry<TBridge>() {\n const registries = new Map<string, Map<string, TBridge>>()\n\n function register(keys: string | string[], bridge: TBridge, pageKeys: string[]) {\n const normalizedKeys = normalizeLayoutHostKeys(keys)\n if (normalizedKeys.length === 0 || pageKeys.length === 0) {\n return null\n }\n\n for (const pageKey of pageKeys) {\n const registry = registries.get(pageKey) ?? new Map<string, TBridge>()\n for (const key of normalizedKeys) {\n registry.set(key, bridge)\n }\n registries.set(pageKey, registry)\n }\n\n return normalizedKeys\n }\n\n function unregister(keys: string | string[], bridge: TBridge, pageKeys: string[]) {\n const normalizedKeys = normalizeLayoutHostKeys(keys)\n if (normalizedKeys.length === 0 || pageKeys.length === 0) {\n return false\n }\n\n let removed = false\n for (const pageKey of pageKeys) {\n const registry = registries.get(pageKey)\n if (!registry) {\n continue\n }\n\n for (const key of normalizedKeys) {\n if (registry.get(key) === bridge) {\n registry.delete(key)\n removed = true\n }\n }\n\n if (registry.size === 0) {\n registries.delete(pageKey)\n }\n }\n\n return removed\n }\n\n function resolveBridge(key: string, pageKeys: string[]) {\n return pageKeys\n .map(pageKey => registries.get(pageKey)?.get(key))\n .find(Boolean)\n }\n\n function resolveHost<THost>(\n key: string,\n pageKeys: string[],\n resolver: (bridge: TBridge, key: string) => THost | null | undefined,\n ) {\n const bridge = resolveBridge(key, pageKeys)\n if (!bridge) {\n return null\n }\n return resolver(bridge, key) ?? null\n }\n\n function waitForHost<THost>(\n key: string,\n resolvePageKeys: () => string[],\n resolver: (bridge: TBridge, key: string) => THost | null | undefined,\n options: { interval?: number, retries?: number } = {},\n ): Promise<THost | null> {\n const retries = options.retries ?? 20\n const interval = options.interval ?? 16\n const host = resolveHost(key, resolvePageKeys(), resolver)\n if (host || retries <= 0) {\n return Promise.resolve(host)\n }\n\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(waitForHost(key, resolvePageKeys, resolver, {\n ...options,\n retries: retries - 1,\n }))\n }, interval)\n })\n }\n\n return {\n register,\n resolveBridge,\n resolveHost,\n unregister,\n waitForHost,\n }\n}\n\nconst pageLayoutBridgeRegistry = createLayoutHostRegistry<LayoutBridgeContext>()\n\nfunction resolveCurrentPageInstance() {\n const pages = getCurrentMiniProgramPages()\n return pages[pages.length - 1]\n}\n\nfunction resolvePageKeys(page?: LayoutBridgeContext) {\n return resolvePageIdentityKeys(page as Record<string, any> | undefined)\n}\n\nfunction resolveNativeLayoutContext(context?: LayoutBridgeContext) {\n if (!context || typeof context !== 'object') {\n return undefined\n }\n\n const runtimeNativeInstance = context[WEVU_PUBLIC_RUNTIME_KEY]?.state?.[WEVU_NATIVE_INSTANCE_KEY]\n if (runtimeNativeInstance && typeof runtimeNativeInstance === 'object') {\n return runtimeNativeInstance as LayoutBridgeContext\n }\n\n const stateNativeInstance = context.$state?.[WEVU_NATIVE_INSTANCE_KEY]\n if (stateNativeInstance && typeof stateNativeInstance === 'object') {\n return stateNativeInstance as LayoutBridgeContext\n }\n\n if (context[WEVU_NATIVE_INSTANCE_KEY] && typeof context[WEVU_NATIVE_INSTANCE_KEY] === 'object') {\n return context[WEVU_NATIVE_INSTANCE_KEY] as LayoutBridgeContext\n }\n\n return context\n}\n\nfunction resolvePageFromContext(\n context?: LayoutBridgeContext,\n visited = new Set<LayoutBridgeContext>(),\n): LayoutBridgeContext | undefined {\n if (!context || typeof context !== 'object' || visited.has(context)) {\n return resolveCurrentPageInstance()\n }\n visited.add(context)\n\n if (typeof context.__wevuSetPageLayout === 'function') {\n return context\n }\n\n const nativeContext = resolveNativeLayoutContext(context)\n if (nativeContext && nativeContext !== context) {\n const nativePage = resolvePageFromContext(nativeContext, visited)\n if (nativePage) {\n return nativePage\n }\n }\n\n const publicNativePage = context.$\n if (publicNativePage && typeof publicNativePage === 'object') {\n const nativePage = resolvePageFromContext(publicNativePage as LayoutBridgeContext, visited)\n if (nativePage) {\n return nativePage\n }\n }\n\n const ownerContext = nativeContext ?? context\n const selectOwnerComponent = ownerContext.selectOwnerComponent\n if (typeof selectOwnerComponent === 'function') {\n try {\n const owner = selectOwnerComponent.call(ownerContext) as LayoutBridgeContext | undefined\n if (owner && owner !== ownerContext) {\n const ownerPage = resolvePageFromContext(owner, visited)\n if (ownerPage) {\n return ownerPage\n }\n }\n }\n catch {\n // 部分宿主或生命周期阶段暂不支持 owner 查询,继续使用页面栈兜底。\n }\n }\n\n return resolveCurrentPageInstance()\n}\n\nfunction resolveHostEntry(entry: unknown) {\n if (typeof entry === 'function') {\n return (entry as () => unknown)()\n }\n if (isRef(entry as Ref<unknown>)) {\n return (entry as Ref<unknown>).value\n }\n return entry\n}\n\nfunction findLayoutHostBinding(bindings: LayoutHostBinding[], key: string) {\n return bindings.find(binding => binding.key === key)\n}\n\nfunction safeSelectComponent(target: LayoutBridgeContext | undefined, selector: string) {\n const selectComponent = target?.selectComponent\n if (typeof selectComponent !== 'function') {\n return null\n }\n try {\n return selectComponent.call(target, selector) ?? null\n }\n catch {\n return null\n }\n}\n\nfunction resolveDeclaredLayoutHostFromRefs(\n binding: LayoutHostBinding,\n context: LayoutBridgeContext,\n) {\n if (!binding.refName) {\n return null\n }\n const refMap = getTemplateRefMap(context as any)\n const stateRefs = context[WEVU_PUBLIC_RUNTIME_KEY]?.state?.$refs\n ?? context.__wevu?.state?.$refs\n ?? context.$state?.$refs\n ?? context.$refs\n const refValue = refMap?.get(binding.refName)?.value\n ?? stateRefs?.[binding.refName]\n if (Array.isArray(refValue)) {\n return refValue[0] ?? null\n }\n return refValue ?? null\n}\n\nfunction createDeclaredLayoutHostBridge(bindings: LayoutHostBinding[], context: LayoutBridgeContext) {\n const nativeContext = resolveNativeLayoutContext(context)\n const bridgeBase = nativeContext && typeof nativeContext === 'object'\n ? Object.create(nativeContext)\n : {}\n return Object.assign(bridgeBase, {\n selectComponent(key: string) {\n const binding = findLayoutHostBinding(bindings, key)\n if (!binding) {\n return null\n }\n if (binding.kind === 'component' || !binding.kind) {\n const cachedHost = resolveDeclaredLayoutHostFromRefs(binding, context)\n if (cachedHost) {\n return cachedHost\n }\n return safeSelectComponent(nativeContext, binding.selector)\n ?? safeSelectComponent(resolveCurrentPageInstance(), binding.selector)\n ?? null\n }\n return null\n },\n })\n}\n\n/**\n * 为当前页面注册 layout bridge,使页面或子组件可消费 layout 内部能力。\n */\nexport function registerPageLayoutBridge(\n selectors: string | string[],\n context?: LayoutBridgeContext,\n) {\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n const page = resolvePageFromContext(bridgeContext)\n const pageKeys = resolvePageKeys(page)\n if (!bridgeContext || !page || pageKeys.length === 0) {\n return false\n }\n\n const normalizedSelectors = pageLayoutBridgeRegistry.register(selectors, bridgeContext, pageKeys)\n if (!normalizedSelectors) {\n return false\n }\n\n bridgeContext[WEVU_LAYOUT_BRIDGE_PAGE_KEYS] = pageKeys\n return true\n}\n\n/**\n * 移除当前页面的 layout bridge 注册。\n */\nexport function unregisterPageLayoutBridge(\n selectors: string | string[],\n context?: LayoutBridgeContext,\n) {\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n const page = resolvePageFromContext(bridgeContext)\n const pageKeys = bridgeContext?.[WEVU_LAYOUT_BRIDGE_PAGE_KEYS] ?? resolvePageKeys(page)\n if (!bridgeContext || !Array.isArray(pageKeys) || pageKeys.length === 0) {\n return false\n }\n\n const removed = pageLayoutBridgeRegistry.unregister(selectors, bridgeContext, pageKeys)\n delete bridgeContext[WEVU_LAYOUT_BRIDGE_PAGE_KEYS]\n return removed\n}\n\n/**\n * 解析当前页面已注册的 layout bridge,找不到时回退到传入上下文。\n */\nexport function resolveLayoutBridge<T = any>(\n selector: string,\n fallbackContext?: T,\n) {\n const page = resolveCurrentPageInstance() ?? resolvePageFromContext(fallbackContext as LayoutBridgeContext | undefined)\n const bridgeContext = pageLayoutBridgeRegistry.resolveBridge(selector, resolvePageKeys(page))\n return (bridgeContext ?? fallbackContext ?? getCurrentInstance()) as LayoutBridgeInstance<T> | undefined\n}\n\n/**\n * 解析当前页面 layout 内通过指定 key 暴露的宿主实例。\n */\nexport function resolveLayoutHost<T = any, C = any>(\n key: string,\n options: LayoutHostResolveOptions<C> = {},\n) {\n const context = options.context ?? options.fallbackContext\n const page = resolveCurrentPageInstance() ?? resolvePageFromContext(context as LayoutBridgeContext | undefined)\n return pageLayoutBridgeRegistry.resolveHost<T>(\n key,\n resolvePageKeys(page),\n (bridge, key) => bridge.selectComponent?.(key) as T | null,\n )\n}\n\n/**\n * 等待当前页面 layout 宿主实例可用,适合页面初次进入时的异步宿主解析。\n */\nexport function waitForLayoutHost<T = any, C = any>(\n key: string,\n options: LayoutHostResolveOptions<C> = {},\n) {\n const context = options.context ?? options.fallbackContext\n return pageLayoutBridgeRegistry.waitForHost<T>(\n key,\n () => resolvePageKeys(resolveCurrentPageInstance() ?? resolvePageFromContext(context as LayoutBridgeContext | undefined)),\n (bridge, key) => bridge.selectComponent?.(key) as T | null,\n options,\n )\n}\n\n/**\n * 在 layout 生命周期内暴露 bridge,使页面或子组件可访问 layout 内部实例。\n */\nexport function useLayoutBridge(\n selectors: string | string[],\n options: {\n resolveComponent?: LayoutBridgeComponentResolver\n } = {},\n) {\n if (!getCurrentSetupContext()) {\n throw new Error('useLayoutBridge() 必须在 setup() 的同步阶段调用')\n }\n\n const context = getCurrentInstance<LayoutBridgeContext>()\n const normalizedSelectors = normalizeLayoutHostKeys(selectors)\n const resolveComponent = options.resolveComponent\n const nativeContext = resolveNativeLayoutContext(context)\n const bridgeBase = nativeContext && typeof nativeContext === 'object'\n ? Object.create(nativeContext)\n : {}\n const bridge = Object.assign(bridgeBase, {\n selectComponent(selector: string) {\n if (!normalizedSelectors.includes(selector)) {\n return null\n }\n\n const resolvedComponent = resolveComponent?.(selector)\n if (resolvedComponent !== undefined) {\n return resolvedComponent\n }\n\n const nativeContext = resolveNativeLayoutContext(context)\n const directMatch = nativeContext?.selectComponent?.(selector)\n if (directMatch) {\n return directMatch\n }\n\n const currentPage = resolveCurrentPageInstance()\n return currentPage?.selectComponent?.(selector) ?? null\n },\n })\n\n registerPageLayoutBridge(normalizedSelectors, bridge)\n\n onAttached(() => {\n registerPageLayoutBridge(normalizedSelectors, bridge)\n })\n\n onDetached(() => {\n unregisterPageLayoutBridge(normalizedSelectors, bridge)\n })\n}\n\n/**\n * 使用编译期注入的宿主绑定信息,直接从当前 layout 运行时实例解析子组件宿主并注册 bridge。\n */\nexport function registerRuntimeLayoutHosts(\n bindings: LayoutHostBinding[],\n context?: LayoutBridgeContext,\n) {\n if (!bindings.length) {\n return null\n }\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n if (!bridgeContext) {\n return null\n }\n const bridge = createDeclaredLayoutHostBridge(bindings, bridgeContext)\n registerPageLayoutBridge(bindings.map(binding => binding.key), bridge)\n return bridge\n}\n\n/**\n * 移除运行时自动注册的 layout 宿主 bridge。\n */\nexport function unregisterRuntimeLayoutHosts(\n bindings: LayoutHostBinding[],\n context?: LayoutBridgeContext,\n) {\n if (!bindings.length) {\n return false\n }\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n if (!bridgeContext) {\n return false\n }\n return unregisterPageLayoutBridge(\n bindings.map(binding => binding.key),\n bridgeContext,\n )\n}\n\n/**\n * 使用 key -> 宿主实例的映射批量暴露 layout 内部宿主,适合 toast/dialog 等共享反馈节点。\n */\nexport function useLayoutHosts(hosts: LayoutHostMap) {\n const selectors = Object.keys(hosts)\n useLayoutBridge(selectors, {\n resolveComponent(key) {\n return resolveHostEntry(hosts[key])\n },\n })\n}\n"],"mappings":";;;;;;;;;;;AAiCA,SAAS,wBAAwB,MAAyB;CACxD,OAAO,MAAM,KAAK,IAAI,IAAI,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAC5D,QAAQ,QAAuB,OAAO,QAAQ,YAAY,IAAI,SAAS,CAAC;AAC7E;;;;AAKA,SAAS,wBAAwB,MAAsC;CACrE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO,CAAC;CAGV,MAAM,OAAiB,CAAC;CACxB,MAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,MAAM,QAAQ,QAAQ,EAAE,IAAI;CAChF,IAAI,OACF,KAAK,KAAK,SAAS,OAAO;CAE5B,KAAK,MAAM,CAAC,QAAQ,UAAU,CAC5B,CAAC,WAAW,iBAAiB,GAC7B,CAAC,YAAY,sBAAsB,CACrC,GAAY;EACV,MAAM,QAAQ,KAAK;EACnB,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,UAChD,KAAK,KAAK,GAAG,OAAO,GAAG,OAAO,KAAK,GAAG;CAE1C;CAEA,OAAO,MAAM,KAAK,IAAI,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AAM;CACtD,CAAC;CAED,iBAAiB;EACf,2BAA2B,qBAAqB,MAAM;CACxD,CAAC;AACH;;;;AAKA,SAAgB,2BACd,UACA,SACA;CACA,IAAI,CAAC,SAAS,QACZ,OAAO;CAET,MAAM,gBAAgB,mDAAW,mBAAwC;CACzE,IAAI,CAAC,eACH,OAAO;CAET,MAAM,SAAS,+BAA+B,UAAU,aAAa;CACrE,yBAAyB,SAAS,KAAI,YAAW,QAAQ,GAAG,GAAG,MAAM;CACrE,OAAO;AACT;;;;AAKA,SAAgB,6BACd,UACA,SACA;CACA,IAAI,CAAC,SAAS,QACZ,OAAO;CAET,MAAM,gBAAgB,mDAAW,mBAAwC;CACzE,IAAI,CAAC,eACH,OAAO;CAET,OAAO,2BACL,SAAS,KAAI,YAAW,QAAQ,GAAG,GACnC,aACF;AACF;;;;AAKA,SAAgB,eAAe,OAAsB;CAEnD,gBADkB,OAAO,KAAK,KACN,GAAG,EACzB,iBAAiB,KAAK;EACpB,OAAO,iBAAiB,MAAM,IAAI;CACpC,EACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"layoutBridge.mjs","names":[],"sources":["../../../src/runtime/layoutBridge.ts"],"sourcesContent":["import type { Ref } from '../reactivity'\nimport {\n WEVU_LAYOUT_BRIDGE_PAGE_KEYS,\n WEVU_NATIVE_INSTANCE_KEY,\n WEVU_PUBLIC_RUNTIME_KEY,\n} from '@weapp-core/constants'\nimport { isRef } from '../reactivity'\nimport { getCurrentInstance, getCurrentSetupContext, onAttached, onDetached } from './hooks'\nimport { getCurrentMiniProgramPages } from './platform'\nimport { getTemplateRefMap } from './templateRefs/helpers'\n\ntype LayoutBridgeContext = Record<string, any>\ntype LayoutBridgeComponentResolver = (selector: string) => any\ntype LayoutHostMap = Record<string, unknown>\nexport type LayoutBridgeInstance<T = LayoutBridgeContext> = T & {\n selectComponent?: LayoutBridgeComponentResolver\n}\nexport interface LayoutHostBinding {\n key: string\n refName?: string\n selector: string\n kind?: 'component'\n}\ninterface LayoutHostResolveOptions<T = any> {\n context?: T\n fallbackContext?: T\n interval?: number\n retries?: number\n}\n\n/**\n * @description 对 layout host key 去重并过滤空字符串。\n */\nfunction normalizeLayoutHostKeys(keys: string | string[]) {\n return Array.from(new Set(Array.isArray(keys) ? keys : [keys]))\n .filter((key): key is string => typeof key === 'string' && key.length > 0)\n}\n\n/**\n * @description 解析小程序页面实例的稳定身份 key。\n */\nfunction resolvePageIdentityKeys(page?: Record<string, any>): string[] {\n if (!page || typeof page !== 'object') {\n return []\n }\n\n const keys: string[] = []\n const route = typeof page.route === 'string' ? page.route.replace(/^\\/+/, '') : ''\n if (route) {\n keys.push(`route:${route}`)\n }\n for (const [prefix, field] of [\n ['webview', '__wxWebviewId__'],\n ['exparser', '__wxExparserNodeId__'],\n ] as const) {\n const value = page[field]\n if (typeof value === 'number' || typeof value === 'string') {\n keys.push(`${prefix}:${String(value)}`)\n }\n }\n\n return Array.from(new Set(keys))\n}\n\n/**\n * @description 创建小程序 layout host 注册表。\n */\nfunction createLayoutHostRegistry<TBridge>() {\n const registries = new Map<string, Map<string, TBridge>>()\n\n function register(keys: string | string[], bridge: TBridge, pageKeys: string[]) {\n const normalizedKeys = normalizeLayoutHostKeys(keys)\n if (normalizedKeys.length === 0 || pageKeys.length === 0) {\n return null\n }\n\n for (const pageKey of pageKeys) {\n const registry = registries.get(pageKey) ?? new Map<string, TBridge>()\n for (const key of normalizedKeys) {\n registry.set(key, bridge)\n }\n registries.set(pageKey, registry)\n }\n\n return normalizedKeys\n }\n\n function unregister(keys: string | string[], bridge: TBridge, pageKeys: string[]) {\n const normalizedKeys = normalizeLayoutHostKeys(keys)\n if (normalizedKeys.length === 0 || pageKeys.length === 0) {\n return false\n }\n\n let removed = false\n for (const pageKey of pageKeys) {\n const registry = registries.get(pageKey)\n if (!registry) {\n continue\n }\n\n for (const key of normalizedKeys) {\n if (registry.get(key) === bridge) {\n registry.delete(key)\n removed = true\n }\n }\n\n if (registry.size === 0) {\n registries.delete(pageKey)\n }\n }\n\n return removed\n }\n\n function resolveBridge(key: string, pageKeys: string[]) {\n return pageKeys\n .map(pageKey => registries.get(pageKey)?.get(key))\n .find(Boolean)\n }\n\n function resolveHost<THost>(\n key: string,\n pageKeys: string[],\n resolver: (bridge: TBridge, key: string) => THost | null | undefined,\n ) {\n const bridge = resolveBridge(key, pageKeys)\n if (!bridge) {\n return null\n }\n return resolver(bridge, key) ?? null\n }\n\n function waitForHost<THost>(\n key: string,\n resolvePageKeys: () => string[],\n resolver: (bridge: TBridge, key: string) => THost | null | undefined,\n options: { interval?: number, retries?: number } = {},\n ): Promise<THost | null> {\n const retries = options.retries ?? 20\n const interval = options.interval ?? 16\n const host = resolveHost(key, resolvePageKeys(), resolver)\n if (host || retries <= 0) {\n return Promise.resolve(host)\n }\n\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve(waitForHost(key, resolvePageKeys, resolver, {\n ...options,\n retries: retries - 1,\n }))\n }, interval)\n })\n }\n\n return {\n register,\n resolveBridge,\n resolveHost,\n unregister,\n waitForHost,\n }\n}\n\nconst pageLayoutBridgeRegistry = createLayoutHostRegistry<LayoutBridgeContext>()\n\nfunction resolveCurrentPageInstance() {\n const pages = getCurrentMiniProgramPages()\n return pages[pages.length - 1]\n}\n\nfunction resolvePageKeys(page?: LayoutBridgeContext) {\n return resolvePageIdentityKeys(page as Record<string, any> | undefined)\n}\n\nfunction resolveNativeLayoutContext(context?: LayoutBridgeContext) {\n if (!context || typeof context !== 'object') {\n return undefined\n }\n\n const runtimeNativeInstance = context[WEVU_PUBLIC_RUNTIME_KEY]?.state?.[WEVU_NATIVE_INSTANCE_KEY]\n if (runtimeNativeInstance && typeof runtimeNativeInstance === 'object') {\n return runtimeNativeInstance as LayoutBridgeContext\n }\n\n const stateNativeInstance = context.$state?.[WEVU_NATIVE_INSTANCE_KEY]\n if (stateNativeInstance && typeof stateNativeInstance === 'object') {\n return stateNativeInstance as LayoutBridgeContext\n }\n\n if (context[WEVU_NATIVE_INSTANCE_KEY] && typeof context[WEVU_NATIVE_INSTANCE_KEY] === 'object') {\n return context[WEVU_NATIVE_INSTANCE_KEY] as LayoutBridgeContext\n }\n\n return context\n}\n\nfunction resolvePageFromContext(\n context?: LayoutBridgeContext,\n visited = new Set<LayoutBridgeContext>(),\n): LayoutBridgeContext | undefined {\n if (!context || typeof context !== 'object' || visited.has(context)) {\n return resolveCurrentPageInstance()\n }\n visited.add(context)\n\n if (typeof context.__wevuSetPageLayout === 'function') {\n return context\n }\n\n const nativeContext = resolveNativeLayoutContext(context)\n if (nativeContext && nativeContext !== context) {\n const nativePage = resolvePageFromContext(nativeContext, visited)\n if (nativePage) {\n return nativePage\n }\n }\n\n const publicNativePage = context.$\n if (publicNativePage && typeof publicNativePage === 'object') {\n const nativePage = resolvePageFromContext(publicNativePage as LayoutBridgeContext, visited)\n if (nativePage) {\n return nativePage\n }\n }\n\n const ownerContext = nativeContext ?? context\n const selectOwnerComponent = ownerContext.selectOwnerComponent\n if (typeof selectOwnerComponent === 'function') {\n try {\n const owner = selectOwnerComponent.call(ownerContext) as LayoutBridgeContext | undefined\n if (owner && owner !== ownerContext) {\n const ownerPage = resolvePageFromContext(owner, visited)\n if (ownerPage) {\n return ownerPage\n }\n }\n }\n catch {\n // 部分宿主或生命周期阶段暂不支持 owner 查询,继续使用页面栈兜底。\n }\n }\n\n return resolveCurrentPageInstance()\n}\n\nfunction resolveHostEntry(entry: unknown) {\n if (typeof entry === 'function') {\n return (entry as () => unknown)()\n }\n if (isRef(entry as Ref<unknown>)) {\n return (entry as Ref<unknown>).value\n }\n return entry\n}\n\nfunction findLayoutHostBinding(bindings: LayoutHostBinding[], key: string) {\n return bindings.find(binding => binding.key === key)\n}\n\nfunction safeSelectComponent(target: LayoutBridgeContext | undefined, selector: string) {\n const selectComponent = target?.selectComponent\n if (typeof selectComponent !== 'function') {\n return null\n }\n try {\n return selectComponent.call(target, selector) ?? null\n }\n catch {\n return null\n }\n}\n\nfunction resolveDeclaredLayoutHostFromRefs(\n binding: LayoutHostBinding,\n context: LayoutBridgeContext,\n) {\n if (!binding.refName) {\n return null\n }\n const refMap = getTemplateRefMap(context as any)\n const stateRefs = context[WEVU_PUBLIC_RUNTIME_KEY]?.state?.$refs\n ?? context.__wevu?.state?.$refs\n ?? context.$state?.$refs\n ?? context.$refs\n const refValue = refMap?.get(binding.refName)?.value\n ?? stateRefs?.[binding.refName]\n if (Array.isArray(refValue)) {\n return refValue[0] ?? null\n }\n return refValue ?? null\n}\n\nfunction createDeclaredLayoutHostBridge(bindings: LayoutHostBinding[], context: LayoutBridgeContext) {\n const nativeContext = resolveNativeLayoutContext(context)\n const bridgeBase = nativeContext && typeof nativeContext === 'object'\n ? Object.create(nativeContext)\n : {}\n return Object.assign(bridgeBase, {\n selectComponent(key: string) {\n const binding = findLayoutHostBinding(bindings, key)\n if (!binding) {\n return null\n }\n if (binding.kind === 'component' || !binding.kind) {\n const cachedHost = resolveDeclaredLayoutHostFromRefs(binding, context)\n if (cachedHost) {\n return cachedHost\n }\n return safeSelectComponent(nativeContext, binding.selector)\n ?? safeSelectComponent(resolveCurrentPageInstance(), binding.selector)\n ?? null\n }\n return null\n },\n })\n}\n\n/**\n * 为当前页面注册 layout bridge,使页面或子组件可消费 layout 内部能力。\n */\nexport function registerPageLayoutBridge(\n selectors: string | string[],\n context?: LayoutBridgeContext,\n) {\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n const page = resolvePageFromContext(bridgeContext)\n const pageKeys = resolvePageKeys(page)\n if (!bridgeContext || !page || pageKeys.length === 0) {\n return false\n }\n\n const normalizedSelectors = pageLayoutBridgeRegistry.register(selectors, bridgeContext, pageKeys)\n if (!normalizedSelectors) {\n return false\n }\n\n bridgeContext[WEVU_LAYOUT_BRIDGE_PAGE_KEYS] = pageKeys\n return true\n}\n\n/**\n * 移除当前页面的 layout bridge 注册。\n */\nexport function unregisterPageLayoutBridge(\n selectors: string | string[],\n context?: LayoutBridgeContext,\n) {\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n const page = resolvePageFromContext(bridgeContext)\n const pageKeys = bridgeContext?.[WEVU_LAYOUT_BRIDGE_PAGE_KEYS] ?? resolvePageKeys(page)\n if (!bridgeContext || !Array.isArray(pageKeys) || pageKeys.length === 0) {\n return false\n }\n\n const removed = pageLayoutBridgeRegistry.unregister(selectors, bridgeContext, pageKeys)\n delete bridgeContext[WEVU_LAYOUT_BRIDGE_PAGE_KEYS]\n return removed\n}\n\n/**\n * 解析当前页面已注册的 layout bridge,找不到时回退到传入上下文。\n */\nexport function resolveLayoutBridge<T = any>(\n selector: string,\n fallbackContext?: T,\n) {\n const page = resolveCurrentPageInstance() ?? resolvePageFromContext(fallbackContext as LayoutBridgeContext | undefined)\n const bridgeContext = pageLayoutBridgeRegistry.resolveBridge(selector, resolvePageKeys(page))\n return (bridgeContext ?? fallbackContext ?? getCurrentInstance()) as LayoutBridgeInstance<T> | undefined\n}\n\n/**\n * 解析当前页面 layout 内通过指定 key 暴露的宿主实例。\n */\nexport function resolveLayoutHost<T = any, C = any>(\n key: string,\n options: LayoutHostResolveOptions<C> = {},\n) {\n const context = options.context ?? options.fallbackContext\n const page = resolveCurrentPageInstance() ?? resolvePageFromContext(context as LayoutBridgeContext | undefined)\n return pageLayoutBridgeRegistry.resolveHost<T>(\n key,\n resolvePageKeys(page),\n (bridge, key) => bridge.selectComponent?.(key) as T | null,\n )\n}\n\n/**\n * 等待当前页面 layout 宿主实例可用,适合页面初次进入时的异步宿主解析。\n */\nexport function waitForLayoutHost<T = any, C = any>(\n key: string,\n options: LayoutHostResolveOptions<C> = {},\n) {\n const context = options.context ?? options.fallbackContext\n return pageLayoutBridgeRegistry.waitForHost<T>(\n key,\n () => resolvePageKeys(resolveCurrentPageInstance() ?? resolvePageFromContext(context as LayoutBridgeContext | undefined)),\n (bridge, key) => bridge.selectComponent?.(key) as T | null,\n options,\n )\n}\n\n/**\n * 在 layout 生命周期内暴露 bridge,使页面或子组件可访问 layout 内部实例。\n */\nexport function useLayoutBridge(\n selectors: string | string[],\n options: {\n resolveComponent?: LayoutBridgeComponentResolver\n } = {},\n) {\n if (!getCurrentSetupContext()) {\n throw new Error('useLayoutBridge() 必须在 setup() 的同步阶段调用')\n }\n\n const context = getCurrentInstance<LayoutBridgeContext>()\n const normalizedSelectors = normalizeLayoutHostKeys(selectors)\n const resolveComponent = options.resolveComponent\n const nativeContext = resolveNativeLayoutContext(context)\n const bridgeBase = nativeContext && typeof nativeContext === 'object'\n ? Object.create(nativeContext)\n : {}\n const bridge = Object.assign(bridgeBase, {\n selectComponent(selector: string) {\n if (!normalizedSelectors.includes(selector)) {\n return null\n }\n\n const resolvedComponent = resolveComponent?.(selector)\n if (resolvedComponent !== undefined) {\n return resolvedComponent\n }\n\n const nativeContext = resolveNativeLayoutContext(context)\n const directMatch = nativeContext?.selectComponent?.(selector)\n if (directMatch) {\n return directMatch\n }\n\n const currentPage = resolveCurrentPageInstance()\n return currentPage?.selectComponent?.(selector) ?? null\n },\n })\n\n registerPageLayoutBridge(normalizedSelectors, bridge)\n\n onAttached(() => {\n registerPageLayoutBridge(normalizedSelectors, bridge)\n })\n\n onDetached(() => {\n unregisterPageLayoutBridge(normalizedSelectors, bridge)\n })\n}\n\n/**\n * 使用编译期注入的宿主绑定信息,直接从当前 layout 运行时实例解析子组件宿主并注册 bridge。\n */\nexport function registerRuntimeLayoutHosts(\n bindings: LayoutHostBinding[],\n context?: LayoutBridgeContext,\n) {\n if (!bindings.length) {\n return null\n }\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n if (!bridgeContext) {\n return null\n }\n const bridge = createDeclaredLayoutHostBridge(bindings, bridgeContext)\n registerPageLayoutBridge(bindings.map(binding => binding.key), bridge)\n return bridge\n}\n\n/**\n * 移除运行时自动注册的 layout 宿主 bridge。\n */\nexport function unregisterRuntimeLayoutHosts(\n bindings: LayoutHostBinding[],\n context?: LayoutBridgeContext,\n) {\n if (!bindings.length) {\n return false\n }\n const bridgeContext = context ?? getCurrentInstance<LayoutBridgeContext>()\n if (!bridgeContext) {\n return false\n }\n return unregisterPageLayoutBridge(\n bindings.map(binding => binding.key),\n bridgeContext,\n )\n}\n\n/**\n * 使用 key -> 宿主实例的映射批量暴露 layout 内部宿主,适合 toast/dialog 等共享反馈节点。\n */\nexport function useLayoutHosts(hosts: LayoutHostMap) {\n const selectors = Object.keys(hosts)\n useLayoutBridge(selectors, {\n resolveComponent(key) {\n return resolveHostEntry(hosts[key])\n },\n })\n}\n"],"mappings":";;;;;;;;;;;AAiCA,SAAS,wBAAwB,MAAyB;CACxD,OAAO,MAAM,KAAK,IAAI,IAAI,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAC5D,QAAQ,QAAuB,OAAO,QAAQ,YAAY,IAAI,SAAS,CAAC;AAC7E;;;;AAKA,SAAS,wBAAwB,MAAsC;CACrE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO,CAAC;CAGV,MAAM,OAAiB,CAAC;CACxB,MAAM,QAAQ,OAAO,KAAK,UAAU,WAAW,KAAK,MAAM,QAAQ,QAAQ,EAAE,IAAI;CAChF,IAAI,OACF,KAAK,KAAK,SAAS,OAAO;CAE5B,KAAK,MAAM,CAAC,QAAQ,UAAU,CAC5B,CAAC,WAAW,iBAAiB,GAC7B,CAAC,YAAY,sBAAsB,CACrC,GAAY;EACV,MAAM,QAAQ,KAAK;EACnB,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,UAChD,KAAK,KAAK,GAAG,OAAO,GAAG,OAAO,KAAK,GAAG;CAE1C;CAEA,OAAO,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC;AACjC;;;;AAKA,SAAS,2BAAoC;CAC3C,MAAM,6BAAa,IAAI,IAAkC;CAEzD,SAAS,SAAS,MAAyB,QAAiB,UAAoB;EAC9E,MAAM,iBAAiB,wBAAwB,IAAI;EACnD,IAAI,eAAe,WAAW,KAAK,SAAS,WAAW,GACrD,OAAO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+BAA+B,UAAU,aAAa;CACrE,yBAAyB,SAAS,KAAI,YAAW,QAAQ,GAAG,GAAG,MAAM;CACrE,OAAO;AACT;;;;AAKA,SAAgB,6BACd,UACA,SACA;CACA,IAAI,CAAC,SAAS,QACZ,OAAO;CAET,MAAM,gBAAgB,mDAAW,mBAAwC;CACzE,IAAI,CAAC,eACH,OAAO;CAET,OAAO,2BACL,SAAS,KAAI,YAAW,QAAQ,GAAG,GACnC,aACF;AACF;;;;AAKA,SAAgB,eAAe,OAAsB;CAEnD,gBADkB,OAAO,KAAK,KACN,GAAG,EACzB,iBAAiB,KAAK;EACpB,OAAO,iBAAiB,MAAM,IAAI;CACpC,EACF,CAAC;AACH"}
|
|
@@ -15,7 +15,8 @@ function getGlobalRuntime() {
|
|
|
15
15
|
function resolveCurrentMiniProgramPlatform() {
|
|
16
16
|
var _env;
|
|
17
17
|
const globalRuntime = getGlobalRuntime();
|
|
18
|
-
const
|
|
18
|
+
const compiledPlatform = (_env = import.meta.env) === null || _env === void 0 ? void 0 : _env.PLATFORM;
|
|
19
|
+
const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform);
|
|
19
20
|
if (resolvedCompiledPlatform) return resolvedCompiledPlatform;
|
|
20
21
|
for (const globalKey of getMiniProgramRuntimeGlobalKeys()) if (globalRuntime === null || globalRuntime === void 0 ? void 0 : globalRuntime[globalKey]) return getMiniProgramPlatformByRuntimeGlobalKey(globalKey);
|
|
21
22
|
}
|
|
@@ -45,7 +46,8 @@ function getCurrentMiniProgramHostConfig() {
|
|
|
45
46
|
function getMiniProgramGlobalObject(platformInput) {
|
|
46
47
|
var _env2;
|
|
47
48
|
const globalRuntime = getGlobalRuntime();
|
|
48
|
-
const
|
|
49
|
+
const compiledPlatform = platformInput !== null && platformInput !== void 0 ? platformInput : (_env2 = import.meta.env) === null || _env2 === void 0 ? void 0 : _env2.PLATFORM;
|
|
50
|
+
const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform);
|
|
49
51
|
if (resolvedCompiledPlatform) {
|
|
50
52
|
const globalKey = getMiniProgramRuntimeGlobalKey(resolvedCompiledPlatform);
|
|
51
53
|
return globalRuntime === null || globalRuntime === void 0 ? void 0 : globalRuntime[globalKey];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform.mjs","names":[],"sources":["../../../src/runtime/platform.ts"],"sourcesContent":["import type { MiniProgramRuntimeCapabilities, MiniProgramRuntimeCapabilityName } from '@weapp-core/shared/platforms'\nimport {\n getMiniProgramPlatformByRuntimeGlobalKey,\n getMiniProgramRuntimeCapabilities,\n getMiniProgramRuntimeGlobalKey,\n getMiniProgramRuntimeGlobalKeys,\n getMiniProgramRuntimeHostConfigKey,\n resolveMiniProgramPlatform,\n supportsMiniProgramRuntimeCapability,\n} from '@weapp-core/shared/platforms'\n\ntype MiniProgramGlobal = Record<string, any>\ntype MiniProgramHostConfig = Record<string, any>\ntype MiniProgramGlobalRouterMethodName = 'switchTab' | 'reLaunch' | 'redirectTo' | 'navigateTo' | 'navigateBack'\ntype MiniProgramGlobalRouter = Record<MiniProgramGlobalRouterMethodName, (...args: any[]) => any>\ntype ImportMetaWithEnv = ImportMeta & {\n env?: {\n PLATFORM?: string\n }\n}\nconst MINI_PROGRAM_GLOBAL_ROUTER_METHODS: readonly MiniProgramGlobalRouterMethodName[] = [\n 'switchTab',\n 'reLaunch',\n 'redirectTo',\n 'navigateTo',\n 'navigateBack',\n]\n\nfunction getGlobalRuntime() {\n if (typeof globalThis === 'undefined') {\n return undefined\n }\n return globalThis as MiniProgramGlobal\n}\n\nexport function resolveCurrentMiniProgramPlatform() {\n const globalRuntime = getGlobalRuntime()\n const compiledPlatform = (import.meta as ImportMetaWithEnv).env?.PLATFORM\n\n // 优先命中编译期平台分支,便于构建阶段做 dead-code elimination。\n const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform)\n if (resolvedCompiledPlatform) {\n return resolvedCompiledPlatform\n }\n\n for (const globalKey of getMiniProgramRuntimeGlobalKeys()) {\n if (globalRuntime?.[globalKey]) {\n return getMiniProgramPlatformByRuntimeGlobalKey(globalKey)\n }\n }\n\n return undefined\n}\n\nexport function getCurrentMiniProgramRuntimeCapabilities(): MiniProgramRuntimeCapabilities {\n return getMiniProgramRuntimeCapabilities(resolveCurrentMiniProgramPlatform())\n}\n\nexport function supportsCurrentMiniProgramRuntimeCapability(capabilityName: MiniProgramRuntimeCapabilityName): boolean {\n return supportsMiniProgramRuntimeCapability(resolveCurrentMiniProgramPlatform(), capabilityName)\n}\n\nexport function getCurrentMiniProgramPages(): Array<Record<string, any>> {\n if (!supportsCurrentMiniProgramRuntimeCapability('globalPageStack')) {\n return []\n }\n const getCurrentPagesFn = (globalThis as Record<string, unknown>).getCurrentPages\n if (typeof getCurrentPagesFn !== 'function') {\n return []\n }\n try {\n const pages = getCurrentPagesFn()\n return Array.isArray(pages) ? pages as Array<Record<string, any>> : []\n }\n catch {\n return []\n }\n}\n\nexport function getCurrentMiniProgramHostConfig(): MiniProgramHostConfig | undefined {\n const globalRuntime = getGlobalRuntime()\n const hostConfigKey = getMiniProgramRuntimeHostConfigKey(resolveCurrentMiniProgramPlatform())\n const hostConfig = globalRuntime?.[hostConfigKey]\n return hostConfig && typeof hostConfig === 'object' ? hostConfig as MiniProgramHostConfig : undefined\n}\n\nexport function getMiniProgramGlobalObject(platformInput?: string): MiniProgramGlobal | undefined {\n const globalRuntime = getGlobalRuntime()\n const compiledPlatform = platformInput ?? (import.meta as ImportMetaWithEnv).env?.PLATFORM\n const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform)\n\n if (resolvedCompiledPlatform) {\n const globalKey = getMiniProgramRuntimeGlobalKey(resolvedCompiledPlatform)\n return globalRuntime?.[globalKey] as MiniProgramGlobal | undefined\n }\n\n for (const globalKey of getMiniProgramRuntimeGlobalKeys()) {\n const candidate = globalRuntime?.[globalKey]\n if (candidate) {\n return candidate as MiniProgramGlobal\n }\n }\n return undefined\n}\n\nexport function getCurrentMiniProgramGlobalRouter(): MiniProgramGlobalRouter | undefined {\n if (!supportsCurrentMiniProgramRuntimeCapability('globalRouterApi')) {\n return undefined\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n if (!miniProgramGlobal) {\n return undefined\n }\n const routerMethods = Object.create(null) as Partial<MiniProgramGlobalRouter>\n for (const methodName of MINI_PROGRAM_GLOBAL_ROUTER_METHODS) {\n const handler = miniProgramGlobal[methodName]\n if (typeof handler !== 'function') {\n return undefined\n }\n routerMethods[methodName] = (...args: any[]) => handler.apply(miniProgramGlobal, args)\n }\n return routerMethods as MiniProgramGlobalRouter\n}\n\nexport function getScopedSlotHostGlobalObject(): MiniProgramGlobal | undefined {\n return getMiniProgramGlobalObject() ?? getGlobalRuntime()\n}\n"],"mappings":";;;AAoBA,MAAM,qCAAmF;CACvF;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,mBAAmB;CAC1B,IAAI,OAAO,eAAe,aACxB;CAEF,OAAO;AACT;AAEA,SAAgB,oCAAoC;;CAClD,MAAM,gBAAgB,iBAAiB;
|
|
1
|
+
{"version":3,"file":"platform.mjs","names":[],"sources":["../../../src/runtime/platform.ts"],"sourcesContent":["import type { MiniProgramRuntimeCapabilities, MiniProgramRuntimeCapabilityName } from '@weapp-core/shared/platforms'\nimport {\n getMiniProgramPlatformByRuntimeGlobalKey,\n getMiniProgramRuntimeCapabilities,\n getMiniProgramRuntimeGlobalKey,\n getMiniProgramRuntimeGlobalKeys,\n getMiniProgramRuntimeHostConfigKey,\n resolveMiniProgramPlatform,\n supportsMiniProgramRuntimeCapability,\n} from '@weapp-core/shared/platforms'\n\ntype MiniProgramGlobal = Record<string, any>\ntype MiniProgramHostConfig = Record<string, any>\ntype MiniProgramGlobalRouterMethodName = 'switchTab' | 'reLaunch' | 'redirectTo' | 'navigateTo' | 'navigateBack'\ntype MiniProgramGlobalRouter = Record<MiniProgramGlobalRouterMethodName, (...args: any[]) => any>\ntype ImportMetaWithEnv = ImportMeta & {\n env?: {\n PLATFORM?: string\n }\n}\nconst MINI_PROGRAM_GLOBAL_ROUTER_METHODS: readonly MiniProgramGlobalRouterMethodName[] = [\n 'switchTab',\n 'reLaunch',\n 'redirectTo',\n 'navigateTo',\n 'navigateBack',\n]\n\nfunction getGlobalRuntime() {\n if (typeof globalThis === 'undefined') {\n return undefined\n }\n return globalThis as MiniProgramGlobal\n}\n\nexport function resolveCurrentMiniProgramPlatform() {\n const globalRuntime = getGlobalRuntime()\n const compiledPlatform = (import.meta as ImportMetaWithEnv).env?.PLATFORM\n\n // 优先命中编译期平台分支,便于构建阶段做 dead-code elimination。\n const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform)\n if (resolvedCompiledPlatform) {\n return resolvedCompiledPlatform\n }\n\n for (const globalKey of getMiniProgramRuntimeGlobalKeys()) {\n if (globalRuntime?.[globalKey]) {\n return getMiniProgramPlatformByRuntimeGlobalKey(globalKey)\n }\n }\n\n return undefined\n}\n\nexport function getCurrentMiniProgramRuntimeCapabilities(): MiniProgramRuntimeCapabilities {\n return getMiniProgramRuntimeCapabilities(resolveCurrentMiniProgramPlatform())\n}\n\nexport function supportsCurrentMiniProgramRuntimeCapability(capabilityName: MiniProgramRuntimeCapabilityName): boolean {\n return supportsMiniProgramRuntimeCapability(resolveCurrentMiniProgramPlatform(), capabilityName)\n}\n\nexport function getCurrentMiniProgramPages(): Array<Record<string, any>> {\n if (!supportsCurrentMiniProgramRuntimeCapability('globalPageStack')) {\n return []\n }\n const getCurrentPagesFn = (globalThis as Record<string, unknown>).getCurrentPages\n if (typeof getCurrentPagesFn !== 'function') {\n return []\n }\n try {\n const pages = getCurrentPagesFn()\n return Array.isArray(pages) ? pages as Array<Record<string, any>> : []\n }\n catch {\n return []\n }\n}\n\nexport function getCurrentMiniProgramHostConfig(): MiniProgramHostConfig | undefined {\n const globalRuntime = getGlobalRuntime()\n const hostConfigKey = getMiniProgramRuntimeHostConfigKey(resolveCurrentMiniProgramPlatform())\n const hostConfig = globalRuntime?.[hostConfigKey]\n return hostConfig && typeof hostConfig === 'object' ? hostConfig as MiniProgramHostConfig : undefined\n}\n\nexport function getMiniProgramGlobalObject(platformInput?: string): MiniProgramGlobal | undefined {\n const globalRuntime = getGlobalRuntime()\n const compiledPlatform = platformInput ?? (import.meta as ImportMetaWithEnv).env?.PLATFORM\n const resolvedCompiledPlatform = resolveMiniProgramPlatform(compiledPlatform)\n\n if (resolvedCompiledPlatform) {\n const globalKey = getMiniProgramRuntimeGlobalKey(resolvedCompiledPlatform)\n return globalRuntime?.[globalKey] as MiniProgramGlobal | undefined\n }\n\n for (const globalKey of getMiniProgramRuntimeGlobalKeys()) {\n const candidate = globalRuntime?.[globalKey]\n if (candidate) {\n return candidate as MiniProgramGlobal\n }\n }\n return undefined\n}\n\nexport function getCurrentMiniProgramGlobalRouter(): MiniProgramGlobalRouter | undefined {\n if (!supportsCurrentMiniProgramRuntimeCapability('globalRouterApi')) {\n return undefined\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n if (!miniProgramGlobal) {\n return undefined\n }\n const routerMethods = Object.create(null) as Partial<MiniProgramGlobalRouter>\n for (const methodName of MINI_PROGRAM_GLOBAL_ROUTER_METHODS) {\n const handler = miniProgramGlobal[methodName]\n if (typeof handler !== 'function') {\n return undefined\n }\n routerMethods[methodName] = (...args: any[]) => handler.apply(miniProgramGlobal, args)\n }\n return routerMethods as MiniProgramGlobalRouter\n}\n\nexport function getScopedSlotHostGlobalObject(): MiniProgramGlobal | undefined {\n return getMiniProgramGlobalObject() ?? getGlobalRuntime()\n}\n"],"mappings":";;;AAoBA,MAAM,qCAAmF;CACvF;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,mBAAmB;CAC1B,IAAI,OAAO,eAAe,aACxB;CAEF,OAAO;AACT;AAEA,SAAgB,oCAAoC;;CAClD,MAAM,gBAAgB,iBAAiB;CACvC,MAAM,2BAAoB,YAAkC,iDAAK;CAGjE,MAAM,2BAA2B,2BAA2B,gBAAgB;CAC5E,I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AClC,IAAI,OAAO,YAAY,YACrB;EAEF,cAAc,eAAe,GAAG,SAAgB,QAAQ,MAAM,mBAAmB,IAAI;CACvF;CACA,OAAO;AACT;AAEA,SAAgB,gCAA+D;;CAC7E,gCAAO,2BAA2B,0EAAK,iBAAiB;AAC1D"}
|
|
@@ -105,7 +105,9 @@ function registerApp(runtimeApp, methods, watch, setup, mpOptions) {
|
|
|
105
105
|
if (!appOptions[WEVU_INLINE_HANDLER]) appOptions[WEVU_INLINE_HANDLER] = function __weapp_vite_inline(event) {
|
|
106
106
|
var _runtime$proxy, _runtime$methods;
|
|
107
107
|
const runtime = this.__wevu;
|
|
108
|
-
|
|
108
|
+
const ctx = (_runtime$proxy = runtime === null || runtime === void 0 ? void 0 : runtime.proxy) !== null && _runtime$proxy !== void 0 ? _runtime$proxy : this;
|
|
109
|
+
const inlineMap = runtime === null || runtime === void 0 || (_runtime$methods = runtime.methods) === null || _runtime$methods === void 0 ? void 0 : _runtime$methods[WEVU_INLINE_MAP_KEY];
|
|
110
|
+
return runInlineExpression(ctx, void 0, event, inlineMap);
|
|
109
111
|
};
|
|
110
112
|
const userOnLaunch = appOptions.onLaunch;
|
|
111
113
|
const userOnError = appOptions.onError;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.mjs","names":[],"sources":["../../../../src/runtime/register/app.ts"],"sourcesContent":["import type {\n ComputedDefinitions,\n DefineAppOptions,\n InternalRuntimeState,\n MethodDefinitions,\n MiniProgramAppOptions,\n MiniProgramMemoryWarningResult,\n RuntimeApp,\n} from '../types'\nimport type { WatchMap } from './watch'\nimport {\n WEVU_HOOKS_KEY,\n WEVU_INLINE_HANDLER,\n WEVU_INLINE_MAP_KEY,\n WEVU_IS_APP_INSTANCE_KEY,\n} from '@weapp-core/constants'\nimport { callHookList } from '../hooks'\nimport { getMiniProgramGlobalObject, supportsCurrentMiniProgramRuntimeCapability } from '../platform'\nimport { runInlineExpression } from './inline'\nimport { mountRuntimeInstance } from './runtimeInstance'\n\nconst APP_GLOBAL_LISTENER_STORE_KEY = '__wevuAppGlobalListeners'\nconst MEMORY_WARNING_LISTENER_KEY = '__wevuOnMemoryWarningListener'\n\nfunction bindMemoryWarningListener(target: InternalRuntimeState) {\n const hooks = target[WEVU_HOOKS_KEY] as Record<string, any> | undefined\n const hasMemoryWarningHook = Boolean(hooks?.onMemoryWarning)\n if (!supportsCurrentMiniProgramRuntimeCapability('appMemoryWarningListener')) {\n delete (target as any)[MEMORY_WARNING_LISTENER_KEY]\n return\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n const onMemoryWarning = miniProgramGlobal?.onMemoryWarning\n const offMemoryWarning = miniProgramGlobal?.offMemoryWarning\n if (typeof onMemoryWarning !== 'function') {\n return\n }\n\n const existing = (target as any)[MEMORY_WARNING_LISTENER_KEY]\n if (typeof existing === 'function' && typeof offMemoryWarning === 'function') {\n try {\n offMemoryWarning(existing)\n }\n catch {\n // 忽略平台差异导致的取消监听异常\n }\n }\n\n if (!hasMemoryWarningHook) {\n delete (target as any)[MEMORY_WARNING_LISTENER_KEY]\n return\n }\n\n const listener = (result: MiniProgramMemoryWarningResult) => {\n callHookList(target, 'onMemoryWarning', [result])\n }\n ;(target as any)[MEMORY_WARNING_LISTENER_KEY] = listener\n onMemoryWarning(listener)\n}\n\nfunction bindAppGlobalListener(target: InternalRuntimeState, options: {\n hookName: 'onError' | 'onPageNotFound' | 'onUnhandledRejection' | 'onThemeChange'\n onApiName: 'onError' | 'onPageNotFound' | 'onUnhandledRejection' | 'onThemeChange'\n offApiName: 'offError' | 'offPageNotFound' | 'offUnhandledRejection' | 'offThemeChange'\n capabilityName: 'appErrorListener' | 'appPageNotFoundListener' | 'appUnhandledRejectionListener' | 'appThemeChangeListener'\n userHandler?: ((...args: any[]) => any) | undefined\n}) {\n const { hookName, onApiName, offApiName, capabilityName, userHandler } = options\n const hooks = target[WEVU_HOOKS_KEY] as Record<string, any> | undefined\n const hasHook = Boolean(hooks?.[hookName])\n const store = ((target as any)[APP_GLOBAL_LISTENER_STORE_KEY] ??= Object.create(null)) as Record<string, ((...args: any[]) => void) | undefined>\n const existing = store[hookName]\n if (!supportsCurrentMiniProgramRuntimeCapability(capabilityName)) {\n delete store[hookName]\n delete (target as any)[hookName]\n return\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n const onApi = miniProgramGlobal?.[onApiName]\n const offApi = miniProgramGlobal?.[offApiName]\n\n if (typeof existing === 'function' && typeof offApi === 'function') {\n try {\n offApi(existing)\n }\n catch {\n // 忽略平台差异导致的取消监听异常\n }\n }\n\n if (!hasHook && typeof userHandler !== 'function') {\n delete store[hookName]\n return\n }\n\n const dispatch = (...args: any[]) => {\n callHookList(target, hookName, args)\n if (typeof userHandler === 'function') {\n userHandler.apply(target, args)\n }\n }\n\n ;(target as any)[hookName] = dispatch\n store[hookName] = dispatch\n\n if (typeof onApi === 'function') {\n onApi(dispatch)\n }\n}\n\nfunction bindAppGlobalListeners(\n target: InternalRuntimeState,\n handlers: {\n onError?: ((...args: any[]) => any) | undefined\n onPageNotFound?: ((...args: any[]) => any) | undefined\n onUnhandledRejection?: ((...args: any[]) => any) | undefined\n onThemeChange?: ((...args: any[]) => any) | undefined\n },\n) {\n bindAppGlobalListener(target, {\n hookName: 'onError',\n onApiName: 'onError',\n offApiName: 'offError',\n capabilityName: 'appErrorListener',\n userHandler: handlers.onError,\n })\n bindAppGlobalListener(target, {\n hookName: 'onPageNotFound',\n onApiName: 'onPageNotFound',\n offApiName: 'offPageNotFound',\n capabilityName: 'appPageNotFoundListener',\n userHandler: handlers.onPageNotFound,\n })\n bindAppGlobalListener(target, {\n hookName: 'onUnhandledRejection',\n onApiName: 'onUnhandledRejection',\n offApiName: 'offUnhandledRejection',\n capabilityName: 'appUnhandledRejectionListener',\n userHandler: handlers.onUnhandledRejection,\n })\n bindAppGlobalListener(target, {\n hookName: 'onThemeChange',\n onApiName: 'onThemeChange',\n offApiName: 'offThemeChange',\n capabilityName: 'appThemeChangeListener',\n userHandler: handlers.onThemeChange,\n })\n}\n\n/**\n * 注册 App 入口(框架内部使用)。\n * @internal\n */\nexport function registerApp<D extends object, C extends ComputedDefinitions, M extends MethodDefinitions>(\n runtimeApp: RuntimeApp<D, C, M>,\n methods: MethodDefinitions,\n watch: WatchMap | undefined,\n setup: DefineAppOptions<D, C, M>['setup'],\n mpOptions: MiniProgramAppOptions,\n) {\n if (typeof App !== 'function') {\n throw new TypeError('createApp 需要全局 App 构造器可用')\n }\n\n const methodNames = Object.keys(methods ?? {})\n const appOptions: Record<string, any> = {\n ...mpOptions,\n }\n\n appOptions.globalData = appOptions.globalData ?? {}\n\n if (!appOptions[WEVU_INLINE_HANDLER]) {\n appOptions[WEVU_INLINE_HANDLER] = function __weapp_vite_inline(this: InternalRuntimeState, event: any) {\n const runtime = (this as any).__wevu\n const ctx = runtime?.proxy ?? this\n const inlineMap = runtime?.methods?.[WEVU_INLINE_MAP_KEY]\n return runInlineExpression(ctx, undefined, event, inlineMap)\n }\n }\n\n const userOnLaunch = appOptions.onLaunch\n const userOnError = appOptions.onError\n const userOnPageNotFound = (appOptions as any).onPageNotFound\n const userOnUnhandledRejection = (appOptions as any).onUnhandledRejection\n const userOnThemeChange = (appOptions as any).onThemeChange\n appOptions.onLaunch = function onLaunch(this: InternalRuntimeState, ...args: any[]) {\n this[WEVU_IS_APP_INSTANCE_KEY] = true\n mountRuntimeInstance(this, runtimeApp, watch, setup)\n bindMemoryWarningListener(this)\n bindAppGlobalListeners(this, {\n onError: userOnError,\n onPageNotFound: userOnPageNotFound,\n onUnhandledRejection: userOnUnhandledRejection,\n onThemeChange: userOnThemeChange,\n })\n callHookList(this, 'onLaunch', args)\n if (typeof userOnLaunch === 'function') {\n userOnLaunch.apply(this, args)\n }\n }\n\n const userOnShow = appOptions.onShow\n appOptions.onShow = function onShow(this: InternalRuntimeState, ...args: any[]) {\n callHookList(this, 'onShow', args)\n if (typeof userOnShow === 'function') {\n userOnShow.apply(this, args)\n }\n }\n\n const userOnHide = appOptions.onHide\n appOptions.onHide = function onHide(this: InternalRuntimeState, ...args: any[]) {\n callHookList(this, 'onHide', args)\n if (typeof userOnHide === 'function') {\n userOnHide.apply(this, args)\n }\n }\n\n delete appOptions.onError\n delete (appOptions as any).onPageNotFound\n delete (appOptions as any).onUnhandledRejection\n delete (appOptions as any).onThemeChange\n\n for (const methodName of methodNames) {\n const userMethod = appOptions[methodName]\n appOptions[methodName] = function runtimeMethod(this: InternalRuntimeState, ...args: any[]) {\n const runtime = this.__wevu\n let result: unknown\n const bound = runtime?.methods?.[methodName]\n if (bound) {\n result = bound.apply(runtime.proxy, args)\n }\n if (typeof userMethod === 'function') {\n return userMethod.apply(this, args)\n }\n return result\n }\n }\n\n App(appOptions)\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,gCAAgC;AACtC,MAAM,8BAA8B;AAEpC,SAAS,0BAA0B,QAA8B;CAC/D,MAAM,QAAQ,OAAO;CACrB,MAAM,uBAAuB,sDAAQ,MAAO,eAAe;CAC3D,IAAI,CAAC,4CAA4C,0BAA0B,GAAG;EAC5E,OAAQ,OAAe;EACvB;CACF;CACA,MAAM,oBAAoB,2BAA2B;CACrD,MAAM,wFAAkB,kBAAmB;CAC3C,MAAM,yFAAmB,kBAAmB;CAC5C,IAAI,OAAO,oBAAoB,YAC7B;CAGF,MAAM,WAAY,OAAe;CACjC,IAAI,OAAO,aAAa,cAAc,OAAO,qBAAqB,YAChE,IAAI;EACF,iBAAiB,QAAQ;CAC3B,kBACM,CAEN;CAGF,IAAI,CAAC,sBAAsB;EACzB,OAAQ,OAAe;EACvB;CACF;CAEA,MAAM,YAAY,WAA2C;EAC3D,aAAa,QAAQ,mBAAmB,CAAC,MAAM,CAAC;CAClD;CACC,AAAC,OAAe,+BAA+B;CAChD,gBAAgB,QAAQ;AAC1B;AAEA,SAAS,sBAAsB,QAA8B,SAM1D;;CACD,MAAM,EAAE,UAAU,WAAW,YAAY,gBAAgB,gBAAgB;CACzE,MAAM,QAAQ,OAAO;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,KAAK;GACrB,IAAI;GACJ,MAAM,uEAAQ,QAAS,+EAAU;GACjC,IAAI,OACF,SAAS,MAAM,MAAM,QAAQ,OAAO,IAAI;GAE1C,IAAI,OAAO,eAAe,YACxB,OAAO,WAAW,MAAM,MAAM,IAAI;GAEpC,OAAO;EACT;CACF;CAEA,IAAI,UAAU;AAChB"}
|
|
1
|
+
{"version":3,"file":"app.mjs","names":[],"sources":["../../../../src/runtime/register/app.ts"],"sourcesContent":["import type {\n ComputedDefinitions,\n DefineAppOptions,\n InternalRuntimeState,\n MethodDefinitions,\n MiniProgramAppOptions,\n MiniProgramMemoryWarningResult,\n RuntimeApp,\n} from '../types'\nimport type { WatchMap } from './watch'\nimport {\n WEVU_HOOKS_KEY,\n WEVU_INLINE_HANDLER,\n WEVU_INLINE_MAP_KEY,\n WEVU_IS_APP_INSTANCE_KEY,\n} from '@weapp-core/constants'\nimport { callHookList } from '../hooks'\nimport { getMiniProgramGlobalObject, supportsCurrentMiniProgramRuntimeCapability } from '../platform'\nimport { runInlineExpression } from './inline'\nimport { mountRuntimeInstance } from './runtimeInstance'\n\nconst APP_GLOBAL_LISTENER_STORE_KEY = '__wevuAppGlobalListeners'\nconst MEMORY_WARNING_LISTENER_KEY = '__wevuOnMemoryWarningListener'\n\nfunction bindMemoryWarningListener(target: InternalRuntimeState) {\n const hooks = target[WEVU_HOOKS_KEY] as Record<string, any> | undefined\n const hasMemoryWarningHook = Boolean(hooks?.onMemoryWarning)\n if (!supportsCurrentMiniProgramRuntimeCapability('appMemoryWarningListener')) {\n delete (target as any)[MEMORY_WARNING_LISTENER_KEY]\n return\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n const onMemoryWarning = miniProgramGlobal?.onMemoryWarning\n const offMemoryWarning = miniProgramGlobal?.offMemoryWarning\n if (typeof onMemoryWarning !== 'function') {\n return\n }\n\n const existing = (target as any)[MEMORY_WARNING_LISTENER_KEY]\n if (typeof existing === 'function' && typeof offMemoryWarning === 'function') {\n try {\n offMemoryWarning(existing)\n }\n catch {\n // 忽略平台差异导致的取消监听异常\n }\n }\n\n if (!hasMemoryWarningHook) {\n delete (target as any)[MEMORY_WARNING_LISTENER_KEY]\n return\n }\n\n const listener = (result: MiniProgramMemoryWarningResult) => {\n callHookList(target, 'onMemoryWarning', [result])\n }\n ;(target as any)[MEMORY_WARNING_LISTENER_KEY] = listener\n onMemoryWarning(listener)\n}\n\nfunction bindAppGlobalListener(target: InternalRuntimeState, options: {\n hookName: 'onError' | 'onPageNotFound' | 'onUnhandledRejection' | 'onThemeChange'\n onApiName: 'onError' | 'onPageNotFound' | 'onUnhandledRejection' | 'onThemeChange'\n offApiName: 'offError' | 'offPageNotFound' | 'offUnhandledRejection' | 'offThemeChange'\n capabilityName: 'appErrorListener' | 'appPageNotFoundListener' | 'appUnhandledRejectionListener' | 'appThemeChangeListener'\n userHandler?: ((...args: any[]) => any) | undefined\n}) {\n const { hookName, onApiName, offApiName, capabilityName, userHandler } = options\n const hooks = target[WEVU_HOOKS_KEY] as Record<string, any> | undefined\n const hasHook = Boolean(hooks?.[hookName])\n const store = ((target as any)[APP_GLOBAL_LISTENER_STORE_KEY] ??= Object.create(null)) as Record<string, ((...args: any[]) => void) | undefined>\n const existing = store[hookName]\n if (!supportsCurrentMiniProgramRuntimeCapability(capabilityName)) {\n delete store[hookName]\n delete (target as any)[hookName]\n return\n }\n const miniProgramGlobal = getMiniProgramGlobalObject()\n const onApi = miniProgramGlobal?.[onApiName]\n const offApi = miniProgramGlobal?.[offApiName]\n\n if (typeof existing === 'function' && typeof offApi === 'function') {\n try {\n offApi(existing)\n }\n catch {\n // 忽略平台差异导致的取消监听异常\n }\n }\n\n if (!hasHook && typeof userHandler !== 'function') {\n delete store[hookName]\n return\n }\n\n const dispatch = (...args: any[]) => {\n callHookList(target, hookName, args)\n if (typeof userHandler === 'function') {\n userHandler.apply(target, args)\n }\n }\n\n ;(target as any)[hookName] = dispatch\n store[hookName] = dispatch\n\n if (typeof onApi === 'function') {\n onApi(dispatch)\n }\n}\n\nfunction bindAppGlobalListeners(\n target: InternalRuntimeState,\n handlers: {\n onError?: ((...args: any[]) => any) | undefined\n onPageNotFound?: ((...args: any[]) => any) | undefined\n onUnhandledRejection?: ((...args: any[]) => any) | undefined\n onThemeChange?: ((...args: any[]) => any) | undefined\n },\n) {\n bindAppGlobalListener(target, {\n hookName: 'onError',\n onApiName: 'onError',\n offApiName: 'offError',\n capabilityName: 'appErrorListener',\n userHandler: handlers.onError,\n })\n bindAppGlobalListener(target, {\n hookName: 'onPageNotFound',\n onApiName: 'onPageNotFound',\n offApiName: 'offPageNotFound',\n capabilityName: 'appPageNotFoundListener',\n userHandler: handlers.onPageNotFound,\n })\n bindAppGlobalListener(target, {\n hookName: 'onUnhandledRejection',\n onApiName: 'onUnhandledRejection',\n offApiName: 'offUnhandledRejection',\n capabilityName: 'appUnhandledRejectionListener',\n userHandler: handlers.onUnhandledRejection,\n })\n bindAppGlobalListener(target, {\n hookName: 'onThemeChange',\n onApiName: 'onThemeChange',\n offApiName: 'offThemeChange',\n capabilityName: 'appThemeChangeListener',\n userHandler: handlers.onThemeChange,\n })\n}\n\n/**\n * 注册 App 入口(框架内部使用)。\n * @internal\n */\nexport function registerApp<D extends object, C extends ComputedDefinitions, M extends MethodDefinitions>(\n runtimeApp: RuntimeApp<D, C, M>,\n methods: MethodDefinitions,\n watch: WatchMap | undefined,\n setup: DefineAppOptions<D, C, M>['setup'],\n mpOptions: MiniProgramAppOptions,\n) {\n if (typeof App !== 'function') {\n throw new TypeError('createApp 需要全局 App 构造器可用')\n }\n\n const methodNames = Object.keys(methods ?? {})\n const appOptions: Record<string, any> = {\n ...mpOptions,\n }\n\n appOptions.globalData = appOptions.globalData ?? {}\n\n if (!appOptions[WEVU_INLINE_HANDLER]) {\n appOptions[WEVU_INLINE_HANDLER] = function __weapp_vite_inline(this: InternalRuntimeState, event: any) {\n const runtime = (this as any).__wevu\n const ctx = runtime?.proxy ?? this\n const inlineMap = runtime?.methods?.[WEVU_INLINE_MAP_KEY]\n return runInlineExpression(ctx, undefined, event, inlineMap)\n }\n }\n\n const userOnLaunch = appOptions.onLaunch\n const userOnError = appOptions.onError\n const userOnPageNotFound = (appOptions as any).onPageNotFound\n const userOnUnhandledRejection = (appOptions as any).onUnhandledRejection\n const userOnThemeChange = (appOptions as any).onThemeChange\n appOptions.onLaunch = function onLaunch(this: InternalRuntimeState, ...args: any[]) {\n this[WEVU_IS_APP_INSTANCE_KEY] = true\n mountRuntimeInstance(this, runtimeApp, watch, setup)\n bindMemoryWarningListener(this)\n bindAppGlobalListeners(this, {\n onError: userOnError,\n onPageNotFound: userOnPageNotFound,\n onUnhandledRejection: userOnUnhandledRejection,\n onThemeChange: userOnThemeChange,\n })\n callHookList(this, 'onLaunch', args)\n if (typeof userOnLaunch === 'function') {\n userOnLaunch.apply(this, args)\n }\n }\n\n const userOnShow = appOptions.onShow\n appOptions.onShow = function onShow(this: InternalRuntimeState, ...args: any[]) {\n callHookList(this, 'onShow', args)\n if (typeof userOnShow === 'function') {\n userOnShow.apply(this, args)\n }\n }\n\n const userOnHide = appOptions.onHide\n appOptions.onHide = function onHide(this: InternalRuntimeState, ...args: any[]) {\n callHookList(this, 'onHide', args)\n if (typeof userOnHide === 'function') {\n userOnHide.apply(this, args)\n }\n }\n\n delete appOptions.onError\n delete (appOptions as any).onPageNotFound\n delete (appOptions as any).onUnhandledRejection\n delete (appOptions as any).onThemeChange\n\n for (const methodName of methodNames) {\n const userMethod = appOptions[methodName]\n appOptions[methodName] = function runtimeMethod(this: InternalRuntimeState, ...args: any[]) {\n const runtime = this.__wevu\n let result: unknown\n const bound = runtime?.methods?.[methodName]\n if (bound) {\n result = bound.apply(runtime.proxy, args)\n }\n if (typeof userMethod === 'function') {\n return userMethod.apply(this, args)\n }\n return result\n }\n }\n\n App(appOptions)\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,gCAAgC;AACtC,MAAM,8BAA8B;AAEpC,SAAS,0BAA0B,QAA8B;CAC/D,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