@mpcore/simulator 0.4.3 → 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(() => {
@@ -591,6 +684,32 @@ function createHeadlessWx(driver) {
591
684
  };
592
685
  }
593
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
594
713
  //#region src/runtime/runtimeGlobals.ts
595
714
  const MINI_PROGRAM_UNAVAILABLE_GLOBAL_NAMES = [
596
715
  "window",
@@ -654,24 +773,93 @@ function hasBrowserVirtualFile(files, filePath) {
654
773
  return files.has(normalizeBrowserFilePath(filePath));
655
774
  }
656
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
657
856
  //#region src/browser/moduleLoader.ts
658
857
  function createRequireNotFoundError$1(request, importer) {
659
858
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
660
859
  }
661
- function resolveRequiredModulePath$1(files, importer, request) {
662
- if (!request.startsWith(".")) throw createRequireNotFoundError$1(request, importer);
663
- const basePath = normalize(join(dirname(importer), request));
664
- const candidates = [
665
- basePath,
666
- `${basePath}.js`,
667
- `${basePath}.json`,
668
- join(basePath, "index.js")
669
- ];
670
- for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
671
- throw createRequireNotFoundError$1(request, importer);
672
- }
673
860
  function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
674
- const wx = createHeadlessWx(wxDriver);
861
+ const runtimeConsole = kernel.diagnostics.createConsole();
862
+ const wx = createHeadlessWx(wxDriver, runtimeConsole);
675
863
  return createMiniProgramRuntimeGlobals({
676
864
  App(definition) {
677
865
  return registerAppDefinition(registries, definition);
@@ -690,7 +878,7 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver,
690
878
  },
691
879
  clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
692
880
  clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
693
- console: kernel.diagnostics.createConsole(),
881
+ console: runtimeConsole,
694
882
  getApp,
695
883
  getCurrentPages,
696
884
  globalThis: void 0,
@@ -720,7 +908,8 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
720
908
  const previousLoadContext = registries.currentLoadContext;
721
909
  registries.currentLoadContext = loadContext;
722
910
  const localRequire = ((request) => {
723
- 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);
724
913
  if (requiredPath.endsWith(".json")) {
725
914
  const content = readBrowserVirtualFile(files, requiredPath);
726
915
  if (typeof content !== "string") throw new TypeError(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
@@ -732,8 +921,13 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
732
921
  });
733
922
  localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
734
923
  try {
735
- const contextEntries = Object.entries(executionContext);
736
- 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));
737
931
  const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
738
932
  module.componentDefinitions = [.../* @__PURE__ */ new Set([
739
933
  ...requiredComponentDefinitions,
@@ -741,6 +935,9 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
741
935
  ...registeredDefinitions
742
936
  ])];
743
937
  return module;
938
+ } catch (error) {
939
+ moduleCache.delete(resolvedPath);
940
+ throw error;
744
941
  } finally {
745
942
  registries.currentLoadContext = previousLoadContext;
746
943
  }
@@ -751,14 +948,14 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
751
948
  const main = typeof plugin.config.main === "string" && plugin.config.main ? plugin.config.main : "index.js";
752
949
  return executeModule(normalize(join(options.miniprogramRootPath, plugin.virtualRoot, main)), null).exports;
753
950
  };
754
- return {
951
+ const loader = {
755
952
  close() {
756
953
  moduleCache.clear();
954
+ closeBrowserWxsLoader(loader);
757
955
  },
758
956
  executeAppModule(filePath) {
759
957
  executeModule(filePath, { kind: "app" });
760
- if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
761
- return registries.appDefinition;
958
+ return registries.appDefinition ?? registerAppDefinition(registries, {});
762
959
  },
763
960
  executePageModule(filePath, route) {
764
961
  const fallbackDefinition = executeModule(filePath, {
@@ -782,6 +979,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
782
979
  },
783
980
  wx: executionContext.wx
784
981
  };
982
+ return loader;
785
983
  }
786
984
  //#endregion
787
985
  //#region src/kernel/artifactSource.ts
@@ -1131,7 +1329,7 @@ function isStructuralValue(value) {
1131
1329
  return value !== null && typeof value === "object";
1132
1330
  }
1133
1331
  function hasComponentPropertyValueChanged(currentValue, previousSnapshot, nextValue, bindingAffected) {
1134
- const identityChanged = !Object.is(currentValue, nextValue);
1332
+ const identityChanged = !Object.is(bindingAffected ? currentValue : previousSnapshot, nextValue);
1135
1333
  if (!identityChanged && !bindingAffected) return false;
1136
1334
  if (!isStructuralValue(currentValue) && !isStructuralValue(nextValue)) return identityChanged;
1137
1335
  try {
@@ -1176,10 +1374,12 @@ function mergeRecord(...records) {
1176
1374
  function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
1177
1375
  const propOptions = definition.properties;
1178
1376
  if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
1179
- 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;
1180
1380
  const option = propOptions[changedKey];
1181
1381
  if (!option || typeof option !== "object" || Array.isArray(option)) continue;
1182
- const observer = option.observer;
1382
+ const observer = typeof option.observer === "string" ? instance[option.observer] : option.observer;
1183
1383
  if (typeof observer !== "function") continue;
1184
1384
  observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
1185
1385
  }
@@ -1215,13 +1415,32 @@ function matchObserverPattern(pattern, changedKeys) {
1215
1415
  }
1216
1416
  function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
1217
1417
  if (changedKeys.length === 0) return;
1218
- runPropertyObservers(definition, instance, changedKeys, previousProperties);
1219
1418
  const observers = definition.observers;
1220
1419
  if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
1221
1420
  if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
1222
1421
  const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
1223
1422
  handler.call(instance, ...args);
1224
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;
1225
1444
  }
1226
1445
  //#endregion
1227
1446
  //#region src/runtime/componentInstance/properties.ts
@@ -1256,7 +1475,8 @@ function normalizeComponentDefinition(definition) {
1256
1475
  observers: mergeRecord(...behaviors.map((item) => item.observers), definition.observers),
1257
1476
  pageLifetimes: mergeRecord(...behaviors.map((item) => item.pageLifetimes), definition.pageLifetimes),
1258
1477
  properties: mergeRecord(...behaviors.map((item) => item.properties), definition.properties),
1259
- lifetimes: mergeRecord(...behaviors.map((item) => item.lifetimes), definition.lifetimes)
1478
+ relations: mergeRecord(...behaviors.map((item) => item.relations), definition.relations),
1479
+ lifetimes: mergeComponentLifetimes(behaviors, definition)
1260
1480
  };
1261
1481
  if (mergedDataEntries.length > 0 || definition.data) mergedDefinition.data = function mergedComponentData() {
1262
1482
  return mergeRecord(mergeRecord(...mergedDataEntries.map((entry) => {
@@ -1354,6 +1574,7 @@ function resolvePropertyDefaultValue(option, definition) {
1354
1574
  }
1355
1575
  function normalizeComponentPropertyValue(definition, key, rawValue) {
1356
1576
  const option = definition.properties?.[key];
1577
+ if (rawValue === null && normalizePropertyType(option) === null) return null;
1357
1578
  if (rawValue == null) {
1358
1579
  if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) return resolvePropertyDefaultValue(option, definition);
1359
1580
  return cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
@@ -1375,22 +1596,119 @@ function resolveInitialProperties(definition, properties) {
1375
1596
  return resolved;
1376
1597
  }
1377
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
1378
1685
  //#region src/runtime/componentInstance/index.ts
1379
1686
  function createComponentInstance(options) {
1380
1687
  const definition = normalizeComponentDefinition(options.definition);
1381
- 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
+ };
1382
1693
  const instance = {
1383
1694
  __definition__: definition,
1384
- data: {
1385
- ...resolveInitialData$2(definition),
1386
- ...properties
1387
- },
1695
+ data,
1388
1696
  __propertySnapshots__: {},
1389
- properties,
1697
+ properties: {
1698
+ ...data,
1699
+ ...inputProperties
1700
+ },
1701
+ getRelationNodes(key) {
1702
+ return getComponentRelationNodes(instance, key);
1703
+ },
1390
1704
  setData(patch, callback) {
1391
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])]));
1392
1709
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1393
- runComponentObservers(definition, instance, changedKeys);
1710
+ for (const key of dataKeys) instance.properties[key] = instance.data[key];
1711
+ runComponentObservers(definition, instance, changedKeys, previousProperties);
1394
1712
  if (options.requestRender) options.requestRender(callback);
1395
1713
  else callback?.();
1396
1714
  },
@@ -1403,6 +1721,12 @@ function createComponentInstance(options) {
1403
1721
  bindFunction$2(instance, key, value);
1404
1722
  }
1405
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
+ });
1406
1730
  return instance;
1407
1731
  }
1408
1732
  function runComponentLifecycle(instance, lifecycleName) {
@@ -1421,6 +1745,129 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
1421
1745
  handler.call(instance, payload);
1422
1746
  }
1423
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
1424
1871
  //#region src/view/templateExpression.ts
1425
1872
  const expressionCache = /* @__PURE__ */ new Map();
1426
1873
  const BLOCKED_MEMBER_KEYS = /* @__PURE__ */ new Set([
@@ -1527,6 +1974,12 @@ function evaluateTemplateLiteral(node, source) {
1527
1974
  }
1528
1975
  return result;
1529
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
+ }
1530
1983
  function evaluateExpressionNode(node, source) {
1531
1984
  if (!node) return;
1532
1985
  switch (node.type) {
@@ -1537,6 +1990,8 @@ function evaluateExpressionNode(node, source) {
1537
1990
  case "NullLiteral": return null;
1538
1991
  case "MemberExpression":
1539
1992
  case "OptionalMemberExpression": return readMemberValue(node, source);
1993
+ case "CallExpression":
1994
+ case "OptionalCallExpression": return evaluateCallExpression(node, source);
1540
1995
  case "UnaryExpression": return evaluateUnaryExpression(node, source);
1541
1996
  case "BinaryExpression": return evaluateBinaryExpression(node, source);
1542
1997
  case "LogicalExpression": {
@@ -1601,6 +2056,86 @@ function resolveTemplateData(node, source) {
1601
2056
  return resolved && typeof resolved === "object" ? resolved : {};
1602
2057
  }
1603
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
1604
2139
  //#region src/view/eventBinding.ts
1605
2140
  const LEGACY_EVENT_NAME_RE = /^\w+$/;
1606
2141
  const EVENT_BINDING_PREFIXES = [
@@ -1714,6 +2249,89 @@ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
1714
2249
  return null;
1715
2250
  }
1716
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
1717
2335
  //#region src/browser/render/shared.ts
1718
2336
  const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
1719
2337
  const DATASET_NAME_RE$4 = /-([a-z])/g;
@@ -1733,7 +2351,6 @@ const STRUCTURAL_ATTRS$1 = [
1733
2351
  "wx:for-index",
1734
2352
  "wx:key"
1735
2353
  ];
1736
- const WX_ELSE_ATTRS$1 = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
1737
2354
  const CLASS_SPLIT_RE$1 = /\s+/;
1738
2355
  const JS_FILE_RE$1 = /\.js$/;
1739
2356
  function isMustacheOnly$1(value) {
@@ -1783,12 +2400,21 @@ function readTemplateSource$1(files, filePath) {
1783
2400
  return templateSource;
1784
2401
  }
1785
2402
  function parseTemplateDocument$1(templateSource) {
1786
- return parseDocument(`<page>${templateSource}</page>`, {
1787
- xmlMode: false,
1788
- decodeEntities: false,
1789
- lowerCaseAttributeNames: false,
1790
- lowerCaseTags: false,
1791
- 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);
1792
2418
  });
1793
2419
  }
1794
2420
  function serializeDomNode$2(node) {
@@ -1801,26 +2427,23 @@ function serializeDomNode$2(node) {
1801
2427
  function isTagNode$1(node) {
1802
2428
  return node.type === "tag" && typeof node.name === "string";
1803
2429
  }
1804
- function isIgnorableTextNode$1(node) {
1805
- return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
1806
- }
1807
2430
  function resolveAttributeValue$1(value, scope) {
1808
2431
  if (isMustacheOnly$1(value)) {
1809
2432
  const expression = value.trim().slice(2, -2);
1810
- return resolveValueByPath$2(scope.data, expression);
2433
+ return resolveValueByPath$2(wxsScopeData(scope), expression);
1811
2434
  }
1812
- return interpolateTemplate$2(value, scope.data);
2435
+ return interpolateTemplate$2(value, wxsScopeData(scope));
1813
2436
  }
1814
2437
  function resolveComponentAttributeValue$1(value, scope) {
1815
2438
  if (isMustacheOnly$1(value)) {
1816
2439
  const expression = value.trim().slice(2, -2);
1817
- return resolveRawValueByPath$1(scope.data, expression);
2440
+ return resolveRawValueByPath$1(wxsScopeData(scope), expression) ?? null;
1818
2441
  }
1819
- return interpolateTemplate$2(value, scope.data);
2442
+ return interpolateTemplate$2(value, wxsScopeData(scope));
1820
2443
  }
1821
2444
  function applyNodeBindings$1(node, scope) {
1822
2445
  if (!isTagNode$1(node)) {
1823
- 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));
1824
2447
  return;
1825
2448
  }
1826
2449
  node.attribs ??= {};
@@ -1834,17 +2457,10 @@ function applyNodeBindings$1(node, scope) {
1834
2457
  node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1835
2458
  }
1836
2459
  }
1837
- function createMergedScopeData$1(pageData, componentProperties, componentData) {
1838
- return {
1839
- ...pageData,
1840
- ...componentProperties,
1841
- ...componentData
1842
- };
1843
- }
1844
2460
  function evaluateConditionalBranch$1(node, scope) {
1845
2461
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1846
2462
  if (condition == null) return true;
1847
- return Boolean(resolveRawValueByPath$1(scope.data, condition));
2463
+ return Boolean(resolveRawValueByPath$1(wxsScopeData(scope), condition));
1848
2464
  }
1849
2465
  function createLoopScope$1(scope, itemName, indexName, item, index) {
1850
2466
  return {
@@ -1865,7 +2481,7 @@ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath,
1865
2481
  const filePath = `${componentBasePath}.js`;
1866
2482
  const templatePath = `${componentBasePath}.wxml`;
1867
2483
  return {
1868
- definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
2484
+ definition: context.moduleLoader.executeComponentModule(join(context.project.miniprogramRootPath, filePath), componentBasePath),
1869
2485
  filePath,
1870
2486
  templatePath
1871
2487
  };
@@ -1881,12 +2497,12 @@ function readComponentConfig$1(files, jsonPath) {
1881
2497
  }
1882
2498
  function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
1883
2499
  try {
1884
- const usingComponents = readComponentConfig$1(context.files, ownerJsonPath).usingComponents;
2500
+ const usingComponents = readComponentConfig$1(context.files, join(context.project.miniprogramRootPath, ownerJsonPath)).usingComponents;
1885
2501
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
1886
2502
  const resolved = /* @__PURE__ */ new Map();
1887
2503
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
1888
2504
  if (typeof rawPath !== "string") continue;
1889
- 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);
1890
2506
  resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
1891
2507
  }
1892
2508
  return resolved;
@@ -1895,7 +2511,7 @@ function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
1895
2511
  }
1896
2512
  }
1897
2513
  function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
1898
- const componentJsonPath = `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`;
2514
+ const componentJsonPath = join(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`);
1899
2515
  const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
1900
2516
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
1901
2517
  const ownerComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
@@ -1921,13 +2537,11 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1921
2537
  const hostDataset = collectDataset$4(hostNode);
1922
2538
  const hostId = hostNode.attribs?.id ?? "";
1923
2539
  return (instance, eventName, detail, triggerOptions) => {
1924
- const interactionTarget = instance.__lastInteractionEvent__?.target;
1925
- const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
1926
- const componentDataset = context.componentScopes.get(componentScopeId)?.dataset ?? hostDataset;
2540
+ const originScope = context.componentScopes.get(componentScopeId);
1927
2541
  const interactionMark = instance.__lastInteractionEvent__?.mark;
1928
2542
  const target = {
1929
- dataset: interactionTarget?.dataset ?? componentDataset,
1930
- id: interactionTarget?.id ?? hostId
2543
+ dataset: originScope?.dataset ?? hostDataset,
2544
+ id: originScope?.hostId ?? hostId
1931
2545
  };
1932
2546
  let currentScopeId = componentScopeId;
1933
2547
  while (currentScopeId) {
@@ -1944,8 +2558,8 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1944
2558
  target,
1945
2559
  type: eventName,
1946
2560
  currentTarget: {
1947
- dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
1948
- id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
2561
+ dataset: currentScope?.dataset ?? hostDataset,
2562
+ id: currentScope?.hostId ?? hostId
1949
2563
  }
1950
2564
  });
1951
2565
  if (binding?.stopAfter) break;
@@ -1967,7 +2581,7 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1967
2581
  if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
1968
2582
  previousProperties[key] = instance.properties[key];
1969
2583
  instance.properties[key] = nextValue;
1970
- instance.data[key] = nextValue;
2584
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
1971
2585
  changedRootKeys.push(key);
1972
2586
  }
1973
2587
  instance.__propertySnapshots ??= {};
@@ -1981,12 +2595,12 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
1981
2595
  return {
1982
2596
  alias: clonedNode.name,
1983
2597
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1984
- data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1985
- dataset: collectDataset$4(clonedNode, scope.data),
2598
+ data: { ...componentInstance.data },
2599
+ dataset: collectDataset$4(clonedNode, wxsScopeData(scope)),
1986
2600
  eventBindings: collectComponentEventBindings$1(clonedNode),
1987
2601
  getMethod: (methodName) => {
1988
2602
  const method = componentInstance?.[methodName];
1989
- return typeof method === "function" ? method : void 0;
2603
+ return typeof method === "function" ? method.bind(componentInstance) : void 0;
1990
2604
  },
1991
2605
  getScopeId: () => componentScopeId,
1992
2606
  genericComponents,
@@ -2017,7 +2631,6 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2017
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;
2018
2632
  const componentInstance = createComponentInstance({
2019
2633
  definition: componentEntry.definition,
2020
- properties: componentProperties,
2021
2634
  requestRender: (callback) => context.session.requestRender(callback),
2022
2635
  triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
2023
2636
  });
@@ -2025,21 +2638,21 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2025
2638
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
2026
2639
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
2027
2640
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
2641
+ componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
2028
2642
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
2029
2643
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
2030
2644
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
2031
2645
  context.componentCache.set(componentScopeId, componentInstance);
2032
2646
  runComponentLifecycle(componentInstance, "created");
2033
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(componentProperties), {});
2034
2647
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
2035
- runComponentLifecycle(componentInstance, "attached");
2036
- runComponentPageLifetime(componentInstance, "show");
2648
+ syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
2037
2649
  return componentInstance;
2038
2650
  }
2039
2651
  function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
2040
- 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));
2041
2654
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
2042
- const templateRenderState = createTemplateRenderState(componentRoot);
2655
+ const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2043
2656
  return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
2044
2657
  }
2045
2658
  //#endregion
@@ -2051,11 +2664,10 @@ function expandNodeByFor$1(node, scope) {
2051
2664
  scope,
2052
2665
  instanceSuffix: ""
2053
2666
  }];
2054
- const list = resolveRawValueByPath$1(scope.data, forExpression);
2055
- const items = Array.isArray(list) ? list : [];
2667
+ const items = resolveLoopEntries(resolveRawValueByPath$1(wxsScopeData(scope), forExpression));
2056
2668
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
2057
2669
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
2058
- return items.map((item, index) => ({
2670
+ return items.map(([index, item]) => ({
2059
2671
  node: cloneNode$1(node),
2060
2672
  scope: createLoopScope$1(scope, itemName, indexName, item, index),
2061
2673
  instanceSuffix: `:for-${index}`
@@ -2066,40 +2678,12 @@ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath
2066
2678
  }
2067
2679
  function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2068
2680
  const renderedChildren = [];
2069
- for (let index = 0; index < children.length; index += 1) {
2070
- const child = children[index];
2681
+ for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch$1(node, scope))) {
2071
2682
  if (!isTagNode$1(child)) {
2072
2683
  renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
2073
2684
  continue;
2074
2685
  }
2075
- if (isTemplateDefinition(child)) continue;
2076
- const hasConditional = child.attribs?.["wx:if"] != null;
2077
- const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
2078
- if (hasConditional) {
2079
- let branchMatched = false;
2080
- let cursor = index;
2081
- while (cursor < children.length) {
2082
- const branch = children[cursor];
2083
- if (cursor !== index && isIgnorableTextNode$1(branch)) {
2084
- cursor += 1;
2085
- continue;
2086
- }
2087
- if (!isTagNode$1(branch)) break;
2088
- if (cursor !== index && !WX_ELSE_ATTRS$1.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
2089
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch$1(branch, scope)) {
2090
- renderedChildren.push(...renderNodeVariants$1(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes, templateRenderState));
2091
- branchMatched = true;
2092
- }
2093
- let nextBranchIndex = cursor + 1;
2094
- while (nextBranchIndex < children.length && isIgnorableTextNode$1(children[nextBranchIndex])) nextBranchIndex += 1;
2095
- const nextBranch = children[nextBranchIndex];
2096
- if (!(!!nextBranch && isTagNode$1(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
2097
- cursor = nextBranchIndex;
2098
- }
2099
- index = cursor;
2100
- continue;
2101
- }
2102
- if (isElseBranch) continue;
2686
+ if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
2103
2687
  renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
2104
2688
  }
2105
2689
  return renderedChildren;
@@ -2133,6 +2717,10 @@ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFileP
2133
2717
  return slots;
2134
2718
  }
2135
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
+ };
2136
2724
  const clonedNode = cloneNode$1(node);
2137
2725
  if (!isTagNode$1(clonedNode)) {
2138
2726
  applyNodeBindings$1(clonedNode, scope);
@@ -2144,15 +2732,19 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2144
2732
  attribs: {},
2145
2733
  children: []
2146
2734
  };
2147
- const templateName = resolveTemplateCall(clonedNode, scope.data);
2735
+ const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
2148
2736
  if (templateName) {
2149
2737
  const definition = templateRenderState.definitions.get(templateName);
2150
2738
  const templateScope = {
2151
2739
  ...scope,
2152
- data: resolveTemplateData(clonedNode, scope.data)
2740
+ data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
2741
+ wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
2153
2742
  };
2154
2743
  const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
2155
- definitions: templateRenderState.definitions,
2744
+ definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
2745
+ definitionScopes: templateRenderState.definitionScopes,
2746
+ definitionWxsScopes: templateRenderState.definitionWxsScopes,
2747
+ wxsModules: templateScope.wxs,
2156
2748
  stack: [...templateRenderState.stack, templateName]
2157
2749
  }) : [];
2158
2750
  return {
@@ -2168,7 +2760,10 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2168
2760
  if (clonedNode.name === "slot") {
2169
2761
  const slotName = clonedNode.attribs?.name?.trim() || "default";
2170
2762
  const projected = scope.slots?.get(slotName) ?? [];
2171
- 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);
2172
2767
  return {
2173
2768
  type: "tag",
2174
2769
  name: "block",
@@ -2191,13 +2786,14 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2191
2786
  context.componentScopes.set(componentScopeId, componentScope);
2192
2787
  const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
2193
2788
  if (renderedComponentRoot.attribs) {
2789
+ applyNodeBindings$1(clonedNode, scope);
2790
+ renderedComponentRoot.attribs = {
2791
+ ...clonedNode.attribs,
2792
+ ...renderedComponentRoot.attribs
2793
+ };
2194
2794
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
2195
2795
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
2196
2796
  }
2197
- if (!componentInstance.__ready__) {
2198
- runComponentLifecycle(componentInstance, "ready");
2199
- componentInstance.__ready__ = true;
2200
- }
2201
2797
  return renderedComponentRoot;
2202
2798
  }
2203
2799
  applyNodeBindings$1(clonedNode, scope);
@@ -2214,25 +2810,73 @@ function renderBrowserPageTree(context, page) {
2214
2810
  data: page.data,
2215
2811
  getMethod: (methodName) => {
2216
2812
  const method = page[methodName];
2217
- return typeof method === "function" ? method : void 0;
2813
+ return typeof method === "function" ? method.bind(page) : void 0;
2218
2814
  },
2219
2815
  getScopeId: () => pageScopeId,
2220
2816
  id: "page-root"
2221
2817
  };
2222
- context.componentScopes.clear();
2818
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
2223
2819
  context.componentScopes.set(pageScopeId, pageScope);
2224
2820
  const seenComponentScopes = /* @__PURE__ */ new Set();
2225
2821
  const root = (document.children ?? [])[0] ?? document;
2226
- const templateRenderState = createTemplateRenderState(root);
2822
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2227
2823
  const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
2228
- for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
2229
- 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) {
2230
2842
  context.componentCache.delete(scopeId);
2231
2843
  context.componentScopes.delete(scopeId);
2232
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);
2233
2852
  return {
2234
- root: renderedRoot,
2235
- 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("")
2859
+ };
2860
+ }
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
2236
2880
  };
2237
2881
  }
2238
2882
  //#endregion
@@ -2340,10 +2984,74 @@ function createAppInstance(definition) {
2340
2984
  return instance;
2341
2985
  }
2342
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
2343
3041
  //#region src/runtime/pageInstance.ts
2344
3042
  const ARRAY_INDEX_PATH_RE = /\[(\d+)\]/g;
2345
3043
  const ARRAY_INDEX_SEGMENT_RE = /^\d+$/;
2346
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
+ }
2347
3055
  function bindFunction(target, key, value) {
2348
3056
  if (typeof value !== "function") {
2349
3057
  target[key] = value;
@@ -2392,25 +3100,33 @@ function normalizeRoute$1(route) {
2392
3100
  }
2393
3101
  function createPageInstance(route, definition, options = {}, pageState = {}) {
2394
3102
  const normalizedRoute = normalizeRoute$1(route);
3103
+ const data = resolveInitialData(definition);
2395
3104
  const instance = {
2396
3105
  __background__: pageState.background ? cloneBackgroundSnapshot(pageState.background) : void 0,
2397
3106
  __backgroundTextStyle__: pageState.background?.textStyle ?? pageState.backgroundTextStyle,
2398
3107
  __route__: normalizedRoute,
2399
3108
  __navigationBar__: pageState.navigationBar ? cloneNavigationBarSnapshot(pageState.navigationBar) : void 0,
2400
3109
  __navigationBarTitle__: pageState.navigationBar?.title,
2401
- data: resolveInitialData(definition),
3110
+ data,
3111
+ properties: { ...data },
2402
3112
  options: { ...options },
2403
3113
  route: normalizedRoute,
2404
3114
  setData(patch, callback) {
2405
3115
  instance.__lastChangedKeys__ = Object.keys(patch);
2406
- for (const [key, value] of Object.entries(patch)) assignByPath(instance.data, key, value);
2407
- 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?.();
2408
3123
  }
2409
3124
  };
2410
3125
  for (const [key, value] of Object.entries(definition)) {
2411
- if (key === "data") continue;
3126
+ if (key === "data" || key === "options" || key === "properties") continue;
2412
3127
  bindFunction(instance, key, value);
2413
3128
  }
3129
+ bindComponentPageAttachment(instance, definition);
2414
3130
  return instance;
2415
3131
  }
2416
3132
  //#endregion
@@ -4071,56 +4787,107 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
4071
4787
  }
4072
4788
  //#endregion
4073
4789
  //#region src/view/selectors.ts
4074
- const WHITESPACE_RE$2 = /\s+/;
4075
- const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
4076
- const COMPOUND_SELECTOR_PART_RE$2 = /#[\w-]+|\.[\w-]+|\[data-[^=\]]+="[^"]*"\]|[A-Za-z][\w-]*/g;
4077
- function getClassList(node) {
4078
- return String(node.attribs?.class ?? "").split(WHITESPACE_RE$2).map((item) => item.trim()).filter(Boolean);
4079
- }
4080
- function matchesSimpleSelector(node, selector) {
4081
- if (node.type !== "tag") return false;
4082
- if (selector === "page") return node.name === "page";
4083
- if (selector === "*") return true;
4084
- if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
4085
- if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
4086
- const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
4087
- if (dataAttrMatch) {
4088
- const [, key, value] = dataAttrMatch;
4089
- return node.attribs?.[`data-${key}`] === value;
4090
- }
4091
- return node.name === selector;
4092
- }
4093
- function parseCompoundSelector$2(selector) {
4094
- const parts = selector.match(COMPOUND_SELECTOR_PART_RE$2) ?? [];
4095
- return parts.join("") === selector ? parts : [];
4096
- }
4097
- function matchesSelectorToken(node, selector) {
4098
- if (selector === "*") return node.type === "tag";
4099
- const simpleSelectors = parseCompoundSelector$2(selector);
4100
- if (simpleSelectors.length === 0) return false;
4101
- return simpleSelectors.every((simpleSelector) => matchesSimpleSelector(node, simpleSelector));
4102
- }
4103
- function collectDescendants(node, into) {
4104
- for (const child of node.children ?? []) {
4105
- into.push(child);
4106
- 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
+ });
4107
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
+ }));
4108
4828
  }
4109
4829
  function querySelectorAll(root, selector) {
4110
- const parts = selector.trim().split(WHITESPACE_RE$2).filter(Boolean);
4111
- if (parts.length === 0) return [];
4112
- let current = [root];
4113
- for (const part of parts) {
4114
- const next = [];
4115
- for (const node of current) {
4116
- const candidates = [];
4117
- if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
4118
- collectDescendants(node, candidates);
4119
- for (const candidate of candidates) if (matchesSelectorToken(candidate, part)) next.push(candidate);
4120
- }
4121
- current = next;
4122
- }
4123
- 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);
4124
4891
  }
4125
4892
  //#endregion
4126
4893
  //#region src/view/nodeHandle.ts
@@ -4156,6 +4923,7 @@ function createEventPayload$1(node, eventName, event) {
4156
4923
  dataset: event.target?.dataset ?? event.dataset ?? dataset,
4157
4924
  id: event.target?.id ?? event.id ?? nodeId
4158
4925
  },
4926
+ timeStamp: Date.now(),
4159
4927
  type: eventName
4160
4928
  };
4161
4929
  }
@@ -4199,14 +4967,27 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
4199
4967
  assertActive() {
4200
4968
  this.interactions?.assertActive?.();
4201
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
+ }
4202
4979
  async $(selector) {
4203
4980
  this.assertActive();
4204
- const match = querySelectorAll(this.node, selector)[0];
4981
+ const match = this.query(selector)[0];
4205
4982
  return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
4206
4983
  }
4207
4984
  async $$(selector) {
4208
4985
  this.assertActive();
4209
- 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));
4210
4991
  }
4211
4992
  async attr(name) {
4212
4993
  this.assertActive();
@@ -4309,7 +5090,7 @@ function visitDom(node, visitor) {
4309
5090
  }
4310
5091
  function interpolateDomTree(root, data) {
4311
5092
  visitDom(root, (node) => {
4312
- if (typeof node.data === "string") node.data = interpolateTemplate$1(node.data, data);
5093
+ if (typeof node.data === "string") node.data = interpolateTemplateText(node.data, data);
4313
5094
  if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate$1(value, data);
4314
5095
  });
4315
5096
  }
@@ -5290,17 +6071,6 @@ function matchesComponentSelector$1(scope, selector) {
5290
6071
  function normalizeSelectorParts$1(selector) {
5291
6072
  return selector.trim().split(WHITESPACE_RE$1).filter(Boolean);
5292
6073
  }
5293
- function createAppLaunchOptions$1(pathname, query) {
5294
- return {
5295
- path: stripLeadingSlash$1(pathname),
5296
- query: { ...query },
5297
- referrerInfo: {
5298
- appId: "",
5299
- extraData: {}
5300
- },
5301
- scene: 1001
5302
- };
5303
- }
5304
6074
  function readJsonObject$2(files, filePath) {
5305
6075
  const content = readBrowserVirtualFile(files, filePath);
5306
6076
  if (!content) return;
@@ -5322,6 +6092,7 @@ var BrowserHeadlessSession = class {
5322
6092
  project;
5323
6093
  appDefinition = null;
5324
6094
  appInstance = null;
6095
+ appLifecycle = new HeadlessAppLifecycle();
5325
6096
  moduleLoader;
5326
6097
  onRender;
5327
6098
  registries;
@@ -5340,8 +6111,8 @@ var BrowserHeadlessSession = class {
5340
6111
  systemInfo = createDefaultSystemInfo();
5341
6112
  mediaQueryObservers = /* @__PURE__ */ new Set();
5342
6113
  canvasContexts = /* @__PURE__ */ new Map();
5343
- enterOptions = createAppLaunchOptions$1("", {});
5344
- launchOptions = createAppLaunchOptions$1("", {});
6114
+ enterOptions = createAppLaunchOptions("", {});
6115
+ launchOptions = createAppLaunchOptions("", {});
5345
6116
  kernel = new RuntimeKernel();
5346
6117
  wxState;
5347
6118
  pullDownRefreshState = {
@@ -5393,24 +6164,10 @@ var BrowserHeadlessSession = class {
5393
6164
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
5394
6165
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
5395
6166
  getSavedFileList: () => this.wxState.getSavedFileList(),
5396
- getEnterOptionsSync: () => ({
5397
- ...this.enterOptions,
5398
- query: { ...this.enterOptions.query },
5399
- referrerInfo: {
5400
- ...this.enterOptions.referrerInfo,
5401
- extraData: { ...this.enterOptions.referrerInfo.extraData }
5402
- }
5403
- }),
6167
+ getEnterOptionsSync: () => this.getEnterOptions(),
5404
6168
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
5405
6169
  getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
5406
- getLaunchOptionsSync: () => ({
5407
- ...this.launchOptions,
5408
- query: { ...this.launchOptions.query },
5409
- referrerInfo: {
5410
- ...this.launchOptions.referrerInfo,
5411
- extraData: { ...this.launchOptions.referrerInfo.extraData }
5412
- }
5413
- }),
6170
+ getLaunchOptionsSync: () => this.getLaunchOptions(),
5414
6171
  getClipboardData: () => this.wxState.getClipboardData(),
5415
6172
  getLocation: () => createDefaultLocationResult(),
5416
6173
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
@@ -5433,7 +6190,11 @@ var BrowserHeadlessSession = class {
5433
6190
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
5434
6191
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
5435
6192
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
6193
+ offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
6194
+ offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
5436
6195
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
6196
+ onAppHide: (callback) => this.appLifecycle.onAppHide(callback),
6197
+ onAppShow: (callback) => this.appLifecycle.onAppShow(callback),
5437
6198
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
5438
6199
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
5439
6200
  previewImage: (option) => this.wxState.previewImage(option),
@@ -5480,6 +6241,7 @@ var BrowserHeadlessSession = class {
5480
6241
  this.canvasContexts.clear();
5481
6242
  this.renderRequestCallbacks.length = 0;
5482
6243
  this.renderRequestPending = false;
6244
+ this.appLifecycle.close();
5483
6245
  this.wxState.close();
5484
6246
  this.moduleLoader.close();
5485
6247
  this.kernel.close();
@@ -5582,24 +6344,10 @@ var BrowserHeadlessSession = class {
5582
6344
  return deriveDeviceInfo(this.systemInfo);
5583
6345
  }
5584
6346
  getLaunchOptions() {
5585
- return {
5586
- ...this.launchOptions,
5587
- query: { ...this.launchOptions.query },
5588
- referrerInfo: {
5589
- ...this.launchOptions.referrerInfo,
5590
- extraData: { ...this.launchOptions.referrerInfo.extraData }
5591
- }
5592
- };
6347
+ return cloneAppLaunchOptions(this.launchOptions);
5593
6348
  }
5594
6349
  getEnterOptions() {
5595
- return {
5596
- ...this.enterOptions,
5597
- query: { ...this.enterOptions.query },
5598
- referrerInfo: {
5599
- ...this.enterOptions.referrerInfo,
5600
- extraData: { ...this.enterOptions.referrerInfo.extraData }
5601
- }
5602
- };
6350
+ return cloneAppLaunchOptions(this.enterOptions);
5603
6351
  }
5604
6352
  getMenuButtonBoundingClientRect() {
5605
6353
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
@@ -5941,21 +6689,21 @@ var BrowserHeadlessSession = class {
5941
6689
  type: "tap"
5942
6690
  });
5943
6691
  }
5944
- bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
6692
+ bootstrap(launchOptions = createAppLaunchOptions("", {})) {
5945
6693
  this.assertActive();
5946
6694
  if (this.appInstance) return this.appInstance;
5947
- this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
5948
- this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
6695
+ this.launchOptions = cloneAppLaunchOptions(launchOptions);
6696
+ this.enterOptions = cloneAppLaunchOptions(launchOptions);
5949
6697
  const appModulePath = join(this.project.miniprogramRootPath, "app.js");
5950
6698
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
5951
6699
  this.appInstance = createAppInstance(this.appDefinition);
5952
6700
  this.appInstance.onLaunch?.(launchOptions);
5953
- this.appInstance.onShow?.(launchOptions);
6701
+ this.appLifecycle.triggerAppShow(this.appInstance, launchOptions);
5954
6702
  return this.appInstance;
5955
6703
  }
5956
6704
  reLaunch(url) {
5957
6705
  const target = this.resolveNavigationTarget(url);
5958
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6706
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5959
6707
  this.unloadAllPages();
5960
6708
  const pageInstance = this.createFreshPage(target);
5961
6709
  this.pages.push(pageInstance);
@@ -5965,7 +6713,7 @@ var BrowserHeadlessSession = class {
5965
6713
  }
5966
6714
  navigateTo(url) {
5967
6715
  const target = this.resolveNavigationTarget(url);
5968
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6716
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5969
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.`);
5970
6718
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
5971
6719
  this.currentPageInstance?.onHide?.();
@@ -5978,7 +6726,7 @@ var BrowserHeadlessSession = class {
5978
6726
  }
5979
6727
  redirectTo(url) {
5980
6728
  const target = this.resolveNavigationTarget(url);
5981
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6729
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
5982
6730
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
5983
6731
  const current = this.currentPageInstance;
5984
6732
  if (current) {
@@ -6011,7 +6759,7 @@ var BrowserHeadlessSession = class {
6011
6759
  const target = this.resolveNavigationTarget(url);
6012
6760
  if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
6013
6761
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
6014
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
6762
+ this.bootstrap(createAppLaunchOptions(target.normalizedRoute, target.query));
6015
6763
  return () => this.commitSwitchTab(target);
6016
6764
  }
6017
6765
  commitSwitchTab(target) {
@@ -6064,6 +6812,21 @@ var BrowserHeadlessSession = class {
6064
6812
  current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
6065
6813
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
6066
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
+ }
6067
6830
  triggerPullDownRefresh() {
6068
6831
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
6069
6832
  this.pullDownRefreshState = {
@@ -6157,20 +6920,22 @@ var BrowserHeadlessSession = class {
6157
6920
  const pageConfig = readJsonObject$2(this.files, pageConfigPath);
6158
6921
  const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
6159
6922
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
6160
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
6923
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
6924
+ requestRender: (callback) => this.requestRender(callback)
6161
6925
  });
6162
6926
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
6163
6927
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
6164
6928
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
6165
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
+ };
6166
6934
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
6167
6935
  return pageInstance;
6168
6936
  }
6169
6937
  runInitialPageLifecycles(pageInstance, query) {
6170
- pageInstance.onLoad?.(query);
6171
- pageInstance.onShow?.();
6172
- pageInstance.onReady?.();
6173
- pageInstance.onRouteDone?.({});
6938
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
6174
6939
  }
6175
6940
  isTabBarRoute(route) {
6176
6941
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
@@ -6186,8 +6951,8 @@ var BrowserHeadlessSession = class {
6186
6951
  const normalizedRoute = pluginRequest ? `plugin-private://${pluginRequest.plugin.provider}/${pluginRequest.resourcePath.slice(pluginRequest.plugin.virtualRoot.length + 1)}` : resolveNavigationPath$1(pathname, baseRoute);
6187
6952
  const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
6188
6953
  if (!routeRecord) {
6189
- this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
6190
- this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
6954
+ this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
6955
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
6191
6956
  throw new Error(`Unknown route for browser simulator navigation: ${url}`);
6192
6957
  }
6193
6958
  return {
@@ -6226,9 +6991,10 @@ var BrowserHeadlessSession = class {
6226
6991
  }
6227
6992
  detachPageComponents(route) {
6228
6993
  const prefix = `page:${stripLeadingSlash$1(route)}`;
6229
- for (const [scopeId, instance] of [...this.componentCache.entries()]) {
6230
- if (!scopeId.startsWith(prefix)) continue;
6231
- 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) {
6232
6998
  this.componentCache.delete(scopeId);
6233
6999
  this.componentScopes.delete(scopeId);
6234
7000
  }
@@ -6474,6 +7240,32 @@ function loadProject(projectPath) {
6474
7240
  });
6475
7241
  }
6476
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
6477
7269
  //#region src/runtime/render/shared.ts
6478
7270
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
6479
7271
  const DATASET_NAME_RE = /-([a-z])/g;
@@ -6493,7 +7285,6 @@ const STRUCTURAL_ATTRS = [
6493
7285
  "wx:for-index",
6494
7286
  "wx:key"
6495
7287
  ];
6496
- const WX_ELSE_ATTRS = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
6497
7288
  const CLASS_SPLIT_RE = /\s+/;
6498
7289
  const JS_FILE_RE = /\.js$/;
6499
7290
  function isMustacheOnly(value) {
@@ -6543,12 +7334,21 @@ function readTemplateSource(artifactSource, filePath) {
6543
7334
  return source;
6544
7335
  }
6545
7336
  function parseTemplateDocument(templateSource) {
6546
- return parseDocument(`<page>${templateSource}</page>`, {
6547
- xmlMode: false,
6548
- decodeEntities: false,
6549
- lowerCaseAttributeNames: false,
6550
- lowerCaseTags: false,
6551
- 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);
6552
7352
  });
6553
7353
  }
6554
7354
  function serializeDomNode(node) {
@@ -6561,26 +7361,23 @@ function serializeDomNode(node) {
6561
7361
  function isTagNode(node) {
6562
7362
  return node.type === "tag" && typeof node.name === "string";
6563
7363
  }
6564
- function isIgnorableTextNode(node) {
6565
- return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
6566
- }
6567
7364
  function resolveAttributeValue(value, scope) {
6568
7365
  if (isMustacheOnly(value)) {
6569
7366
  const expression = value.trim().slice(2, -2);
6570
- return resolveValueByPath(scope.data, expression);
7367
+ return resolveValueByPath(wxsScopeData(scope), expression);
6571
7368
  }
6572
- return interpolateTemplate(value, scope.data);
7369
+ return interpolateTemplate(value, wxsScopeData(scope));
6573
7370
  }
6574
7371
  function resolveComponentAttributeValue(value, scope) {
6575
7372
  if (isMustacheOnly(value)) {
6576
7373
  const expression = value.trim().slice(2, -2);
6577
- return resolveRawValueByPath(scope.data, expression);
7374
+ return resolveRawValueByPath(wxsScopeData(scope), expression) ?? null;
6578
7375
  }
6579
- return interpolateTemplate(value, scope.data);
7376
+ return interpolateTemplate(value, wxsScopeData(scope));
6580
7377
  }
6581
7378
  function applyNodeBindings(node, scope) {
6582
7379
  if (!isTagNode(node)) {
6583
- 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));
6584
7381
  return;
6585
7382
  }
6586
7383
  node.attribs ??= {};
@@ -6594,17 +7391,10 @@ function applyNodeBindings(node, scope) {
6594
7391
  node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
6595
7392
  }
6596
7393
  }
6597
- function createMergedScopeData(pageData, componentProperties, componentData) {
6598
- return {
6599
- ...pageData,
6600
- ...componentProperties,
6601
- ...componentData
6602
- };
6603
- }
6604
7394
  function evaluateConditionalBranch(node, scope) {
6605
7395
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
6606
7396
  if (condition == null) return true;
6607
- return Boolean(resolveRawValueByPath(scope.data, condition));
7397
+ return Boolean(resolveRawValueByPath(wxsScopeData(scope), condition));
6608
7398
  }
6609
7399
  function createLoopScope(scope, itemName, indexName, item, index) {
6610
7400
  return {
@@ -6648,7 +7438,7 @@ function resolveUsingComponents(context, ownerJsonPath, ownerFilePath) {
6648
7438
  const resolved = /* @__PURE__ */ new Map();
6649
7439
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
6650
7440
  if (typeof rawPath !== "string") continue;
6651
- 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);
6652
7442
  resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
6653
7443
  }
6654
7444
  return resolved;
@@ -6683,13 +7473,11 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
6683
7473
  const hostDataset = collectDataset(hostNode);
6684
7474
  const hostId = hostNode.attribs?.id ?? "";
6685
7475
  return (instance, eventName, detail, triggerOptions) => {
6686
- const interactionTarget = instance.__lastInteractionEvent__?.target;
6687
- const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
6688
- const componentDataset = context.componentScopes.get(componentScopeId)?.dataset ?? hostDataset;
7476
+ const originScope = context.componentScopes.get(componentScopeId);
6689
7477
  const interactionMark = instance.__lastInteractionEvent__?.mark;
6690
7478
  const target = {
6691
- dataset: interactionTarget?.dataset ?? componentDataset,
6692
- id: interactionTarget?.id ?? hostId
7479
+ dataset: originScope?.dataset ?? hostDataset,
7480
+ id: originScope?.hostId ?? hostId
6693
7481
  };
6694
7482
  let currentScopeId = componentScopeId;
6695
7483
  while (currentScopeId) {
@@ -6702,8 +7490,8 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
6702
7490
  capturePhase: false,
6703
7491
  composed: triggerOptions?.composed ?? false,
6704
7492
  currentTarget: {
6705
- dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
6706
- id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
7493
+ dataset: currentScope?.dataset ?? hostDataset,
7494
+ id: currentScope?.hostId ?? hostId
6707
7495
  },
6708
7496
  detail,
6709
7497
  mark: interactionMark,
@@ -6729,7 +7517,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
6729
7517
  if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
6730
7518
  previousProperties[key] = instance.properties[key];
6731
7519
  instance.properties[key] = nextValue;
6732
- instance.data[key] = nextValue;
7520
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
6733
7521
  changedRootKeys.push(key);
6734
7522
  }
6735
7523
  instance.__propertySnapshots ??= {};
@@ -6743,12 +7531,12 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
6743
7531
  return {
6744
7532
  alias: clonedNode.name,
6745
7533
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
6746
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
6747
- dataset: collectDataset(clonedNode, scope.data),
7534
+ data: { ...componentInstance.data },
7535
+ dataset: collectDataset(clonedNode, wxsScopeData(scope)),
6748
7536
  eventBindings: collectComponentEventBindings(clonedNode),
6749
7537
  getMethod: (methodName) => {
6750
7538
  const method = componentInstance?.[methodName];
6751
- return typeof method === "function" ? method : void 0;
7539
+ return typeof method === "function" ? method.bind(componentInstance) : void 0;
6752
7540
  },
6753
7541
  getScopeId: () => componentScopeId,
6754
7542
  genericComponents,
@@ -6779,7 +7567,6 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
6779
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;
6780
7568
  const componentInstance = createComponentInstance({
6781
7569
  definition: componentEntry.definition,
6782
- properties: componentProperties,
6783
7570
  requestRender: (callback) => context.session.requestRender(callback),
6784
7571
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
6785
7572
  });
@@ -6787,20 +7574,20 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
6787
7574
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
6788
7575
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
6789
7576
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
7577
+ componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
6790
7578
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
6791
7579
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
6792
7580
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
6793
7581
  context.componentCache.set(componentScopeId, componentInstance);
6794
7582
  runComponentLifecycle(componentInstance, "created");
6795
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(componentProperties), {});
6796
7583
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
6797
- runComponentLifecycle(componentInstance, "attached");
7584
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
6798
7585
  return componentInstance;
6799
7586
  }
6800
7587
  function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
6801
7588
  const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
6802
7589
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
6803
- const templateRenderState = createTemplateRenderState(componentRoot);
7590
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, componentRoot, componentEntry.absoluteTemplatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
6804
7591
  return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
6805
7592
  }
6806
7593
  //#endregion
@@ -6812,11 +7599,10 @@ function expandNodeByFor(node, scope) {
6812
7599
  scope,
6813
7600
  instanceSuffix: ""
6814
7601
  }];
6815
- const list = resolveRawValueByPath(scope.data, forExpression);
6816
- const items = Array.isArray(list) ? list : [];
7602
+ const items = resolveLoopEntries(resolveRawValueByPath(wxsScopeData(scope), forExpression));
6817
7603
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
6818
7604
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
6819
- return items.map((item, index) => ({
7605
+ return items.map(([index, item]) => ({
6820
7606
  node: cloneNode(node),
6821
7607
  scope: createLoopScope(scope, itemName, indexName, item, index),
6822
7608
  instanceSuffix: `:for-${index}`
@@ -6827,40 +7613,12 @@ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath,
6827
7613
  }
6828
7614
  function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
6829
7615
  const renderedChildren = [];
6830
- for (let index = 0; index < children.length; index += 1) {
6831
- const child = children[index];
7616
+ for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch(node, scope))) {
6832
7617
  if (!isTagNode(child)) {
6833
7618
  renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
6834
7619
  continue;
6835
7620
  }
6836
- if (isTemplateDefinition(child)) continue;
6837
- const hasConditional = child.attribs?.["wx:if"] != null;
6838
- const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
6839
- if (hasConditional) {
6840
- let branchMatched = false;
6841
- let cursor = index;
6842
- while (cursor < children.length) {
6843
- const branch = children[cursor];
6844
- if (cursor !== index && isIgnorableTextNode(branch)) {
6845
- cursor += 1;
6846
- continue;
6847
- }
6848
- if (!isTagNode(branch)) break;
6849
- if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
6850
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
6851
- renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes, templateRenderState));
6852
- branchMatched = true;
6853
- }
6854
- let nextBranchIndex = cursor + 1;
6855
- while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
6856
- const nextBranch = children[nextBranchIndex];
6857
- if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
6858
- cursor = nextBranchIndex;
6859
- }
6860
- index = cursor;
6861
- continue;
6862
- }
6863
- if (isElseBranch) continue;
7621
+ if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
6864
7622
  renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
6865
7623
  }
6866
7624
  return renderedChildren;
@@ -6894,6 +7652,10 @@ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePat
6894
7652
  return slots;
6895
7653
  }
6896
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
+ };
6897
7659
  const clonedNode = cloneNode(node);
6898
7660
  if (!isTagNode(clonedNode)) {
6899
7661
  applyNodeBindings(clonedNode, scope);
@@ -6905,15 +7667,19 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6905
7667
  attribs: {},
6906
7668
  children: []
6907
7669
  };
6908
- const templateName = resolveTemplateCall(clonedNode, scope.data);
7670
+ const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
6909
7671
  if (templateName) {
6910
7672
  const definition = templateRenderState.definitions.get(templateName);
6911
7673
  const templateScope = {
6912
7674
  ...scope,
6913
- data: resolveTemplateData(clonedNode, scope.data)
7675
+ data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
7676
+ wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
6914
7677
  };
6915
7678
  const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
6916
- definitions: templateRenderState.definitions,
7679
+ definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
7680
+ definitionScopes: templateRenderState.definitionScopes,
7681
+ definitionWxsScopes: templateRenderState.definitionWxsScopes,
7682
+ wxsModules: templateScope.wxs,
6917
7683
  stack: [...templateRenderState.stack, templateName]
6918
7684
  }) : [];
6919
7685
  return {
@@ -6929,7 +7695,10 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6929
7695
  if (clonedNode.name === "slot") {
6930
7696
  const slotName = clonedNode.attribs?.name?.trim() || "default";
6931
7697
  const projected = scope.slots?.get(slotName) ?? [];
6932
- 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);
6933
7702
  return {
6934
7703
  type: "tag",
6935
7704
  name: "block",
@@ -6955,15 +7724,15 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
6955
7724
  context.componentScopes.set(componentScopeId, componentScope);
6956
7725
  const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
6957
7726
  if (renderedComponentRoot.attribs) {
7727
+ applyNodeBindings(clonedNode, scope);
7728
+ renderedComponentRoot.attribs = {
7729
+ ...clonedNode.attribs,
7730
+ ...renderedComponentRoot.attribs
7731
+ };
6958
7732
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
6959
7733
  renderedComponentRoot.attribs["data-sim-node"] = instancePath;
6960
7734
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
6961
7735
  }
6962
- if (!componentInstance.__ready__) {
6963
- runComponentLifecycle(componentInstance, "ready");
6964
- componentInstance.__ready__ = true;
6965
- componentInstance.__definition__?.pageLifetimes?.show?.call(componentInstance);
6966
- }
6967
7736
  return renderedComponentRoot;
6968
7737
  }
6969
7738
  applyNodeBindings(clonedNode, scope);
@@ -6981,25 +7750,48 @@ function renderRuntimePageTree(context, page) {
6981
7750
  data: page.data,
6982
7751
  getMethod: (methodName) => {
6983
7752
  const method = page[methodName];
6984
- return typeof method === "function" ? method : void 0;
7753
+ return typeof method === "function" ? method.bind(page) : void 0;
6985
7754
  },
6986
7755
  getScopeId: () => pageScopeId,
6987
7756
  id: "page-root"
6988
7757
  };
6989
- context.componentScopes.clear();
7758
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
6990
7759
  context.componentScopes.set(pageScopeId, pageScope);
6991
7760
  const seenComponentScopes = /* @__PURE__ */ new Set();
6992
7761
  const root = (document.children ?? [])[0] ?? document;
6993
- const templateRenderState = createTemplateRenderState(root);
7762
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
6994
7763
  const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
6995
- for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
6996
- 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) {
6997
7779
  context.componentCache.delete(scopeId);
6998
7780
  context.componentScopes.delete(scopeId);
6999
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);
7000
7792
  return {
7001
- root: renderedRoot,
7002
- wxml: serializeDomNode(renderedRoot)
7793
+ root: treeRoot,
7794
+ wxml: roots.map(serializeDomNode).join("")
7003
7795
  };
7004
7796
  }
7005
7797
  //#endregion
@@ -7103,20 +7895,9 @@ function transformEsmToCommonJs(source) {
7103
7895
  function createRequireNotFoundError(request, importer) {
7104
7896
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
7105
7897
  }
7106
- function resolveRequiredModulePath(artifactSource, importer, request) {
7107
- if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
7108
- const basePath = path.resolve(path.dirname(importer), request);
7109
- const candidates = [
7110
- basePath,
7111
- `${basePath}.js`,
7112
- `${basePath}.json`,
7113
- path.join(basePath, "index.js")
7114
- ];
7115
- for (const candidate of candidates) if (artifactSource.has(candidate)) return candidate;
7116
- throw createRequireNotFoundError(request, importer);
7117
- }
7118
7898
  function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole) {
7119
- const wx = createHeadlessWx(wxDriver);
7899
+ const runtimeConsole = kernel.diagnostics.createConsole(console, onConsole);
7900
+ const wx = createHeadlessWx(wxDriver, runtimeConsole);
7120
7901
  return createMiniProgramRuntimeGlobals({
7121
7902
  App(definition) {
7122
7903
  return registerAppDefinition(registries, definition);
@@ -7133,7 +7914,7 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, k
7133
7914
  Page(definition) {
7134
7915
  return registerPageDefinition(registries, definition);
7135
7916
  },
7136
- console: kernel.diagnostics.createConsole(console, onConsole),
7917
+ console: runtimeConsole,
7137
7918
  clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
7138
7919
  clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
7139
7920
  getApp,
@@ -7168,7 +7949,8 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7168
7949
  const previousLoadContext = registries.currentLoadContext;
7169
7950
  registries.currentLoadContext = loadContext;
7170
7951
  const localRequire = ((request) => {
7171
- 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);
7172
7954
  if (requiredPath.endsWith(".json")) {
7173
7955
  const content = options.artifactSource.readText(requiredPath);
7174
7956
  if (content == null) throw createRequireNotFoundError(request, resolvedPath);
@@ -7188,6 +7970,9 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7188
7970
  ...registeredDefinitions
7189
7971
  ])];
7190
7972
  return module;
7973
+ } catch (error) {
7974
+ moduleCache.delete(resolvedPath);
7975
+ throw error;
7191
7976
  } finally {
7192
7977
  registries.currentLoadContext = previousLoadContext;
7193
7978
  }
@@ -7198,14 +7983,19 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7198
7983
  const main = typeof plugin.config.main === "string" && plugin.config.main ? plugin.config.main : "index.js";
7199
7984
  return executeModule(path.resolve(options.miniprogramRootPath, plugin.virtualRoot, main), null).exports;
7200
7985
  };
7201
- 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
+ },
7202
7992
  close() {
7203
7993
  moduleCache.clear();
7994
+ closeRuntimeWxsLoader(loader);
7204
7995
  },
7205
7996
  executeAppModule(filePath) {
7206
7997
  executeModule(filePath, { kind: "app" });
7207
- if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
7208
- return registries.appDefinition;
7998
+ return registries.appDefinition ?? registerAppDefinition(registries, {});
7209
7999
  },
7210
8000
  executePageModule(filePath, route) {
7211
8001
  const fallbackDefinition = executeModule(filePath, {
@@ -7229,6 +8019,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
7229
8019
  },
7230
8020
  wx: executionContext.wx
7231
8021
  };
8022
+ return loader;
7232
8023
  }
7233
8024
  //#endregion
7234
8025
  //#region src/runtime/session.ts
@@ -7279,17 +8070,6 @@ function matchesComponentSelector(scope, selector) {
7279
8070
  function normalizeSelectorParts(selector) {
7280
8071
  return selector.trim().split(WHITESPACE_RE).filter(Boolean);
7281
8072
  }
7282
- function createAppLaunchOptions(pathname, query) {
7283
- return {
7284
- path: stripLeadingSlash(pathname),
7285
- query: { ...query },
7286
- referrerInfo: {
7287
- appId: "",
7288
- extraData: {}
7289
- },
7290
- scene: 1001
7291
- };
7292
- }
7293
8073
  function readJsonObject(project, filePath) {
7294
8074
  try {
7295
8075
  const source = project.artifactSource.readText(filePath);
@@ -7310,6 +8090,7 @@ var HeadlessSession = class {
7310
8090
  kernel = new RuntimeKernel();
7311
8091
  appDefinition = null;
7312
8092
  appInstance = null;
8093
+ appLifecycle = new HeadlessAppLifecycle();
7313
8094
  moduleLoader;
7314
8095
  eventListeners = /* @__PURE__ */ new Map();
7315
8096
  registries;
@@ -7379,24 +8160,10 @@ var HeadlessSession = class {
7379
8160
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
7380
8161
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
7381
8162
  getSavedFileList: () => this.wxState.getSavedFileList(),
7382
- getEnterOptionsSync: () => ({
7383
- ...this.enterOptions,
7384
- query: { ...this.enterOptions.query },
7385
- referrerInfo: {
7386
- ...this.enterOptions.referrerInfo,
7387
- extraData: { ...this.enterOptions.referrerInfo.extraData }
7388
- }
7389
- }),
8163
+ getEnterOptionsSync: () => this.getEnterOptions(),
7390
8164
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
7391
8165
  getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
7392
- getLaunchOptionsSync: () => ({
7393
- ...this.launchOptions,
7394
- query: { ...this.launchOptions.query },
7395
- referrerInfo: {
7396
- ...this.launchOptions.referrerInfo,
7397
- extraData: { ...this.launchOptions.referrerInfo.extraData }
7398
- }
7399
- }),
8166
+ getLaunchOptionsSync: () => this.getLaunchOptions(),
7400
8167
  getClipboardData: () => this.wxState.getClipboardData(),
7401
8168
  getLocation: () => createDefaultLocationResult(),
7402
8169
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
@@ -7419,7 +8186,11 @@ var HeadlessSession = class {
7419
8186
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
7420
8187
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
7421
8188
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
8189
+ offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
8190
+ offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
7422
8191
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
8192
+ onAppHide: (callback) => this.appLifecycle.onAppHide(callback),
8193
+ onAppShow: (callback) => this.appLifecycle.onAppShow(callback),
7423
8194
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
7424
8195
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
7425
8196
  previewImage: (option) => this.wxState.previewImage(option),
@@ -7468,6 +8239,7 @@ var HeadlessSession = class {
7468
8239
  this.canvasContexts.clear();
7469
8240
  this.renderRequestCallbacks.length = 0;
7470
8241
  this.renderRequestPending = false;
8242
+ this.appLifecycle.close();
7471
8243
  this.wxState.close();
7472
8244
  this.moduleLoader.close();
7473
8245
  this.eventListeners.clear();
@@ -7505,6 +8277,11 @@ var HeadlessSession = class {
7505
8277
  this.assertActive();
7506
8278
  return this.moduleLoader.wx;
7507
8279
  }
8280
+ /** 在当前小程序实例的上下文执行测试函数,复用应用全局对象与调度器。 */
8281
+ evaluateRuntime(source, args = []) {
8282
+ this.assertActive();
8283
+ return this.moduleLoader.evaluate(source, args);
8284
+ }
7508
8285
  callWxMethod(methodName, ...args) {
7509
8286
  this.assertActive();
7510
8287
  const method = this.moduleLoader.wx[methodName];
@@ -7723,24 +8500,10 @@ var HeadlessSession = class {
7723
8500
  return deriveDeviceInfo(this.systemInfo);
7724
8501
  }
7725
8502
  getLaunchOptions() {
7726
- return {
7727
- ...this.launchOptions,
7728
- query: { ...this.launchOptions.query },
7729
- referrerInfo: {
7730
- ...this.launchOptions.referrerInfo,
7731
- extraData: { ...this.launchOptions.referrerInfo.extraData }
7732
- }
7733
- };
8503
+ return cloneAppLaunchOptions(this.launchOptions);
7734
8504
  }
7735
8505
  getEnterOptions() {
7736
- return {
7737
- ...this.enterOptions,
7738
- query: { ...this.enterOptions.query },
7739
- referrerInfo: {
7740
- ...this.enterOptions.referrerInfo,
7741
- extraData: { ...this.enterOptions.referrerInfo.extraData }
7742
- }
7743
- };
8506
+ return cloneAppLaunchOptions(this.enterOptions);
7744
8507
  }
7745
8508
  getMenuButtonBoundingClientRect() {
7746
8509
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
@@ -7894,14 +8657,14 @@ var HeadlessSession = class {
7894
8657
  bootstrap(launchOptions = createAppLaunchOptions("", {})) {
7895
8658
  this.assertActive();
7896
8659
  if (this.appInstance) return this.appInstance;
7897
- this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
7898
- this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
8660
+ this.launchOptions = cloneAppLaunchOptions(launchOptions);
8661
+ this.enterOptions = cloneAppLaunchOptions(launchOptions);
7899
8662
  const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
7900
8663
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
7901
8664
  this.appInstance = createAppInstance(this.appDefinition);
7902
8665
  this.appInstance.onLaunch?.(launchOptions);
7903
8666
  this.syncRuntimeAppState();
7904
- this.appInstance.onShow?.(launchOptions);
8667
+ this.appLifecycle.triggerAppShow(this.appInstance, launchOptions);
7905
8668
  return this.appInstance;
7906
8669
  }
7907
8670
  syncRuntimeAppState() {
@@ -8009,6 +8772,21 @@ var HeadlessSession = class {
8009
8772
  current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
8010
8773
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
8011
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
+ }
8012
8790
  triggerPullDownRefresh() {
8013
8791
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
8014
8792
  this.pullDownRefreshState = {
@@ -8088,20 +8866,22 @@ var HeadlessSession = class {
8088
8866
  const pageConfig = readJsonObject(this.project, pageConfigPath);
8089
8867
  const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
8090
8868
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
8091
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
8869
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
8870
+ requestRender: (callback) => this.requestRender(callback)
8092
8871
  });
8093
8872
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
8094
8873
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
8095
8874
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
8096
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
+ };
8097
8880
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
8098
8881
  return pageInstance;
8099
8882
  }
8100
8883
  runInitialPageLifecycles(pageInstance, query) {
8101
- pageInstance.onLoad?.(query);
8102
- pageInstance.onShow?.();
8103
- pageInstance.onReady?.();
8104
- pageInstance.onRouteDone?.({});
8884
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
8105
8885
  }
8106
8886
  isTabBarRoute(route) {
8107
8887
  return this.tabBarRoutes.has(stripLeadingSlash(route));
@@ -8177,9 +8957,10 @@ var HeadlessSession = class {
8177
8957
  }
8178
8958
  detachPageComponents(route) {
8179
8959
  const prefix = `page:${stripLeadingSlash(route)}`;
8180
- for (const [scopeId, instance] of [...this.componentCache.entries()]) {
8181
- if (!scopeId.startsWith(prefix)) continue;
8182
- 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) {
8183
8964
  this.componentCache.delete(scopeId);
8184
8965
  this.componentScopes.delete(scopeId);
8185
8966
  }
@@ -8328,11 +9109,19 @@ function createLogicalNode(node) {
8328
9109
  };
8329
9110
  }
8330
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
8331
9120
  //#region src/testing/pageNodeAccess.ts
8332
9121
  function createPageRootNodeHandle(options) {
8333
9122
  const { page, project, session } = options;
8334
9123
  const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
8335
- 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, {
8336
9125
  assertActive: options.assertActive,
8337
9126
  callMethod: (scopeId, methodName, event) => {
8338
9127
  if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
@@ -8354,6 +9143,13 @@ function createPageRootNodeHandle(options) {
8354
9143
  });
8355
9144
  }
8356
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
8357
9153
  //#region src/testing/pageWait.ts
8358
9154
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
8359
9155
  const DEFAULT_WAIT_INTERVAL$1 = 10;
@@ -8538,9 +9334,14 @@ var HeadlessTestingPageHandle = class {
8538
9334
  this.page = page;
8539
9335
  this.session = session;
8540
9336
  }
9337
+ /** 返回底层页面实例身份;重新获取 handle 不会改变该身份。 */
9338
+ get pageId() {
9339
+ this.assertActive();
9340
+ return getPageInstanceId(this.page);
9341
+ }
8541
9342
  get path() {
8542
9343
  this.assertActive();
8543
- return this.page.route;
9344
+ return resolveTestingPagePath(this.page.route);
8544
9345
  }
8545
9346
  get query() {
8546
9347
  this.assertActive();
@@ -8567,19 +9368,29 @@ var HeadlessTestingPageHandle = class {
8567
9368
  this.assertActive();
8568
9369
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "Page method name");
8569
9370
  return await runWithTimeout(async () => {
9371
+ const target = resolveTestingPageMethodTarget(this.page, this.session?.getCurrentPages(), options);
9372
+ if (!target) return;
8570
9373
  this.session?.renderCurrentPage();
8571
- const method = this.page[normalizedMethodName];
9374
+ const method = target[normalizedMethodName];
8572
9375
  if (typeof method !== "function") {
8573
9376
  if (options.routeOnly) return;
8574
9377
  throw new TypeError(`Method "${normalizedMethodName}" does not exist on headless page ${this.page.route}.`);
8575
9378
  }
8576
- return cloneProtocolValue(await method.apply(this.page, args));
9379
+ return cloneProtocolValue(await method.apply(target, args));
8577
9380
  }, options.timeout, `Timed out calling page method "${normalizedMethodName}" in headless testing runtime.`);
8578
9381
  }
8579
9382
  async data(path) {
8580
9383
  this.assertActive();
8581
9384
  return cloneProtocolValue(this.resolveDataByPath(path));
8582
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
+ }
8583
9394
  async selectComponent(selector) {
8584
9395
  this.assertActive();
8585
9396
  const normalizedSelector = selector.trim();
@@ -8615,6 +9426,17 @@ var HeadlessTestingPageHandle = class {
8615
9426
  if (selector === "page") return [root];
8616
9427
  return await root.$$(selector);
8617
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
+ }
8618
9440
  async renderedNodes(selector, options = {}) {
8619
9441
  return await readRenderedNodes(this.renderedAccess(), selector, options);
8620
9442
  }
@@ -8811,25 +9633,23 @@ var HeadlessTestingSessionHandle = class {
8811
9633
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
8812
9634
  }
8813
9635
  async reLaunch(route) {
8814
- this.session.callWxMethod("reLaunch", { url: route });
8815
- const page = this.session.getCurrentPages().at(-1);
8816
- if (!page) throw new Error(`Failed to reLaunch route "${route}" through the headless wx runtime.`);
8817
- return new HeadlessTestingPageHandle(this.project, page, this.session);
9636
+ this.invokeNavigation("reLaunch", { url: route });
9637
+ return await this.requireCurrentPage("reLaunch", route);
8818
9638
  }
8819
9639
  async navigateTo(route) {
8820
- this.session.callWxMethod("navigateTo", { url: route });
9640
+ this.invokeNavigation("navigateTo", { url: route });
8821
9641
  return await this.requireCurrentPage("navigateTo", route);
8822
9642
  }
8823
9643
  async redirectTo(route) {
8824
- this.session.callWxMethod("redirectTo", { url: route });
9644
+ this.invokeNavigation("redirectTo", { url: route });
8825
9645
  return await this.requireCurrentPage("redirectTo", route);
8826
9646
  }
8827
9647
  async navigateBack(delta = 1) {
8828
- this.session.callWxMethod("navigateBack", { delta });
9648
+ this.invokeNavigation("navigateBack", { delta });
8829
9649
  return await this.currentPage();
8830
9650
  }
8831
9651
  async switchTab(route) {
8832
- this.session.callWxMethod("switchTab", { url: route });
9652
+ this.invokeNavigation("switchTab", { url: route });
8833
9653
  return await this.requireCurrentPage("switchTab", route);
8834
9654
  }
8835
9655
  async waitForCurrentPage(route, options = {}) {
@@ -8840,13 +9660,19 @@ var HeadlessTestingSessionHandle = class {
8840
9660
  if (!currentPageInstance) return null;
8841
9661
  const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
8842
9662
  if (!normalizedRoute) return current;
8843
- if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
9663
+ if (normalizeRoute(current.path) === resolveTestingPagePath(normalizeRoute(normalizedRoute))) return current;
8844
9664
  return null;
8845
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);
8846
9666
  }
8847
9667
  async pageScrollTo(scrollTop) {
8848
9668
  this.session.pageScrollTo({ scrollTop });
8849
9669
  }
9670
+ async triggerAppHide(options) {
9671
+ this.session.triggerAppHide(options);
9672
+ }
9673
+ async triggerAppShow(options) {
9674
+ this.session.triggerAppShow(options);
9675
+ }
8850
9676
  async triggerPullDownRefresh() {
8851
9677
  this.session.triggerPullDownRefresh();
8852
9678
  }
@@ -8859,29 +9685,31 @@ var HeadlessTestingSessionHandle = class {
8859
9685
  async triggerRouteDone(options) {
8860
9686
  this.session.triggerRouteDone(options);
8861
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
+ }
8862
9705
  async requireCurrentPage(methodName, route) {
8863
9706
  const page = await this.currentPage();
8864
9707
  if (!page) throw new Error(`Failed to ${methodName} route "${route}" through the headless wx runtime.`);
8865
9708
  return page;
8866
9709
  }
8867
9710
  async evaluateInRuntime(evaluator, args) {
8868
- const runtimeGlobals = createMiniProgramRuntimeGlobals({
8869
- clearInterval: globalThis.clearInterval,
8870
- clearTimeout: globalThis.clearTimeout,
8871
- getApp: () => this.session.getApp(),
8872
- getCurrentPages: () => this.session.getCurrentPages(),
8873
- setInterval: globalThis.setInterval,
8874
- setTimeout: globalThis.setTimeout,
8875
- TextDecoder: globalThis.TextDecoder,
8876
- TextEncoder: globalThis.TextEncoder,
8877
- URL: globalThis.URL,
8878
- wx: this.session.getWx()
8879
- }, {});
8880
- runtimeGlobals.globalThis = runtimeGlobals;
8881
9711
  const source = typeof evaluator === "string" ? evaluator : Function.prototype.toString.call(evaluator);
8882
- const fn = new vm.Script(`(${source})`).runInNewContext(runtimeGlobals);
8883
- if (typeof fn !== "function") throw new TypeError("Headless evaluator must be a function or function source string.");
8884
- return await fn(...args);
9712
+ return await this.session.evaluateRuntime(source, args);
8885
9713
  }
8886
9714
  };
8887
9715
  //#endregion
@@ -8893,10 +9721,18 @@ function resolveInitialRoute(session) {
8893
9721
  }
8894
9722
  async function launch(options) {
8895
9723
  const session = createHeadlessSession({ projectPath: options.projectPath });
8896
- session.bootstrap();
8897
- const initialRoute = resolveInitialRoute(session);
8898
- if (initialRoute) session.reLaunch(`/${initialRoute}`);
8899
- 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
+ }
8900
9736
  }
8901
9737
  //#endregion
8902
- 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 };