@mpcore/simulator 0.4.2 → 0.5.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
@@ -1,10 +1,66 @@
1
- import { dirname, join, normalize, posix } from "pathe";
1
+ import { dirname, join, normalize, posix, relative } from "pathe";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { parseExpression } from "@babel/parser";
5
+ import postcss from "postcss";
5
6
  import { WEVU_NATIVE_INSTANCE_KEY } from "@weapp-core/constants";
6
7
  import { parseDocument } from "htmlparser2";
8
+ import { selectAll } from "css-select";
9
+ import { AttributeAction, SelectorType, parse } from "css-what";
10
+ import * as fontoxpath from "fontoxpath";
7
11
  import vm from "node:vm";
12
+ //#region src/host/behavior.ts
13
+ function validateConstructedBehaviors(definition, visited = /* @__PURE__ */ new WeakSet()) {
14
+ if (visited.has(definition)) return;
15
+ visited.add(definition);
16
+ const behaviors = Array.isArray(definition.behaviors) ? definition.behaviors : [];
17
+ for (const behavior of behaviors) {
18
+ if (!behavior || typeof behavior !== "object" || Array.isArray(behavior)) continue;
19
+ if (!("__isHeadlessBehavior__" in behavior) || behavior.__isHeadlessBehavior__ !== true) throw new Error("Behaviors should be constructed with Behavior()");
20
+ validateConstructedBehaviors(behavior, visited);
21
+ }
22
+ }
23
+ //#endregion
24
+ //#region src/host/componentPageAttachment.ts
25
+ const definitionAttachments = /* @__PURE__ */ new WeakMap();
26
+ const instanceAttachments = /* @__PURE__ */ new WeakMap();
27
+ const attachingInstances = /* @__PURE__ */ new WeakSet();
28
+ const instanceStyleIsolation = /* @__PURE__ */ new WeakMap();
29
+ const componentPageInstances = /* @__PURE__ */ new WeakSet();
30
+ function isComponentPageInstance(instance) {
31
+ return componentPageInstances.has(instance);
32
+ }
33
+ function getComponentPageStyleIsolation(instance) {
34
+ return instanceStyleIsolation.get(instance);
35
+ }
36
+ function isComponentPageAttaching(instance) {
37
+ return attachingInstances.has(instance);
38
+ }
39
+ function registerComponentPageAttachment(definition, attach) {
40
+ definitionAttachments.set(definition, attach);
41
+ }
42
+ function bindComponentPageAttachment(instance, definition) {
43
+ const attach = definitionAttachments.get(definition);
44
+ if (attach) {
45
+ componentPageInstances.add(instance);
46
+ instanceAttachments.set(instance, attach);
47
+ const options = definition.options;
48
+ if (typeof options?.styleIsolation === "string") instanceStyleIsolation.set(instance, options.styleIsolation);
49
+ }
50
+ }
51
+ function attachComponentPage(instance) {
52
+ const attach = instanceAttachments.get(instance);
53
+ if (!attach) return false;
54
+ instanceAttachments.delete(instance);
55
+ attachingInstances.add(instance);
56
+ try {
57
+ attach.call(instance);
58
+ } finally {
59
+ attachingInstances.delete(instance);
60
+ }
61
+ return true;
62
+ }
63
+ //#endregion
8
64
  //#region src/host/globals.ts
9
65
  function createDuplicateRegistrationError(kind, id) {
10
66
  return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
@@ -23,12 +79,10 @@ function normalizeComponentPageDefinition(definition) {
23
79
  const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
24
80
  const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
25
81
  const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
26
- return {
82
+ const pageDefinition = {
27
83
  ...rest,
28
84
  ...methods,
29
85
  onLoad(...args) {
30
- callDefinitionMethod(this, created, []);
31
- callDefinitionMethod(this, attached, []);
32
86
  return callDefinitionMethod(this, load, args);
33
87
  },
34
88
  onShow(...args) {
@@ -50,6 +104,11 @@ function normalizeComponentPageDefinition(definition) {
50
104
  return callDefinitionMethod(this, routeDone, args);
51
105
  }
52
106
  };
107
+ registerComponentPageAttachment(pageDefinition, function() {
108
+ callDefinitionMethod(this, created, []);
109
+ callDefinitionMethod(this, attached, []);
110
+ });
111
+ return pageDefinition;
53
112
  }
54
113
  function createHostRegistries() {
55
114
  return {
@@ -72,6 +131,7 @@ function registerPageDefinition(registries, definition, explicitRoute) {
72
131
  return definition;
73
132
  }
74
133
  function registerComponentDefinition(registries, definition) {
134
+ validateConstructedBehaviors(definition);
75
135
  if (registries.currentLoadContext?.kind === "page") {
76
136
  if (registries.currentLoadContext.componentDefinitions) {
77
137
  registries.currentLoadContext.componentDefinitions.push(definition);
@@ -141,6 +201,24 @@ function createHeadlessUniEventBus() {
141
201
  };
142
202
  }
143
203
  //#endregion
204
+ //#region src/host/wx/logManager.ts
205
+ function createHeadlessLogManager(runtimeConsole) {
206
+ return {
207
+ debug(...args) {
208
+ runtimeConsole.debug(...args);
209
+ },
210
+ info(...args) {
211
+ runtimeConsole.info(...args);
212
+ },
213
+ log(...args) {
214
+ runtimeConsole.log(...args);
215
+ },
216
+ warn(...args) {
217
+ runtimeConsole.warn(...args);
218
+ }
219
+ };
220
+ }
221
+ //#endregion
144
222
  //#region src/host/wx/index.ts
145
223
  function invokeWxApi(operation, option) {
146
224
  try {
@@ -163,7 +241,7 @@ function resolveCapabilityValue(source, schema) {
163
241
  }
164
242
  return current;
165
243
  }
166
- function createHeadlessWx(driver) {
244
+ function createHeadlessWx(driver, runtimeConsole = console) {
167
245
  const eventBus = createHeadlessUniEventBus();
168
246
  const rpx2px = (value) => {
169
247
  const width = driver.getWindowInfoSync().windowWidth;
@@ -224,6 +302,12 @@ function createHeadlessWx(driver) {
224
302
  verticalAccuracy: true
225
303
  } },
226
304
  getLocale: true,
305
+ getLogManager: { return: {
306
+ debug: true,
307
+ info: true,
308
+ log: true,
309
+ warn: true
310
+ } },
227
311
  getFileInfo: { return: {
228
312
  digest: true,
229
313
  errMsg: true,
@@ -365,7 +449,11 @@ function createHeadlessWx(driver) {
365
449
  navigateBack: true,
366
450
  navigateTo: true,
367
451
  nextTick: true,
452
+ offAppHide: true,
453
+ offAppShow: true,
368
454
  offNetworkStatusChange: true,
455
+ onAppHide: true,
456
+ onAppShow: true,
369
457
  onNetworkStatusChange: true,
370
458
  pageScrollTo: true,
371
459
  previewImage: true,
@@ -500,6 +588,7 @@ function createHeadlessWx(driver) {
500
588
  },
501
589
  getVideoInfo: (option) => invokeWxApi(() => driver.getVideoInfo(option), option),
502
590
  getFileSystemManager: () => driver.getFileSystemManager(),
591
+ getLogManager: () => createHeadlessLogManager(runtimeConsole),
503
592
  getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
504
593
  getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
505
594
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
@@ -534,7 +623,11 @@ function createHeadlessWx(driver) {
534
623
  driver.navigateTo(option);
535
624
  }, option),
536
625
  nextTick: (callback) => driver.nextTick(callback),
626
+ offAppHide: (callback) => driver.offAppHide(callback),
627
+ offAppShow: (callback) => driver.offAppShow(callback),
537
628
  offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
629
+ onAppHide: (callback) => driver.onAppHide(callback),
630
+ onAppShow: (callback) => driver.onAppShow(callback),
538
631
  onNetworkStatusChange: (callback) => driver.onNetworkStatusChange(callback),
539
632
  openDocument: (option) => invokeWxApi(() => driver.openDocument(option), option),
540
633
  pageScrollTo: (option) => invokeWxApi(() => {
@@ -582,9 +675,7 @@ function createHeadlessWx(driver) {
582
675
  showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
583
676
  startPullDownRefresh: (option) => invokeWxApi(() => driver.startPullDownRefresh(), option),
584
677
  stopPullDownRefresh: () => driver.stopPullDownRefresh(),
585
- switchTab: (option) => invokeWxApi(() => {
586
- driver.switchTab(option);
587
- }, option),
678
+ switchTab: (option) => driver.switchTab(option),
588
679
  uploadFile: (option) => driver.uploadFile(option),
589
680
  removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
590
681
  setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
@@ -593,6 +684,32 @@ function createHeadlessWx(driver) {
593
684
  };
594
685
  }
595
686
  //#endregion
687
+ //#region src/runtime/moduleResolution.ts
688
+ function resolveMiniProgramModule(importer, request, miniprogramRootPath, hasFile) {
689
+ function resolveFile(basePath) {
690
+ return [
691
+ basePath,
692
+ `${basePath}.js`,
693
+ `${basePath}.json`,
694
+ join(basePath, "index.js")
695
+ ].find(hasFile);
696
+ }
697
+ if (request.startsWith(".")) return resolveFile(join(dirname(importer), request));
698
+ if (request.includes("\\") || request.includes(":") || request.split("/").some((part) => !part || part === "." || part === "..")) return;
699
+ const root = normalize(miniprogramRootPath);
700
+ let directory = dirname(importer);
701
+ while (true) {
702
+ const relativeDirectory = relative(root, directory);
703
+ if (relativeDirectory === ".." || relativeDirectory.startsWith("../")) return;
704
+ const resolved = resolveFile(join(directory, "miniprogram_npm", request));
705
+ if (resolved) return resolved;
706
+ if (normalize(directory) === root) return;
707
+ const parent = dirname(directory);
708
+ if (parent === directory) return;
709
+ directory = parent;
710
+ }
711
+ }
712
+ //#endregion
596
713
  //#region src/runtime/runtimeGlobals.ts
597
714
  const MINI_PROGRAM_UNAVAILABLE_GLOBAL_NAMES = [
598
715
  "window",
@@ -656,24 +773,93 @@ function hasBrowserVirtualFile(files, filePath) {
656
773
  return files.has(normalizeBrowserFilePath(filePath));
657
774
  }
658
775
  //#endregion
776
+ //#region src/view/wxs.ts
777
+ const wxsFunctions = /* @__PURE__ */ new WeakSet();
778
+ function registerWxsExports(value, visited = /* @__PURE__ */ new Set()) {
779
+ if (value == null || visited.has(value) || typeof value !== "object" && typeof value !== "function") return;
780
+ visited.add(value);
781
+ if (typeof value === "function") wxsFunctions.add(value);
782
+ for (const exported of Object.values(value)) registerWxsExports(exported, visited);
783
+ }
784
+ function callWxsFunction(fn, receiver, args) {
785
+ if (typeof fn !== "function" || !wxsFunctions.has(fn)) return;
786
+ return Reflect.apply(fn, receiver, structuredClone(args));
787
+ }
788
+ function wxsScopeData(scope) {
789
+ return scope.wxs ? {
790
+ ...scope.data,
791
+ ...scope.wxs
792
+ } : scope.data;
793
+ }
794
+ function createWxsModuleLoader(options) {
795
+ const cache = /* @__PURE__ */ new Map();
796
+ const load = (filePath, inlineSource) => {
797
+ const cached = cache.get(filePath);
798
+ if (cached) return cached.exports;
799
+ const source = inlineSource ?? options.readSource(filePath);
800
+ if (source == null) throw new Error(`Missing WXS module: ${filePath}`);
801
+ const module = { exports: {} };
802
+ cache.set(filePath, module);
803
+ try {
804
+ options.execute(source, filePath, module, (request) => {
805
+ if (typeof request !== "string" || !request.startsWith(".") || !request.endsWith(".wxs")) throw new Error(`WXS require must reference a relative .wxs file: ${String(request)}`);
806
+ return load(options.resolvePath(filePath, request));
807
+ });
808
+ registerWxsExports(module.exports);
809
+ return module.exports;
810
+ } catch (error) {
811
+ cache.delete(filePath);
812
+ throw error;
813
+ }
814
+ };
815
+ return {
816
+ load,
817
+ clear: () => cache.clear()
818
+ };
819
+ }
820
+ //#endregion
821
+ //#region src/browser/wxs.ts
822
+ const loaders$1 = /* @__PURE__ */ new WeakMap();
823
+ const HOST_GLOBALS = [
824
+ "wx",
825
+ "App",
826
+ "Page",
827
+ "Component",
828
+ "Behavior",
829
+ "getApp",
830
+ "getCurrentPages",
831
+ "window",
832
+ "document",
833
+ "globalThis",
834
+ "global",
835
+ "process"
836
+ ];
837
+ function closeBrowserWxsLoader(owner) {
838
+ loaders$1.get(owner)?.clear();
839
+ loaders$1.delete(owner);
840
+ }
841
+ function getBrowserWxsLoader(owner, files) {
842
+ let loader = loaders$1.get(owner);
843
+ if (!loader) {
844
+ loader = createWxsModuleLoader({
845
+ readSource: (filePath) => readBrowserVirtualFile(files, filePath),
846
+ resolvePath: (filePath, request) => normalize(join(dirname(filePath), request)),
847
+ execute(source, _filePath, module, require) {
848
+ new Function("module", "exports", "require", "getDate", "getRegExp", ...HOST_GLOBALS, `"use strict";\n${source}`)(module, module.exports, require, (...args) => Reflect.construct(Date, args), (...args) => Reflect.construct(RegExp, args), ...HOST_GLOBALS.map(() => void 0));
849
+ }
850
+ });
851
+ loaders$1.set(owner, loader);
852
+ }
853
+ return loader.load;
854
+ }
855
+ //#endregion
659
856
  //#region src/browser/moduleLoader.ts
660
857
  function createRequireNotFoundError$1(request, importer) {
661
858
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
662
859
  }
663
- function resolveRequiredModulePath$1(files, importer, request) {
664
- if (!request.startsWith(".")) throw createRequireNotFoundError$1(request, importer);
665
- const basePath = normalize(join(dirname(importer), request));
666
- const candidates = [
667
- basePath,
668
- `${basePath}.js`,
669
- `${basePath}.json`,
670
- join(basePath, "index.js")
671
- ];
672
- for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
673
- throw createRequireNotFoundError$1(request, importer);
674
- }
675
860
  function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
676
- const wx = createHeadlessWx(wxDriver);
861
+ const runtimeConsole = kernel.diagnostics.createConsole();
862
+ const wx = createHeadlessWx(wxDriver, runtimeConsole);
677
863
  return createMiniProgramRuntimeGlobals({
678
864
  App(definition) {
679
865
  return registerAppDefinition(registries, definition);
@@ -692,7 +878,7 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver,
692
878
  },
693
879
  clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
694
880
  clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
695
- console: kernel.diagnostics.createConsole(),
881
+ console: runtimeConsole,
696
882
  getApp,
697
883
  getCurrentPages,
698
884
  globalThis: void 0,
@@ -722,7 +908,8 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
722
908
  const previousLoadContext = registries.currentLoadContext;
723
909
  registries.currentLoadContext = loadContext;
724
910
  const localRequire = ((request) => {
725
- const requiredPath = resolveRequiredModulePath$1(files, resolvedPath, request);
911
+ const requiredPath = resolveMiniProgramModule(resolvedPath, request, options.miniprogramRootPath, (candidate) => readBrowserVirtualFile(files, candidate) !== void 0);
912
+ if (!requiredPath) throw createRequireNotFoundError$1(request, resolvedPath);
726
913
  if (requiredPath.endsWith(".json")) {
727
914
  const content = readBrowserVirtualFile(files, requiredPath);
728
915
  if (typeof content !== "string") throw new TypeError(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
@@ -734,8 +921,13 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
734
921
  });
735
922
  localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
736
923
  try {
737
- const contextEntries = Object.entries(executionContext);
738
- new Function(...contextEntries.map(([key]) => key), "exports", "module", "require", "__filename", "__dirname", source)(...contextEntries.map(([, value]) => value), module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
924
+ new Function(`
925
+ with (this) {
926
+ return function(exports, module, require, __filename, __dirname) {
927
+ ${source}
928
+ };
929
+ }
930
+ `).call(executionContext).call(executionContext, module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
739
931
  const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
740
932
  module.componentDefinitions = [.../* @__PURE__ */ new Set([
741
933
  ...requiredComponentDefinitions,
@@ -743,6 +935,9 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
743
935
  ...registeredDefinitions
744
936
  ])];
745
937
  return module;
938
+ } catch (error) {
939
+ moduleCache.delete(resolvedPath);
940
+ throw error;
746
941
  } finally {
747
942
  registries.currentLoadContext = previousLoadContext;
748
943
  }
@@ -753,14 +948,14 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
753
948
  const main = typeof plugin.config.main === "string" && plugin.config.main ? plugin.config.main : "index.js";
754
949
  return executeModule(normalize(join(options.miniprogramRootPath, plugin.virtualRoot, main)), null).exports;
755
950
  };
756
- return {
951
+ const loader = {
757
952
  close() {
758
953
  moduleCache.clear();
954
+ closeBrowserWxsLoader(loader);
759
955
  },
760
956
  executeAppModule(filePath) {
761
957
  executeModule(filePath, { kind: "app" });
762
- if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
763
- return registries.appDefinition;
958
+ return registries.appDefinition ?? registerAppDefinition(registries, {});
764
959
  },
765
960
  executePageModule(filePath, route) {
766
961
  const fallbackDefinition = executeModule(filePath, {
@@ -784,6 +979,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
784
979
  },
785
980
  wx: executionContext.wx
786
981
  };
982
+ return loader;
787
983
  }
788
984
  //#endregion
789
985
  //#region src/kernel/artifactSource.ts
@@ -1133,7 +1329,7 @@ function isStructuralValue(value) {
1133
1329
  return value !== null && typeof value === "object";
1134
1330
  }
1135
1331
  function hasComponentPropertyValueChanged(currentValue, previousSnapshot, nextValue, bindingAffected) {
1136
- const identityChanged = !Object.is(currentValue, nextValue);
1332
+ const identityChanged = !Object.is(bindingAffected ? currentValue : previousSnapshot, nextValue);
1137
1333
  if (!identityChanged && !bindingAffected) return false;
1138
1334
  if (!isStructuralValue(currentValue) && !isStructuralValue(nextValue)) return identityChanged;
1139
1335
  try {
@@ -1178,10 +1374,12 @@ function mergeRecord(...records) {
1178
1374
  function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
1179
1375
  const propOptions = definition.properties;
1180
1376
  if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
1181
- for (const changedKey of changedKeys) {
1377
+ const changedRoots = new Set(changedKeys.map((key) => parseDataPath$1(key)[0]));
1378
+ for (const changedKey of Object.keys(propOptions)) {
1379
+ if (!changedRoots.has(changedKey)) continue;
1182
1380
  const option = propOptions[changedKey];
1183
1381
  if (!option || typeof option !== "object" || Array.isArray(option)) continue;
1184
- const observer = option.observer;
1382
+ const observer = typeof option.observer === "string" ? instance[option.observer] : option.observer;
1185
1383
  if (typeof observer !== "function") continue;
1186
1384
  observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
1187
1385
  }
@@ -1217,13 +1415,32 @@ function matchObserverPattern(pattern, changedKeys) {
1217
1415
  }
1218
1416
  function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
1219
1417
  if (changedKeys.length === 0) return;
1220
- runPropertyObservers(definition, instance, changedKeys, previousProperties);
1221
1418
  const observers = definition.observers;
1222
1419
  if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
1223
1420
  if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
1224
1421
  const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
1225
1422
  handler.call(instance, ...args);
1226
1423
  }
1424
+ runPropertyObservers(definition, instance, changedKeys, previousProperties);
1425
+ }
1426
+ //#endregion
1427
+ //#region src/runtime/componentInstance/lifetimes.ts
1428
+ function mergeComponentLifetimes(behaviors, definition) {
1429
+ const lifetimes = mergeRecord(...behaviors.map((item) => item.lifetimes), definition.lifetimes);
1430
+ for (const name of [
1431
+ "created",
1432
+ "attached",
1433
+ "ready",
1434
+ "detached",
1435
+ "moved",
1436
+ "error"
1437
+ ]) {
1438
+ const handlers = [...behaviors, definition].map((item) => item.lifetimes?.[name] ?? item[name]).filter((handler) => typeof handler === "function");
1439
+ if (handlers.length > 0) lifetimes[name] = function(...args) {
1440
+ for (const handler of handlers) handler.apply(this, args);
1441
+ };
1442
+ }
1443
+ return lifetimes;
1227
1444
  }
1228
1445
  //#endregion
1229
1446
  //#region src/runtime/componentInstance/properties.ts
@@ -1258,7 +1475,8 @@ function normalizeComponentDefinition(definition) {
1258
1475
  observers: mergeRecord(...behaviors.map((item) => item.observers), definition.observers),
1259
1476
  pageLifetimes: mergeRecord(...behaviors.map((item) => item.pageLifetimes), definition.pageLifetimes),
1260
1477
  properties: mergeRecord(...behaviors.map((item) => item.properties), definition.properties),
1261
- lifetimes: mergeRecord(...behaviors.map((item) => item.lifetimes), definition.lifetimes)
1478
+ relations: mergeRecord(...behaviors.map((item) => item.relations), definition.relations),
1479
+ lifetimes: mergeComponentLifetimes(behaviors, definition)
1262
1480
  };
1263
1481
  if (mergedDataEntries.length > 0 || definition.data) mergedDefinition.data = function mergedComponentData() {
1264
1482
  return mergeRecord(mergeRecord(...mergedDataEntries.map((entry) => {
@@ -1356,6 +1574,7 @@ function resolvePropertyDefaultValue(option, definition) {
1356
1574
  }
1357
1575
  function normalizeComponentPropertyValue(definition, key, rawValue) {
1358
1576
  const option = definition.properties?.[key];
1577
+ if (rawValue === null && normalizePropertyType(option) === null) return null;
1359
1578
  if (rawValue == null) {
1360
1579
  if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) return resolvePropertyDefaultValue(option, definition);
1361
1580
  return cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
@@ -1377,22 +1596,119 @@ function resolveInitialProperties(definition, properties) {
1377
1596
  return resolved;
1378
1597
  }
1379
1598
  //#endregion
1599
+ //#region src/runtime/componentInstance/relations.ts
1600
+ const states = /* @__PURE__ */ new WeakMap();
1601
+ const opposite = {
1602
+ ancestor: "descendant",
1603
+ descendant: "ancestor",
1604
+ parent: "child",
1605
+ child: "parent"
1606
+ };
1607
+ function definitions(instance) {
1608
+ return Object.entries(instance.__definition__?.relations ?? {});
1609
+ }
1610
+ function includesBehavior(behaviors, target) {
1611
+ return Array.isArray(behaviors) && behaviors.some((behavior) => behavior === target || behavior && typeof behavior === "object" && includesBehavior(behavior.behaviors, target));
1612
+ }
1613
+ function matches(source, key, relation, target) {
1614
+ if (relation.target) return includesBehavior(target.__definition__?.behaviors, relation.target);
1615
+ const targetPath = key.startsWith("/") ? key.slice(1) : posix.join(posix.dirname(String(source.is)), key);
1616
+ return posix.normalize(targetPath) === target.is;
1617
+ }
1618
+ function getComponentRelationNodes(instance, key) {
1619
+ return [...states.get(instance)?.get(key)?.targets ?? []];
1620
+ }
1621
+ function publishRelations(nextStates) {
1622
+ const callbacks = [];
1623
+ let changed = false;
1624
+ for (const [instance, next] of nextStates) {
1625
+ const previous = states.get(instance) ?? /* @__PURE__ */ new Map();
1626
+ for (const [key, previousState] of previous) {
1627
+ const nextTargets = next.get(key)?.targets ?? [];
1628
+ for (const target of previousState.targets) if (!nextTargets.includes(target)) {
1629
+ changed = true;
1630
+ callbacks.push(() => previousState.definition.unlinked?.call(instance, target));
1631
+ }
1632
+ }
1633
+ for (const [key, nextState] of next) {
1634
+ const previousTargets = previous.get(key)?.targets ?? [];
1635
+ for (const target of nextState.targets) if (!previousTargets.includes(target)) {
1636
+ changed = true;
1637
+ callbacks.push(() => nextState.definition.linked?.call(instance, target));
1638
+ }
1639
+ }
1640
+ states.set(instance, next);
1641
+ }
1642
+ for (const callback of callbacks) callback();
1643
+ return changed;
1644
+ }
1645
+ function syncComponentRelations(cache, activeScopeIds, pageScopeId) {
1646
+ const entries = [...cache].filter(([scopeId]) => activeScopeIds.has(scopeId));
1647
+ const nextStates = /* @__PURE__ */ new Map();
1648
+ for (const [scopeId, instance] of cache) {
1649
+ if (!scopeId.startsWith(`${pageScopeId}/`) && !activeScopeIds.has(scopeId)) continue;
1650
+ const next = /* @__PURE__ */ new Map();
1651
+ nextStates.set(instance, next);
1652
+ if (!activeScopeIds.has(scopeId)) continue;
1653
+ for (const [key, relation] of definitions(instance)) {
1654
+ const upward = relation.type === "parent" || relation.type === "ancestor";
1655
+ const candidates = entries.filter(([targetScopeId, target]) => {
1656
+ if (target === instance) return false;
1657
+ const ancestor = upward ? targetScopeId : scopeId;
1658
+ const descendant = upward ? scopeId : targetScopeId;
1659
+ if (!descendant.startsWith(`${ancestor}/`)) return false;
1660
+ if ((relation.type === "parent" || relation.type === "child") && entries.some(([between]) => between !== ancestor && between !== descendant && between.startsWith(`${ancestor}/`) && descendant.startsWith(`${between}/`))) return false;
1661
+ return matches(instance, key, relation, target) && definitions(target).some(([otherKey, other]) => other.type === opposite[relation.type] && matches(target, otherKey, other, instance));
1662
+ });
1663
+ if (upward) candidates.sort(([left], [right]) => right.length - left.length);
1664
+ next.set(key, {
1665
+ definition: relation,
1666
+ targets: candidates.map(([, target]) => target)
1667
+ });
1668
+ }
1669
+ }
1670
+ return publishRelations(nextStates);
1671
+ }
1672
+ function detachComponentRelations(instances) {
1673
+ const removed = new Set(instances);
1674
+ const nextStates = /* @__PURE__ */ new Map();
1675
+ for (const instance of instances) {
1676
+ nextStates.set(instance, /* @__PURE__ */ new Map());
1677
+ for (const relation of states.get(instance)?.values() ?? []) for (const target of relation.targets) if (!removed.has(target) && !nextStates.has(target)) nextStates.set(target, new Map([...states.get(target) ?? []].map(([key, state]) => [key, {
1678
+ ...state,
1679
+ targets: state.targets.filter((candidate) => !removed.has(candidate))
1680
+ }])));
1681
+ }
1682
+ publishRelations(nextStates);
1683
+ }
1684
+ //#endregion
1380
1685
  //#region src/runtime/componentInstance/index.ts
1381
1686
  function createComponentInstance(options) {
1382
1687
  const definition = normalizeComponentDefinition(options.definition);
1383
- const properties = resolveInitialProperties(definition, options.properties ?? {});
1688
+ const inputProperties = resolveInitialProperties(definition, options.properties ?? {});
1689
+ const data = {
1690
+ ...resolveInitialData$2(definition),
1691
+ ...Object.fromEntries(Object.keys(definition.properties ?? {}).map((key) => [key, inputProperties[key]]))
1692
+ };
1384
1693
  const instance = {
1385
1694
  __definition__: definition,
1386
- data: {
1387
- ...resolveInitialData$2(definition),
1388
- ...properties
1389
- },
1695
+ data,
1390
1696
  __propertySnapshots__: {},
1391
- properties,
1697
+ properties: {
1698
+ ...data,
1699
+ ...inputProperties
1700
+ },
1701
+ getRelationNodes(key) {
1702
+ return getComponentRelationNodes(instance, key);
1703
+ },
1392
1704
  setData(patch, callback) {
1393
1705
  const changedKeys = Object.keys(patch);
1706
+ const dataKeys = [...new Set(changedKeys.map((key) => parseDataPath$1(key)[0]))];
1707
+ const propertyKeys = dataKeys.filter((key) => Object.hasOwn(definition.properties ?? {}, key));
1708
+ const previousProperties = Object.fromEntries(propertyKeys.map((key) => [key, cloneValue(instance.properties[key])]));
1394
1709
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1395
- runComponentObservers(definition, instance, changedKeys);
1710
+ for (const key of dataKeys) instance.properties[key] = instance.data[key];
1711
+ runComponentObservers(definition, instance, changedKeys, previousProperties);
1396
1712
  if (options.requestRender) options.requestRender(callback);
1397
1713
  else callback?.();
1398
1714
  },
@@ -1405,6 +1721,12 @@ function createComponentInstance(options) {
1405
1721
  bindFunction$2(instance, key, value);
1406
1722
  }
1407
1723
  for (const [key, value] of Object.entries(definition.methods ?? {})) bindFunction$2(instance, key, value);
1724
+ Object.defineProperty(instance, "__data__", {
1725
+ value: instance.data,
1726
+ enumerable: true,
1727
+ configurable: false,
1728
+ writable: false
1729
+ });
1408
1730
  return instance;
1409
1731
  }
1410
1732
  function runComponentLifecycle(instance, lifecycleName) {
@@ -1423,6 +1745,129 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
1423
1745
  handler.call(instance, payload);
1424
1746
  }
1425
1747
  //#endregion
1748
+ //#region src/runtime/componentInstance/attachment.ts
1749
+ const attachmentStates = /* @__PURE__ */ new WeakMap();
1750
+ function isComponentAttached(instance) {
1751
+ return attachmentStates.get(instance) === "attached";
1752
+ }
1753
+ function hasPendingComponentAttachments(instances) {
1754
+ return [...instances].some((instance) => attachmentStates.get(instance) === "attaching");
1755
+ }
1756
+ function flushComponentReady(instances, ready) {
1757
+ const all = [...instances];
1758
+ if (hasPendingComponentAttachments(all)) return false;
1759
+ const pending = all.filter((instance) => isComponentAttached(instance) && !instance.__ready__);
1760
+ for (const instance of pending) instance.__ready__ = true;
1761
+ for (const instance of pending) ready(instance);
1762
+ return pending.length > 0;
1763
+ }
1764
+ function flushComponentAttachments(instances, attach) {
1765
+ const pending = [...instances].filter((instance) => !attachmentStates.has(instance));
1766
+ for (const instance of pending) attachmentStates.set(instance, "attaching");
1767
+ try {
1768
+ for (const instance of pending) try {
1769
+ attach(instance);
1770
+ } finally {
1771
+ attachmentStates.set(instance, "attached");
1772
+ }
1773
+ } finally {
1774
+ for (const instance of pending) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
1775
+ }
1776
+ return pending.length > 0;
1777
+ }
1778
+ //#endregion
1779
+ //#region src/runtime/pageLifecycle.ts
1780
+ const loadingPages = /* @__PURE__ */ new WeakSet();
1781
+ function isPageBeforeReady(page) {
1782
+ return loadingPages.has(page);
1783
+ }
1784
+ function runInitialPageLifecycles(page, query, scheduler, isAlive, renderComponents) {
1785
+ loadingPages.add(page);
1786
+ try {
1787
+ renderComponents?.();
1788
+ page.onLoad?.(query);
1789
+ if (!isAlive()) return;
1790
+ page.onShow?.();
1791
+ if (!isAlive()) return;
1792
+ } finally {
1793
+ loadingPages.delete(page);
1794
+ }
1795
+ renderComponents?.();
1796
+ scheduler.setTimeout(() => {
1797
+ if (!isAlive()) return;
1798
+ page.onReady?.();
1799
+ if (isAlive()) page.onRouteDone?.({});
1800
+ }, 0);
1801
+ }
1802
+ //#endregion
1803
+ //#region src/view/conditionalChildren.ts
1804
+ function selectConditionalChildren(children, evaluate) {
1805
+ const selected = [];
1806
+ let inChain = false;
1807
+ let matched = false;
1808
+ for (const [index, node] of children.entries()) {
1809
+ if (node.type === "text" && !node.data?.trim() && inChain) continue;
1810
+ const attributes = node.attribs ?? {};
1811
+ const isTag = node.type === "tag";
1812
+ if (isTag && attributes["wx:if"] != null) {
1813
+ inChain = true;
1814
+ matched = evaluate(node, index);
1815
+ if (matched) selected.push({
1816
+ node,
1817
+ index
1818
+ });
1819
+ continue;
1820
+ }
1821
+ if (isTag && (attributes["wx:elif"] != null || attributes["wx:else"] != null)) {
1822
+ if (inChain && !matched && (attributes["wx:else"] != null || evaluate(node, index))) {
1823
+ selected.push({
1824
+ node,
1825
+ index
1826
+ });
1827
+ matched = true;
1828
+ }
1829
+ continue;
1830
+ }
1831
+ inChain = false;
1832
+ matched = false;
1833
+ selected.push({
1834
+ node,
1835
+ index
1836
+ });
1837
+ }
1838
+ return selected;
1839
+ }
1840
+ //#endregion
1841
+ //#region src/view/customTabBar.ts
1842
+ function customTabBarScopeId(route) {
1843
+ return `page:${route.replace(/^\/+/, "")}/custom-tab-bar`;
1844
+ }
1845
+ function hasCustomTabBar(appConfig, route) {
1846
+ const tabBar = appConfig.tabBar;
1847
+ return tabBar?.custom === true && Array.isArray(tabBar.list) && tabBar.list.some((item) => item.pagePath === route.replace(/^\/+/, ""));
1848
+ }
1849
+ function customTabBarHostScope() {
1850
+ return {
1851
+ data: {},
1852
+ genericComponents: /* @__PURE__ */ new Map([["custom-tab-bar", "custom-tab-bar/index"]]),
1853
+ getMethod: () => void 0,
1854
+ getScopeId: () => "tabbar-root"
1855
+ };
1856
+ }
1857
+ //#endregion
1858
+ //#region src/view/loopEntries.ts
1859
+ function resolveLoopEntries(value) {
1860
+ if (Array.isArray(value)) return value.map((item, index) => [index, item]);
1861
+ return value !== null && typeof value === "object" ? Object.entries(value) : [];
1862
+ }
1863
+ //#endregion
1864
+ //#region src/view/renderedTree.ts
1865
+ /** 在循环展开和组件替换完成后,让父节点关系指向本次渲染树。 */
1866
+ function linkRenderedParents(root, parent = null) {
1867
+ root.parent = parent;
1868
+ for (const child of root.children ?? []) linkRenderedParents(child, root);
1869
+ }
1870
+ //#endregion
1426
1871
  //#region src/view/templateExpression.ts
1427
1872
  const expressionCache = /* @__PURE__ */ new Map();
1428
1873
  const BLOCKED_MEMBER_KEYS = /* @__PURE__ */ new Set([
@@ -1529,6 +1974,12 @@ function evaluateTemplateLiteral(node, source) {
1529
1974
  }
1530
1975
  return result;
1531
1976
  }
1977
+ function evaluateCallExpression(node, source) {
1978
+ const member = node.callee?.type === "MemberExpression" || node.callee?.type === "OptionalMemberExpression";
1979
+ const receiver = member ? evaluateExpressionNode(node.callee.object, source) : void 0;
1980
+ const key = member ? resolveMemberKey(node.callee, source) : void 0;
1981
+ return callWxsFunction(member ? receiver != null && (typeof key === "string" || typeof key === "number") && !BLOCKED_MEMBER_KEYS.has(String(key)) ? receiver[key] : void 0 : evaluateExpressionNode(node.callee, source), receiver, (node.arguments ?? []).flatMap((argument) => argument.type === "SpreadElement" ? evaluateExpressionNode(argument.argument, source) : [evaluateExpressionNode(argument, source)]));
1982
+ }
1532
1983
  function evaluateExpressionNode(node, source) {
1533
1984
  if (!node) return;
1534
1985
  switch (node.type) {
@@ -1539,6 +1990,8 @@ function evaluateExpressionNode(node, source) {
1539
1990
  case "NullLiteral": return null;
1540
1991
  case "MemberExpression":
1541
1992
  case "OptionalMemberExpression": return readMemberValue(node, source);
1993
+ case "CallExpression":
1994
+ case "OptionalCallExpression": return evaluateCallExpression(node, source);
1542
1995
  case "UnaryExpression": return evaluateUnaryExpression(node, source);
1543
1996
  case "BinaryExpression": return evaluateBinaryExpression(node, source);
1544
1997
  case "LogicalExpression": {
@@ -1603,6 +2056,86 @@ function resolveTemplateData(node, source) {
1603
2056
  return resolved && typeof resolved === "object" ? resolved : {};
1604
2057
  }
1605
2058
  //#endregion
2059
+ //#region src/browser/styles/index.ts
2060
+ const IMPORT_RE = /^(?:"([^"]+)"|'([^']+)'|url\(\s*(?:"([^"]+)"|'([^']+)'|([^'"()\s]+))\s*\))(?:\s+(\S[\s\S]*))?$/i;
2061
+ const PAGE_ISOLATION = /* @__PURE__ */ new Set([
2062
+ "page-isolated",
2063
+ "page-strong-isolated",
2064
+ "page-apply-shared",
2065
+ "page-shared"
2066
+ ]);
2067
+ /** 读取当前文件内容并展开页面样式依赖,保持 app 在前、页面声明在后的层叠顺序。 */
2068
+ function resolveBrowserPageStyles(files, route, options = {}) {
2069
+ const root = normalizeBrowserFilePath(options.miniprogramRootPath ?? "");
2070
+ const dependencies = /* @__PURE__ */ new Set();
2071
+ const appWxssEnabled = !PAGE_ISOLATION.has(options.styleIsolation ?? "");
2072
+ const label = (filename) => posix.relative(root || ".", filename);
2073
+ function visit(filename, stack) {
2074
+ const source = readBrowserVirtualFile(files, filename);
2075
+ if (source === void 0) throw new Error(`Missing browser WXSS dependency: ${label(filename)} (import chain: ${[...stack, filename].map(label).join(" -> ")})`);
2076
+ if (stack.includes(filename)) throw new Error(`Circular browser WXSS import: ${[...stack, filename].map(label).join(" -> ")}`);
2077
+ dependencies.add(label(filename));
2078
+ let stylesheet;
2079
+ try {
2080
+ stylesheet = postcss.parse(source);
2081
+ } catch {
2082
+ throw new Error(`Invalid browser WXSS syntax: ${label(filename)}`);
2083
+ }
2084
+ stylesheet.walkAtRules(/^import$/i, (rule) => {
2085
+ const match = rule.params.match(IMPORT_RE);
2086
+ const target = (match?.[1] ?? match?.[2] ?? match?.[3] ?? match?.[4] ?? match?.[5])?.trim();
2087
+ const media = match?.[6]?.trim();
2088
+ if (!target || target.includes("\\") || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(target) || media && /^(?:layer|supports)\b/i.test(media)) throw new Error(`Unsupported browser WXSS import: ${label(filename)}`);
2089
+ const pathname = target.split(/[?#]/, 1)[0];
2090
+ const dependency = normalizeBrowserFilePath(posix.join(target.startsWith("/") ? root : posix.dirname(filename), pathname.replace(/^\/+/, "")));
2091
+ const relative = label(dependency);
2092
+ if (!pathname || relative === ".." || relative.startsWith("../")) throw new Error(`Browser WXSS import escapes project root: ${label(filename)}`);
2093
+ const imported = visit(dependency, [...stack, filename]);
2094
+ if (media) {
2095
+ const wrapper = postcss.atRule({
2096
+ name: "media",
2097
+ params: media
2098
+ });
2099
+ wrapper.append(imported.nodes);
2100
+ rule.replaceWith(wrapper);
2101
+ } else rule.replaceWith(...imported.nodes);
2102
+ });
2103
+ return stylesheet;
2104
+ }
2105
+ return {
2106
+ appWxssEnabled,
2107
+ cssText: [...appWxssEnabled ? [posix.join(root, "app.wxss")] : [], posix.join(root, `${route}.wxss`)].filter((filename) => readBrowserVirtualFile(files, filename) !== void 0).map((filename) => visit(normalizeBrowserFilePath(filename), []).toString()).join("\n"),
2108
+ dependencies: [...dependencies]
2109
+ };
2110
+ }
2111
+ //#endregion
2112
+ //#region src/browser/styles/componentPage.ts
2113
+ /** 已确认的 Component 页面使用最终 JSON 覆盖定义选项,普通 Page 不参与组件隔离。 */
2114
+ function resolveBrowserComponentPageStyleIsolation(files, page, route, miniprogramRootPath) {
2115
+ if (!isComponentPageInstance(page)) return;
2116
+ const definitionIsolation = getComponentPageStyleIsolation(page);
2117
+ const filename = `${route}.json`;
2118
+ const source = readBrowserVirtualFile(files, join(miniprogramRootPath, filename));
2119
+ if (source === void 0) return definitionIsolation;
2120
+ let config;
2121
+ try {
2122
+ config = JSON.parse(source);
2123
+ } catch {
2124
+ throw new Error(`Invalid browser Component page JSON: ${filename}`);
2125
+ }
2126
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2127
+ const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2128
+ return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2129
+ }
2130
+ //#endregion
2131
+ //#region src/runtime/componentResolution.ts
2132
+ function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2133
+ const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2134
+ if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2135
+ const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2136
+ return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2137
+ }
2138
+ //#endregion
1606
2139
  //#region src/view/eventBinding.ts
1607
2140
  const LEGACY_EVENT_NAME_RE = /^\w+$/;
1608
2141
  const EVENT_BINDING_PREFIXES = [
@@ -1716,6 +2249,89 @@ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
1716
2249
  return null;
1717
2250
  }
1718
2251
  //#endregion
2252
+ //#region src/view/templateImports.ts
2253
+ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2254
+ const documents = /* @__PURE__ */ new Map();
2255
+ const definitionScopes = /* @__PURE__ */ new Map();
2256
+ const definitionWxsScopes = /* @__PURE__ */ new Map();
2257
+ const collect = (node, owner) => {
2258
+ const existing = documents.get(owner);
2259
+ if (existing) return existing;
2260
+ const state = createTemplateRenderState(node);
2261
+ const wxsModules = Object.create(null);
2262
+ const ownDefinitions = new Map(state.definitions);
2263
+ const document = {
2264
+ state,
2265
+ exports: ownDefinitions
2266
+ };
2267
+ documents.set(owner, document);
2268
+ const visit = (child) => {
2269
+ if (child.name === "wxs" && loadWxs) {
2270
+ const name = child.attribs?.module;
2271
+ if (!name || !/^[a-z_$][\w$]*$/i.test(name) || [
2272
+ "__proto__",
2273
+ "constructor",
2274
+ "prototype"
2275
+ ].includes(name)) throw new Error(`Invalid WXS module name in ${owner}: ${String(name)}`);
2276
+ if (Object.hasOwn(wxsModules, name)) throw new Error(`Duplicate WXS module in ${owner}: ${name}`);
2277
+ wxsModules[name] = loadWxs(owner, child);
2278
+ return;
2279
+ }
2280
+ if (child.name === "import" && child.attribs?.src) {
2281
+ const imported = loadImport(owner, child.attribs.src);
2282
+ const importedDocument = collect(imported.root, imported.filePath);
2283
+ for (const [name, definition] of importedDocument.exports) state.definitions.set(name, definition);
2284
+ }
2285
+ for (const nested of child.children ?? []) visit(nested);
2286
+ };
2287
+ visit(node);
2288
+ if (Object.keys(wxsModules).length) state.wxsModules = wxsModules;
2289
+ for (const [name, definition] of ownDefinitions) {
2290
+ state.definitions.set(name, definition);
2291
+ definitionScopes.set(definition, state.definitions);
2292
+ if (state.wxsModules) definitionWxsScopes.set(definition, state.wxsModules);
2293
+ }
2294
+ state.definitionScopes = definitionScopes;
2295
+ state.definitionWxsScopes = definitionWxsScopes;
2296
+ return document;
2297
+ };
2298
+ return collect(root, filePath).state;
2299
+ }
2300
+ //#endregion
2301
+ //#region src/view/templateText.ts
2302
+ const TEMPLATE_INTERPOLATION_RE$3 = /\{\{([^{}]+)\}\}/g;
2303
+ function interpolateTemplateText(input, data) {
2304
+ return input.replace(TEMPLATE_INTERPOLATION_RE$3, (_match, expression) => {
2305
+ const value = resolveTemplateExpression(data, expression);
2306
+ return value === void 0 ? "" : String(value);
2307
+ });
2308
+ }
2309
+ //#endregion
2310
+ //#region src/view/wxsDocument.ts
2311
+ const INLINE_WXS_RE = /<wxs\b([^>]*)(?<!\/)>([\s\S]*?)<\/wxs\s*>/g;
2312
+ function parseWxsTemplateDocument(templateSource) {
2313
+ const scripts = [];
2314
+ const source = templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
2315
+ return `<wxs data-sim-wxs="${scripts.push(script) - 1}"${attributes}>wxs-source</wxs>`;
2316
+ });
2317
+ const document = parseDocument(`<page>${source}</page>`, {
2318
+ xmlMode: false,
2319
+ decodeEntities: false,
2320
+ lowerCaseAttributeNames: false,
2321
+ lowerCaseTags: false,
2322
+ recognizeSelfClosing: true
2323
+ });
2324
+ const restore = (node) => {
2325
+ if (node.name === "wxs" && Object.hasOwn(node.attribs ?? {}, "data-sim-wxs")) {
2326
+ node.children[0].data = scripts[Number(node.attribs["data-sim-wxs"])];
2327
+ delete node.attribs["data-sim-wxs"];
2328
+ }
2329
+ for (const child of node.children ?? []) restore(child);
2330
+ };
2331
+ restore(document);
2332
+ return document;
2333
+ }
2334
+ //#endregion
1719
2335
  //#region src/browser/render/shared.ts
1720
2336
  const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
1721
2337
  const DATASET_NAME_RE$4 = /-([a-z])/g;
@@ -1735,7 +2351,6 @@ const STRUCTURAL_ATTRS$1 = [
1735
2351
  "wx:for-index",
1736
2352
  "wx:key"
1737
2353
  ];
1738
- const WX_ELSE_ATTRS$1 = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
1739
2354
  const CLASS_SPLIT_RE$1 = /\s+/;
1740
2355
  const JS_FILE_RE$1 = /\.js$/;
1741
2356
  function isMustacheOnly$1(value) {
@@ -1785,12 +2400,21 @@ function readTemplateSource$1(files, filePath) {
1785
2400
  return templateSource;
1786
2401
  }
1787
2402
  function parseTemplateDocument$1(templateSource) {
1788
- return parseDocument(`<page>${templateSource}</page>`, {
1789
- xmlMode: false,
1790
- decodeEntities: false,
1791
- lowerCaseAttributeNames: false,
1792
- lowerCaseTags: false,
1793
- recognizeSelfClosing: true
2403
+ return parseWxsTemplateDocument(templateSource);
2404
+ }
2405
+ function prepareTemplateRenderState$1(files, root, filePath, projectRoot, loadWxs) {
2406
+ return createImportedTemplateState(root, filePath, (owner, source) => {
2407
+ const resolved = normalize(source.startsWith("/") ? join(projectRoot, source.slice(1)) : join(dirname(owner), source));
2408
+ const document = parseTemplateDocument$1(readTemplateSource$1(files, resolved));
2409
+ return {
2410
+ filePath: resolved,
2411
+ root: document.children?.[0] ?? document
2412
+ };
2413
+ }, (owner, node) => {
2414
+ const source = node.attribs?.src;
2415
+ if (source) return loadWxs(normalize(source.startsWith("/") ? join(projectRoot, source.slice(1)) : join(dirname(owner), source)));
2416
+ const inlineSource = (node.children ?? []).map((child) => child.data ?? "").join("");
2417
+ return loadWxs(`${owner}#wxs:${node.attribs?.module}`, inlineSource);
1794
2418
  });
1795
2419
  }
1796
2420
  function serializeDomNode$2(node) {
@@ -1803,26 +2427,23 @@ function serializeDomNode$2(node) {
1803
2427
  function isTagNode$1(node) {
1804
2428
  return node.type === "tag" && typeof node.name === "string";
1805
2429
  }
1806
- function isIgnorableTextNode$1(node) {
1807
- return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
1808
- }
1809
2430
  function resolveAttributeValue$1(value, scope) {
1810
2431
  if (isMustacheOnly$1(value)) {
1811
2432
  const expression = value.trim().slice(2, -2);
1812
- return resolveValueByPath$2(scope.data, expression);
2433
+ return resolveValueByPath$2(wxsScopeData(scope), expression);
1813
2434
  }
1814
- return interpolateTemplate$2(value, scope.data);
2435
+ return interpolateTemplate$2(value, wxsScopeData(scope));
1815
2436
  }
1816
2437
  function resolveComponentAttributeValue$1(value, scope) {
1817
2438
  if (isMustacheOnly$1(value)) {
1818
2439
  const expression = value.trim().slice(2, -2);
1819
- return resolveRawValueByPath$1(scope.data, expression);
2440
+ return resolveRawValueByPath$1(wxsScopeData(scope), expression) ?? null;
1820
2441
  }
1821
- return interpolateTemplate$2(value, scope.data);
2442
+ return interpolateTemplate$2(value, wxsScopeData(scope));
1822
2443
  }
1823
2444
  function applyNodeBindings$1(node, scope) {
1824
2445
  if (!isTagNode$1(node)) {
1825
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
2446
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
1826
2447
  return;
1827
2448
  }
1828
2449
  node.attribs ??= {};
@@ -1836,17 +2457,10 @@ function applyNodeBindings$1(node, scope) {
1836
2457
  node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1837
2458
  }
1838
2459
  }
1839
- function createMergedScopeData$1(pageData, componentProperties, componentData) {
1840
- return {
1841
- ...pageData,
1842
- ...componentProperties,
1843
- ...componentData
1844
- };
1845
- }
1846
2460
  function evaluateConditionalBranch$1(node, scope) {
1847
2461
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1848
2462
  if (condition == null) return true;
1849
- return Boolean(resolveRawValueByPath$1(scope.data, condition));
2463
+ return Boolean(resolveRawValueByPath$1(wxsScopeData(scope), condition));
1850
2464
  }
1851
2465
  function createLoopScope$1(scope, itemName, indexName, item, index) {
1852
2466
  return {
@@ -1867,7 +2481,7 @@ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath,
1867
2481
  const filePath = `${componentBasePath}.js`;
1868
2482
  const templatePath = `${componentBasePath}.wxml`;
1869
2483
  return {
1870
- definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
2484
+ definition: context.moduleLoader.executeComponentModule(join(context.project.miniprogramRootPath, filePath), componentBasePath),
1871
2485
  filePath,
1872
2486
  templatePath
1873
2487
  };
@@ -1883,12 +2497,12 @@ function readComponentConfig$1(files, jsonPath) {
1883
2497
  }
1884
2498
  function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
1885
2499
  try {
1886
- const usingComponents = readComponentConfig$1(context.files, ownerJsonPath).usingComponents;
2500
+ const usingComponents = readComponentConfig$1(context.files, join(context.project.miniprogramRootPath, ownerJsonPath)).usingComponents;
1887
2501
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
1888
2502
  const resolved = /* @__PURE__ */ new Map();
1889
2503
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
1890
2504
  if (typeof rawPath !== "string") continue;
1891
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? (rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$5, "") : normalize(join(dirname(ownerFilePath), rawPath)));
2505
+ const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => readBrowserVirtualFile(context.files, candidate) !== void 0);
1892
2506
  resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
1893
2507
  }
1894
2508
  return resolved;
@@ -1897,7 +2511,7 @@ function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
1897
2511
  }
1898
2512
  }
1899
2513
  function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
1900
- const componentJsonPath = `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`;
2514
+ const componentJsonPath = join(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`);
1901
2515
  const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
1902
2516
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
1903
2517
  const ownerComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
@@ -1923,13 +2537,11 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1923
2537
  const hostDataset = collectDataset$4(hostNode);
1924
2538
  const hostId = hostNode.attribs?.id ?? "";
1925
2539
  return (instance, eventName, detail, triggerOptions) => {
1926
- const interactionTarget = instance.__lastInteractionEvent__?.target;
1927
- const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
1928
- const componentDataset = context.componentScopes.get(componentScopeId)?.dataset ?? hostDataset;
2540
+ const originScope = context.componentScopes.get(componentScopeId);
1929
2541
  const interactionMark = instance.__lastInteractionEvent__?.mark;
1930
2542
  const target = {
1931
- dataset: interactionTarget?.dataset ?? componentDataset,
1932
- id: interactionTarget?.id ?? hostId
2543
+ dataset: originScope?.dataset ?? hostDataset,
2544
+ id: originScope?.hostId ?? hostId
1933
2545
  };
1934
2546
  let currentScopeId = componentScopeId;
1935
2547
  while (currentScopeId) {
@@ -1946,8 +2558,8 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1946
2558
  target,
1947
2559
  type: eventName,
1948
2560
  currentTarget: {
1949
- dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
1950
- id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
2561
+ dataset: currentScope?.dataset ?? hostDataset,
2562
+ id: currentScope?.hostId ?? hostId
1951
2563
  }
1952
2564
  });
1953
2565
  if (binding?.stopAfter) break;
@@ -1969,7 +2581,7 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1969
2581
  if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
1970
2582
  previousProperties[key] = instance.properties[key];
1971
2583
  instance.properties[key] = nextValue;
1972
- instance.data[key] = nextValue;
2584
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
1973
2585
  changedRootKeys.push(key);
1974
2586
  }
1975
2587
  instance.__propertySnapshots ??= {};
@@ -1983,12 +2595,12 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
1983
2595
  return {
1984
2596
  alias: clonedNode.name,
1985
2597
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1986
- data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1987
- dataset: collectDataset$4(clonedNode, scope.data),
2598
+ data: { ...componentInstance.data },
2599
+ dataset: collectDataset$4(clonedNode, wxsScopeData(scope)),
1988
2600
  eventBindings: collectComponentEventBindings$1(clonedNode),
1989
2601
  getMethod: (methodName) => {
1990
2602
  const method = componentInstance?.[methodName];
1991
- return typeof method === "function" ? method : void 0;
2603
+ return typeof method === "function" ? method.bind(componentInstance) : void 0;
1992
2604
  },
1993
2605
  getScopeId: () => componentScopeId,
1994
2606
  genericComponents,
@@ -2019,7 +2631,6 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2019
2631
  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;
2020
2632
  const componentInstance = createComponentInstance({
2021
2633
  definition: componentEntry.definition,
2022
- properties: componentProperties,
2023
2634
  requestRender: (callback) => context.session.requestRender(callback),
2024
2635
  triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
2025
2636
  });
@@ -2027,21 +2638,21 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2027
2638
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
2028
2639
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
2029
2640
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
2641
+ componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
2030
2642
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
2031
2643
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
2032
2644
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
2033
2645
  context.componentCache.set(componentScopeId, componentInstance);
2034
2646
  runComponentLifecycle(componentInstance, "created");
2035
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(componentProperties), {});
2036
2647
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
2037
- runComponentLifecycle(componentInstance, "attached");
2038
- runComponentPageLifetime(componentInstance, "show");
2648
+ syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
2039
2649
  return componentInstance;
2040
2650
  }
2041
2651
  function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
2042
- const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
2652
+ const templatePath = join(context.project.miniprogramRootPath, componentEntry.templatePath);
2653
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
2043
2654
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
2044
- const templateRenderState = createTemplateRenderState(componentRoot);
2655
+ const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2045
2656
  return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
2046
2657
  }
2047
2658
  //#endregion
@@ -2053,11 +2664,10 @@ function expandNodeByFor$1(node, scope) {
2053
2664
  scope,
2054
2665
  instanceSuffix: ""
2055
2666
  }];
2056
- const list = resolveRawValueByPath$1(scope.data, forExpression);
2057
- const items = Array.isArray(list) ? list : [];
2667
+ const items = resolveLoopEntries(resolveRawValueByPath$1(wxsScopeData(scope), forExpression));
2058
2668
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
2059
2669
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
2060
- return items.map((item, index) => ({
2670
+ return items.map(([index, item]) => ({
2061
2671
  node: cloneNode$1(node),
2062
2672
  scope: createLoopScope$1(scope, itemName, indexName, item, index),
2063
2673
  instanceSuffix: `:for-${index}`
@@ -2068,40 +2678,12 @@ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath
2068
2678
  }
2069
2679
  function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2070
2680
  const renderedChildren = [];
2071
- for (let index = 0; index < children.length; index += 1) {
2072
- const child = children[index];
2681
+ for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch$1(node, scope))) {
2073
2682
  if (!isTagNode$1(child)) {
2074
2683
  renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
2075
2684
  continue;
2076
2685
  }
2077
- if (isTemplateDefinition(child)) continue;
2078
- const hasConditional = child.attribs?.["wx:if"] != null;
2079
- const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
2080
- if (hasConditional) {
2081
- let branchMatched = false;
2082
- let cursor = index;
2083
- while (cursor < children.length) {
2084
- const branch = children[cursor];
2085
- if (cursor !== index && isIgnorableTextNode$1(branch)) {
2086
- cursor += 1;
2087
- continue;
2088
- }
2089
- if (!isTagNode$1(branch)) break;
2090
- if (cursor !== index && !WX_ELSE_ATTRS$1.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
2091
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch$1(branch, scope)) {
2092
- renderedChildren.push(...renderNodeVariants$1(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes, templateRenderState));
2093
- branchMatched = true;
2094
- }
2095
- let nextBranchIndex = cursor + 1;
2096
- while (nextBranchIndex < children.length && isIgnorableTextNode$1(children[nextBranchIndex])) nextBranchIndex += 1;
2097
- const nextBranch = children[nextBranchIndex];
2098
- if (!(!!nextBranch && isTagNode$1(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
2099
- cursor = nextBranchIndex;
2100
- }
2101
- index = cursor;
2102
- continue;
2103
- }
2104
- if (isElseBranch) continue;
2686
+ if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
2105
2687
  renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
2106
2688
  }
2107
2689
  return renderedChildren;
@@ -2135,6 +2717,10 @@ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFileP
2135
2717
  return slots;
2136
2718
  }
2137
2719
  function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2720
+ if (scope.wxs !== templateRenderState.wxsModules) scope = {
2721
+ ...scope,
2722
+ wxs: templateRenderState.wxsModules
2723
+ };
2138
2724
  const clonedNode = cloneNode$1(node);
2139
2725
  if (!isTagNode$1(clonedNode)) {
2140
2726
  applyNodeBindings$1(clonedNode, scope);
@@ -2146,15 +2732,19 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2146
2732
  attribs: {},
2147
2733
  children: []
2148
2734
  };
2149
- const templateName = resolveTemplateCall(clonedNode, scope.data);
2735
+ const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
2150
2736
  if (templateName) {
2151
2737
  const definition = templateRenderState.definitions.get(templateName);
2152
2738
  const templateScope = {
2153
2739
  ...scope,
2154
- data: resolveTemplateData(clonedNode, scope.data)
2740
+ data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
2741
+ wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
2155
2742
  };
2156
2743
  const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
2157
- definitions: templateRenderState.definitions,
2744
+ definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
2745
+ definitionScopes: templateRenderState.definitionScopes,
2746
+ definitionWxsScopes: templateRenderState.definitionWxsScopes,
2747
+ wxsModules: templateScope.wxs,
2158
2748
  stack: [...templateRenderState.stack, templateName]
2159
2749
  }) : [];
2160
2750
  return {
@@ -2170,7 +2760,10 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2170
2760
  if (clonedNode.name === "slot") {
2171
2761
  const slotName = clonedNode.attribs?.name?.trim() || "default";
2172
2762
  const projected = scope.slots?.get(slotName) ?? [];
2173
- const children = projected.length ? projected.flatMap((entry) => renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState)) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
2763
+ const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
2764
+ const entry = projected[index];
2765
+ return renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
2766
+ }) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
2174
2767
  return {
2175
2768
  type: "tag",
2176
2769
  name: "block",
@@ -2193,13 +2786,14 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2193
2786
  context.componentScopes.set(componentScopeId, componentScope);
2194
2787
  const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
2195
2788
  if (renderedComponentRoot.attribs) {
2789
+ applyNodeBindings$1(clonedNode, scope);
2790
+ renderedComponentRoot.attribs = {
2791
+ ...clonedNode.attribs,
2792
+ ...renderedComponentRoot.attribs
2793
+ };
2196
2794
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
2197
2795
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
2198
2796
  }
2199
- if (!componentInstance.__ready__) {
2200
- runComponentLifecycle(componentInstance, "ready");
2201
- componentInstance.__ready__ = true;
2202
- }
2203
2797
  return renderedComponentRoot;
2204
2798
  }
2205
2799
  applyNodeBindings$1(clonedNode, scope);
@@ -2216,28 +2810,92 @@ function renderBrowserPageTree(context, page) {
2216
2810
  data: page.data,
2217
2811
  getMethod: (methodName) => {
2218
2812
  const method = page[methodName];
2219
- return typeof method === "function" ? method : void 0;
2813
+ return typeof method === "function" ? method.bind(page) : void 0;
2220
2814
  },
2221
2815
  getScopeId: () => pageScopeId,
2222
2816
  id: "page-root"
2223
2817
  };
2224
- context.componentScopes.clear();
2818
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
2225
2819
  context.componentScopes.set(pageScopeId, pageScope);
2226
2820
  const seenComponentScopes = /* @__PURE__ */ new Set();
2227
2821
  const root = (document.children ?? [])[0] ?? document;
2228
- const templateRenderState = createTemplateRenderState(root);
2822
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2229
2823
  const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
2230
- for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
2231
- runComponentLifecycle(instance, "detached");
2824
+ const roots = [renderedRoot];
2825
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
2826
+ type: "tag",
2827
+ name: "custom-tab-bar",
2828
+ attribs: {},
2829
+ children: []
2830
+ }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, seenComponentScopes, templateRenderState));
2831
+ const pageAttached = attachComponentPage(page);
2832
+ const pageAttaching = isComponentPageAttaching(page);
2833
+ const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => {
2834
+ runComponentLifecycle(instance, "attached");
2835
+ runComponentPageLifetime(instance, "show");
2836
+ });
2837
+ const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
2838
+ for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
2839
+ const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
2840
+ const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
2841
+ for (const [scopeId] of removed) {
2232
2842
  context.componentCache.delete(scopeId);
2233
2843
  context.componentScopes.delete(scopeId);
2234
2844
  }
2845
+ if (pageAttached || attached || relationsChanged) return renderBrowserPageTree(context, page);
2846
+ if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) return renderBrowserPageTree(context, page);
2847
+ const treeRoot = roots.length > 1 ? {
2848
+ type: "root",
2849
+ children: roots
2850
+ } : renderedRoot;
2851
+ linkRenderedParents(treeRoot);
2235
2852
  return {
2236
- root: renderedRoot,
2237
- wxml: serializeDomNode$2(renderedRoot)
2853
+ root: treeRoot,
2854
+ styles: resolveBrowserPageStyles(context.files, resourcePath, {
2855
+ miniprogramRootPath: context.project.miniprogramRootPath,
2856
+ styleIsolation: resolveBrowserComponentPageStyleIsolation(context.files, page, resourcePath, context.project.miniprogramRootPath)
2857
+ }),
2858
+ wxml: roots.map(serializeDomNode$2).join("")
2238
2859
  };
2239
2860
  }
2240
2861
  //#endregion
2862
+ //#region src/host/appLaunchOptions.ts
2863
+ /** 普通启动没有来源小程序,保留宿主返回的空 referrerInfo。 */
2864
+ function createAppLaunchOptions(pathname, query) {
2865
+ return {
2866
+ path: pathname.replace(/^\/+/, ""),
2867
+ query: { ...query },
2868
+ referrerInfo: {},
2869
+ scene: 1001
2870
+ };
2871
+ }
2872
+ /** 复制启动快照,保留真实 scene 与来源字段的存在性,不向缺失字段填充默认值。 */
2873
+ function cloneAppLaunchOptions(options) {
2874
+ const referrerInfo = { ...options.referrerInfo };
2875
+ if (referrerInfo.extraData !== void 0) referrerInfo.extraData = { ...referrerInfo.extraData };
2876
+ return {
2877
+ ...options,
2878
+ query: { ...options.query },
2879
+ referrerInfo
2880
+ };
2881
+ }
2882
+ //#endregion
2883
+ //#region src/host/wx/navigation.ts
2884
+ function invokePreparedNavigationApi(prepare, option) {
2885
+ try {
2886
+ const finalize = prepare()();
2887
+ try {
2888
+ option?.success?.();
2889
+ } finally {
2890
+ if (typeof finalize === "function") finalize();
2891
+ }
2892
+ option?.complete?.();
2893
+ } catch (error) {
2894
+ option?.fail?.(error);
2895
+ option?.complete?.();
2896
+ }
2897
+ }
2898
+ //#endregion
2241
2899
  //#region src/project/pageConfig.ts
2242
2900
  const DEFAULT_NAVIGATION_BAR_BACKGROUND_COLOR = "#ffffff";
2243
2901
  const DEFAULT_NAVIGATION_BAR_FRONT_COLOR = "#000000";
@@ -2326,10 +2984,74 @@ function createAppInstance(definition) {
2326
2984
  return instance;
2327
2985
  }
2328
2986
  //#endregion
2987
+ //#region src/runtime/appLifecycle.ts
2988
+ var HeadlessAppLifecycle = class {
2989
+ hideCallbacks = [];
2990
+ showCallbacks = [];
2991
+ isInitialShow = true;
2992
+ close() {
2993
+ this.hideCallbacks.length = 0;
2994
+ this.showCallbacks.length = 0;
2995
+ }
2996
+ offAppHide(callback) {
2997
+ if (!callback) {
2998
+ this.hideCallbacks.length = 0;
2999
+ return;
3000
+ }
3001
+ let retainedCount = 0;
3002
+ for (const registeredCallback of this.hideCallbacks) if (registeredCallback !== callback) {
3003
+ this.hideCallbacks[retainedCount] = registeredCallback;
3004
+ retainedCount += 1;
3005
+ }
3006
+ this.hideCallbacks.length = retainedCount;
3007
+ }
3008
+ offAppShow(callback) {
3009
+ if (!callback) {
3010
+ this.showCallbacks.length = 0;
3011
+ return;
3012
+ }
3013
+ let retainedCount = 0;
3014
+ for (const registeredCallback of this.showCallbacks) if (registeredCallback !== callback) {
3015
+ this.showCallbacks[retainedCount] = registeredCallback;
3016
+ retainedCount += 1;
3017
+ }
3018
+ this.showCallbacks.length = retainedCount;
3019
+ }
3020
+ onAppHide(callback) {
3021
+ this.hideCallbacks.push(callback);
3022
+ }
3023
+ onAppShow(callback) {
3024
+ this.showCallbacks.push(callback);
3025
+ }
3026
+ triggerAppHide(app, options) {
3027
+ const callbacks = [...this.hideCallbacks];
3028
+ for (const callback of callbacks) callback(options);
3029
+ app.onHide?.(options);
3030
+ }
3031
+ triggerAppShow(app, options) {
3032
+ const callbacks = [...this.showCallbacks];
3033
+ const isInitialShow = this.isInitialShow;
3034
+ this.isInitialShow = false;
3035
+ if (isInitialShow) app.onShow?.(options);
3036
+ for (const callback of callbacks) callback(options);
3037
+ if (!isInitialShow) app.onShow?.(options);
3038
+ }
3039
+ };
3040
+ //#endregion
2329
3041
  //#region src/runtime/pageInstance.ts
2330
3042
  const ARRAY_INDEX_PATH_RE = /\[(\d+)\]/g;
2331
3043
  const ARRAY_INDEX_SEGMENT_RE = /^\d+$/;
2332
3044
  const LEADING_ROUTE_SLASH_RE = /^\/+/;
3045
+ const pageInstanceIds = /* @__PURE__ */ new WeakMap();
3046
+ let nextPageInstanceId = 0;
3047
+ function getPageInstanceId(page) {
3048
+ let id = pageInstanceIds.get(page);
3049
+ if (id === void 0) {
3050
+ id = ++nextPageInstanceId;
3051
+ pageInstanceIds.set(page, id);
3052
+ }
3053
+ return id;
3054
+ }
2333
3055
  function bindFunction(target, key, value) {
2334
3056
  if (typeof value !== "function") {
2335
3057
  target[key] = value;
@@ -2378,25 +3100,33 @@ function normalizeRoute$1(route) {
2378
3100
  }
2379
3101
  function createPageInstance(route, definition, options = {}, pageState = {}) {
2380
3102
  const normalizedRoute = normalizeRoute$1(route);
3103
+ const data = resolveInitialData(definition);
2381
3104
  const instance = {
2382
3105
  __background__: pageState.background ? cloneBackgroundSnapshot(pageState.background) : void 0,
2383
3106
  __backgroundTextStyle__: pageState.background?.textStyle ?? pageState.backgroundTextStyle,
2384
3107
  __route__: normalizedRoute,
2385
3108
  __navigationBar__: pageState.navigationBar ? cloneNavigationBarSnapshot(pageState.navigationBar) : void 0,
2386
3109
  __navigationBarTitle__: pageState.navigationBar?.title,
2387
- data: resolveInitialData(definition),
3110
+ data,
3111
+ properties: { ...data },
2388
3112
  options: { ...options },
2389
3113
  route: normalizedRoute,
2390
3114
  setData(patch, callback) {
2391
3115
  instance.__lastChangedKeys__ = Object.keys(patch);
2392
- for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
2393
- callback?.();
3116
+ for (const [key, value] of Object.entries(patch)) {
3117
+ assignByPath(instance.data, key, value);
3118
+ const rootKey = parseDataPath(key)[0];
3119
+ if (rootKey) instance.properties[rootKey] = instance.data[rootKey];
3120
+ }
3121
+ if (pageState.requestRender) pageState.requestRender(callback);
3122
+ else callback?.();
2394
3123
  }
2395
3124
  };
2396
3125
  for (const [key, value] of Object.entries(definition)) {
2397
- if (key === "data") continue;
3126
+ if (key === "data" || key === "options" || key === "properties") continue;
2398
3127
  bindFunction(instance, key, value);
2399
3128
  }
3129
+ bindComponentPageAttachment(instance, definition);
2400
3130
  return instance;
2401
3131
  }
2402
3132
  //#endregion
@@ -4057,56 +4787,107 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
4057
4787
  }
4058
4788
  //#endregion
4059
4789
  //#region src/view/selectors.ts
4060
- const WHITESPACE_RE$2 = /\s+/;
4061
- const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
4062
- const COMPOUND_SELECTOR_PART_RE$2 = /#[\w-]+|\.[\w-]+|\[data-[^=\]]+="[^"]*"\]|[A-Za-z][\w-]*/g;
4063
- function getClassList(node) {
4064
- return String(node.attribs?.class ?? "").split(WHITESPACE_RE$2).map((item) => item.trim()).filter(Boolean);
4065
- }
4066
- function matchesSimpleSelector(node, selector) {
4067
- if (node.type !== "tag") return false;
4068
- if (selector === "page") return node.name === "page";
4069
- if (selector === "*") return true;
4070
- if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
4071
- if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
4072
- const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
4073
- if (dataAttrMatch) {
4074
- const [, key, value] = dataAttrMatch;
4075
- return node.attribs?.[`data-${key}`] === value;
4076
- }
4077
- return node.name === selector;
4078
- }
4079
- function parseCompoundSelector$2(selector) {
4080
- const parts = selector.match(COMPOUND_SELECTOR_PART_RE$2) ?? [];
4081
- return parts.join("") === selector ? parts : [];
4082
- }
4083
- function matchesSelectorToken(node, selector) {
4084
- if (selector === "*") return node.type === "tag";
4085
- const simpleSelectors = parseCompoundSelector$2(selector);
4086
- if (simpleSelectors.length === 0) return false;
4087
- return simpleSelectors.every((simpleSelector) => matchesSimpleSelector(node, simpleSelector));
4088
- }
4089
- function collectDescendants(node, into) {
4090
- for (const child of node.children ?? []) {
4091
- into.push(child);
4092
- collectDescendants(child, into);
4790
+ const adapter = {
4791
+ isTag: (node) => node.type === "tag",
4792
+ getAttributeValue: (node, name) => node.attribs?.[name],
4793
+ getChildren: (node) => node.children ?? [],
4794
+ getName: (node) => node.name ?? "",
4795
+ getParent: (node) => node.parent ?? null,
4796
+ getSiblings: (node) => node.parent?.children ?? [node],
4797
+ getText: (node) => node.type === "text" ? node.data ?? "" : (node.children ?? []).map((child) => adapter.getText(child)).join(""),
4798
+ hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
4799
+ removeSubsets: (nodes) => {
4800
+ const unique = new Set(nodes);
4801
+ return [...unique].filter((node) => {
4802
+ for (let parent = node.parent; parent; parent = parent.parent) if (unique.has(parent)) return false;
4803
+ return true;
4804
+ });
4093
4805
  }
4806
+ };
4807
+ function resolveComponentTags(selectors) {
4808
+ return selectors.map((group) => group.map((token) => {
4809
+ if (token.type === SelectorType.Pseudo && Array.isArray(token.data)) return {
4810
+ ...token,
4811
+ data: resolveComponentTags(token.data)
4812
+ };
4813
+ if (token.type !== SelectorType.Tag || token.namespace !== null || token.name === "page") return token;
4814
+ const component = {
4815
+ type: SelectorType.Attribute,
4816
+ name: "data-sim-component",
4817
+ action: token.name === "component" ? AttributeAction.Exists : AttributeAction.Equals,
4818
+ value: token.name === "component" ? "" : token.name,
4819
+ ignoreCase: false,
4820
+ namespace: null
4821
+ };
4822
+ return token.name === "component" ? component : {
4823
+ type: SelectorType.Pseudo,
4824
+ name: "is",
4825
+ data: [[token], [component]]
4826
+ };
4827
+ }));
4094
4828
  }
4095
4829
  function querySelectorAll(root, selector) {
4096
- const parts = selector.trim().split(WHITESPACE_RE$2).filter(Boolean);
4097
- if (parts.length === 0) return [];
4098
- let current = [root];
4099
- for (const part of parts) {
4100
- const next = [];
4101
- for (const node of current) {
4102
- const candidates = [];
4103
- if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
4104
- collectDescendants(node, candidates);
4105
- for (const candidate of candidates) if (matchesSelectorToken(candidate, part)) next.push(candidate);
4106
- }
4107
- current = next;
4108
- }
4109
- return current;
4830
+ const parsed = parse(selector);
4831
+ const query = resolveComponentTags(parsed);
4832
+ const includesPageRoot = root.type === "tag" && root.name === "page" && parsed.some((group) => group.some((token) => token.type === SelectorType.Tag && token.name === "page"));
4833
+ return selectAll(query, includesPageRoot ? [root] : root, {
4834
+ adapter,
4835
+ cacheResults: false
4836
+ });
4837
+ }
4838
+ //#endregion
4839
+ //#region src/view/xpath.ts
4840
+ const xpathEngine = Reflect.get(fontoxpath, "default") ?? fontoxpath;
4841
+ function wrapNode(source, parent = null) {
4842
+ const node = {
4843
+ attributes: [],
4844
+ children: [],
4845
+ data: source.data ?? "",
4846
+ localName: source.name ?? "",
4847
+ namespaceURI: null,
4848
+ nodeName: source.name ?? "",
4849
+ nodeType: source.type === "tag" ? 1 : source.type === "text" ? 3 : source.type === "comment" ? 8 : 9,
4850
+ parent,
4851
+ prefix: null,
4852
+ source
4853
+ };
4854
+ node.attributes = Object.entries(source.attribs ?? {}).map(([name, value]) => ({
4855
+ localName: name,
4856
+ name,
4857
+ namespaceURI: null,
4858
+ nodeName: name,
4859
+ nodeType: 2,
4860
+ parent: node,
4861
+ prefix: null,
4862
+ value
4863
+ }));
4864
+ node.children = (source.children ?? []).map((child) => wrapNode(child, node));
4865
+ return node;
4866
+ }
4867
+ function sibling(node, offset) {
4868
+ const current = node;
4869
+ if (current.nodeType === 2) return null;
4870
+ const children = current.parent?.children ?? [];
4871
+ return children[children.indexOf(current) + offset] ?? null;
4872
+ }
4873
+ const domFacade = {
4874
+ getAllAttributes: (node) => node.attributes,
4875
+ getAttribute: (node, name) => node.attributes.find((attribute) => attribute.name === name)?.value ?? null,
4876
+ getChildNodes: (node) => node.children ?? [],
4877
+ getData: (node) => node.nodeType === 2 ? node.value : node.data,
4878
+ getFirstChild: (node) => node.children?.[0] ?? null,
4879
+ getLastChild: (node) => node.children?.at(-1) ?? null,
4880
+ getNextSibling: (node) => sibling(node, 1),
4881
+ getParentNode: (node) => node.parent,
4882
+ getPreviousSibling: (node) => sibling(node, -1)
4883
+ };
4884
+ function queryXPathElements(root, expression) {
4885
+ if (!expression.trim()) throw new Error("XPath must be a non-empty expression in headless testing runtime.");
4886
+ const document = wrapNode(root.type === "root" ? root : {
4887
+ type: "root",
4888
+ children: [root]
4889
+ });
4890
+ return xpathEngine.evaluateXPathToNodes(expression, document, domFacade).filter((node) => node.nodeType === 1).map((node) => node.source);
4110
4891
  }
4111
4892
  //#endregion
4112
4893
  //#region src/view/nodeHandle.ts
@@ -4142,6 +4923,7 @@ function createEventPayload$1(node, eventName, event) {
4142
4923
  dataset: event.target?.dataset ?? event.dataset ?? dataset,
4143
4924
  id: event.target?.id ?? event.id ?? nodeId
4144
4925
  },
4926
+ timeStamp: Date.now(),
4145
4927
  type: eventName
4146
4928
  };
4147
4929
  }
@@ -4185,14 +4967,27 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
4185
4967
  assertActive() {
4186
4968
  this.interactions?.assertActive?.();
4187
4969
  }
4970
+ query(selector) {
4971
+ const nodes = querySelectorAll(this.node, selector);
4972
+ const scope = this.node.attribs?.["data-sim-scope"];
4973
+ if (!scope || !this.interactions) return nodes;
4974
+ return nodes.filter((node) => {
4975
+ const nodeScope = node.attribs?.["data-sim-scope"];
4976
+ return nodeScope === scope || node.attribs?.["data-sim-component"] && (this.interactions.ownerScopeId(nodeScope ?? null) ?? resolvePageScopeId$1(nodeScope)) === scope;
4977
+ });
4978
+ }
4188
4979
  async $(selector) {
4189
4980
  this.assertActive();
4190
- const match = querySelectorAll(this.node, selector)[0];
4981
+ const match = this.query(selector)[0];
4191
4982
  return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
4192
4983
  }
4193
4984
  async $$(selector) {
4194
4985
  this.assertActive();
4195
- return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
4986
+ return this.query(selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
4987
+ }
4988
+ async getElementsByXpath(expression) {
4989
+ this.assertActive();
4990
+ return queryXPathElements(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
4196
4991
  }
4197
4992
  async attr(name) {
4198
4993
  this.assertActive();
@@ -4295,7 +5090,7 @@ function visitDom(node, visitor) {
4295
5090
  }
4296
5091
  function interpolateDomTree(root, data) {
4297
5092
  visitDom(root, (node) => {
4298
- if (typeof node.data === "string") node.data = interpolateTemplate$1(node.data, data);
5093
+ if (typeof node.data === "string") node.data = interpolateTemplateText(node.data, data);
4299
5094
  if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate$1(value, data);
4300
5095
  });
4301
5096
  }
@@ -5276,17 +6071,6 @@ function matchesComponentSelector$1(scope, selector) {
5276
6071
  function normalizeSelectorParts$1(selector) {
5277
6072
  return selector.trim().split(WHITESPACE_RE$1).filter(Boolean);
5278
6073
  }
5279
- function createAppLaunchOptions$1(pathname, query) {
5280
- return {
5281
- path: stripLeadingSlash$1(pathname),
5282
- query: { ...query },
5283
- referrerInfo: {
5284
- appId: "",
5285
- extraData: {}
5286
- },
5287
- scene: 1001
5288
- };
5289
- }
5290
6074
  function readJsonObject$2(files, filePath) {
5291
6075
  const content = readBrowserVirtualFile(files, filePath);
5292
6076
  if (!content) return;
@@ -5308,6 +6092,7 @@ var BrowserHeadlessSession = class {
5308
6092
  project;
5309
6093
  appDefinition = null;
5310
6094
  appInstance = null;
6095
+ appLifecycle = new HeadlessAppLifecycle();
5311
6096
  moduleLoader;
5312
6097
  onRender;
5313
6098
  registries;
@@ -5326,8 +6111,8 @@ var BrowserHeadlessSession = class {
5326
6111
  systemInfo = createDefaultSystemInfo();
5327
6112
  mediaQueryObservers = /* @__PURE__ */ new Set();
5328
6113
  canvasContexts = /* @__PURE__ */ new Map();
5329
- enterOptions = createAppLaunchOptions$1("", {});
5330
- launchOptions = createAppLaunchOptions$1("", {});
6114
+ enterOptions = createAppLaunchOptions("", {});
6115
+ launchOptions = createAppLaunchOptions("", {});
5331
6116
  kernel = new RuntimeKernel();
5332
6117
  wxState;
5333
6118
  pullDownRefreshState = {
@@ -5379,24 +6164,10 @@ var BrowserHeadlessSession = class {
5379
6164
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
5380
6165
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
5381
6166
  getSavedFileList: () => this.wxState.getSavedFileList(),
5382
- getEnterOptionsSync: () => ({
5383
- ...this.enterOptions,
5384
- query: { ...this.enterOptions.query },
5385
- referrerInfo: {
5386
- ...this.enterOptions.referrerInfo,
5387
- extraData: { ...this.enterOptions.referrerInfo.extraData }
5388
- }
5389
- }),
6167
+ getEnterOptionsSync: () => this.getEnterOptions(),
5390
6168
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
5391
6169
  getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
5392
- getLaunchOptionsSync: () => ({
5393
- ...this.launchOptions,
5394
- query: { ...this.launchOptions.query },
5395
- referrerInfo: {
5396
- ...this.launchOptions.referrerInfo,
5397
- extraData: { ...this.launchOptions.referrerInfo.extraData }
5398
- }
5399
- }),
6170
+ getLaunchOptionsSync: () => this.getLaunchOptions(),
5400
6171
  getClipboardData: () => this.wxState.getClipboardData(),
5401
6172
  getLocation: () => createDefaultLocationResult(),
5402
6173
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
@@ -5419,7 +6190,11 @@ var BrowserHeadlessSession = class {
5419
6190
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
5420
6191
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
5421
6192
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
6193
+ offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
6194
+ offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
5422
6195
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
6196
+ onAppHide: (callback) => this.appLifecycle.onAppHide(callback),
6197
+ onAppShow: (callback) => this.appLifecycle.onAppShow(callback),
5423
6198
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
5424
6199
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
5425
6200
  previewImage: (option) => this.wxState.previewImage(option),
@@ -5445,7 +6220,7 @@ var BrowserHeadlessSession = class {
5445
6220
  showToast: (option) => this.wxState.showToast(option),
5446
6221
  startPullDownRefresh: () => this.startPullDownRefresh(),
5447
6222
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
5448
- switchTab: (option) => this.switchTab(option.url),
6223
+ switchTab: (option) => invokePreparedNavigationApi(() => this.prepareSwitchTab(option.url), option),
5449
6224
  uploadFile: (option) => this.wxState.uploadFile(option),
5450
6225
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
5451
6226
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
@@ -5466,6 +6241,7 @@ var BrowserHeadlessSession = class {
5466
6241
  this.canvasContexts.clear();
5467
6242
  this.renderRequestCallbacks.length = 0;
5468
6243
  this.renderRequestPending = false;
6244
+ this.appLifecycle.close();
5469
6245
  this.wxState.close();
5470
6246
  this.moduleLoader.close();
5471
6247
  this.kernel.close();
@@ -5568,24 +6344,10 @@ var BrowserHeadlessSession = class {
5568
6344
  return deriveDeviceInfo(this.systemInfo);
5569
6345
  }
5570
6346
  getLaunchOptions() {
5571
- return {
5572
- ...this.launchOptions,
5573
- query: { ...this.launchOptions.query },
5574
- referrerInfo: {
5575
- ...this.launchOptions.referrerInfo,
5576
- extraData: { ...this.launchOptions.referrerInfo.extraData }
5577
- }
5578
- };
6347
+ return cloneAppLaunchOptions(this.launchOptions);
5579
6348
  }
5580
6349
  getEnterOptions() {
5581
- return {
5582
- ...this.enterOptions,
5583
- query: { ...this.enterOptions.query },
5584
- referrerInfo: {
5585
- ...this.enterOptions.referrerInfo,
5586
- extraData: { ...this.enterOptions.referrerInfo.extraData }
5587
- }
5588
- };
6350
+ return cloneAppLaunchOptions(this.enterOptions);
5589
6351
  }
5590
6352
  getMenuButtonBoundingClientRect() {
5591
6353
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
@@ -5927,21 +6689,21 @@ var BrowserHeadlessSession = class {
5927
6689
  type: "tap"
5928
6690
  });
5929
6691
  }
5930
- bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
6692
+ bootstrap(launchOptions = createAppLaunchOptions("", {})) {
5931
6693
  this.assertActive();
5932
6694
  if (this.appInstance) return this.appInstance;
5933
- this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
5934
- this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
6695
+ this.launchOptions = cloneAppLaunchOptions(launchOptions);
6696
+ this.enterOptions = cloneAppLaunchOptions(launchOptions);
5935
6697
  const appModulePath = join(this.project.miniprogramRootPath, "app.js");
5936
6698
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
5937
6699
  this.appInstance = createAppInstance(this.appDefinition);
5938
6700
  this.appInstance.onLaunch?.(launchOptions);
5939
- this.appInstance.onShow?.(launchOptions);
6701
+ this.appLifecycle.triggerAppShow(this.appInstance, launchOptions);
5940
6702
  return this.appInstance;
5941
6703
  }
5942
6704
  reLaunch(url) {
5943
6705
  const target = this.resolveNavigationTarget(url);
5944
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6706
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5945
6707
  this.unloadAllPages();
5946
6708
  const pageInstance = this.createFreshPage(target);
5947
6709
  this.pages.push(pageInstance);
@@ -5951,7 +6713,7 @@ var BrowserHeadlessSession = class {
5951
6713
  }
5952
6714
  navigateTo(url) {
5953
6715
  const target = this.resolveNavigationTarget(url);
5954
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6716
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5955
6717
  if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
5956
6718
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
5957
6719
  this.currentPageInstance?.onHide?.();
@@ -5964,7 +6726,7 @@ var BrowserHeadlessSession = class {
5964
6726
  }
5965
6727
  redirectTo(url) {
5966
6728
  const target = this.resolveNavigationTarget(url);
5967
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6729
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5968
6730
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
5969
6731
  const current = this.currentPageInstance;
5970
6732
  if (current) {
@@ -5990,22 +6752,26 @@ var BrowserHeadlessSession = class {
5990
6752
  return nextPage;
5991
6753
  }
5992
6754
  switchTab(url) {
6755
+ this.prepareSwitchTab(url)()();
6756
+ return this.currentPageInstance;
6757
+ }
6758
+ prepareSwitchTab(url) {
5993
6759
  const target = this.resolveNavigationTarget(url);
5994
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
5995
6760
  if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
5996
6761
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
6762
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
6763
+ return () => this.commitSwitchTab(target);
6764
+ }
6765
+ commitSwitchTab(target) {
5997
6766
  const current = this.currentPageInstance;
5998
6767
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
5999
- if (current === cachedTarget && current) return current;
6768
+ if (current === cachedTarget && current) return () => {};
6000
6769
  if (current && current !== cachedTarget) {
6001
6770
  current.onHide?.();
6002
6771
  this.runPageComponentLifetime(current.route, "hide");
6003
6772
  }
6004
- for (const page of [...this.pages].reverse()) {
6005
- if (this.isTabBarRoute(stripLeadingSlash$1(page.route))) continue;
6006
- this.removePageInstance(page);
6007
- this.unloadPage(page);
6008
- }
6773
+ const pagesToUnload = [...this.pages].reverse().filter((page) => !this.isTabBarRoute(stripLeadingSlash$1(page.route)));
6774
+ for (const page of pagesToUnload) this.removePageInstance(page);
6009
6775
  let nextPage = cachedTarget;
6010
6776
  let shouldRunInitialLifecycles = false;
6011
6777
  if (!nextPage) {
@@ -6021,7 +6787,9 @@ var BrowserHeadlessSession = class {
6021
6787
  nextPage.onShow?.();
6022
6788
  this.runPageComponentLifetime(nextPage.route, "show");
6023
6789
  }
6024
- return nextPage;
6790
+ return () => {
6791
+ for (const page of pagesToUnload) this.unloadPage(page);
6792
+ };
6025
6793
  }
6026
6794
  pageScrollTo(option) {
6027
6795
  const current = this.requireCurrentPage("wx.pageScrollTo()");
@@ -6044,6 +6812,21 @@ var BrowserHeadlessSession = class {
6044
6812
  current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
6045
6813
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
6046
6814
  }
6815
+ triggerAppHide(options) {
6816
+ this.assertActive();
6817
+ const app = this.appInstance ?? this.bootstrap();
6818
+ this.appLifecycle.triggerAppHide(app, options);
6819
+ }
6820
+ triggerAppShow(options) {
6821
+ this.assertActive();
6822
+ if (!this.appInstance) {
6823
+ this.bootstrap(options);
6824
+ return;
6825
+ }
6826
+ const nextOptions = options ?? cloneAppLaunchOptions(this.enterOptions);
6827
+ if (options) this.enterOptions = cloneAppLaunchOptions(options);
6828
+ this.appLifecycle.triggerAppShow(this.appInstance, nextOptions);
6829
+ }
6047
6830
  triggerPullDownRefresh() {
6048
6831
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
6049
6832
  this.pullDownRefreshState = {
@@ -6137,20 +6920,22 @@ var BrowserHeadlessSession = class {
6137
6920
  const pageConfig = readJsonObject$2(this.files, pageConfigPath);
6138
6921
  const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
6139
6922
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
6140
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
6923
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
6924
+ requestRender: (callback) => this.requestRender(callback)
6141
6925
  });
6142
6926
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
6143
6927
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
6144
6928
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
6145
6929
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
6930
+ pageInstance.getTabBar = () => {
6931
+ if (this.currentPageInstance === pageInstance) this.renderCurrentPage();
6932
+ return this.componentCache.get(customTabBarScopeId(pageInstance.route)) ?? null;
6933
+ };
6146
6934
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
6147
6935
  return pageInstance;
6148
6936
  }
6149
6937
  runInitialPageLifecycles(pageInstance, query) {
6150
- pageInstance.onLoad?.(query);
6151
- pageInstance.onShow?.();
6152
- pageInstance.onReady?.();
6153
- pageInstance.onRouteDone?.({});
6938
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
6154
6939
  }
6155
6940
  isTabBarRoute(route) {
6156
6941
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
@@ -6166,8 +6951,8 @@ var BrowserHeadlessSession = class {
6166
6951
  const normalizedRoute = pluginRequest ? `plugin-private://${pluginRequest.plugin.provider}/${pluginRequest.resourcePath.slice(pluginRequest.plugin.virtualRoot.length + 1)}` : resolveNavigationPath$1(pathname, baseRoute);
6167
6952
  const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
6168
6953
  if (!routeRecord) {
6169
- this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
6170
- this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
6954
+ this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
6955
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
6171
6956
  throw new Error(`Unknown route for browser simulator navigation: ${url}`);
6172
6957
  }
6173
6958
  return {
@@ -6206,9 +6991,10 @@ var BrowserHeadlessSession = class {
6206
6991
  }
6207
6992
  detachPageComponents(route) {
6208
6993
  const prefix = `page:${stripLeadingSlash$1(route)}`;
6209
- for (const [scopeId, instance] of [...this.componentCache.entries()]) {
6210
- if (!scopeId.startsWith(prefix)) continue;
6211
- instance.__definition__?.lifetimes?.detached?.call(instance);
6994
+ const removed = [...this.componentCache].filter(([scopeId]) => scopeId.startsWith(prefix));
6995
+ for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
6996
+ detachComponentRelations(removed.map(([, instance]) => instance));
6997
+ for (const [scopeId] of removed) {
6212
6998
  this.componentCache.delete(scopeId);
6213
6999
  this.componentScopes.delete(scopeId);
6214
7000
  }
@@ -6454,6 +7240,32 @@ function loadProject(projectPath) {
6454
7240
  });
6455
7241
  }
6456
7242
  //#endregion
7243
+ //#region src/runtime/wxs.ts
7244
+ const loaders = /* @__PURE__ */ new WeakMap();
7245
+ function closeRuntimeWxsLoader(owner) {
7246
+ loaders.get(owner)?.clear();
7247
+ loaders.delete(owner);
7248
+ }
7249
+ function getRuntimeWxsLoader(owner, artifactSource) {
7250
+ let loader = loaders.get(owner);
7251
+ if (!loader) {
7252
+ loader = createWxsModuleLoader({
7253
+ readSource: (filePath) => artifactSource.readText(filePath),
7254
+ resolvePath: (filePath, request) => path.resolve(path.dirname(filePath), request),
7255
+ execute(source, filePath, module, require) {
7256
+ const script = new vm.Script(`(function(module, exports, require) { ${source}\n})`, { filename: filePath });
7257
+ const context = vm.createContext({
7258
+ getDate: (...args) => Reflect.construct(Date, args),
7259
+ getRegExp: (...args) => Reflect.construct(RegExp, args)
7260
+ });
7261
+ script.runInContext(context)(module, module.exports, require);
7262
+ }
7263
+ });
7264
+ loaders.set(owner, loader);
7265
+ }
7266
+ return loader.load;
7267
+ }
7268
+ //#endregion
6457
7269
  //#region src/runtime/render/shared.ts
6458
7270
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
6459
7271
  const DATASET_NAME_RE = /-([a-z])/g;
@@ -6473,7 +7285,6 @@ const STRUCTURAL_ATTRS = [
6473
7285
  "wx:for-index",
6474
7286
  "wx:key"
6475
7287
  ];
6476
- const WX_ELSE_ATTRS = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
6477
7288
  const CLASS_SPLIT_RE = /\s+/;
6478
7289
  const JS_FILE_RE = /\.js$/;
6479
7290
  function isMustacheOnly(value) {
@@ -6523,12 +7334,21 @@ function readTemplateSource(artifactSource, filePath) {
6523
7334
  return source;
6524
7335
  }
6525
7336
  function parseTemplateDocument(templateSource) {
6526
- return parseDocument(`<page>${templateSource}</page>`, {
6527
- xmlMode: false,
6528
- decodeEntities: false,
6529
- lowerCaseAttributeNames: false,
6530
- lowerCaseTags: false,
6531
- recognizeSelfClosing: true
7337
+ return parseWxsTemplateDocument(templateSource);
7338
+ }
7339
+ function prepareTemplateRenderState(artifactSource, root, filePath, projectRoot, loadWxs) {
7340
+ return createImportedTemplateState(root, filePath, (owner, source) => {
7341
+ const resolved = source.startsWith("/") ? path.resolve(projectRoot, source.slice(1)) : path.resolve(path.dirname(owner), source);
7342
+ const document = parseTemplateDocument(readTemplateSource(artifactSource, resolved));
7343
+ return {
7344
+ filePath: resolved,
7345
+ root: document.children?.[0] ?? document
7346
+ };
7347
+ }, (owner, node) => {
7348
+ const source = node.attribs?.src;
7349
+ if (source) return loadWxs(source.startsWith("/") ? path.resolve(projectRoot, source.slice(1)) : path.resolve(path.dirname(owner), source));
7350
+ const inlineSource = (node.children ?? []).map((child) => child.data ?? "").join("");
7351
+ return loadWxs(`${owner}#wxs:${node.attribs?.module}`, inlineSource);
6532
7352
  });
6533
7353
  }
6534
7354
  function serializeDomNode(node) {
@@ -6541,26 +7361,23 @@ function serializeDomNode(node) {
6541
7361
  function isTagNode(node) {
6542
7362
  return node.type === "tag" && typeof node.name === "string";
6543
7363
  }
6544
- function isIgnorableTextNode(node) {
6545
- return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
6546
- }
6547
7364
  function resolveAttributeValue(value, scope) {
6548
7365
  if (isMustacheOnly(value)) {
6549
7366
  const expression = value.trim().slice(2, -2);
6550
- return resolveValueByPath(scope.data, expression);
7367
+ return resolveValueByPath(wxsScopeData(scope), expression);
6551
7368
  }
6552
- return interpolateTemplate(value, scope.data);
7369
+ return interpolateTemplate(value, wxsScopeData(scope));
6553
7370
  }
6554
7371
  function resolveComponentAttributeValue(value, scope) {
6555
7372
  if (isMustacheOnly(value)) {
6556
7373
  const expression = value.trim().slice(2, -2);
6557
- return resolveRawValueByPath(scope.data, expression);
7374
+ return resolveRawValueByPath(wxsScopeData(scope), expression) ?? null;
6558
7375
  }
6559
- return interpolateTemplate(value, scope.data);
7376
+ return interpolateTemplate(value, wxsScopeData(scope));
6560
7377
  }
6561
7378
  function applyNodeBindings(node, scope) {
6562
7379
  if (!isTagNode(node)) {
6563
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
7380
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
6564
7381
  return;
6565
7382
  }
6566
7383
  node.attribs ??= {};
@@ -6574,17 +7391,10 @@ function applyNodeBindings(node, scope) {
6574
7391
  node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
6575
7392
  }
6576
7393
  }
6577
- function createMergedScopeData(pageData, componentProperties, componentData) {
6578
- return {
6579
- ...pageData,
6580
- ...componentProperties,
6581
- ...componentData
6582
- };
6583
- }
6584
7394
  function evaluateConditionalBranch(node, scope) {
6585
7395
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
6586
7396
  if (condition == null) return true;
6587
- return Boolean(resolveRawValueByPath(scope.data, condition));
7397
+ return Boolean(resolveRawValueByPath(wxsScopeData(scope), condition));
6588
7398
  }
6589
7399
  function createLoopScope(scope, itemName, indexName, item, index) {
6590
7400
  return {
@@ -6628,7 +7438,7 @@ function resolveUsingComponents(context, ownerJsonPath, ownerFilePath) {
6628
7438
  const resolved = /* @__PURE__ */ new Map();
6629
7439
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
6630
7440
  if (typeof rawPath !== "string") continue;
6631
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? (rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath)));
7441
+ const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => context.artifactSource.readText(candidate) !== void 0);
6632
7442
  resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
6633
7443
  }
6634
7444
  return resolved;
@@ -6663,13 +7473,11 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
6663
7473
  const hostDataset = collectDataset(hostNode);
6664
7474
  const hostId = hostNode.attribs?.id ?? "";
6665
7475
  return (instance, eventName, detail, triggerOptions) => {
6666
- const interactionTarget = instance.__lastInteractionEvent__?.target;
6667
- const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
6668
- const componentDataset = context.componentScopes.get(componentScopeId)?.dataset ?? hostDataset;
7476
+ const originScope = context.componentScopes.get(componentScopeId);
6669
7477
  const interactionMark = instance.__lastInteractionEvent__?.mark;
6670
7478
  const target = {
6671
- dataset: interactionTarget?.dataset ?? componentDataset,
6672
- id: interactionTarget?.id ?? hostId
7479
+ dataset: originScope?.dataset ?? hostDataset,
7480
+ id: originScope?.hostId ?? hostId
6673
7481
  };
6674
7482
  let currentScopeId = componentScopeId;
6675
7483
  while (currentScopeId) {
@@ -6682,8 +7490,8 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
6682
7490
  capturePhase: false,
6683
7491
  composed: triggerOptions?.composed ?? false,
6684
7492
  currentTarget: {
6685
- dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
6686
- id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
7493
+ dataset: currentScope?.dataset ?? hostDataset,
7494
+ id: currentScope?.hostId ?? hostId
6687
7495
  },
6688
7496
  detail,
6689
7497
  mark: interactionMark,
@@ -6709,7 +7517,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
6709
7517
  if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
6710
7518
  previousProperties[key] = instance.properties[key];
6711
7519
  instance.properties[key] = nextValue;
6712
- instance.data[key] = nextValue;
7520
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
6713
7521
  changedRootKeys.push(key);
6714
7522
  }
6715
7523
  instance.__propertySnapshots ??= {};
@@ -6723,12 +7531,12 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
6723
7531
  return {
6724
7532
  alias: clonedNode.name,
6725
7533
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
6726
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
6727
- dataset: collectDataset(clonedNode, scope.data),
7534
+ data: { ...componentInstance.data },
7535
+ dataset: collectDataset(clonedNode, wxsScopeData(scope)),
6728
7536
  eventBindings: collectComponentEventBindings(clonedNode),
6729
7537
  getMethod: (methodName) => {
6730
7538
  const method = componentInstance?.[methodName];
6731
- return typeof method === "function" ? method : void 0;
7539
+ return typeof method === "function" ? method.bind(componentInstance) : void 0;
6732
7540
  },
6733
7541
  getScopeId: () => componentScopeId,
6734
7542
  genericComponents,
@@ -6759,7 +7567,6 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
6759
7567
  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;
6760
7568
  const componentInstance = createComponentInstance({
6761
7569
  definition: componentEntry.definition,
6762
- properties: componentProperties,
6763
7570
  requestRender: (callback) => context.session.requestRender(callback),
6764
7571
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
6765
7572
  });
@@ -6767,20 +7574,20 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
6767
7574
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
6768
7575
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
6769
7576
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
7577
+ componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
6770
7578
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
6771
7579
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
6772
7580
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
6773
7581
  context.componentCache.set(componentScopeId, componentInstance);
6774
7582
  runComponentLifecycle(componentInstance, "created");
6775
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(componentProperties), {});
6776
7583
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
6777
- runComponentLifecycle(componentInstance, "attached");
7584
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
6778
7585
  return componentInstance;
6779
7586
  }
6780
7587
  function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
6781
7588
  const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
6782
7589
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
6783
- const templateRenderState = createTemplateRenderState(componentRoot);
7590
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, componentRoot, componentEntry.absoluteTemplatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
6784
7591
  return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
6785
7592
  }
6786
7593
  //#endregion
@@ -6792,11 +7599,10 @@ function expandNodeByFor(node, scope) {
6792
7599
  scope,
6793
7600
  instanceSuffix: ""
6794
7601
  }];
6795
- const list = resolveRawValueByPath(scope.data, forExpression);
6796
- const items = Array.isArray(list) ? list : [];
7602
+ const items = resolveLoopEntries(resolveRawValueByPath(wxsScopeData(scope), forExpression));
6797
7603
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
6798
7604
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
6799
- return items.map((item, index) => ({
7605
+ return items.map(([index, item]) => ({
6800
7606
  node: cloneNode(node),
6801
7607
  scope: createLoopScope(scope, itemName, indexName, item, index),
6802
7608
  instanceSuffix: `:for-${index}`
@@ -6807,40 +7613,12 @@ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath,
6807
7613
  }
6808
7614
  function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
6809
7615
  const renderedChildren = [];
6810
- for (let index = 0; index < children.length; index += 1) {
6811
- const child = children[index];
7616
+ for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch(node, scope))) {
6812
7617
  if (!isTagNode(child)) {
6813
7618
  renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
6814
7619
  continue;
6815
7620
  }
6816
- if (isTemplateDefinition(child)) continue;
6817
- const hasConditional = child.attribs?.["wx:if"] != null;
6818
- const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
6819
- if (hasConditional) {
6820
- let branchMatched = false;
6821
- let cursor = index;
6822
- while (cursor < children.length) {
6823
- const branch = children[cursor];
6824
- if (cursor !== index && isIgnorableTextNode(branch)) {
6825
- cursor += 1;
6826
- continue;
6827
- }
6828
- if (!isTagNode(branch)) break;
6829
- if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
6830
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
6831
- renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes, templateRenderState));
6832
- branchMatched = true;
6833
- }
6834
- let nextBranchIndex = cursor + 1;
6835
- while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
6836
- const nextBranch = children[nextBranchIndex];
6837
- if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
6838
- cursor = nextBranchIndex;
6839
- }
6840
- index = cursor;
6841
- continue;
6842
- }
6843
- if (isElseBranch) continue;
7621
+ if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
6844
7622
  renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
6845
7623
  }
6846
7624
  return renderedChildren;
@@ -6874,6 +7652,10 @@ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePat
6874
7652
  return slots;
6875
7653
  }
6876
7654
  function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
7655
+ if (scope.wxs !== templateRenderState.wxsModules) scope = {
7656
+ ...scope,
7657
+ wxs: templateRenderState.wxsModules
7658
+ };
6877
7659
  const clonedNode = cloneNode(node);
6878
7660
  if (!isTagNode(clonedNode)) {
6879
7661
  applyNodeBindings(clonedNode, scope);
@@ -6885,15 +7667,19 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6885
7667
  attribs: {},
6886
7668
  children: []
6887
7669
  };
6888
- const templateName = resolveTemplateCall(clonedNode, scope.data);
7670
+ const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
6889
7671
  if (templateName) {
6890
7672
  const definition = templateRenderState.definitions.get(templateName);
6891
7673
  const templateScope = {
6892
7674
  ...scope,
6893
- data: resolveTemplateData(clonedNode, scope.data)
7675
+ data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
7676
+ wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
6894
7677
  };
6895
7678
  const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
6896
- definitions: templateRenderState.definitions,
7679
+ definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
7680
+ definitionScopes: templateRenderState.definitionScopes,
7681
+ definitionWxsScopes: templateRenderState.definitionWxsScopes,
7682
+ wxsModules: templateScope.wxs,
6897
7683
  stack: [...templateRenderState.stack, templateName]
6898
7684
  }) : [];
6899
7685
  return {
@@ -6909,7 +7695,10 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6909
7695
  if (clonedNode.name === "slot") {
6910
7696
  const slotName = clonedNode.attribs?.name?.trim() || "default";
6911
7697
  const projected = scope.slots?.get(slotName) ?? [];
6912
- const children = projected.length ? projected.flatMap((entry) => renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState)) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
7698
+ const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
7699
+ const entry = projected[index];
7700
+ return renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
7701
+ }) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
6913
7702
  return {
6914
7703
  type: "tag",
6915
7704
  name: "block",
@@ -6935,15 +7724,15 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6935
7724
  context.componentScopes.set(componentScopeId, componentScope);
6936
7725
  const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
6937
7726
  if (renderedComponentRoot.attribs) {
7727
+ applyNodeBindings(clonedNode, scope);
7728
+ renderedComponentRoot.attribs = {
7729
+ ...clonedNode.attribs,
7730
+ ...renderedComponentRoot.attribs
7731
+ };
6938
7732
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
6939
7733
  renderedComponentRoot.attribs["data-sim-node"] = instancePath;
6940
7734
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
6941
7735
  }
6942
- if (!componentInstance.__ready__) {
6943
- runComponentLifecycle(componentInstance, "ready");
6944
- componentInstance.__ready__ = true;
6945
- componentInstance.__definition__?.pageLifetimes?.show?.call(componentInstance);
6946
- }
6947
7736
  return renderedComponentRoot;
6948
7737
  }
6949
7738
  applyNodeBindings(clonedNode, scope);
@@ -6961,25 +7750,48 @@ function renderRuntimePageTree(context, page) {
6961
7750
  data: page.data,
6962
7751
  getMethod: (methodName) => {
6963
7752
  const method = page[methodName];
6964
- return typeof method === "function" ? method : void 0;
7753
+ return typeof method === "function" ? method.bind(page) : void 0;
6965
7754
  },
6966
7755
  getScopeId: () => pageScopeId,
6967
7756
  id: "page-root"
6968
7757
  };
6969
- context.componentScopes.clear();
7758
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
6970
7759
  context.componentScopes.set(pageScopeId, pageScope);
6971
7760
  const seenComponentScopes = /* @__PURE__ */ new Set();
6972
7761
  const root = (document.children ?? [])[0] ?? document;
6973
- const templateRenderState = createTemplateRenderState(root);
7762
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
6974
7763
  const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
6975
- for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
6976
- runComponentLifecycle(instance, "detached");
7764
+ const roots = [renderedRoot];
7765
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
7766
+ type: "tag",
7767
+ name: "custom-tab-bar",
7768
+ attribs: {},
7769
+ children: []
7770
+ }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, seenComponentScopes, templateRenderState));
7771
+ const pageAttached = attachComponentPage(page);
7772
+ const pageAttaching = isComponentPageAttaching(page);
7773
+ const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => runComponentLifecycle(instance, "attached"));
7774
+ const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
7775
+ for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
7776
+ const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
7777
+ const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
7778
+ for (const [scopeId] of removed) {
6977
7779
  context.componentCache.delete(scopeId);
6978
7780
  context.componentScopes.delete(scopeId);
6979
7781
  }
7782
+ if (pageAttached || attached || relationsChanged) return renderRuntimePageTree(context, page);
7783
+ if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
7784
+ runComponentLifecycle(instance, "ready");
7785
+ instance.__definition__?.pageLifetimes?.show?.call(instance);
7786
+ })) return renderRuntimePageTree(context, page);
7787
+ const treeRoot = roots.length > 1 ? {
7788
+ type: "root",
7789
+ children: roots
7790
+ } : renderedRoot;
7791
+ linkRenderedParents(treeRoot);
6980
7792
  return {
6981
- root: renderedRoot,
6982
- wxml: serializeDomNode(renderedRoot)
7793
+ root: treeRoot,
7794
+ wxml: roots.map(serializeDomNode).join("")
6983
7795
  };
6984
7796
  }
6985
7797
  //#endregion
@@ -7083,20 +7895,9 @@ function transformEsmToCommonJs(source) {
7083
7895
  function createRequireNotFoundError(request, importer) {
7084
7896
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
7085
7897
  }
7086
- function resolveRequiredModulePath(artifactSource, importer, request) {
7087
- if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
7088
- const basePath = path.resolve(path.dirname(importer), request);
7089
- const candidates = [
7090
- basePath,
7091
- `${basePath}.js`,
7092
- `${basePath}.json`,
7093
- path.join(basePath, "index.js")
7094
- ];
7095
- for (const candidate of candidates) if (artifactSource.has(candidate)) return candidate;
7096
- throw createRequireNotFoundError(request, importer);
7097
- }
7098
7898
  function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole) {
7099
- const wx = createHeadlessWx(wxDriver);
7899
+ const runtimeConsole = kernel.diagnostics.createConsole(console, onConsole);
7900
+ const wx = createHeadlessWx(wxDriver, runtimeConsole);
7100
7901
  return createMiniProgramRuntimeGlobals({
7101
7902
  App(definition) {
7102
7903
  return registerAppDefinition(registries, definition);
@@ -7113,7 +7914,7 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, k
7113
7914
  Page(definition) {
7114
7915
  return registerPageDefinition(registries, definition);
7115
7916
  },
7116
- console: kernel.diagnostics.createConsole(console, onConsole),
7917
+ console: runtimeConsole,
7117
7918
  clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
7118
7919
  clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
7119
7920
  getApp,
@@ -7148,7 +7949,8 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7148
7949
  const previousLoadContext = registries.currentLoadContext;
7149
7950
  registries.currentLoadContext = loadContext;
7150
7951
  const localRequire = ((request) => {
7151
- const requiredPath = resolveRequiredModulePath(options.artifactSource, resolvedPath, request);
7952
+ const requiredPath = resolveMiniProgramModule(resolvedPath, request, options.miniprogramRootPath, (candidate) => options.artifactSource.readText(candidate) !== void 0);
7953
+ if (!requiredPath) throw createRequireNotFoundError(request, resolvedPath);
7152
7954
  if (requiredPath.endsWith(".json")) {
7153
7955
  const content = options.artifactSource.readText(requiredPath);
7154
7956
  if (content == null) throw createRequireNotFoundError(request, resolvedPath);
@@ -7168,6 +7970,9 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7168
7970
  ...registeredDefinitions
7169
7971
  ])];
7170
7972
  return module;
7973
+ } catch (error) {
7974
+ moduleCache.delete(resolvedPath);
7975
+ throw error;
7171
7976
  } finally {
7172
7977
  registries.currentLoadContext = previousLoadContext;
7173
7978
  }
@@ -7178,14 +7983,19 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7178
7983
  const main = typeof plugin.config.main === "string" && plugin.config.main ? plugin.config.main : "index.js";
7179
7984
  return executeModule(path.resolve(options.miniprogramRootPath, plugin.virtualRoot, main), null).exports;
7180
7985
  };
7181
- return {
7986
+ const loader = {
7987
+ evaluate(source, args) {
7988
+ const callback = new vm.Script(`(${source})`).runInNewContext(executionContext);
7989
+ if (typeof callback !== "function") throw new TypeError("Headless evaluator must be a function or function source string.");
7990
+ return callback(...args);
7991
+ },
7182
7992
  close() {
7183
7993
  moduleCache.clear();
7994
+ closeRuntimeWxsLoader(loader);
7184
7995
  },
7185
7996
  executeAppModule(filePath) {
7186
7997
  executeModule(filePath, { kind: "app" });
7187
- if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
7188
- return registries.appDefinition;
7998
+ return registries.appDefinition ?? registerAppDefinition(registries, {});
7189
7999
  },
7190
8000
  executePageModule(filePath, route) {
7191
8001
  const fallbackDefinition = executeModule(filePath, {
@@ -7209,6 +8019,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7209
8019
  },
7210
8020
  wx: executionContext.wx
7211
8021
  };
8022
+ return loader;
7212
8023
  }
7213
8024
  //#endregion
7214
8025
  //#region src/runtime/session.ts
@@ -7259,17 +8070,6 @@ function matchesComponentSelector(scope, selector) {
7259
8070
  function normalizeSelectorParts(selector) {
7260
8071
  return selector.trim().split(WHITESPACE_RE).filter(Boolean);
7261
8072
  }
7262
- function createAppLaunchOptions(pathname, query) {
7263
- return {
7264
- path: stripLeadingSlash(pathname),
7265
- query: { ...query },
7266
- referrerInfo: {
7267
- appId: "",
7268
- extraData: {}
7269
- },
7270
- scene: 1001
7271
- };
7272
- }
7273
8073
  function readJsonObject(project, filePath) {
7274
8074
  try {
7275
8075
  const source = project.artifactSource.readText(filePath);
@@ -7290,6 +8090,7 @@ var HeadlessSession = class {
7290
8090
  kernel = new RuntimeKernel();
7291
8091
  appDefinition = null;
7292
8092
  appInstance = null;
8093
+ appLifecycle = new HeadlessAppLifecycle();
7293
8094
  moduleLoader;
7294
8095
  eventListeners = /* @__PURE__ */ new Map();
7295
8096
  registries;
@@ -7359,24 +8160,10 @@ var HeadlessSession = class {
7359
8160
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
7360
8161
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
7361
8162
  getSavedFileList: () => this.wxState.getSavedFileList(),
7362
- getEnterOptionsSync: () => ({
7363
- ...this.enterOptions,
7364
- query: { ...this.enterOptions.query },
7365
- referrerInfo: {
7366
- ...this.enterOptions.referrerInfo,
7367
- extraData: { ...this.enterOptions.referrerInfo.extraData }
7368
- }
7369
- }),
8163
+ getEnterOptionsSync: () => this.getEnterOptions(),
7370
8164
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
7371
8165
  getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
7372
- getLaunchOptionsSync: () => ({
7373
- ...this.launchOptions,
7374
- query: { ...this.launchOptions.query },
7375
- referrerInfo: {
7376
- ...this.launchOptions.referrerInfo,
7377
- extraData: { ...this.launchOptions.referrerInfo.extraData }
7378
- }
7379
- }),
8166
+ getLaunchOptionsSync: () => this.getLaunchOptions(),
7380
8167
  getClipboardData: () => this.wxState.getClipboardData(),
7381
8168
  getLocation: () => createDefaultLocationResult(),
7382
8169
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
@@ -7399,7 +8186,11 @@ var HeadlessSession = class {
7399
8186
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
7400
8187
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
7401
8188
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
8189
+ offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
8190
+ offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
7402
8191
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
8192
+ onAppHide: (callback) => this.appLifecycle.onAppHide(callback),
8193
+ onAppShow: (callback) => this.appLifecycle.onAppShow(callback),
7403
8194
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
7404
8195
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
7405
8196
  previewImage: (option) => this.wxState.previewImage(option),
@@ -7425,7 +8216,7 @@ var HeadlessSession = class {
7425
8216
  showToast: (option) => this.wxState.showToast(option),
7426
8217
  startPullDownRefresh: () => this.startPullDownRefresh(),
7427
8218
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
7428
- switchTab: (option) => this.switchTab(option.url),
8219
+ switchTab: (option) => invokePreparedNavigationApi(() => this.prepareSwitchTab(option.url), option),
7429
8220
  uploadFile: (option) => this.wxState.uploadFile(option),
7430
8221
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
7431
8222
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
@@ -7448,6 +8239,7 @@ var HeadlessSession = class {
7448
8239
  this.canvasContexts.clear();
7449
8240
  this.renderRequestCallbacks.length = 0;
7450
8241
  this.renderRequestPending = false;
8242
+ this.appLifecycle.close();
7451
8243
  this.wxState.close();
7452
8244
  this.moduleLoader.close();
7453
8245
  this.eventListeners.clear();
@@ -7485,6 +8277,11 @@ var HeadlessSession = class {
7485
8277
  this.assertActive();
7486
8278
  return this.moduleLoader.wx;
7487
8279
  }
8280
+ /** 在当前小程序实例的上下文执行测试函数,复用应用全局对象与调度器。 */
8281
+ evaluateRuntime(source, args = []) {
8282
+ this.assertActive();
8283
+ return this.moduleLoader.evaluate(source, args);
8284
+ }
7488
8285
  callWxMethod(methodName, ...args) {
7489
8286
  this.assertActive();
7490
8287
  const method = this.moduleLoader.wx[methodName];
@@ -7703,24 +8500,10 @@ var HeadlessSession = class {
7703
8500
  return deriveDeviceInfo(this.systemInfo);
7704
8501
  }
7705
8502
  getLaunchOptions() {
7706
- return {
7707
- ...this.launchOptions,
7708
- query: { ...this.launchOptions.query },
7709
- referrerInfo: {
7710
- ...this.launchOptions.referrerInfo,
7711
- extraData: { ...this.launchOptions.referrerInfo.extraData }
7712
- }
7713
- };
8503
+ return cloneAppLaunchOptions(this.launchOptions);
7714
8504
  }
7715
8505
  getEnterOptions() {
7716
- return {
7717
- ...this.enterOptions,
7718
- query: { ...this.enterOptions.query },
7719
- referrerInfo: {
7720
- ...this.enterOptions.referrerInfo,
7721
- extraData: { ...this.enterOptions.referrerInfo.extraData }
7722
- }
7723
- };
8506
+ return cloneAppLaunchOptions(this.enterOptions);
7724
8507
  }
7725
8508
  getMenuButtonBoundingClientRect() {
7726
8509
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
@@ -7874,14 +8657,14 @@ var HeadlessSession = class {
7874
8657
  bootstrap(launchOptions = createAppLaunchOptions("", {})) {
7875
8658
  this.assertActive();
7876
8659
  if (this.appInstance) return this.appInstance;
7877
- this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
7878
- this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
8660
+ this.launchOptions = cloneAppLaunchOptions(launchOptions);
8661
+ this.enterOptions = cloneAppLaunchOptions(launchOptions);
7879
8662
  const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
7880
8663
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
7881
8664
  this.appInstance = createAppInstance(this.appDefinition);
7882
8665
  this.appInstance.onLaunch?.(launchOptions);
7883
8666
  this.syncRuntimeAppState();
7884
- this.appInstance.onShow?.(launchOptions);
8667
+ this.appLifecycle.triggerAppShow(this.appInstance, launchOptions);
7885
8668
  return this.appInstance;
7886
8669
  }
7887
8670
  syncRuntimeAppState() {
@@ -7944,22 +8727,26 @@ var HeadlessSession = class {
7944
8727
  return nextPage;
7945
8728
  }
7946
8729
  switchTab(url) {
8730
+ this.prepareSwitchTab(url)()();
8731
+ return this.currentPageInstance;
8732
+ }
8733
+ prepareSwitchTab(url) {
7947
8734
  const target = this.resolveNavigationTarget(url);
7948
- this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
7949
8735
  if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in headless runtime: ${url}`);
7950
8736
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in headless runtime: ${url}`);
8737
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
8738
+ return () => this.commitSwitchTab(target);
8739
+ }
8740
+ commitSwitchTab(target) {
7951
8741
  const current = this.currentPageInstance;
7952
8742
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
7953
- if (current === cachedTarget && current) return current;
8743
+ if (current === cachedTarget && current) return () => {};
7954
8744
  if (current && current !== cachedTarget) {
7955
8745
  current.onHide?.();
7956
8746
  this.runPageComponentLifetime(current.route, "hide");
7957
8747
  }
7958
- for (const page of [...this.pages].reverse()) {
7959
- if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
7960
- this.removePageInstance(page);
7961
- this.unloadPage(page);
7962
- }
8748
+ const pagesToUnload = [...this.pages].reverse().filter((page) => !this.isTabBarRoute(stripLeadingSlash(page.route)));
8749
+ for (const page of pagesToUnload) this.removePageInstance(page);
7963
8750
  let nextPage = cachedTarget;
7964
8751
  let shouldRunInitialLifecycles = false;
7965
8752
  if (!nextPage) {
@@ -7975,7 +8762,9 @@ var HeadlessSession = class {
7975
8762
  nextPage.onShow?.();
7976
8763
  this.runPageComponentLifetime(nextPage.route, "show");
7977
8764
  }
7978
- return nextPage;
8765
+ return () => {
8766
+ for (const page of pagesToUnload) this.unloadPage(page);
8767
+ };
7979
8768
  }
7980
8769
  pageScrollTo(option) {
7981
8770
  const current = this.requireCurrentPage("wx.pageScrollTo()");
@@ -7983,6 +8772,21 @@ var HeadlessSession = class {
7983
8772
  current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
7984
8773
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
7985
8774
  }
8775
+ triggerAppHide(options) {
8776
+ this.assertActive();
8777
+ const app = this.appInstance ?? this.bootstrap();
8778
+ this.appLifecycle.triggerAppHide(app, options);
8779
+ }
8780
+ triggerAppShow(options) {
8781
+ this.assertActive();
8782
+ if (!this.appInstance) {
8783
+ this.bootstrap(options);
8784
+ return;
8785
+ }
8786
+ const nextOptions = options ?? cloneAppLaunchOptions(this.enterOptions);
8787
+ if (options) this.enterOptions = cloneAppLaunchOptions(options);
8788
+ this.appLifecycle.triggerAppShow(this.appInstance, nextOptions);
8789
+ }
7986
8790
  triggerPullDownRefresh() {
7987
8791
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
7988
8792
  this.pullDownRefreshState = {
@@ -8062,20 +8866,22 @@ var HeadlessSession = class {
8062
8866
  const pageConfig = readJsonObject(this.project, pageConfigPath);
8063
8867
  const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
8064
8868
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
8065
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
8869
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
8870
+ requestRender: (callback) => this.requestRender(callback)
8066
8871
  });
8067
8872
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
8068
8873
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
8069
8874
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
8070
8875
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
8876
+ pageInstance.getTabBar = () => {
8877
+ if (this.currentPageInstance === pageInstance) this.renderCurrentPage();
8878
+ return this.componentCache.get(customTabBarScopeId(pageInstance.route)) ?? null;
8879
+ };
8071
8880
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
8072
8881
  return pageInstance;
8073
8882
  }
8074
8883
  runInitialPageLifecycles(pageInstance, query) {
8075
- pageInstance.onLoad?.(query);
8076
- pageInstance.onShow?.();
8077
- pageInstance.onReady?.();
8078
- pageInstance.onRouteDone?.({});
8884
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
8079
8885
  }
8080
8886
  isTabBarRoute(route) {
8081
8887
  return this.tabBarRoutes.has(stripLeadingSlash(route));
@@ -8151,9 +8957,10 @@ var HeadlessSession = class {
8151
8957
  }
8152
8958
  detachPageComponents(route) {
8153
8959
  const prefix = `page:${stripLeadingSlash(route)}`;
8154
- for (const [scopeId, instance] of [...this.componentCache.entries()]) {
8155
- if (!scopeId.startsWith(prefix)) continue;
8156
- instance.__definition__?.lifetimes?.detached?.call(instance);
8960
+ const removed = [...this.componentCache].filter(([scopeId]) => scopeId.startsWith(prefix));
8961
+ for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
8962
+ detachComponentRelations(removed.map(([, instance]) => instance));
8963
+ for (const [scopeId] of removed) {
8157
8964
  this.componentCache.delete(scopeId);
8158
8965
  this.componentScopes.delete(scopeId);
8159
8966
  }
@@ -8302,11 +9109,19 @@ function createLogicalNode(node) {
8302
9109
  };
8303
9110
  }
8304
9111
  //#endregion
9112
+ //#region src/testing/pageMethodTarget.ts
9113
+ /** 对齐 Page 协议的栈顶约束;AppService 模式仅访问 handle 对应且仍存活的页面。 */
9114
+ function resolveTestingPageMethodTarget(page, pages, options) {
9115
+ if (!pages) return page;
9116
+ if (!options.routeOnly && options.fallback === false && pages.at(-1) !== page) throw new Error("page is not on top of page stack");
9117
+ return pages.includes(page) ? page : void 0;
9118
+ }
9119
+ //#endregion
8305
9120
  //#region src/testing/pageNodeAccess.ts
8306
9121
  function createPageRootNodeHandle(options) {
8307
9122
  const { page, project, session } = options;
8308
9123
  const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
8309
- return new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
9124
+ return new HeadlessTestingNodeHandle(tree.root.type === "root" && !options.includeHostRoots ? tree.root.children?.[0] ?? tree.root : tree.root, {
8310
9125
  assertActive: options.assertActive,
8311
9126
  callMethod: (scopeId, methodName, event) => {
8312
9127
  if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
@@ -8328,6 +9143,13 @@ function createPageRootNodeHandle(options) {
8328
9143
  });
8329
9144
  }
8330
9145
  //#endregion
9146
+ //#region src/testing/pagePath.ts
9147
+ const PRIVATE_PLUGIN_ROUTE_RE = /^plugin-private:\/\/([^/]+)\/(.+)$/;
9148
+ /** 将内部插件路由映射为 DevTools 页面协议路径,保留 AppService 实例路由。 */
9149
+ function resolveTestingPagePath(route) {
9150
+ return route.replace(PRIVATE_PLUGIN_ROUTE_RE, "__plugin__/$1/$2");
9151
+ }
9152
+ //#endregion
8331
9153
  //#region src/testing/pageWait.ts
8332
9154
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
8333
9155
  const DEFAULT_WAIT_INTERVAL$1 = 10;
@@ -8512,9 +9334,14 @@ var HeadlessTestingPageHandle = class {
8512
9334
  this.page = page;
8513
9335
  this.session = session;
8514
9336
  }
9337
+ /** 返回底层页面实例身份;重新获取 handle 不会改变该身份。 */
9338
+ get pageId() {
9339
+ this.assertActive();
9340
+ return getPageInstanceId(this.page);
9341
+ }
8515
9342
  get path() {
8516
9343
  this.assertActive();
8517
- return this.page.route;
9344
+ return resolveTestingPagePath(this.page.route);
8518
9345
  }
8519
9346
  get query() {
8520
9347
  this.assertActive();
@@ -8541,19 +9368,29 @@ var HeadlessTestingPageHandle = class {
8541
9368
  this.assertActive();
8542
9369
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "Page method name");
8543
9370
  return await runWithTimeout(async () => {
9371
+ const target = resolveTestingPageMethodTarget(this.page, this.session?.getCurrentPages(), options);
9372
+ if (!target) return;
8544
9373
  this.session?.renderCurrentPage();
8545
- const method = this.page[normalizedMethodName];
9374
+ const method = target[normalizedMethodName];
8546
9375
  if (typeof method !== "function") {
8547
9376
  if (options.routeOnly) return;
8548
9377
  throw new TypeError(`Method "${normalizedMethodName}" does not exist on headless page ${this.page.route}.`);
8549
9378
  }
8550
- return cloneProtocolValue(await method.apply(this.page, args));
9379
+ return cloneProtocolValue(await method.apply(target, args));
8551
9380
  }, options.timeout, `Timed out calling page method "${normalizedMethodName}" in headless testing runtime.`);
8552
9381
  }
8553
9382
  async data(path) {
8554
9383
  this.assertActive();
8555
9384
  return cloneProtocolValue(this.resolveDataByPath(path));
8556
9385
  }
9386
+ async setData(data) {
9387
+ this.assertActive();
9388
+ const payload = cloneProtocolValue(data);
9389
+ await new Promise((resolve) => {
9390
+ this.page.setData(payload, resolve);
9391
+ });
9392
+ this.session?.renderCurrentPage();
9393
+ }
8557
9394
  async selectComponent(selector) {
8558
9395
  this.assertActive();
8559
9396
  const normalizedSelector = selector.trim();
@@ -8589,6 +9426,17 @@ var HeadlessTestingPageHandle = class {
8589
9426
  if (selector === "page") return [root];
8590
9427
  return await root.$$(selector);
8591
9428
  }
9429
+ async getElementsByXpath(expression) {
9430
+ this.assertActive();
9431
+ return await createPageRootNodeHandle({
9432
+ assertActive: () => this.assertActive(),
9433
+ createPageHandle: () => this,
9434
+ includeHostRoots: true,
9435
+ page: this.page,
9436
+ project: this.project,
9437
+ session: this.session
9438
+ }).getElementsByXpath(expression);
9439
+ }
8592
9440
  async renderedNodes(selector, options = {}) {
8593
9441
  return await readRenderedNodes(this.renderedAccess(), selector, options);
8594
9442
  }
@@ -8721,6 +9569,9 @@ var HeadlessTestingSessionHandle = class {
8721
9569
  async close() {
8722
9570
  this.session.close();
8723
9571
  }
9572
+ async toolInfo() {
9573
+ return { version: "mpcore-simulator" };
9574
+ }
8724
9575
  on(eventName, handler) {
8725
9576
  this.session.on(eventName, handler);
8726
9577
  return this;
@@ -8782,25 +9633,23 @@ var HeadlessTestingSessionHandle = class {
8782
9633
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
8783
9634
  }
8784
9635
  async reLaunch(route) {
8785
- this.session.callWxMethod("reLaunch", { url: route });
8786
- const page = this.session.getCurrentPages().at(-1);
8787
- if (!page) throw new Error(`Failed to reLaunch route "${route}" through the headless wx runtime.`);
8788
- return new HeadlessTestingPageHandle(this.project, page, this.session);
9636
+ this.invokeNavigation("reLaunch", { url: route });
9637
+ return await this.requireCurrentPage("reLaunch", route);
8789
9638
  }
8790
9639
  async navigateTo(route) {
8791
- this.session.callWxMethod("navigateTo", { url: route });
9640
+ this.invokeNavigation("navigateTo", { url: route });
8792
9641
  return await this.requireCurrentPage("navigateTo", route);
8793
9642
  }
8794
9643
  async redirectTo(route) {
8795
- this.session.callWxMethod("redirectTo", { url: route });
9644
+ this.invokeNavigation("redirectTo", { url: route });
8796
9645
  return await this.requireCurrentPage("redirectTo", route);
8797
9646
  }
8798
9647
  async navigateBack(delta = 1) {
8799
- this.session.callWxMethod("navigateBack", { delta });
9648
+ this.invokeNavigation("navigateBack", { delta });
8800
9649
  return await this.currentPage();
8801
9650
  }
8802
9651
  async switchTab(route) {
8803
- this.session.callWxMethod("switchTab", { url: route });
9652
+ this.invokeNavigation("switchTab", { url: route });
8804
9653
  return await this.requireCurrentPage("switchTab", route);
8805
9654
  }
8806
9655
  async waitForCurrentPage(route, options = {}) {
@@ -8811,13 +9660,19 @@ var HeadlessTestingSessionHandle = class {
8811
9660
  if (!currentPageInstance) return null;
8812
9661
  const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
8813
9662
  if (!normalizedRoute) return current;
8814
- if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
9663
+ if (normalizeRoute(current.path) === resolveTestingPagePath(normalizeRoute(normalizedRoute))) return current;
8815
9664
  return null;
8816
9665
  }, normalizedRoute ? `Timed out waiting for current page "${normalizeRoute(normalizedRoute)}" in headless testing runtime.` : "Timed out waiting for a current page in headless testing runtime.", options);
8817
9666
  }
8818
9667
  async pageScrollTo(scrollTop) {
8819
9668
  this.session.pageScrollTo({ scrollTop });
8820
9669
  }
9670
+ async triggerAppHide(options) {
9671
+ this.session.triggerAppHide(options);
9672
+ }
9673
+ async triggerAppShow(options) {
9674
+ this.session.triggerAppShow(options);
9675
+ }
8821
9676
  async triggerPullDownRefresh() {
8822
9677
  this.session.triggerPullDownRefresh();
8823
9678
  }
@@ -8830,36 +9685,31 @@ var HeadlessTestingSessionHandle = class {
8830
9685
  async triggerRouteDone(options) {
8831
9686
  this.session.triggerRouteDone(options);
8832
9687
  }
9688
+ invokeNavigation(methodName, options) {
9689
+ const failure = { received: false };
9690
+ this.session.callWxMethod(methodName, {
9691
+ ...options,
9692
+ fail(error) {
9693
+ failure.received = true;
9694
+ failure.error = error;
9695
+ }
9696
+ });
9697
+ if (failure.received) {
9698
+ const error = failure.error;
9699
+ const details = error && typeof error === "object" ? error : void 0;
9700
+ const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
9701
+ const target = options.url ? ` route "${options.url}"` : "";
9702
+ throw new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error });
9703
+ }
9704
+ }
8833
9705
  async requireCurrentPage(methodName, route) {
8834
9706
  const page = await this.currentPage();
8835
9707
  if (!page) throw new Error(`Failed to ${methodName} route "${route}" through the headless wx runtime.`);
8836
9708
  return page;
8837
9709
  }
8838
9710
  async evaluateInRuntime(evaluator, args) {
8839
- const runtimeGlobals = {
8840
- getApp: () => this.session.getApp(),
8841
- getCurrentPages: () => this.session.getCurrentPages(),
8842
- wx: this.session.getWx()
8843
- };
8844
- const host = globalThis;
8845
- const previous = /* @__PURE__ */ new Map();
8846
- for (const [name, value] of Object.entries(runtimeGlobals)) {
8847
- previous.set(name, Object.getOwnPropertyDescriptor(host, name));
8848
- Object.defineProperty(host, name, {
8849
- configurable: true,
8850
- enumerable: false,
8851
- value,
8852
- writable: true
8853
- });
8854
- }
8855
- try {
8856
- const fn = typeof evaluator === "string" ? new vm.Script(`(${evaluator})`).runInThisContext() : evaluator;
8857
- if (typeof fn !== "function") throw new TypeError("Headless evaluator must be a function or function source string.");
8858
- return await fn(...args);
8859
- } finally {
8860
- for (const [name, descriptor] of previous) if (descriptor) Object.defineProperty(host, name, descriptor);
8861
- else delete host[name];
8862
- }
9711
+ const source = typeof evaluator === "string" ? evaluator : Function.prototype.toString.call(evaluator);
9712
+ return await this.session.evaluateRuntime(source, args);
8863
9713
  }
8864
9714
  };
8865
9715
  //#endregion
@@ -8871,10 +9721,18 @@ function resolveInitialRoute(session) {
8871
9721
  }
8872
9722
  async function launch(options) {
8873
9723
  const session = createHeadlessSession({ projectPath: options.projectPath });
8874
- session.bootstrap();
8875
- const initialRoute = resolveInitialRoute(session);
8876
- if (initialRoute) session.reLaunch(`/${initialRoute}`);
8877
- return new HeadlessTestingSessionHandle(session.project, session);
9724
+ const handle = new HeadlessTestingSessionHandle(session.project, session);
9725
+ try {
9726
+ await options.onSessionCreated?.(handle);
9727
+ await options.configureSession?.(session);
9728
+ const initialRoute = resolveInitialRoute(session);
9729
+ if (initialRoute) session.reLaunch(`/${initialRoute}`);
9730
+ else session.bootstrap();
9731
+ return handle;
9732
+ } catch (error) {
9733
+ session.close();
9734
+ throw error;
9735
+ }
8878
9736
  }
8879
9737
  //#endregion
8880
- export { BrowserHeadlessSession, HEADLESS_PLUGIN_VIRTUAL_ROOT, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createOverlayArtifactSource, createPageInstance, createPluginArtifactSource, createPluginVirtualRoot, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPageDefinition, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveMiniProgramEventBinding, resolvePluginRequest, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };
9738
+ export { BrowserHeadlessSession, HEADLESS_PLUGIN_VIRTUAL_ROOT, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createOverlayArtifactSource, createPageInstance, createPluginArtifactSource, createPluginVirtualRoot, createProjectDescriptor, executeSelectorQueryRequests, getPageInstanceId, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPageDefinition, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveBrowserPageStyles, resolveMiniProgramEventBinding, resolvePluginRequest, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };