@mpcore/simulator 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -21,6 +21,41 @@ function validateConstructedBehaviors(definition, visited = /* @__PURE__ */ new
21
21
  }
22
22
  }
23
23
  //#endregion
24
+ //#region src/host/attachmentBindingUpdates.ts
25
+ const bindingUpdates = /* @__PURE__ */ new WeakMap();
26
+ const instanceScopes = /* @__PURE__ */ new WeakMap();
27
+ /** 实例经渲染上下文归属页面,不扩展公开 renderer context 的参数契约。 */
28
+ function bindAttachmentBindingScope(instance, scope) {
29
+ instanceScopes.set(instance, instanceScopes.get(scope) ?? scope);
30
+ }
31
+ /** 仅在挂载回调内同步逻辑绑定,不接管视图提交和 setData 回调。 */
32
+ function runWithAttachmentBindingUpdates(scope, update, callback, value) {
33
+ const previous = bindingUpdates.get(scope);
34
+ const state = previous ?? {
35
+ revision: 0,
36
+ update
37
+ };
38
+ const previousUpdate = state.update;
39
+ state.update = update;
40
+ bindingUpdates.set(scope, state);
41
+ try {
42
+ return callback(value);
43
+ } finally {
44
+ if (previous) state.update = previousUpdate;
45
+ else bindingUpdates.delete(scope);
46
+ }
47
+ }
48
+ function getAttachmentBindingRevision(instance) {
49
+ return bindingUpdates.get(instanceScopes.get(instance) ?? instance);
50
+ }
51
+ function synchronizeAttachmentBindings(instance) {
52
+ const state = bindingUpdates.get(instanceScopes.get(instance) ?? instance);
53
+ if (state) {
54
+ state.revision++;
55
+ state.update();
56
+ }
57
+ }
58
+ //#endregion
24
59
  //#region src/host/componentPageAttachment.ts
25
60
  const definitionAttachments = /* @__PURE__ */ new WeakMap();
26
61
  const instanceAttachments = /* @__PURE__ */ new WeakMap();
@@ -36,8 +71,11 @@ function getComponentPageStyleIsolation(instance) {
36
71
  function isComponentPageAttaching(instance) {
37
72
  return attachingInstances.has(instance);
38
73
  }
39
- function registerComponentPageAttachment(definition, attach) {
40
- definitionAttachments.set(definition, attach);
74
+ function registerComponentPageAttachment(definition, created, attached) {
75
+ definitionAttachments.set(definition, {
76
+ created,
77
+ attached
78
+ });
41
79
  }
42
80
  function bindComponentPageAttachment(instance, definition) {
43
81
  const attach = definitionAttachments.get(definition);
@@ -48,13 +86,14 @@ function bindComponentPageAttachment(instance, definition) {
48
86
  if (typeof options?.styleIsolation === "string") instanceStyleIsolation.set(instance, options.styleIsolation);
49
87
  }
50
88
  }
51
- function attachComponentPage(instance) {
89
+ function attachComponentPage(instance, updateBindings) {
52
90
  const attach = instanceAttachments.get(instance);
53
91
  if (!attach) return false;
54
92
  instanceAttachments.delete(instance);
55
93
  attachingInstances.add(instance);
56
94
  try {
57
- attach.call(instance);
95
+ attach.created(instance);
96
+ runWithAttachmentBindingUpdates(instance, updateBindings, attach.attached, instance);
58
97
  } finally {
59
98
  attachingInstances.delete(instance);
60
99
  }
@@ -68,15 +107,23 @@ function createDuplicateRegistrationError(kind, id) {
68
107
  function callDefinitionMethod(instance, method, args) {
69
108
  if (typeof method === "function") return method.apply(instance, args);
70
109
  }
110
+ function composeDefinitionMethods(primary, secondary) {
111
+ if (typeof primary !== "function" || typeof secondary !== "function" || primary === secondary) return primary ?? secondary;
112
+ return function composedDefinitionMethod(...args) {
113
+ const result = primary.apply(this, args);
114
+ secondary.apply(this, args);
115
+ return result;
116
+ };
117
+ }
71
118
  function normalizeComponentPageDefinition(definition) {
72
119
  const { lifetimes = {}, methods = {}, pageLifetimes = {}, ...rest } = definition;
73
120
  const created = lifetimes.created ?? rest.created;
74
121
  const attached = lifetimes.attached ?? rest.attached;
75
- const ready = lifetimes.ready ?? rest.ready ?? methods.onReady ?? rest.onReady;
122
+ const ready = composeDefinitionMethods(lifetimes.ready ?? rest.ready, methods.onReady ?? rest.onReady);
76
123
  const detached = lifetimes.detached ?? rest.detached ?? methods.onUnload ?? rest.onUnload;
77
124
  const load = methods.onLoad ?? rest.onLoad;
78
- const show = pageLifetimes.show ?? methods.onShow ?? rest.onShow;
79
- const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
125
+ const show = typeof pageLifetimes.show === "function" ? composeDefinitionMethods(pageLifetimes.show, methods.onShow) : methods.onShow ?? rest.onShow;
126
+ const hide = typeof pageLifetimes.hide === "function" ? composeDefinitionMethods(pageLifetimes.hide, methods.onHide) : methods.onHide ?? rest.onHide;
80
127
  const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
81
128
  const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
82
129
  const pageDefinition = {
@@ -104,10 +151,7 @@ function normalizeComponentPageDefinition(definition) {
104
151
  return callDefinitionMethod(this, routeDone, args);
105
152
  }
106
153
  };
107
- registerComponentPageAttachment(pageDefinition, function() {
108
- callDefinitionMethod(this, created, []);
109
- callDefinitionMethod(this, attached, []);
110
- });
154
+ registerComponentPageAttachment(pageDefinition, (instance) => callDefinitionMethod(instance, created, []), (instance) => callDefinitionMethod(instance, attached, []));
111
155
  return pageDefinition;
112
156
  }
113
157
  function createHostRegistries() {
@@ -298,7 +342,7 @@ function resolveCapabilityValue(source, schema) {
298
342
  }
299
343
  return current;
300
344
  }
301
- function createHeadlessWx(driver, runtimeConsole = console) {
345
+ function createHeadlessWx(driver, runtimeConsole = console, workers) {
302
346
  const eventBus = createHeadlessUniEventBus();
303
347
  const rpx2px = (value) => {
304
348
  const width = driver.getWindowInfoSync().windowWidth;
@@ -306,6 +350,10 @@ function createHeadlessWx(driver, runtimeConsole = console) {
306
350
  };
307
351
  const capabilityTree = {
308
352
  canIUse: true,
353
+ ...workers ? {
354
+ createWorker: true,
355
+ preDownloadSubpackage: true
356
+ } : {},
309
357
  canvasToTempFilePath: true,
310
358
  chooseImage: { return: {
311
359
  errMsg: true,
@@ -563,6 +611,14 @@ function createHeadlessWx(driver, runtimeConsole = console) {
563
611
  ...eventBus,
564
612
  [WEVU_ROUTE_EVENT_CONTRACT_KEY]: 1,
565
613
  [WEVU_PAGE_SCROLL_EVENT_CONTRACT_KEY]: 1,
614
+ createWorker: (script) => {
615
+ if (!workers) throw new Error("Worker host is unavailable");
616
+ return workers.createWorker(script);
617
+ },
618
+ preDownloadSubpackage: (option) => {
619
+ if (!workers) throw new Error("Worker host is unavailable");
620
+ workers.preDownloadSubpackage(option);
621
+ },
566
622
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
567
623
  canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
568
624
  chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
@@ -686,9 +742,7 @@ function createHeadlessWx(driver, runtimeConsole = console) {
686
742
  navigateBack: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
687
743
  driver.navigateBack(deferred);
688
744
  }, deferred)),
689
- navigateTo: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
690
- driver.navigateTo(deferred);
691
- }, deferred)),
745
+ navigateTo: (option) => runNavigationApi(driver, option, (deferred) => driver.navigateTo(deferred)),
692
746
  nextTick: (callback) => driver.nextTick(callback),
693
747
  offBeforeAppRoute: (listener) => driver.offBeforeAppRoute(listener),
694
748
  offBeforePageUnload: (listener) => driver.offBeforePageUnload(listener),
@@ -827,6 +881,208 @@ function createMiniProgramRuntimeGlobals(availableGlobals, overrides) {
827
881
  return Object.assign(globals, availableGlobals, overrides);
828
882
  }
829
883
  //#endregion
884
+ //#region src/kernel/scheduler.ts
885
+ var RuntimeScheduler = class {
886
+ intervals = /* @__PURE__ */ new Set();
887
+ timeouts = /* @__PURE__ */ new Set();
888
+ closed = false;
889
+ canceledHandle;
890
+ onError;
891
+ constructor(onError) {
892
+ this.onError = onError;
893
+ }
894
+ clearInterval(handle) {
895
+ this.intervals.delete(handle);
896
+ clearInterval(handle);
897
+ }
898
+ clearTimeout(handle) {
899
+ this.timeouts.delete(handle);
900
+ clearTimeout(handle);
901
+ }
902
+ close() {
903
+ if (this.closed) return;
904
+ this.closed = true;
905
+ for (const handle of this.intervals) clearInterval(handle);
906
+ for (const handle of this.timeouts) clearTimeout(handle);
907
+ this.intervals.clear();
908
+ this.timeouts.clear();
909
+ }
910
+ queueMicrotask(handler) {
911
+ if (this.closed) return;
912
+ queueMicrotask(() => {
913
+ if (this.closed) return;
914
+ try {
915
+ handler();
916
+ } catch (error) {
917
+ this.onError(error);
918
+ }
919
+ });
920
+ }
921
+ setInterval(handler, timeout, ...args) {
922
+ if (this.closed) return this.getCanceledHandle();
923
+ const handle = setInterval(() => {
924
+ try {
925
+ handler(...args);
926
+ } catch (error) {
927
+ this.onError(error);
928
+ }
929
+ }, timeout);
930
+ this.intervals.add(handle);
931
+ return handle;
932
+ }
933
+ setTimeout(handler, timeout, ...args) {
934
+ if (this.closed) return this.getCanceledHandle();
935
+ const handle = setTimeout(() => {
936
+ this.timeouts.delete(handle);
937
+ try {
938
+ handler(...args);
939
+ } catch (error) {
940
+ this.onError(error);
941
+ }
942
+ }, timeout);
943
+ this.timeouts.add(handle);
944
+ return handle;
945
+ }
946
+ /** 已销毁 realm 的 Promise 回调不能复活任务,也不能向外泄漏异步拒绝。 */
947
+ getCanceledHandle() {
948
+ if (!this.canceledHandle) {
949
+ this.canceledHandle = setTimeout(() => {}, 0);
950
+ clearTimeout(this.canceledHandle);
951
+ }
952
+ return this.canceledHandle;
953
+ }
954
+ };
955
+ //#endregion
956
+ //#region src/runtime/workerHost.ts
957
+ /** 两种 simulator 共用消息与生命周期;每个 worker 独立模块缓存、全局对象及计时器。 */
958
+ function createWorkerHost(options) {
959
+ const active = /* @__PURE__ */ new Set();
960
+ let closed = false;
961
+ const configuredRoot = () => {
962
+ return JSON.parse(options.read(join(options.root, "app.json")) ?? "{}").workers;
963
+ };
964
+ return {
965
+ apis: {
966
+ preDownloadSubpackage(option) {
967
+ const config = configuredRoot();
968
+ if (option.packageType !== "workers" || typeof config !== "object" || !config.isSubpackage) {
969
+ const error = /* @__PURE__ */ new Error("preDownloadSubpackage:fail workers subpackage is not configured");
970
+ option.fail?.(error);
971
+ option.complete?.();
972
+ return;
973
+ }
974
+ const result = { errMsg: "preDownloadSubpackage:ok" };
975
+ option.success?.(result);
976
+ option.complete?.(result);
977
+ },
978
+ createWorker(scriptPath) {
979
+ if (closed) throw new Error("createWorker:fail runtime has closed");
980
+ const config = configuredRoot();
981
+ const directory = typeof config === "string" ? config : config?.path;
982
+ if (!directory || typeof scriptPath !== "string" || !scriptPath.endsWith(".js")) throw new Error("createWorker:fail invalid worker path");
983
+ const root = normalize(join(options.root, directory));
984
+ const entry = normalize(join(options.root, scriptPath));
985
+ const inside = (file) => file.startsWith(`${root}/`);
986
+ if (!inside(entry) || options.read(entry) === void 0) throw new Error("createWorker:fail worker entry is outside the configured directory or missing");
987
+ const messages = /* @__PURE__ */ new Set();
988
+ const incoming = /* @__PURE__ */ new Set();
989
+ const errors = /* @__PURE__ */ new Set();
990
+ const cache = /* @__PURE__ */ new Map();
991
+ let terminated = false;
992
+ const scheduler = new RuntimeScheduler((error) => {
993
+ const value = { message: error instanceof Error ? error.message : String(error) };
994
+ if (errors.size) for (const listener of errors) listener(value);
995
+ else options.console.error(value.message);
996
+ });
997
+ const post = (listeners, message) => {
998
+ if (terminated) return;
999
+ const copy = structuredClone(message);
1000
+ scheduler.setTimeout(() => {
1001
+ for (const listener of [...listeners]) {
1002
+ if (terminated) break;
1003
+ listener(copy);
1004
+ }
1005
+ }, 0);
1006
+ };
1007
+ const globals = {
1008
+ wx: void 0,
1009
+ App: void 0,
1010
+ Page: void 0,
1011
+ Component: void 0,
1012
+ getApp: void 0,
1013
+ console: options.console,
1014
+ worker: {
1015
+ onMessage: (listener) => incoming.add(listener),
1016
+ postMessage: (message) => post(messages, message)
1017
+ },
1018
+ setTimeout: scheduler.setTimeout.bind(scheduler),
1019
+ clearTimeout: scheduler.clearTimeout.bind(scheduler),
1020
+ setInterval: scheduler.setInterval.bind(scheduler),
1021
+ clearInterval: scheduler.clearInterval.bind(scheduler)
1022
+ };
1023
+ globals.globalThis = globals;
1024
+ const execute = options.createExecutor(globals);
1025
+ const load = (file) => {
1026
+ if (terminated) return;
1027
+ if (!inside(file)) throw new Error("Worker require cannot leave its configured directory");
1028
+ if (cache.has(file)) return cache.get(file).exports;
1029
+ const source = options.read(file);
1030
+ if (source === void 0) throw new Error(`Missing worker module: ${file}`);
1031
+ if (file.endsWith(".json")) return JSON.parse(source);
1032
+ const module = { exports: {} };
1033
+ cache.set(file, module);
1034
+ const require = Object.assign((request) => {
1035
+ const target = resolveMiniProgramModule(file, request, root, (candidate) => options.read(candidate) !== void 0);
1036
+ if (!target) throw new Error(`Cannot resolve worker module: ${request}`);
1037
+ return load(target);
1038
+ }, { async: (request) => Promise.resolve().then(() => require(request)) });
1039
+ try {
1040
+ execute(source, file, module, require);
1041
+ } catch (error) {
1042
+ cache.delete(file);
1043
+ throw error;
1044
+ }
1045
+ return module.exports;
1046
+ };
1047
+ const worker = {
1048
+ onMessage: (listener) => {
1049
+ messages.add(listener);
1050
+ },
1051
+ offMessage: (listener) => {
1052
+ if (listener) messages.delete(listener);
1053
+ else messages.clear();
1054
+ },
1055
+ postMessage: (message) => post(incoming, message),
1056
+ onError: (listener) => {
1057
+ errors.add(listener);
1058
+ },
1059
+ offError: (listener) => {
1060
+ if (listener) errors.delete(listener);
1061
+ else errors.clear();
1062
+ },
1063
+ terminate() {
1064
+ if (terminated) return;
1065
+ terminated = true;
1066
+ scheduler.close();
1067
+ messages.clear();
1068
+ incoming.clear();
1069
+ errors.clear();
1070
+ cache.clear();
1071
+ active.delete(worker);
1072
+ }
1073
+ };
1074
+ active.add(worker);
1075
+ scheduler.setTimeout(() => load(entry), 0);
1076
+ return worker;
1077
+ }
1078
+ },
1079
+ close() {
1080
+ closed = true;
1081
+ for (const worker of active) worker.terminate();
1082
+ }
1083
+ };
1084
+ }
1085
+ //#endregion
830
1086
  //#region src/browser/virtualFiles.ts
831
1087
  function normalizeBrowserFilePath(filePath) {
832
1088
  return normalize(filePath).replace(/^\/+/, "").replace(/^\.\//, "");
@@ -932,9 +1188,9 @@ function getBrowserWxsLoader(owner, files) {
932
1188
  function createRequireNotFoundError$1(request, importer) {
933
1189
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
934
1190
  }
935
- function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
1191
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals, workers) {
936
1192
  const runtimeConsole = kernel.diagnostics.createConsole();
937
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
1193
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
938
1194
  return createMiniProgramRuntimeGlobals({
939
1195
  App(definition) {
940
1196
  return registerAppDefinition(registries, definition);
@@ -964,8 +1220,18 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver,
964
1220
  }, globals);
965
1221
  }
966
1222
  function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver, options) {
1223
+ const workers = createWorkerHost({
1224
+ root: options.miniprogramRootPath,
1225
+ read: (file) => readBrowserVirtualFile(files, file),
1226
+ console: options.kernel.diagnostics.createConsole(),
1227
+ createExecutor(globals) {
1228
+ return (source, _file, module, require) => {
1229
+ new Function(`with (this) { return function(module, exports, require) {${source}\n}; }`).call(globals).call(globals, module, module.exports, require);
1230
+ };
1231
+ }
1232
+ });
967
1233
  const moduleCache = /* @__PURE__ */ new Map();
968
- const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
1234
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, workers.apis);
969
1235
  executionContext.globalThis = executionContext;
970
1236
  function executeModule(filePath, loadContext) {
971
1237
  const resolvedPath = normalize(filePath);
@@ -1025,6 +1291,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1025
1291
  };
1026
1292
  const loader = {
1027
1293
  close() {
1294
+ workers.close();
1028
1295
  moduleCache.clear();
1029
1296
  closeBrowserWxsLoader(loader);
1030
1297
  },
@@ -1137,78 +1404,6 @@ function wechat() {
1137
1404
  return { name: "wechat" };
1138
1405
  }
1139
1406
  //#endregion
1140
- //#region src/kernel/scheduler.ts
1141
- var RuntimeScheduler = class {
1142
- intervals = /* @__PURE__ */ new Set();
1143
- timeouts = /* @__PURE__ */ new Set();
1144
- closed = false;
1145
- canceledHandle;
1146
- onError;
1147
- constructor(onError) {
1148
- this.onError = onError;
1149
- }
1150
- clearInterval(handle) {
1151
- this.intervals.delete(handle);
1152
- clearInterval(handle);
1153
- }
1154
- clearTimeout(handle) {
1155
- this.timeouts.delete(handle);
1156
- clearTimeout(handle);
1157
- }
1158
- close() {
1159
- if (this.closed) return;
1160
- this.closed = true;
1161
- for (const handle of this.intervals) clearInterval(handle);
1162
- for (const handle of this.timeouts) clearTimeout(handle);
1163
- this.intervals.clear();
1164
- this.timeouts.clear();
1165
- }
1166
- queueMicrotask(handler) {
1167
- if (this.closed) return;
1168
- queueMicrotask(() => {
1169
- if (this.closed) return;
1170
- try {
1171
- handler();
1172
- } catch (error) {
1173
- this.onError(error);
1174
- }
1175
- });
1176
- }
1177
- setInterval(handler, timeout, ...args) {
1178
- if (this.closed) return this.getCanceledHandle();
1179
- const handle = setInterval(() => {
1180
- try {
1181
- handler(...args);
1182
- } catch (error) {
1183
- this.onError(error);
1184
- }
1185
- }, timeout);
1186
- this.intervals.add(handle);
1187
- return handle;
1188
- }
1189
- setTimeout(handler, timeout, ...args) {
1190
- if (this.closed) return this.getCanceledHandle();
1191
- const handle = setTimeout(() => {
1192
- this.timeouts.delete(handle);
1193
- try {
1194
- handler(...args);
1195
- } catch (error) {
1196
- this.onError(error);
1197
- }
1198
- }, timeout);
1199
- this.timeouts.add(handle);
1200
- return handle;
1201
- }
1202
- /** 已销毁 realm 的 Promise 回调不能复活任务,也不能向外泄漏异步拒绝。 */
1203
- getCanceledHandle() {
1204
- if (!this.canceledHandle) {
1205
- this.canceledHandle = setTimeout(() => {}, 0);
1206
- clearTimeout(this.canceledHandle);
1207
- }
1208
- return this.canceledHandle;
1209
- }
1210
- };
1211
- //#endregion
1212
1407
  //#region src/kernel/runtimeKernel.ts
1213
1408
  var RuntimeKernel = class {
1214
1409
  diagnostics = new RuntimeDiagnostics();
@@ -1792,6 +1987,7 @@ function createComponentInstance(options) {
1792
1987
  const previousProperties = Object.fromEntries(propertyKeys.map((key) => [key, cloneValue(instance.properties[key])]));
1793
1988
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1794
1989
  for (const key of dataKeys) instance.properties[key] = instance.data[key];
1990
+ synchronizeAttachmentBindings(instance);
1795
1991
  runComponentObservers(definition, instance, changedKeys, previousProperties);
1796
1992
  if (options.requestRender) options.requestRender(callback);
1797
1993
  else callback?.();
@@ -1835,7 +2031,8 @@ function isComponentAttached(instance) {
1835
2031
  return attachmentStates.get(instance) === "attached";
1836
2032
  }
1837
2033
  function hasPendingComponentAttachments(instances) {
1838
- return [...instances].some((instance) => attachmentStates.get(instance) === "attaching");
2034
+ for (const instance of instances) if (attachmentStates.get(instance) === "attaching") return true;
2035
+ return false;
1839
2036
  }
1840
2037
  function flushComponentReady(instances, ready) {
1841
2038
  const all = [...instances];
@@ -1845,19 +2042,71 @@ function flushComponentReady(instances, ready) {
1845
2042
  for (const instance of pending) ready(instance);
1846
2043
  return pending.length > 0;
1847
2044
  }
1848
- function flushComponentAttachments(instances, attach) {
1849
- const pending = [...instances].filter((instance) => !attachmentStates.has(instance));
1850
- for (const instance of pending) attachmentStates.set(instance, "attaching");
2045
+ function flushComponentAttachments(componentCache, scopeIds, attach) {
2046
+ const pending = /* @__PURE__ */ new Map();
2047
+ for (const scopeId of scopeIds) {
2048
+ const instance = componentCache.get(scopeId);
2049
+ if (!instance) continue;
2050
+ const state = attachmentStates.get(instance);
2051
+ if (state === "attaching") return false;
2052
+ if (!state) pending.set(scopeId, instance);
2053
+ }
2054
+ for (const instance of pending.values()) attachmentStates.set(instance, "attaching");
1851
2055
  try {
1852
- for (const instance of pending) try {
1853
- attach(instance);
1854
- } finally {
1855
- attachmentStates.set(instance, "attached");
2056
+ for (const [scopeId, instance] of pending) {
2057
+ if (componentCache.get(scopeId) !== instance) return "restart";
2058
+ let restart;
2059
+ try {
2060
+ restart = attach(instance);
2061
+ } finally {
2062
+ attachmentStates.set(instance, "attached");
2063
+ }
2064
+ if (restart) return "restart";
1856
2065
  }
1857
2066
  } finally {
1858
- for (const instance of pending) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
2067
+ for (const instance of pending.values()) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
1859
2068
  }
1860
- return pending.length > 0;
2069
+ return pending.size > 0 ? "attached" : false;
2070
+ }
2071
+ //#endregion
2072
+ //#region src/runtime/componentInstance/construction.ts
2073
+ const constructionStates = /* @__PURE__ */ new WeakMap();
2074
+ const constructingInstances = /* @__PURE__ */ new WeakSet();
2075
+ function isComponentConstructing(instance) {
2076
+ return instance !== void 0 && constructingInstances.has(instance);
2077
+ }
2078
+ function hasPendingComponentConstruction(componentCache) {
2079
+ return constructionStates.has(componentCache);
2080
+ }
2081
+ function beginComponentConstruction(componentCache, scopeId, instance) {
2082
+ let state = constructionStates.get(componentCache);
2083
+ if (!state) {
2084
+ state = {
2085
+ depth: 0,
2086
+ created: /* @__PURE__ */ new Map()
2087
+ };
2088
+ constructionStates.set(componentCache, state);
2089
+ }
2090
+ state.depth++;
2091
+ state.created.set(scopeId, instance);
2092
+ constructingInstances.add(instance);
2093
+ }
2094
+ function discardComponentConstruction(componentCache, componentScopes, scopeId) {
2095
+ const state = constructionStates.get(componentCache);
2096
+ const prefix = `${scopeId}/`;
2097
+ for (const [createdScopeId, instance] of state.created) {
2098
+ if (createdScopeId !== scopeId && !createdScopeId.startsWith(prefix)) continue;
2099
+ if (componentCache.get(createdScopeId) === instance) {
2100
+ componentCache.delete(createdScopeId);
2101
+ componentScopes.delete(createdScopeId);
2102
+ }
2103
+ state.created.delete(createdScopeId);
2104
+ }
2105
+ }
2106
+ function finishComponentConstruction(componentCache, instance) {
2107
+ constructingInstances.delete(instance);
2108
+ const state = constructionStates.get(componentCache);
2109
+ if (--state.depth === 0) constructionStates.delete(componentCache);
1861
2110
  }
1862
2111
  //#endregion
1863
2112
  //#region src/runtime/componentInstance/discardedReady.ts
@@ -1880,6 +2129,35 @@ function flushDiscardedComponentReady(cache, pageScopeId, ready) {
1880
2129
  if (!pending.size) discardedReady.delete(cache);
1881
2130
  }
1882
2131
  //#endregion
2132
+ //#region src/runtime/componentInstance/propertyBindings.ts
2133
+ const consumedPageChanges = /* @__PURE__ */ new WeakMap();
2134
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys, beforeObservers) {
2135
+ const freshPageChanges = changedPageKeys.length > 0 && consumedPageChanges.get(instance) !== changedPageKeys;
2136
+ if (freshPageChanges) consumedPageChanges.set(instance, changedPageKeys);
2137
+ const changedRootKeys = [];
2138
+ const previousProperties = {};
2139
+ for (const [key, value] of Object.entries(nextProperties)) {
2140
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
2141
+ const bindingExpression = bindingExpressions[key];
2142
+ const bindingAffected = freshPageChanges && !!bindingExpression && changedPageKeys.some((changedKey) => {
2143
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2144
+ });
2145
+ const previousSnapshot = instance.__propertySnapshots?.[key];
2146
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2147
+ previousProperties[key] = instance.properties[key];
2148
+ const deliveredValue = cloneValue(nextValue);
2149
+ instance.properties[key] = deliveredValue;
2150
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
2151
+ changedRootKeys.push(key);
2152
+ }
2153
+ instance.__propertySnapshots ??= {};
2154
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
2155
+ }
2156
+ if (changedRootKeys.length === 0) return;
2157
+ beforeObservers?.(instance, "properties");
2158
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2159
+ }
2160
+ //#endregion
1883
2161
  //#region src/runtime/pageLifecycle.ts
1884
2162
  const loadingPages = /* @__PURE__ */ new WeakSet();
1885
2163
  function isPageBeforeReady(page) {
@@ -1907,6 +2185,262 @@ function runInitialPageLifecycles(page, query, scheduler, isAlive, renderCompone
1907
2185
  }, 0);
1908
2186
  }
1909
2187
  //#endregion
2188
+ //#region src/view/eventBindingParser.ts
2189
+ const LEGACY_EVENT_NAME_RE = /^\w+$/;
2190
+ const EVENT_BINDING_PREFIXES = [
2191
+ {
2192
+ prefix: "capture-bind:",
2193
+ priority: 0,
2194
+ stopAfter: false,
2195
+ phase: "capture"
2196
+ },
2197
+ {
2198
+ prefix: "capture-catch:",
2199
+ priority: 0,
2200
+ stopAfter: true,
2201
+ phase: "capture"
2202
+ },
2203
+ {
2204
+ prefix: "capture-bind",
2205
+ priority: 1,
2206
+ stopAfter: false,
2207
+ phase: "capture"
2208
+ },
2209
+ {
2210
+ prefix: "capture-catch",
2211
+ priority: 1,
2212
+ stopAfter: true,
2213
+ phase: "capture"
2214
+ },
2215
+ {
2216
+ prefix: "bind:",
2217
+ priority: 0,
2218
+ stopAfter: false,
2219
+ phase: "bubble"
2220
+ },
2221
+ {
2222
+ prefix: "catch:",
2223
+ priority: 0,
2224
+ stopAfter: true,
2225
+ phase: "bubble"
2226
+ },
2227
+ {
2228
+ prefix: "bind",
2229
+ priority: 1,
2230
+ stopAfter: false,
2231
+ phase: "bubble"
2232
+ },
2233
+ {
2234
+ prefix: "catch",
2235
+ priority: 1,
2236
+ stopAfter: true,
2237
+ phase: "bubble"
2238
+ }
2239
+ ];
2240
+ function parseEventBinding(attributeName, method) {
2241
+ const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2242
+ if (!definition) return null;
2243
+ const eventName = attributeName.slice(definition.prefix.length);
2244
+ if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2245
+ return {
2246
+ eventName,
2247
+ method,
2248
+ phase: definition.phase,
2249
+ priority: definition.priority,
2250
+ stopAfter: definition.stopAfter
2251
+ };
2252
+ }
2253
+ function collectEventBindings(attributes = {}, includeCapture = true) {
2254
+ const eventBindings = /* @__PURE__ */ new Map();
2255
+ let captureEventBindings;
2256
+ const priorities = /* @__PURE__ */ new Map();
2257
+ for (const [attributeName, method] of Object.entries(attributes)) {
2258
+ const candidate = parseEventBinding(attributeName, method);
2259
+ if (!candidate || !includeCapture && candidate.phase === "capture") continue;
2260
+ const eventPriorities = priorities.get(candidate.eventName) ?? {};
2261
+ if (candidate.priority < (eventPriorities[candidate.phase] ?? -1)) continue;
2262
+ (candidate.phase === "bubble" ? eventBindings : captureEventBindings ??= /* @__PURE__ */ new Map()).set(candidate.eventName, {
2263
+ method: candidate.method,
2264
+ stopAfter: candidate.stopAfter
2265
+ });
2266
+ eventPriorities[candidate.phase] = candidate.priority;
2267
+ priorities.set(candidate.eventName, eventPriorities);
2268
+ }
2269
+ return {
2270
+ eventBindings,
2271
+ captureEventBindings
2272
+ };
2273
+ }
2274
+ /** 单事件查询只保留命中的绑定,原生交互不构造整张事件表。 */
2275
+ function resolveEventBindingPhases(attributes, eventName, includeCapture = true) {
2276
+ if (!attributes) return null;
2277
+ let bindings = null;
2278
+ let bubblePriority = -1;
2279
+ let capturePriority = -1;
2280
+ for (const [attributeName, method] of Object.entries(attributes)) {
2281
+ const candidate = parseEventBinding(attributeName, method);
2282
+ if (!candidate || candidate.eventName !== eventName || !includeCapture && candidate.phase === "capture") continue;
2283
+ const priority = candidate.phase === "bubble" ? bubblePriority : capturePriority;
2284
+ if (candidate.priority < priority) continue;
2285
+ bindings ??= {};
2286
+ bindings[candidate.phase] = {
2287
+ method: candidate.method,
2288
+ stopAfter: candidate.stopAfter
2289
+ };
2290
+ if (candidate.phase === "bubble") bubblePriority = candidate.priority;
2291
+ else capturePriority = candidate.priority;
2292
+ }
2293
+ return bindings;
2294
+ }
2295
+ //#endregion
2296
+ //#region src/view/nodeDataset.ts
2297
+ const DATASET_NAME_RE = /-([a-z])/g;
2298
+ function isDatasetAttribute(attributeName) {
2299
+ return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2300
+ }
2301
+ function toDatasetKey(attributeName) {
2302
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2303
+ }
2304
+ function collectNodeDataset(node) {
2305
+ if (node.dataset) return { ...node.dataset };
2306
+ const dataset = {};
2307
+ for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2308
+ return dataset;
2309
+ }
2310
+ //#endregion
2311
+ //#region src/view/componentEvent.ts
2312
+ const eventNodes = /* @__PURE__ */ new WeakMap();
2313
+ /** 在构造子树之前建立父链,created/observer 中的事件也能访问声明树。 */
2314
+ function registerComponentEventNode(node, scope, parent) {
2315
+ node.parent = parent ?? null;
2316
+ eventNodes.set(node, {
2317
+ scope,
2318
+ target: node
2319
+ });
2320
+ }
2321
+ /** 宿主与作用域共享同一份分阶段绑定,eventBindings 仍是原有的冒泡存储。 */
2322
+ function bindComponentEventHost(node) {
2323
+ const bindings = collectEventBindings(node.attribs);
2324
+ eventNodes.get(node).bindings = bindings;
2325
+ return bindings;
2326
+ }
2327
+ /** 渲染会把宿主折叠进模板根;事件仍保留两层独立的绑定和声明所有者。 */
2328
+ function mergeComponentEventRoot(root, host) {
2329
+ const entry = eventNodes.get(root);
2330
+ if (entry.target === root) entry.target = {
2331
+ attribs: root.attribs,
2332
+ dataset: root.dataset
2333
+ };
2334
+ entry.hosts ??= [];
2335
+ entry.hosts.push(host);
2336
+ root.parent = host.parent;
2337
+ }
2338
+ /** 按渲染完成后的实际宿主父链排序;输入只包含本轮存活的组件作用域。 */
2339
+ function orderComponentAttachmentScopes(scopeIds, componentScopes) {
2340
+ const hostScopes = /* @__PURE__ */ new Map();
2341
+ for (const scopeId of scopeIds) hostScopes.set(componentScopes.get(scopeId).hostNode, scopeId);
2342
+ const ordered = [];
2343
+ const visited = /* @__PURE__ */ new Set();
2344
+ const visit = (node) => {
2345
+ if (!node || visited.has(node)) return;
2346
+ visited.add(node);
2347
+ visit(node.parent);
2348
+ const hosts = eventNodes.get(node)?.hosts;
2349
+ if (hosts) for (let index = hosts.length - 1; index >= 0; index--) visit(hosts[index]);
2350
+ const scopeId = hostScopes.get(node);
2351
+ if (scopeId !== void 0) ordered.push(scopeId);
2352
+ };
2353
+ for (const host of hostScopes.keys()) visit(host);
2354
+ return ordered;
2355
+ }
2356
+ function buildComponentTrigger(componentScopeId, context) {
2357
+ return (instance, eventName, detail, triggerOptions) => {
2358
+ const originScope = context.componentScopes.get(componentScopeId);
2359
+ const origin = originScope?.hostNode;
2360
+ if (!originScope || !origin) return;
2361
+ const bubbles = triggerOptions?.bubbles ?? false;
2362
+ const capturePhase = triggerOptions?.capturePhase ?? false;
2363
+ const composed = triggerOptions?.composed ?? false;
2364
+ const target = {
2365
+ dataset: originScope.dataset ?? collectNodeDataset(origin),
2366
+ id: originScope.hostId ?? ""
2367
+ };
2368
+ const mark = instance.__lastInteractionEvent__?.mark;
2369
+ const listeners = [];
2370
+ const collect = (entry, isOrigin) => {
2371
+ if (!composed && entry.scope.getScopeId() !== originScope.listenerScopeId) return false;
2372
+ const bindings = entry.bindings ? {
2373
+ bubble: entry.bindings.eventBindings?.get(eventName),
2374
+ capture: entry.bindings.captureEventBindings?.get(eventName)
2375
+ } : resolveEventBindingPhases(entry.target.attribs, eventName);
2376
+ if (bindings?.bubble || bindings?.capture) listeners.push({
2377
+ scope: entry.scope,
2378
+ bindings,
2379
+ currentTarget: isOrigin ? target : {
2380
+ dataset: collectNodeDataset(entry.target),
2381
+ id: entry.target.attribs?.id ?? ""
2382
+ },
2383
+ origin: isOrigin
2384
+ });
2385
+ return true;
2386
+ };
2387
+ let current = origin;
2388
+ while (current) {
2389
+ const entry = eventNodes.get(current);
2390
+ if (entry) {
2391
+ if (!collect(entry, current === origin)) break;
2392
+ let crossedBoundary = false;
2393
+ for (const host of entry.hosts ?? []) if (!collect(eventNodes.get(host), false)) {
2394
+ crossedBoundary = true;
2395
+ break;
2396
+ }
2397
+ if (crossedBoundary) break;
2398
+ }
2399
+ if (!bubbles && !capturePhase) break;
2400
+ current = current.parent;
2401
+ }
2402
+ const handlers = [];
2403
+ let stopped = false;
2404
+ if (capturePhase) for (let index = listeners.length - 1; index >= 0; index--) {
2405
+ const listener = listeners[index];
2406
+ const binding = listener.bindings.capture;
2407
+ if (binding) {
2408
+ handlers.push({
2409
+ scope: listener.scope,
2410
+ binding,
2411
+ currentTarget: listener.currentTarget
2412
+ });
2413
+ if (binding.stopAfter) {
2414
+ stopped = true;
2415
+ break;
2416
+ }
2417
+ }
2418
+ }
2419
+ if (!stopped) for (const listener of listeners) {
2420
+ if (!bubbles && !listener.origin) continue;
2421
+ const binding = listener.bindings.bubble;
2422
+ if (binding) {
2423
+ handlers.push({
2424
+ scope: listener.scope,
2425
+ binding,
2426
+ currentTarget: listener.currentTarget
2427
+ });
2428
+ if (binding.stopAfter) break;
2429
+ }
2430
+ }
2431
+ for (const { scope, binding, currentTarget } of handlers) scope.getMethod(binding.method)?.({
2432
+ bubbles,
2433
+ capturePhase,
2434
+ composed,
2435
+ currentTarget,
2436
+ detail,
2437
+ mark,
2438
+ target,
2439
+ type: eventName
2440
+ });
2441
+ };
2442
+ }
2443
+ //#endregion
1910
2444
  //#region src/view/conditionalChildren.ts
1911
2445
  function selectConditionalChildren(children, evaluate) {
1912
2446
  const selected = [];
@@ -1962,11 +2496,77 @@ function customTabBarHostScope() {
1962
2496
  };
1963
2497
  }
1964
2498
  //#endregion
2499
+ //#region src/view/inspectionTree.ts
2500
+ const inspectionChildren = /* @__PURE__ */ new WeakMap();
2501
+ const inspectionParents = /* @__PURE__ */ new WeakMap();
2502
+ const emptyChildren = [];
2503
+ function getInspectionChildren(node) {
2504
+ return inspectionChildren.get(node) ?? node.children ?? emptyChildren;
2505
+ }
2506
+ function getInspectionParent(node) {
2507
+ return inspectionParents.get(node) ?? node.parent ?? null;
2508
+ }
2509
+ function collectRenderedNodes(node, nodes) {
2510
+ if (nodes.has(node)) return;
2511
+ nodes.add(node);
2512
+ for (const child of node.children ?? emptyChildren) collectRenderedNodes(child, nodes);
2513
+ }
2514
+ /** 原生检查器保留未投影声明;可见 DOM、WXML 和事件父链不因此增加节点。 */
2515
+ function registerInspectionTrees(root, pass, scopes) {
2516
+ if (!pass.hasUnprojectedSlots) return;
2517
+ const rendered = /* @__PURE__ */ new Set();
2518
+ collectRenderedNodes(root, rendered);
2519
+ const candidates = /* @__PURE__ */ new Map();
2520
+ for (const [entries, group] of pass.slotDeclarations) {
2521
+ if (scopes.get(group.scopeId)?.hostNode !== group.parent) continue;
2522
+ const host = pass.componentRoots.get(group.scopeId);
2523
+ if (!host) continue;
2524
+ for (const entry of entries) for (const node of pass.renderedSlots.get(entry) ?? emptyChildren) candidates.set(node, host);
2525
+ }
2526
+ const nested = /* @__PURE__ */ new Set();
2527
+ const visited = /* @__PURE__ */ new Set();
2528
+ const indexChildren = (node) => {
2529
+ if (visited.has(node)) return;
2530
+ visited.add(node);
2531
+ for (const child of node.children ?? emptyChildren) {
2532
+ nested.add(child);
2533
+ if (!rendered.has(child)) inspectionParents.set(child, node);
2534
+ indexChildren(child);
2535
+ }
2536
+ };
2537
+ for (const node of candidates.keys()) indexChildren(node);
2538
+ for (const [node, host] of candidates) {
2539
+ if (rendered.has(node) || nested.has(node) || node === host) continue;
2540
+ let children = inspectionChildren.get(host);
2541
+ if (!children) {
2542
+ children = [...host.children ?? emptyChildren];
2543
+ inspectionChildren.set(host, children);
2544
+ }
2545
+ children.push(node);
2546
+ inspectionParents.set(node, host);
2547
+ }
2548
+ }
2549
+ //#endregion
1965
2550
  //#region src/view/loopEntries.ts
2551
+ const LOOP_SCOPE_ESCAPE_RE = /[^\w-]/g;
2552
+ function escapeScopeCodeUnit(character) {
2553
+ return `~${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
2554
+ }
2555
+ function encodeLoopCoordinate(value) {
2556
+ return value.replace(LOOP_SCOPE_ESCAPE_RE, escapeScopeCodeUnit);
2557
+ }
1966
2558
  function resolveLoopEntries(value) {
1967
2559
  if (Array.isArray(value)) return value.map((item, index) => [index, item]);
1968
2560
  return value !== null && typeof value === "object" ? Object.entries(value) : [];
1969
2561
  }
2562
+ function resolveLoopInstanceSuffix(item, index, key, occurrences) {
2563
+ if (!key || !occurrences) return `:for-${encodeLoopCoordinate(String(index))}`;
2564
+ const value = key === "*this" ? item : item?.[key];
2565
+ const normalized = encodeLoopCoordinate(String(value ?? ""));
2566
+ const occurrence = occurrences.get(normalized) ?? 0;
2567
+ occurrences.set(normalized, occurrence + 1);
2568
+ return `:key-${normalized}${occurrence ? `:duplicate-${occurrence}` : ""}`;
2569
+ }
1970
2570
  //#endregion
1971
2571
  //#region src/view/renderedTree.ts
1972
2572
  /** 在循环展开和组件替换完成后,让父节点关系指向本次渲染树。 */
@@ -1975,6 +2575,44 @@ function linkRenderedParents(root, parent = null) {
1975
2575
  for (const child of root.children ?? []) linkRenderedParents(child, root);
1976
2576
  }
1977
2577
  //#endregion
2578
+ //#region src/view/renderPass.ts
2579
+ const initializedPages = /* @__PURE__ */ new WeakMap();
2580
+ function createRenderPass(propertyUpdate = false, parent) {
2581
+ return {
2582
+ seenComponentScopes: /* @__PURE__ */ new Set(),
2583
+ componentRoots: /* @__PURE__ */ new Map(),
2584
+ slotDeclarations: /* @__PURE__ */ new Map(),
2585
+ renderedSlots: /* @__PURE__ */ new Map(),
2586
+ hasUnprojectedSlots: false,
2587
+ propertyUpdate,
2588
+ bindingUpdate: parent?.bindingUpdate,
2589
+ bindingRevision: parent?.bindingUpdate?.revision ?? 0
2590
+ };
2591
+ }
2592
+ function createPageRenderPass(page, cache) {
2593
+ const pass = createRenderPass(initializedPages.get(cache)?.has(page) ?? false);
2594
+ pass.bindingUpdate = getAttachmentBindingRevision(page);
2595
+ pass.bindingRevision = pass.bindingUpdate?.revision ?? 0;
2596
+ return pass;
2597
+ }
2598
+ function isRenderPassStale(pass) {
2599
+ return pass.bindingUpdate !== void 0 && pass.bindingUpdate.revision !== pass.bindingRevision;
2600
+ }
2601
+ function markPageTreeConstructed(page, cache) {
2602
+ let pages = initializedPages.get(cache);
2603
+ if (!pages) {
2604
+ pages = /* @__PURE__ */ new WeakSet();
2605
+ initializedPages.set(cache, pages);
2606
+ }
2607
+ pages.add(page);
2608
+ }
2609
+ function registerSlotDeclarations(pass, slots, parent, scopeId) {
2610
+ for (const entries of slots.values()) if (!pass.slotDeclarations.has(entries)) pass.slotDeclarations.set(entries, {
2611
+ parent,
2612
+ scopeId
2613
+ });
2614
+ }
2615
+ //#endregion
1978
2616
  //#region src/view/templateInterpolation.ts
1979
2617
  /** 按表达式词法寻找插值边界,字符串和对象内部的大括号不结束绑定。 */
1980
2618
  function templateInterpolations(source) {
@@ -2266,125 +2904,33 @@ function resolveBrowserComponentPageStyleIsolation(files, page, route, miniprogr
2266
2904
  try {
2267
2905
  config = JSON.parse(source);
2268
2906
  } catch {
2269
- throw new Error(`Invalid browser Component page JSON: ${filename}`);
2270
- }
2271
- if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2272
- const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2273
- return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2274
- }
2275
- //#endregion
2276
- //#region src/runtime/componentInstance/selection.ts
2277
- function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
2278
- if (visited.has(definition)) return false;
2279
- visited.add(definition);
2280
- return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
2281
- }
2282
- /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
2283
- function resolveNativeComponentSelection(instance) {
2284
- if (!instance) return null;
2285
- const definition = instance.__definition__;
2286
- if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
2287
- return instance.export();
2288
- }
2289
- //#endregion
2290
- //#region src/runtime/componentResolution.ts
2291
- function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2292
- const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2293
- if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2294
- const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2295
- return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2296
- }
2297
- //#endregion
2298
- //#region src/view/nodeDataset.ts
2299
- const DATASET_NAME_RE = /-([a-z])/g;
2300
- function isDatasetAttribute(attributeName) {
2301
- return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2302
- }
2303
- function toDatasetKey(attributeName) {
2304
- return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2305
- }
2306
- function collectNodeDataset(node) {
2307
- if (node.dataset) return { ...node.dataset };
2308
- const dataset = {};
2309
- for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2310
- return dataset;
2311
- }
2312
- //#endregion
2313
- //#region src/view/eventBinding.ts
2314
- const LEGACY_EVENT_NAME_RE = /^\w+$/;
2315
- const EVENT_BINDING_PREFIXES = [
2316
- {
2317
- prefix: "bind:",
2318
- priority: 0,
2319
- stopAfter: false
2320
- },
2321
- {
2322
- prefix: "catch:",
2323
- priority: 0,
2324
- stopAfter: true
2325
- },
2326
- {
2327
- prefix: "bind",
2328
- priority: 1,
2329
- stopAfter: false
2330
- },
2331
- {
2332
- prefix: "catch",
2333
- priority: 1,
2334
- stopAfter: true
2335
- }
2336
- ];
2337
- function parseEventBinding(attributeName, method) {
2338
- const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2339
- if (!definition) return null;
2340
- const eventName = attributeName.slice(definition.prefix.length);
2341
- if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2342
- return {
2343
- eventName,
2344
- method,
2345
- priority: definition.priority,
2346
- stopAfter: definition.stopAfter
2347
- };
2348
- }
2349
- function collectMiniProgramEventBindings(attributes = {}) {
2350
- const bindings = /* @__PURE__ */ new Map();
2351
- const priorities = /* @__PURE__ */ new Map();
2352
- for (const [attributeName, method] of Object.entries(attributes)) {
2353
- const candidate = parseEventBinding(attributeName, method);
2354
- if (!candidate || candidate.priority < (priorities.get(candidate.eventName) ?? -1)) continue;
2355
- bindings.set(candidate.eventName, {
2356
- method: candidate.method,
2357
- stopAfter: candidate.stopAfter
2358
- });
2359
- priorities.set(candidate.eventName, candidate.priority);
2360
- }
2361
- return bindings;
2362
- }
2363
- function resolveMiniProgramEventBinding(attributes, eventName) {
2364
- return collectMiniProgramEventBindings(attributes).get(eventName) ?? null;
2365
- }
2366
- /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
2367
- function createMiniProgramEventPayload(node, eventName, event, origin = node) {
2368
- const dataset = collectNodeDataset(node);
2369
- const nodeId = node.attribs?.id ?? "";
2370
- const isOrigin = node === origin;
2371
- return {
2372
- bubbles: false,
2373
- capturePhase: false,
2374
- composed: false,
2375
- currentTarget: {
2376
- dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
2377
- id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
2378
- },
2379
- detail: event.detail,
2380
- mark: event.mark,
2381
- target: {
2382
- dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
2383
- id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
2384
- },
2385
- timeStamp: Date.now(),
2386
- type: eventName
2387
- };
2907
+ throw new Error(`Invalid browser Component page JSON: ${filename}`);
2908
+ }
2909
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2910
+ const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2911
+ return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2912
+ }
2913
+ //#endregion
2914
+ //#region src/runtime/componentInstance/selection.ts
2915
+ function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
2916
+ if (visited.has(definition)) return false;
2917
+ visited.add(definition);
2918
+ return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
2919
+ }
2920
+ /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
2921
+ function resolveNativeComponentSelection(instance) {
2922
+ if (!instance) return null;
2923
+ const definition = instance.__definition__;
2924
+ if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
2925
+ return instance.export();
2926
+ }
2927
+ //#endregion
2928
+ //#region src/runtime/componentResolution.ts
2929
+ function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2930
+ const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2931
+ if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2932
+ const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2933
+ return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2388
2934
  }
2389
2935
  //#endregion
2390
2936
  //#region src/view/selectorQueryScope.ts
@@ -2562,9 +3108,10 @@ function maskTemplateAttributes(source) {
2562
3108
  const INLINE_WXS_RE = /<wxs\b([^>]*)(?<!\/)>([\s\S]*?)<\/wxs\s*>/g;
2563
3109
  function parseWxsTemplateDocument(templateSource) {
2564
3110
  const scripts = [];
2565
- const masked = maskTemplateAttributes(templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
3111
+ const source = templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
2566
3112
  return `<wxs data-sim-wxs="${scripts.push(script) - 1}"${attributes}>wxs-source</wxs>`;
2567
- }));
3113
+ });
3114
+ const masked = maskTemplateAttributes(source);
2568
3115
  const document = parseDocument(`<page>${masked.source}</page>`, {
2569
3116
  xmlMode: false,
2570
3117
  decodeEntities: false,
@@ -2572,7 +3119,7 @@ function parseWxsTemplateDocument(templateSource) {
2572
3119
  lowerCaseTags: false,
2573
3120
  recognizeSelfClosing: true
2574
3121
  });
2575
- if (!scripts.length && !masked.attributes.size) return document;
3122
+ if (!scripts.length && !masked.attributes.size && !/[\r\n]/.test(source)) return document;
2576
3123
  const hasAttributes = masked.attributes.size > 0;
2577
3124
  const restore = (node) => {
2578
3125
  if (hasAttributes && node.attribs) {
@@ -2581,7 +3128,9 @@ function parseWxsTemplateDocument(templateSource) {
2581
3128
  if (node.name === "wxs" && Object.hasOwn(node.attribs ?? {}, "data-sim-wxs")) {
2582
3129
  node.children[0].data = scripts[Number(node.attribs["data-sim-wxs"])];
2583
3130
  delete node.attribs["data-sim-wxs"];
3131
+ return;
2584
3132
  }
3133
+ if (node.children) node.children = node.children.filter((child) => child.type !== "text" || !/^[\t\r\n ]+$/.test(child.data ?? "") || !/[\r\n]/.test(child.data ?? ""));
2585
3134
  for (const child of node.children ?? []) restore(child);
2586
3135
  };
2587
3136
  restore(document);
@@ -2782,67 +3331,6 @@ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFileP
2782
3331
  }
2783
3332
  return resolved.size > 0 ? resolved : void 0;
2784
3333
  }
2785
- function collectComponentEventBindings$1(hostNode) {
2786
- return collectMiniProgramEventBindings(hostNode.attribs);
2787
- }
2788
- function buildComponentTrigger$1(componentScopeId, context, hostNode) {
2789
- const hostDataset = collectDataset$1(hostNode);
2790
- const hostId = hostNode.attribs?.id ?? "";
2791
- return (instance, eventName, detail, triggerOptions) => {
2792
- const originScope = context.componentScopes.get(componentScopeId);
2793
- const interactionMark = instance.__lastInteractionEvent__?.mark;
2794
- const target = {
2795
- dataset: originScope?.dataset ?? hostDataset,
2796
- id: originScope?.hostId ?? hostId
2797
- };
2798
- let currentScopeId = componentScopeId;
2799
- while (currentScopeId) {
2800
- const currentScope = context.componentScopes.get(currentScopeId);
2801
- const binding = currentScope?.eventBindings?.get(eventName);
2802
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
2803
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
2804
- if (handler) handler({
2805
- bubbles: triggerOptions?.bubbles ?? false,
2806
- capturePhase: false,
2807
- composed: triggerOptions?.composed ?? false,
2808
- detail,
2809
- mark: interactionMark,
2810
- target,
2811
- type: eventName,
2812
- currentTarget: {
2813
- dataset: currentScope?.dataset ?? hostDataset,
2814
- id: currentScope?.hostId ?? hostId
2815
- }
2816
- });
2817
- if (binding?.stopAfter) break;
2818
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
2819
- currentScopeId = currentScope?.ownerScopeId;
2820
- }
2821
- };
2822
- }
2823
- function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
2824
- const changedRootKeys = [];
2825
- const previousProperties = {};
2826
- for (const [key, value] of Object.entries(nextProperties)) {
2827
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
2828
- const bindingExpression = bindingExpressions[key];
2829
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
2830
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2831
- });
2832
- const previousSnapshot = instance.__propertySnapshots?.[key];
2833
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2834
- previousProperties[key] = instance.properties[key];
2835
- const deliveredValue = cloneValue(nextValue);
2836
- instance.properties[key] = deliveredValue;
2837
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
2838
- changedRootKeys.push(key);
2839
- }
2840
- instance.__propertySnapshots ??= {};
2841
- instance.__propertySnapshots[key] = cloneValue(nextValue);
2842
- }
2843
- if (changedRootKeys.length === 0) return;
2844
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2845
- }
2846
3334
  function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
2847
3335
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
2848
3336
  return {
@@ -2850,7 +3338,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2850
3338
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
2851
3339
  data: { ...componentInstance.data },
2852
3340
  dataset: collectDataset$1(clonedNode, wxsScopeData(scope)),
2853
- eventBindings: collectComponentEventBindings$1(clonedNode),
3341
+ ...bindComponentEventHost(clonedNode),
2854
3342
  getMethod: (methodName) => {
2855
3343
  const method = componentInstance?.[methodName];
2856
3344
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -2858,6 +3346,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2858
3346
  getScopeId: () => componentScopeId,
2859
3347
  genericComponents,
2860
3348
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3349
+ hostNode: clonedNode,
2861
3350
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
2862
3351
  listenerScopeId: scope.getScopeId(),
2863
3352
  ownerScopeId,
@@ -2880,13 +3369,14 @@ function resolveComponentProperties$1(clonedNode, scope, definition) {
2880
3369
  bindingExpressions
2881
3370
  };
2882
3371
  }
2883
- function createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
3372
+ function createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
2884
3373
  const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
2885
- const componentInstance = createComponentInstance({
3374
+ const instanceOptions = {
2886
3375
  definition: componentEntry.definition,
2887
- requestRender: (callback) => context.session.requestRender(callback),
2888
- triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
2889
- });
3376
+ requestRender: (callback) => context.session.requestRender(callback)
3377
+ };
3378
+ const componentInstance = createComponentInstance(instanceOptions);
3379
+ bindAttachmentBindingScope(componentInstance, context);
2890
3380
  setSelectorQueryScopeId(componentInstance, componentScopeId);
2891
3381
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
2892
3382
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -2894,20 +3384,30 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2894
3384
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
2895
3385
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
2896
3386
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
2897
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
3387
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
3388
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
2898
3389
  context.componentCache.set(componentScopeId, componentInstance);
2899
- beforeCreated?.(componentInstance);
2900
- runComponentLifecycle(componentInstance, "created");
2901
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
2902
- syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
2903
- return componentInstance;
3390
+ try {
3391
+ renderTemplate?.(componentInstance, "defaults");
3392
+ runComponentLifecycle(componentInstance, "created");
3393
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3394
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
3395
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
3396
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3397
+ return componentInstance;
3398
+ } catch (error) {
3399
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
3400
+ throw error;
3401
+ } finally {
3402
+ finishComponentConstruction(context.componentCache, componentInstance);
3403
+ }
2904
3404
  }
2905
- function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
3405
+ function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
2906
3406
  const templatePath = join(context.project.miniprogramRootPath, componentEntry.templatePath);
2907
3407
  const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
2908
3408
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
2909
3409
  const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2910
- return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
3410
+ return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
2911
3411
  }
2912
3412
  //#endregion
2913
3413
  //#region src/browser/render/index.ts
@@ -2921,24 +3421,33 @@ function expandNodeByFor$1(node, scope) {
2921
3421
  const items = resolveLoopEntries(resolveRawValueByPath$2(wxsScopeData(scope), forExpression));
2922
3422
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
2923
3423
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
3424
+ const key = node.attribs?.["wx:key"]?.trim();
3425
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
2924
3426
  return items.map(([index, item]) => ({
2925
3427
  node: cloneNode$1(node),
2926
3428
  scope: createLoopScope$1(scope, itemName, indexName, item, index),
2927
- instanceSuffix: `:for-${index}`
3429
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
2928
3430
  }));
2929
3431
  }
2930
- function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2931
- return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
3432
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
3433
+ const nodes = [];
3434
+ if (isRenderPassStale(renderPass)) return nodes;
3435
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor$1(node, scope)) {
3436
+ if (isRenderPassStale(renderPass)) break;
3437
+ nodes.push(renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
3438
+ }
3439
+ return nodes;
2932
3440
  }
2933
- function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
3441
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
2934
3442
  const renderedChildren = [];
2935
3443
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch$1(node, scope))) {
3444
+ if (isRenderPassStale(renderPass)) break;
2936
3445
  if (!isTagNode$1(child)) {
2937
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
3446
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2938
3447
  continue;
2939
3448
  }
2940
3449
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
2941
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
3450
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2942
3451
  }
2943
3452
  return renderedChildren;
2944
3453
  }
@@ -2970,22 +3479,38 @@ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFileP
2970
3479
  }
2971
3480
  return slots;
2972
3481
  }
2973
- function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
3482
+ function reconcileSlotDeclarations$1(context, renderPass) {
3483
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
3484
+ if (isRenderPassStale(renderPass)) return;
3485
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
3486
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, entries[index].scope))) {
3487
+ if (isRenderPassStale(renderPass)) return;
3488
+ const entry = entries[index];
3489
+ if (renderPass.renderedSlots.has(entry)) continue;
3490
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
3491
+ renderPass.renderedSlots.set(entry, nodes);
3492
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
3493
+ }
3494
+ }
3495
+ }
3496
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
3497
+ if (isRenderPassStale(renderPass)) return node;
2974
3498
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
2975
3499
  ...scope,
2976
3500
  wxs: templateRenderState.wxsModules
2977
3501
  };
2978
3502
  const clonedNode = cloneNode$1(node);
3503
+ registerComponentEventNode(clonedNode, scope, parent);
2979
3504
  if (!isTagNode$1(clonedNode)) {
2980
3505
  applyNodeBindings$1(clonedNode, scope);
2981
3506
  return clonedNode;
2982
3507
  }
2983
- if (isTemplateDefinition(clonedNode)) return {
2984
- type: "tag",
2985
- name: "block",
2986
- attribs: {},
2987
- children: []
2988
- };
3508
+ if (isTemplateDefinition(clonedNode)) {
3509
+ clonedNode.name = "block";
3510
+ clonedNode.attribs = {};
3511
+ clonedNode.children = [];
3512
+ return clonedNode;
3513
+ }
2989
3514
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
2990
3515
  if (templateName) {
2991
3516
  const definition = templateRenderState.definitions.get(templateName);
@@ -2994,36 +3519,39 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2994
3519
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
2995
3520
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
2996
3521
  };
2997
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
3522
+ clonedNode.name = "block";
3523
+ clonedNode.attribs = {
3524
+ "data-sim-node": instancePath,
3525
+ "data-sim-scope": scope.getScopeId()
3526
+ };
3527
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
2998
3528
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
2999
3529
  definitionScopes: templateRenderState.definitionScopes,
3000
3530
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
3001
3531
  wxsModules: templateScope.wxs,
3002
3532
  stack: [...templateRenderState.stack, templateName]
3003
- }) : [];
3004
- return {
3005
- type: "tag",
3006
- name: "block",
3007
- attribs: {
3008
- "data-sim-node": instancePath,
3009
- "data-sim-scope": scope.getScopeId()
3010
- },
3011
- children
3012
- };
3533
+ }, clonedNode) : [];
3534
+ return clonedNode;
3013
3535
  }
3014
3536
  if (clonedNode.name === "slot") {
3015
3537
  const slotName = clonedNode.attribs?.name?.trim() || "default";
3016
3538
  const projected = scope.slots?.get(slotName) ?? [];
3017
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
3539
+ const fallbackChildren = clonedNode.children ?? [];
3540
+ bindComponentEventHost(clonedNode);
3541
+ clonedNode.name = "block";
3542
+ clonedNode.attribs = { "data-sim-scope": scope.getScopeId() };
3543
+ const slotOwner = scope.getScopeId();
3544
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
3545
+ clonedNode.children = [];
3546
+ return clonedNode;
3547
+ }
3548
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
3018
3549
  const entry = projected[index];
3019
- return renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
3020
- }) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
3021
- return {
3022
- type: "tag",
3023
- name: "block",
3024
- attribs: { "data-sim-scope": scope.getScopeId() },
3025
- children
3026
- };
3550
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
3551
+ renderPass.renderedSlots.set(entry, nodes);
3552
+ return nodes;
3553
+ }) : renderChildren$1(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
3554
+ return clonedNode;
3027
3555
  }
3028
3556
  const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
3029
3557
  if (componentEntry) {
@@ -3032,19 +3560,31 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
3032
3560
  const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope, componentEntry.definition);
3033
3561
  const genericComponents = resolveComponentGenerics$1(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
3034
3562
  const slots = collectComponentSlots$1(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
3563
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
3564
+ applyNodeBindings$1(clonedNode, scope);
3565
+ const reconcilePrivateTemplate = (instance, phase) => {
3566
+ let bindingPass;
3567
+ do {
3568
+ const bindingScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
3569
+ context.componentScopes.set(componentScopeId, bindingScope);
3570
+ bindingPass = createRenderPass(phase === "properties", renderPass);
3571
+ renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, bindingScope, componentScopeId, bindingPass);
3572
+ reconcileSlotDeclarations$1(context, bindingPass);
3573
+ } while (isRenderPassStale(bindingPass));
3574
+ };
3035
3575
  let componentInstance = context.componentCache.get(componentScopeId);
3036
- if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
3037
- const initialScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
3038
- context.componentScopes.set(componentScopeId, initialScope);
3039
- renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, initialScope, componentScopeId, /* @__PURE__ */ new Set());
3040
- });
3041
- else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
3042
- seenComponentScopes.add(componentScopeId);
3576
+ if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
3577
+ else {
3578
+ context.componentScopes.set(componentScopeId, createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
3579
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
3580
+ }
3581
+ if (isRenderPassStale(renderPass)) return clonedNode;
3582
+ renderPass.seenComponentScopes.add(componentScopeId);
3043
3583
  const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
3044
3584
  context.componentScopes.set(componentScopeId, componentScope);
3045
- const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
3585
+ const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, renderPass);
3586
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
3046
3587
  if (renderedComponentRoot.attribs) {
3047
- applyNodeBindings$1(clonedNode, scope);
3048
3588
  renderedComponentRoot.attribs = {
3049
3589
  ...clonedNode.attribs,
3050
3590
  ...renderedComponentRoot.attribs
@@ -3056,66 +3596,99 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
3056
3596
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
3057
3597
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
3058
3598
  }
3599
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
3059
3600
  return renderedComponentRoot;
3060
3601
  }
3061
3602
  applyNodeBindings$1(clonedNode, scope);
3062
3603
  clonedNode.attribs["data-sim-node"] = instancePath;
3063
- clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
3604
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
3064
3605
  return clonedNode;
3065
3606
  }
3607
+ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
3608
+ for (;;) {
3609
+ bindAttachmentBindingScope(context, page);
3610
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
3611
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
3612
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
3613
+ const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
3614
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
3615
+ const pageScopeId = `page:${route}`;
3616
+ const pageScope = {
3617
+ data: page.data,
3618
+ getMethod: (methodName) => {
3619
+ const method = page[methodName];
3620
+ return typeof method === "function" ? method.bind(page) : void 0;
3621
+ },
3622
+ getScopeId: () => pageScopeId,
3623
+ id: "page-root"
3624
+ };
3625
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
3626
+ context.componentScopes.set(pageScopeId, pageScope);
3627
+ const renderPass = createPageRenderPass(page, context.componentCache);
3628
+ const root = (document.children ?? [])[0] ?? document;
3629
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
3630
+ const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
3631
+ const roots = [renderedRoot];
3632
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
3633
+ type: "tag",
3634
+ name: "custom-tab-bar",
3635
+ attribs: {},
3636
+ children: []
3637
+ }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, renderPass, templateRenderState));
3638
+ reconcileSlotDeclarations$1(context, renderPass);
3639
+ if (isRenderPassStale(renderPass)) continue;
3640
+ markPageTreeConstructed(page, context.componentCache);
3641
+ const treeRoot = roots.length > 1 ? {
3642
+ type: "root",
3643
+ children: roots
3644
+ } : renderedRoot;
3645
+ linkRenderedParents(treeRoot);
3646
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
3647
+ if (bindingsOnly) return {
3648
+ root: treeRoot,
3649
+ roots,
3650
+ resourcePath
3651
+ };
3652
+ let bindingsRefreshed = false;
3653
+ const updateBindings = () => {
3654
+ bindingsRefreshed = true;
3655
+ if (hasPendingComponentConstruction(context.componentCache)) return;
3656
+ reconcileBrowserPageTree(context, page, true);
3657
+ };
3658
+ const pageAttached = attachComponentPage(page, updateBindings);
3659
+ if (bindingsRefreshed) continue;
3660
+ const pageAttaching = isComponentPageAttaching(page);
3661
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
3662
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
3663
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
3664
+ runComponentLifecycle(instance, "attached");
3665
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
3666
+ return bindingsRefreshed;
3667
+ }), scopeIds);
3668
+ if (attached === "restart") continue;
3669
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
3670
+ const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
3671
+ for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
3672
+ else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
3673
+ const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
3674
+ for (const [scopeId] of removed) {
3675
+ context.componentCache.delete(scopeId);
3676
+ context.componentScopes.delete(scopeId);
3677
+ }
3678
+ if (pageAttached || attached || relationsChanged) continue;
3679
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
3680
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) continue;
3681
+ return {
3682
+ root: treeRoot,
3683
+ roots,
3684
+ resourcePath
3685
+ };
3686
+ }
3687
+ }
3066
3688
  function renderBrowserPageTree(context, page) {
3067
- const route = page.route.replace(LEADING_SLASH_RE$5, "");
3068
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
3069
- const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
3070
- const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
3071
- const pageScopeId = `page:${route}`;
3072
- const pageScope = {
3073
- data: page.data,
3074
- getMethod: (methodName) => {
3075
- const method = page[methodName];
3076
- return typeof method === "function" ? method.bind(page) : void 0;
3077
- },
3078
- getScopeId: () => pageScopeId,
3079
- id: "page-root"
3080
- };
3081
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
3082
- context.componentScopes.set(pageScopeId, pageScope);
3083
- const seenComponentScopes = /* @__PURE__ */ new Set();
3084
- const root = (document.children ?? [])[0] ?? document;
3085
- const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
3086
- const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
3087
- const roots = [renderedRoot];
3088
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
3089
- type: "tag",
3090
- name: "custom-tab-bar",
3091
- attribs: {},
3092
- children: []
3093
- }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, seenComponentScopes, templateRenderState));
3094
- const pageAttached = attachComponentPage(page);
3095
- const pageAttaching = isComponentPageAttaching(page);
3096
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => {
3097
- runComponentLifecycle(instance, "attached");
3098
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
3099
- });
3100
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
3101
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
3102
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
3103
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
3104
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
3105
- for (const [scopeId] of removed) {
3106
- context.componentCache.delete(scopeId);
3107
- context.componentScopes.delete(scopeId);
3108
- }
3109
- if (pageAttached || attached || relationsChanged) return renderBrowserPageTree(context, page);
3110
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
3111
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) return renderBrowserPageTree(context, page);
3112
- const treeRoot = roots.length > 1 ? {
3113
- type: "root",
3114
- children: roots
3115
- } : renderedRoot;
3116
- linkRenderedParents(treeRoot);
3689
+ const { root, roots, resourcePath } = reconcileBrowserPageTree(context, page);
3117
3690
  return {
3118
- root: treeRoot,
3691
+ root,
3119
3692
  styles: resolveBrowserPageStyles(context.files, resourcePath, {
3120
3693
  miniprogramRootPath: context.project.miniprogramRootPath,
3121
3694
  styleIsolation: resolveBrowserComponentPageStyleIsolation(context.files, page, resourcePath, context.project.miniprogramRootPath)
@@ -3429,6 +4002,7 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
3429
4002
  const rootKey = parseDataPath(key)[0];
3430
4003
  if (rootKey) instance.properties[rootKey] = instance.data[rootKey];
3431
4004
  }
4005
+ synchronizeAttachmentBindings(instance);
3432
4006
  if (pageState.requestRender) pageState.requestRender(callback);
3433
4007
  else callback?.();
3434
4008
  }
@@ -3451,6 +4025,7 @@ var HeadlessRouteEvents = class {
3451
4025
  nextRouteId = 0;
3452
4026
  nextWebviewId = 0;
3453
4027
  activeEvent;
4028
+ activeState;
3454
4029
  constructor(requestRender, isCurrentPage) {
3455
4030
  this.requestRender = requestRender;
3456
4031
  this.isCurrentPage = isCurrentPage;
@@ -3462,6 +4037,7 @@ var HeadlessRouteEvents = class {
3462
4037
  this.bus.$off(name, listener);
3463
4038
  }
3464
4039
  begin(path, query, openType, renderer, page) {
4040
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail navigation was superseded"));
3465
4041
  const previous = page ? this.pages.get(page) : void 0;
3466
4042
  const event = {
3467
4043
  path,
@@ -3478,12 +4054,28 @@ var HeadlessRouteEvents = class {
3478
4054
  }
3479
4055
  attach(page, event) {
3480
4056
  const state = this.pages.get(page);
3481
- this.pages.set(page, {
4057
+ const next = {
3482
4058
  webviewId: event.webviewId,
3483
4059
  ready: state?.ready ?? false,
3484
4060
  event,
3485
- committed: false
3486
- });
4061
+ committed: false,
4062
+ completed: false
4063
+ };
4064
+ this.pages.set(page, next);
4065
+ if (this.activeEvent === event) this.activeState = next;
4066
+ }
4067
+ /** 原生 navigateTo 的回调属于本次路由记录,不能以当前页面或提交栈代替完成。 */
4068
+ navigateTo(operation, callbacks) {
4069
+ let state;
4070
+ try {
4071
+ state = this.pages.get(operation());
4072
+ } catch (error) {
4073
+ this.settle(callbacks, error);
4074
+ return;
4075
+ }
4076
+ if (!state || state.canceled) this.settle(callbacks, state?.canceled ?? /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
4077
+ else if (state.completed) this.settle(callbacks);
4078
+ else state.callbacks = callbacks;
3487
4079
  }
3488
4080
  commit(page, event) {
3489
4081
  const state = this.pages.get(page);
@@ -3500,10 +4092,32 @@ var HeadlessRouteEvents = class {
3500
4092
  }
3501
4093
  complete(page, state) {
3502
4094
  this.requestRender(() => {
3503
- if (this.pages.get(page) !== state || this.activeEvent !== state.event || !this.isCurrentPage(page)) return;
3504
- this.bus.$emit("appRouteDone", state.event);
4095
+ if (state.completed || state.canceled || this.pages.get(page) !== state || this.activeEvent !== state.event || !this.isCurrentPage(page)) return;
4096
+ state.completed = true;
4097
+ const callbacks = state.callbacks;
4098
+ state.callbacks = void 0;
4099
+ try {
4100
+ this.bus.$emit("appRouteDone", state.event);
4101
+ } finally {
4102
+ this.settle(callbacks);
4103
+ }
3505
4104
  });
3506
4105
  }
4106
+ settle(callbacks, error) {
4107
+ try {
4108
+ if (error) callbacks?.fail?.(error);
4109
+ else callbacks?.success?.();
4110
+ } finally {
4111
+ callbacks?.complete?.();
4112
+ }
4113
+ }
4114
+ cancel(state, error) {
4115
+ if (!state || state.completed || state.canceled) return;
4116
+ state.canceled = error;
4117
+ const callbacks = state.callbacks;
4118
+ state.callbacks = void 0;
4119
+ this.settle(callbacks, error);
4120
+ }
3507
4121
  beforeUnload(page, event) {
3508
4122
  const state = this.pages.get(page);
3509
4123
  if (event && state) this.bus.$emit("beforePageUnload", {
@@ -3514,9 +4128,12 @@ var HeadlessRouteEvents = class {
3514
4128
  webviewId: state.webviewId,
3515
4129
  page
3516
4130
  });
4131
+ this.cancel(state, /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
3517
4132
  this.pages.delete(page);
3518
4133
  }
3519
4134
  close() {
4135
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail runtime session closed"));
4136
+ this.activeState = void 0;
3520
4137
  this.activeEvent = void 0;
3521
4138
  this.bus.$off();
3522
4139
  }
@@ -5293,24 +5910,63 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
5293
5910
  };
5294
5911
  }
5295
5912
  //#endregion
5913
+ //#region src/view/eventBinding.ts
5914
+ function collectMiniProgramEventBindings(attributes = {}) {
5915
+ return collectEventBindings(attributes, false).eventBindings;
5916
+ }
5917
+ function resolveMiniProgramEventBinding(attributes, eventName) {
5918
+ return resolveEventBindingPhases(attributes, eventName, false)?.bubble ?? null;
5919
+ }
5920
+ /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
5921
+ function createMiniProgramEventPayload(node, eventName, event, origin = node) {
5922
+ const dataset = collectNodeDataset(node);
5923
+ const nodeId = node.attribs?.id ?? "";
5924
+ const isOrigin = node === origin;
5925
+ return {
5926
+ bubbles: false,
5927
+ capturePhase: false,
5928
+ composed: false,
5929
+ currentTarget: {
5930
+ dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
5931
+ id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
5932
+ },
5933
+ detail: event.detail,
5934
+ mark: event.mark,
5935
+ target: {
5936
+ dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
5937
+ id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
5938
+ },
5939
+ timeStamp: Date.now(),
5940
+ type: eventName
5941
+ };
5942
+ }
5943
+ //#endregion
5296
5944
  //#region src/view/selectors.ts
5297
- const adapter = {
5298
- isTag: (node) => node.type === "tag",
5299
- getAttributeValue: (node, name) => node.attribs?.[name],
5300
- getChildren: (node) => node.children ?? [],
5301
- getName: (node) => node.name ?? "",
5302
- getParent: (node) => node.parent ?? null,
5303
- getSiblings: (node) => node.parent?.children ?? [node],
5304
- getText: (node) => node.type === "text" ? node.data ?? "" : (node.children ?? []).map((child) => adapter.getText(child)).join(""),
5305
- hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
5306
- removeSubsets: (nodes) => {
5307
- const unique = new Set(nodes);
5308
- return [...unique].filter((node) => {
5309
- for (let parent = node.parent; parent; parent = parent.parent) if (unique.has(parent)) return false;
5310
- return true;
5311
- });
5312
- }
5313
- };
5945
+ function createAdapter(getChildren, getParent) {
5946
+ const adapter = {
5947
+ isTag: (node) => node.type === "tag",
5948
+ getAttributeValue: (node, name) => node.attribs?.[name],
5949
+ getChildren,
5950
+ getName: (node) => node.name ?? "",
5951
+ getParent,
5952
+ getSiblings: (node) => {
5953
+ const parent = getParent(node);
5954
+ return parent ? getChildren(parent) : [node];
5955
+ },
5956
+ getText: (node) => node.type === "text" ? node.data ?? "" : getChildren(node).map((child) => adapter.getText(child)).join(""),
5957
+ hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
5958
+ removeSubsets: (nodes) => {
5959
+ const unique = new Set(nodes);
5960
+ return [...unique].filter((node) => {
5961
+ for (let parent = getParent(node); parent; parent = getParent(parent)) if (unique.has(parent)) return false;
5962
+ return true;
5963
+ });
5964
+ }
5965
+ };
5966
+ return adapter;
5967
+ }
5968
+ const renderedAdapter = createAdapter((node) => node.children ?? [], (node) => node.parent ?? null);
5969
+ const inspectionAdapter = createAdapter(getInspectionChildren, getInspectionParent);
5314
5970
  function resolveComponentTags(selectors) {
5315
5971
  return selectors.map((group) => group.map((token) => {
5316
5972
  if (token.type === SelectorType.Pseudo && Array.isArray(token.data)) return {
@@ -5333,7 +5989,7 @@ function resolveComponentTags(selectors) {
5333
5989
  };
5334
5990
  }));
5335
5991
  }
5336
- function querySelectorAll(root, selector) {
5992
+ function queryWithAdapter(root, selector, adapter) {
5337
5993
  const parsed = parse(selector);
5338
5994
  const query = resolveComponentTags(parsed);
5339
5995
  const includesPageRoot = root.type === "tag" && root.name === "page" && parsed.some((group) => group.some((token) => token.type === SelectorType.Tag && token.name === "page"));
@@ -5342,10 +5998,19 @@ function querySelectorAll(root, selector) {
5342
5998
  cacheResults: false
5343
5999
  });
5344
6000
  }
6001
+ function querySelectorAll(root, selector) {
6002
+ return queryWithAdapter(root, selector, renderedAdapter);
6003
+ }
6004
+ function queryInspectionSelectorAll(root, selector) {
6005
+ return queryWithAdapter(root, selector, inspectionAdapter);
6006
+ }
5345
6007
  //#endregion
5346
6008
  //#region src/view/xpath.ts
5347
6009
  const xpathEngine = Reflect.get(fontoxpath, "default") ?? fontoxpath;
5348
- function wrapNode(source, parent = null) {
6010
+ function getRenderedChildren(node) {
6011
+ return node.children ?? [];
6012
+ }
6013
+ function wrapNode(source, getChildren, parent = null) {
5349
6014
  const node = {
5350
6015
  attributes: [],
5351
6016
  children: [],
@@ -5368,7 +6033,7 @@ function wrapNode(source, parent = null) {
5368
6033
  prefix: null,
5369
6034
  value
5370
6035
  }));
5371
- node.children = (source.children ?? []).map((child) => wrapNode(child, node));
6036
+ node.children = getChildren(source).map((child) => wrapNode(child, getChildren, node));
5372
6037
  return node;
5373
6038
  }
5374
6039
  function sibling(node, offset) {
@@ -5388,14 +6053,20 @@ const domFacade = {
5388
6053
  getParentNode: (node) => node.parent,
5389
6054
  getPreviousSibling: (node) => sibling(node, -1)
5390
6055
  };
5391
- function queryXPathElements(root, expression) {
6056
+ function queryElements(root, expression, getChildren) {
5392
6057
  if (!expression.trim()) throw new Error("XPath must be a non-empty expression in headless testing runtime.");
5393
6058
  const document = wrapNode(root.type === "root" ? root : {
5394
6059
  type: "root",
5395
6060
  children: [root]
5396
- });
6061
+ }, getChildren);
5397
6062
  return xpathEngine.evaluateXPathToNodes(expression, document, domFacade).filter((node) => node.nodeType === 1).map((node) => node.source);
5398
6063
  }
6064
+ function queryXPathElements(root, expression) {
6065
+ return queryElements(root, expression, getRenderedChildren);
6066
+ }
6067
+ function queryInspectionXPathElements(root, expression) {
6068
+ return queryElements(root, expression, getInspectionChildren);
6069
+ }
5399
6070
  //#endregion
5400
6071
  //#region src/view/nodeHandle.ts
5401
6072
  function escapeText$2(text) {
@@ -5442,7 +6113,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5442
6113
  this.interactions?.assertActive?.();
5443
6114
  }
5444
6115
  query(selector) {
5445
- const nodes = querySelectorAll(this.node, selector);
6116
+ const nodes = (this.interactions?.projectionOnly ? querySelectorAll : queryInspectionSelectorAll)(this.node, selector);
5446
6117
  const scope = this.node.attribs?.["data-sim-scope"];
5447
6118
  if (!scope || !this.interactions) return nodes;
5448
6119
  return nodes.filter((node) => {
@@ -5461,7 +6132,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5461
6132
  }
5462
6133
  async getElementsByXpath(expression) {
5463
6134
  this.assertActive();
5464
- return queryXPathElements(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
6135
+ return (this.interactions?.projectionOnly ? queryXPathElements : queryInspectionXPathElements)(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
5465
6136
  }
5466
6137
  async attr(name) {
5467
6138
  this.assertActive();
@@ -6844,7 +7515,7 @@ var BrowserHeadlessSession = class {
6844
7515
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
6845
7516
  getNetworkType: () => this.wxState.getNetworkType(),
6846
7517
  navigateBack: (option) => this.navigateBack(option?.delta),
6847
- navigateTo: (option) => this.navigateTo(option.url),
7518
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
6848
7519
  pageScrollTo: (option) => this.pageScrollTo(option),
6849
7520
  openDocument: (option) => this.wxState.openDocument(option),
6850
7521
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -7219,19 +7890,19 @@ var BrowserHeadlessSession = class {
7219
7890
  return this.getComponentScopeId(component);
7220
7891
  }
7221
7892
  selectComponent(selector) {
7222
- this.renderCurrentPage();
7893
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7223
7894
  return this.selectComponentsWithin(null, selector)[0] ?? null;
7224
7895
  }
7225
7896
  selectAllComponents(selector) {
7226
- this.renderCurrentPage();
7897
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7227
7898
  return this.selectComponentsWithin(null, selector);
7228
7899
  }
7229
7900
  selectComponentWithin(scopeId, selector) {
7230
- this.renderCurrentPage();
7901
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7231
7902
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
7232
7903
  }
7233
7904
  selectAllComponentsWithin(scopeId, selector) {
7234
- this.renderCurrentPage();
7905
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7235
7906
  return this.selectComponentsWithin(scopeId, selector);
7236
7907
  }
7237
7908
  selectOwnerComponent(scopeId) {
@@ -8247,67 +8918,6 @@ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePat
8247
8918
  }
8248
8919
  return resolved.size > 0 ? resolved : void 0;
8249
8920
  }
8250
- function collectComponentEventBindings(hostNode) {
8251
- return collectMiniProgramEventBindings(hostNode.attribs);
8252
- }
8253
- function buildComponentTrigger(componentScopeId, context, hostNode) {
8254
- const hostDataset = collectDataset(hostNode);
8255
- const hostId = hostNode.attribs?.id ?? "";
8256
- return (instance, eventName, detail, triggerOptions) => {
8257
- const originScope = context.componentScopes.get(componentScopeId);
8258
- const interactionMark = instance.__lastInteractionEvent__?.mark;
8259
- const target = {
8260
- dataset: originScope?.dataset ?? hostDataset,
8261
- id: originScope?.hostId ?? hostId
8262
- };
8263
- let currentScopeId = componentScopeId;
8264
- while (currentScopeId) {
8265
- const currentScope = context.componentScopes.get(currentScopeId);
8266
- const binding = currentScope?.eventBindings?.get(eventName);
8267
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
8268
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
8269
- if (handler) handler({
8270
- bubbles: triggerOptions?.bubbles ?? false,
8271
- capturePhase: false,
8272
- composed: triggerOptions?.composed ?? false,
8273
- currentTarget: {
8274
- dataset: currentScope?.dataset ?? hostDataset,
8275
- id: currentScope?.hostId ?? hostId
8276
- },
8277
- detail,
8278
- mark: interactionMark,
8279
- target,
8280
- type: eventName
8281
- });
8282
- if (binding?.stopAfter) break;
8283
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
8284
- currentScopeId = currentScope?.ownerScopeId;
8285
- }
8286
- };
8287
- }
8288
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
8289
- const changedRootKeys = [];
8290
- const previousProperties = {};
8291
- for (const [key, value] of Object.entries(nextProperties)) {
8292
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
8293
- const bindingExpression = bindingExpressions[key];
8294
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
8295
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
8296
- });
8297
- const previousSnapshot = instance.__propertySnapshots?.[key];
8298
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
8299
- previousProperties[key] = instance.properties[key];
8300
- const deliveredValue = cloneValue(nextValue);
8301
- instance.properties[key] = deliveredValue;
8302
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
8303
- changedRootKeys.push(key);
8304
- }
8305
- instance.__propertySnapshots ??= {};
8306
- instance.__propertySnapshots[key] = cloneValue(nextValue);
8307
- }
8308
- if (changedRootKeys.length === 0) return;
8309
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
8310
- }
8311
8921
  function createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
8312
8922
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
8313
8923
  return {
@@ -8315,7 +8925,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
8315
8925
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
8316
8926
  data: { ...componentInstance.data },
8317
8927
  dataset: collectDataset(clonedNode, wxsScopeData(scope)),
8318
- eventBindings: collectComponentEventBindings(clonedNode),
8928
+ ...bindComponentEventHost(clonedNode),
8319
8929
  getMethod: (methodName) => {
8320
8930
  const method = componentInstance?.[methodName];
8321
8931
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -8323,6 +8933,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
8323
8933
  getScopeId: () => componentScopeId,
8324
8934
  genericComponents,
8325
8935
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
8936
+ hostNode: clonedNode,
8326
8937
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
8327
8938
  listenerScopeId: scope.getScopeId(),
8328
8939
  ownerScopeId,
@@ -8345,13 +8956,14 @@ function resolveComponentProperties(clonedNode, scope, definition) {
8345
8956
  bindingExpressions
8346
8957
  };
8347
8958
  }
8348
- function createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
8959
+ function createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
8349
8960
  const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
8350
- const componentInstance = createComponentInstance({
8961
+ const instanceOptions = {
8351
8962
  definition: componentEntry.definition,
8352
- requestRender: (callback) => context.session.requestRender(callback),
8353
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
8354
- });
8963
+ requestRender: (callback) => context.session.requestRender(callback)
8964
+ };
8965
+ const componentInstance = createComponentInstance(instanceOptions);
8966
+ bindAttachmentBindingScope(componentInstance, context);
8355
8967
  setSelectorQueryScopeId(componentInstance, componentScopeId);
8356
8968
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
8357
8969
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -8359,19 +8971,29 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
8359
8971
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
8360
8972
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
8361
8973
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
8362
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
8974
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
8975
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
8363
8976
  context.componentCache.set(componentScopeId, componentInstance);
8364
- beforeCreated?.(componentInstance);
8365
- runComponentLifecycle(componentInstance, "created");
8366
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
8367
- syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
8368
- return componentInstance;
8977
+ try {
8978
+ renderTemplate?.(componentInstance, "defaults");
8979
+ runComponentLifecycle(componentInstance, "created");
8980
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8981
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
8982
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
8983
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8984
+ return componentInstance;
8985
+ } catch (error) {
8986
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
8987
+ throw error;
8988
+ } finally {
8989
+ finishComponentConstruction(context.componentCache, componentInstance);
8990
+ }
8369
8991
  }
8370
- function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
8992
+ function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
8371
8993
  const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
8372
8994
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
8373
8995
  const templateRenderState = prepareTemplateRenderState(context.artifactSource, componentRoot, componentEntry.absoluteTemplatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
8374
- return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
8996
+ return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
8375
8997
  }
8376
8998
  //#endregion
8377
8999
  //#region src/runtime/render/index.ts
@@ -8385,24 +9007,33 @@ function expandNodeByFor(node, scope) {
8385
9007
  const items = resolveLoopEntries(resolveRawValueByPath(wxsScopeData(scope), forExpression));
8386
9008
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
8387
9009
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
9010
+ const key = node.attribs?.["wx:key"]?.trim();
9011
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
8388
9012
  return items.map(([index, item]) => ({
8389
9013
  node: cloneNode(node),
8390
9014
  scope: createLoopScope(scope, itemName, indexName, item, index),
8391
- instanceSuffix: `:for-${index}`
9015
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
8392
9016
  }));
8393
9017
  }
8394
- function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
8395
- return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
9018
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9019
+ const nodes = [];
9020
+ if (isRenderPassStale(renderPass)) return nodes;
9021
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor(node, scope)) {
9022
+ if (isRenderPassStale(renderPass)) break;
9023
+ nodes.push(renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
9024
+ }
9025
+ return nodes;
8396
9026
  }
8397
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9027
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
8398
9028
  const renderedChildren = [];
8399
9029
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch(node, scope))) {
9030
+ if (isRenderPassStale(renderPass)) break;
8400
9031
  if (!isTagNode(child)) {
8401
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9032
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
8402
9033
  continue;
8403
9034
  }
8404
9035
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
8405
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9036
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
8406
9037
  }
8407
9038
  return renderedChildren;
8408
9039
  }
@@ -8434,22 +9065,38 @@ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePat
8434
9065
  }
8435
9066
  return slots;
8436
9067
  }
8437
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9068
+ function reconcileSlotDeclarations(context, renderPass) {
9069
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
9070
+ if (isRenderPassStale(renderPass)) return;
9071
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
9072
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, entries[index].scope))) {
9073
+ if (isRenderPassStale(renderPass)) return;
9074
+ const entry = entries[index];
9075
+ if (renderPass.renderedSlots.has(entry)) continue;
9076
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
9077
+ renderPass.renderedSlots.set(entry, nodes);
9078
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
9079
+ }
9080
+ }
9081
+ }
9082
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9083
+ if (isRenderPassStale(renderPass)) return node;
8438
9084
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
8439
9085
  ...scope,
8440
9086
  wxs: templateRenderState.wxsModules
8441
9087
  };
8442
9088
  const clonedNode = cloneNode(node);
9089
+ registerComponentEventNode(clonedNode, scope, parent);
8443
9090
  if (!isTagNode(clonedNode)) {
8444
9091
  applyNodeBindings(clonedNode, scope);
8445
9092
  return clonedNode;
8446
9093
  }
8447
- if (isTemplateDefinition(clonedNode)) return {
8448
- type: "tag",
8449
- name: "block",
8450
- attribs: {},
8451
- children: []
8452
- };
9094
+ if (isTemplateDefinition(clonedNode)) {
9095
+ clonedNode.name = "block";
9096
+ clonedNode.attribs = {};
9097
+ clonedNode.children = [];
9098
+ return clonedNode;
9099
+ }
8453
9100
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
8454
9101
  if (templateName) {
8455
9102
  const definition = templateRenderState.definitions.get(templateName);
@@ -8458,39 +9105,42 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8458
9105
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
8459
9106
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
8460
9107
  };
8461
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
9108
+ clonedNode.name = "block";
9109
+ clonedNode.attribs = {
9110
+ "data-sim-node": instancePath,
9111
+ "data-sim-scope": scope.getScopeId()
9112
+ };
9113
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
8462
9114
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
8463
9115
  definitionScopes: templateRenderState.definitionScopes,
8464
9116
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
8465
9117
  wxsModules: templateScope.wxs,
8466
9118
  stack: [...templateRenderState.stack, templateName]
8467
- }) : [];
8468
- return {
8469
- type: "tag",
8470
- name: "block",
8471
- attribs: {
8472
- "data-sim-node": instancePath,
8473
- "data-sim-scope": scope.getScopeId()
8474
- },
8475
- children
8476
- };
9119
+ }, clonedNode) : [];
9120
+ return clonedNode;
8477
9121
  }
8478
9122
  if (clonedNode.name === "slot") {
8479
9123
  const slotName = clonedNode.attribs?.name?.trim() || "default";
8480
9124
  const projected = scope.slots?.get(slotName) ?? [];
8481
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
8482
- const entry = projected[index];
8483
- return renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
8484
- }) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
8485
- return {
8486
- type: "tag",
8487
- name: "block",
8488
- attribs: {
8489
- "data-sim-node": instancePath,
8490
- "data-sim-scope": scope.getScopeId()
8491
- },
8492
- children
9125
+ const fallbackChildren = clonedNode.children ?? [];
9126
+ bindComponentEventHost(clonedNode);
9127
+ clonedNode.name = "block";
9128
+ clonedNode.attribs = {
9129
+ "data-sim-node": instancePath,
9130
+ "data-sim-scope": scope.getScopeId()
8493
9131
  };
9132
+ const slotOwner = scope.getScopeId();
9133
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
9134
+ clonedNode.children = [];
9135
+ return clonedNode;
9136
+ }
9137
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
9138
+ const entry = projected[index];
9139
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
9140
+ renderPass.renderedSlots.set(entry, nodes);
9141
+ return nodes;
9142
+ }) : renderChildren(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
9143
+ return clonedNode;
8494
9144
  }
8495
9145
  const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
8496
9146
  if (componentEntry) {
@@ -8499,19 +9149,31 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8499
9149
  const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope, componentEntry.definition);
8500
9150
  const genericComponents = resolveComponentGenerics(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
8501
9151
  const slots = collectComponentSlots(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
9152
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
9153
+ applyNodeBindings(clonedNode, scope);
9154
+ const reconcilePrivateTemplate = (instance, phase) => {
9155
+ let bindingPass;
9156
+ do {
9157
+ const bindingScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
9158
+ context.componentScopes.set(componentScopeId, bindingScope);
9159
+ bindingPass = createRenderPass(phase === "properties", renderPass);
9160
+ renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, bindingScope, componentScopeId, bindingPass);
9161
+ reconcileSlotDeclarations(context, bindingPass);
9162
+ } while (isRenderPassStale(bindingPass));
9163
+ };
8502
9164
  let componentInstance = context.componentCache.get(componentScopeId);
8503
- if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
8504
- const initialScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
8505
- context.componentScopes.set(componentScopeId, initialScope);
8506
- renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, initialScope, componentScopeId, /* @__PURE__ */ new Set());
8507
- });
8508
- else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
8509
- seenComponentScopes.add(componentScopeId);
9165
+ if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
9166
+ else {
9167
+ context.componentScopes.set(componentScopeId, createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
9168
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
9169
+ }
9170
+ if (isRenderPassStale(renderPass)) return clonedNode;
9171
+ renderPass.seenComponentScopes.add(componentScopeId);
8510
9172
  const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
8511
9173
  context.componentScopes.set(componentScopeId, componentScope);
8512
- const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
9174
+ const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass);
9175
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
8513
9176
  if (renderedComponentRoot.attribs) {
8514
- applyNodeBindings(clonedNode, scope);
8515
9177
  renderedComponentRoot.attribs = {
8516
9178
  ...clonedNode.attribs,
8517
9179
  ...renderedComponentRoot.attribs
@@ -8524,66 +9186,99 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8524
9186
  renderedComponentRoot.attribs["data-sim-node"] = instancePath;
8525
9187
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
8526
9188
  }
9189
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
8527
9190
  return renderedComponentRoot;
8528
9191
  }
8529
9192
  applyNodeBindings(clonedNode, scope);
8530
9193
  clonedNode.attribs["data-sim-node"] = instancePath;
8531
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
9194
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
8532
9195
  return clonedNode;
8533
9196
  }
9197
+ function reconcileRuntimePageTree(context, page, bindingsOnly = false) {
9198
+ for (;;) {
9199
+ bindAttachmentBindingScope(context, page);
9200
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
9201
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
9202
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
9203
+ const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
9204
+ const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
9205
+ const pageScopeId = `page:${route}`;
9206
+ const pageScope = {
9207
+ data: page.data,
9208
+ getMethod: (methodName) => {
9209
+ const method = page[methodName];
9210
+ return typeof method === "function" ? method.bind(page) : void 0;
9211
+ },
9212
+ getScopeId: () => pageScopeId,
9213
+ id: "page-root"
9214
+ };
9215
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
9216
+ context.componentScopes.set(pageScopeId, pageScope);
9217
+ const renderPass = createPageRenderPass(page, context.componentCache);
9218
+ const root = (document.children ?? [])[0] ?? document;
9219
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
9220
+ const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
9221
+ const roots = [renderedRoot];
9222
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
9223
+ type: "tag",
9224
+ name: "custom-tab-bar",
9225
+ attribs: {},
9226
+ children: []
9227
+ }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, renderPass, templateRenderState));
9228
+ reconcileSlotDeclarations(context, renderPass);
9229
+ if (isRenderPassStale(renderPass)) continue;
9230
+ markPageTreeConstructed(page, context.componentCache);
9231
+ const treeRoot = roots.length > 1 ? {
9232
+ type: "root",
9233
+ children: roots
9234
+ } : renderedRoot;
9235
+ linkRenderedParents(treeRoot);
9236
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
9237
+ if (bindingsOnly) return {
9238
+ root: treeRoot,
9239
+ roots
9240
+ };
9241
+ let bindingsRefreshed = false;
9242
+ const updateBindings = () => {
9243
+ bindingsRefreshed = true;
9244
+ if (hasPendingComponentConstruction(context.componentCache)) return;
9245
+ reconcileRuntimePageTree(context, page, true);
9246
+ };
9247
+ const pageAttached = attachComponentPage(page, updateBindings);
9248
+ if (bindingsRefreshed) continue;
9249
+ const pageAttaching = isComponentPageAttaching(page);
9250
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
9251
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
9252
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
9253
+ runComponentLifecycle(instance, "attached");
9254
+ return bindingsRefreshed;
9255
+ }), scopeIds);
9256
+ if (attached === "restart") continue;
9257
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
9258
+ const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
9259
+ for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
9260
+ else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
9261
+ const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
9262
+ for (const [scopeId] of removed) {
9263
+ context.componentCache.delete(scopeId);
9264
+ context.componentScopes.delete(scopeId);
9265
+ }
9266
+ if (pageAttached || attached || relationsChanged) continue;
9267
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
9268
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
9269
+ runComponentLifecycle(instance, "ready");
9270
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
9271
+ })) continue;
9272
+ return {
9273
+ root: treeRoot,
9274
+ roots
9275
+ };
9276
+ }
9277
+ }
8534
9278
  function renderRuntimePageTree(context, page) {
8535
- const route = page.route.replace(LEADING_SLASH_RE$2, "");
8536
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
8537
- const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
8538
- const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
8539
- const pageScopeId = `page:${route}`;
8540
- const pageScope = {
8541
- data: page.data,
8542
- getMethod: (methodName) => {
8543
- const method = page[methodName];
8544
- return typeof method === "function" ? method.bind(page) : void 0;
8545
- },
8546
- getScopeId: () => pageScopeId,
8547
- id: "page-root"
8548
- };
8549
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
8550
- context.componentScopes.set(pageScopeId, pageScope);
8551
- const seenComponentScopes = /* @__PURE__ */ new Set();
8552
- const root = (document.children ?? [])[0] ?? document;
8553
- const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
8554
- const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
8555
- const roots = [renderedRoot];
8556
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
8557
- type: "tag",
8558
- name: "custom-tab-bar",
8559
- attribs: {},
8560
- children: []
8561
- }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, seenComponentScopes, templateRenderState));
8562
- const pageAttached = attachComponentPage(page);
8563
- const pageAttaching = isComponentPageAttaching(page);
8564
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => runComponentLifecycle(instance, "attached"));
8565
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
8566
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
8567
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
8568
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
8569
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
8570
- for (const [scopeId] of removed) {
8571
- context.componentCache.delete(scopeId);
8572
- context.componentScopes.delete(scopeId);
8573
- }
8574
- if (pageAttached || attached || relationsChanged) return renderRuntimePageTree(context, page);
8575
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
8576
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
8577
- runComponentLifecycle(instance, "ready");
8578
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
8579
- })) return renderRuntimePageTree(context, page);
8580
- const treeRoot = roots.length > 1 ? {
8581
- type: "root",
8582
- children: roots
8583
- } : renderedRoot;
8584
- linkRenderedParents(treeRoot);
9279
+ const { root, roots } = reconcileRuntimePageTree(context, page);
8585
9280
  return {
8586
- root: treeRoot,
9281
+ root,
8587
9282
  wxml: roots.map(serializeDomNode).join("")
8588
9283
  };
8589
9284
  }
@@ -8688,9 +9383,9 @@ function transformEsmToCommonJs(source) {
8688
9383
  function createRequireNotFoundError(request, importer) {
8689
9384
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
8690
9385
  }
8691
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole) {
9386
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole, workers) {
8692
9387
  const runtimeConsole = kernel.diagnostics.createConsole(console, onConsole);
8693
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
9388
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
8694
9389
  return createMiniProgramRuntimeGlobals({
8695
9390
  App(definition) {
8696
9391
  return registerAppDefinition(registries, definition);
@@ -8723,8 +9418,19 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, k
8723
9418
  }, globals);
8724
9419
  }
8725
9420
  function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, options) {
9421
+ const workers = createWorkerHost({
9422
+ root: options.miniprogramRootPath,
9423
+ read: (file) => options.artifactSource.readText(file),
9424
+ console: options.kernel.diagnostics.createConsole(console, options.onConsole),
9425
+ createExecutor(globals) {
9426
+ const realm = vm.createContext(globals);
9427
+ return (source, file, module, require) => {
9428
+ new vm.Script(`(function(module, exports, require) {${source}\n})`, { filename: file }).runInContext(realm)(module, module.exports, require);
9429
+ };
9430
+ }
9431
+ });
8726
9432
  const moduleCache = /* @__PURE__ */ new Map();
8727
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole);
9433
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole, workers.apis);
8728
9434
  executionContext.globalThis = executionContext;
8729
9435
  function executeModule(filePath, loadContext) {
8730
9436
  const resolvedPath = path.resolve(filePath);
@@ -8783,6 +9489,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8783
9489
  return callback(...args);
8784
9490
  },
8785
9491
  close() {
9492
+ workers.close();
8786
9493
  moduleCache.clear();
8787
9494
  closeRuntimeWxsLoader(loader);
8788
9495
  },
@@ -8967,7 +9674,7 @@ var HeadlessSession = class {
8967
9674
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
8968
9675
  getNetworkType: () => this.wxState.getNetworkType(),
8969
9676
  navigateBack: (option) => this.navigateBack(option?.delta),
8970
- navigateTo: (option) => this.navigateTo(option.url),
9677
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
8971
9678
  pageScrollTo: (option) => this.pageScrollTo(option),
8972
9679
  openDocument: (option) => this.wxState.openDocument(option),
8973
9680
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -9282,19 +9989,19 @@ var HeadlessSession = class {
9282
9989
  return this.wxState.getShareMenu();
9283
9990
  }
9284
9991
  selectComponent(selector) {
9285
- this.renderCurrentPage();
9992
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9286
9993
  return this.selectComponentsWithin(null, selector)[0] ?? null;
9287
9994
  }
9288
9995
  selectAllComponents(selector) {
9289
- this.renderCurrentPage();
9996
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9290
9997
  return this.selectComponentsWithin(null, selector);
9291
9998
  }
9292
9999
  selectComponentWithin(scopeId, selector) {
9293
- this.renderCurrentPage();
10000
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9294
10001
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
9295
10002
  }
9296
10003
  selectAllComponentsWithin(scopeId, selector) {
9297
- this.renderCurrentPage();
10004
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9298
10005
  return this.selectComponentsWithin(scopeId, selector);
9299
10006
  }
9300
10007
  selectOwnerComponent(scopeId) {
@@ -10034,6 +10741,7 @@ function createPageRootNodeHandle(options) {
10034
10741
  const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
10035
10742
  return new HeadlessTestingNodeHandle(tree.root.type === "root" && !options.includeHostRoots ? tree.root.children?.[0] ?? tree.root : tree.root, {
10036
10743
  assertActive: options.assertActive,
10744
+ projectionOnly: options.projectionOnly,
10037
10745
  dispatchNativeEvent: (node, eventName, event, onHandlerResult) => session?.getCurrentPages().at(-1) === page ? session.dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) : false,
10038
10746
  callMethod: (scopeId, methodName, event) => {
10039
10747
  if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
@@ -10396,7 +11104,18 @@ var HeadlessTestingPageHandle = class {
10396
11104
  renderedAccess() {
10397
11105
  return {
10398
11106
  assertActive: () => this.assertActive(),
10399
- findAll: async (selector) => await this.$$(selector),
11107
+ findAll: async (selector) => {
11108
+ this.assertActive();
11109
+ const root = createPageRootNodeHandle({
11110
+ assertActive: () => this.assertActive(),
11111
+ createPageHandle: () => this,
11112
+ page: this.page,
11113
+ project: this.project,
11114
+ projectionOnly: true,
11115
+ session: this.session
11116
+ });
11117
+ return selector === "page" ? [root] : await root.$$(selector);
11118
+ },
10400
11119
  waitFor: async (ms) => await this.waitFor(ms),
10401
11120
  wxml: async () => await this.wxml()
10402
11121
  };
@@ -10483,6 +11202,10 @@ var HeadlessTestingSessionHandle = class {
10483
11202
  });
10484
11203
  }
10485
11204
  async close() {
11205
+ this.disconnect();
11206
+ }
11207
+ /** 无头会话独占本地 runtime;同步释放与 automator 的连接清理契约一致。 */
11208
+ disconnect() {
10486
11209
  this.session.close();
10487
11210
  }
10488
11211
  async toolInfo() {
@@ -10522,6 +11245,10 @@ var HeadlessTestingSessionHandle = class {
10522
11245
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "wx method name");
10523
11246
  return await runWithTimeout(() => this.session.callWxMethod(normalizedMethodName, ...args), options.timeout, `Timed out calling wx.${normalizedMethodName} in headless testing runtime.`);
10524
11247
  }
11248
+ /** 返回与 DevTools automator 兼容的运行时系统信息。 */
11249
+ async systemInfo() {
11250
+ return await this.callWxMethod("getSystemInfoSync");
11251
+ }
10525
11252
  async scopeSnapshot(scopeId) {
10526
11253
  const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
10527
11254
  return this.session.getScopeSnapshot(normalizedScopeId);