@mpcore/simulator 0.1.2 → 0.1.4

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
@@ -60,9 +60,65 @@ function resolveCapabilityValue(source, schema) {
60
60
  function createHeadlessWx(driver) {
61
61
  const capabilityTree = {
62
62
  canIUse: true,
63
+ canvasToTempFilePath: true,
64
+ chooseImage: { return: {
65
+ errMsg: true,
66
+ tempFilePaths: true,
67
+ tempFiles: true
68
+ } },
69
+ chooseMessageFile: { return: {
70
+ errMsg: true,
71
+ tempFiles: true
72
+ } },
73
+ chooseMedia: { return: {
74
+ errMsg: true,
75
+ tempFiles: true,
76
+ type: true
77
+ } },
78
+ chooseVideo: { return: {
79
+ duration: true,
80
+ errMsg: true,
81
+ height: true,
82
+ size: true,
83
+ tempFilePath: true,
84
+ width: true
85
+ } },
86
+ compressImage: { return: {
87
+ errMsg: true,
88
+ tempFilePath: true
89
+ } },
63
90
  clearStorage: true,
64
91
  clearStorageSync: true,
92
+ createAnimation: true,
93
+ createCanvasContext: true,
94
+ createIntersectionObserver: true,
95
+ createVideoContext: true,
65
96
  createSelectorQuery: true,
97
+ getImageInfo: { return: {
98
+ errMsg: true,
99
+ height: true,
100
+ orientation: true,
101
+ path: true,
102
+ type: true,
103
+ width: true
104
+ } },
105
+ getFileInfo: { return: {
106
+ digest: true,
107
+ errMsg: true,
108
+ size: true
109
+ } },
110
+ openDocument: { return: { errMsg: true } },
111
+ getVideoInfo: { return: {
112
+ bitrate: true,
113
+ duration: true,
114
+ errMsg: true,
115
+ fps: true,
116
+ height: true,
117
+ orientation: true,
118
+ size: true,
119
+ type: true,
120
+ width: true
121
+ } },
66
122
  getFileSystemManager: true,
67
123
  getSavedFileInfo: true,
68
124
  getSavedFileList: true,
@@ -100,6 +156,10 @@ function createHeadlessWx(driver) {
100
156
  },
101
157
  scene: true
102
158
  } },
159
+ getClipboardData: { return: {
160
+ data: true,
161
+ errMsg: true
162
+ } },
103
163
  getMenuButtonBoundingClientRect: { return: {
104
164
  bottom: true,
105
165
  height: true,
@@ -174,14 +234,18 @@ function createHeadlessWx(driver) {
174
234
  offNetworkStatusChange: true,
175
235
  onNetworkStatusChange: true,
176
236
  pageScrollTo: true,
237
+ previewImage: true,
177
238
  reLaunch: true,
178
239
  redirectTo: true,
240
+ saveImageToPhotosAlbum: true,
241
+ saveVideoToPhotosAlbum: true,
179
242
  removeStorage: true,
180
243
  removeStorageSync: true,
181
244
  request: true,
182
245
  saveFile: true,
183
246
  setBackgroundColor: true,
184
247
  setBackgroundTextStyle: true,
248
+ setClipboardData: true,
185
249
  setStorage: true,
186
250
  setStorageSync: true,
187
251
  setNavigationBarColor: true,
@@ -198,6 +262,7 @@ function createHeadlessWx(driver) {
198
262
  showLoading: true,
199
263
  showModal: true,
200
264
  showToast: true,
265
+ startPullDownRefresh: true,
201
266
  stopPullDownRefresh: true,
202
267
  switchTab: true,
203
268
  uploadFile: true,
@@ -207,11 +272,21 @@ function createHeadlessWx(driver) {
207
272
  };
208
273
  return {
209
274
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
275
+ canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
276
+ chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
277
+ chooseMessageFile: (option) => invokeWxApi(() => driver.chooseMessageFile(option ?? {}), option),
278
+ chooseMedia: (option) => invokeWxApi(() => driver.chooseMedia(option ?? {}), option),
279
+ chooseVideo: (option) => invokeWxApi(() => driver.chooseVideo(option ?? {}), option),
280
+ compressImage: (option) => invokeWxApi(() => driver.compressImage(option), option),
210
281
  clearStorage: (option) => invokeWxApi(() => {
211
282
  driver.clearStorageSync();
212
283
  return { errMsg: "clearStorage:ok" };
213
284
  }, option),
214
285
  clearStorageSync: () => driver.clearStorageSync(),
286
+ createAnimation: (option) => driver.createAnimation(option),
287
+ createCanvasContext: (canvasId, component) => driver.createCanvasContext(canvasId, component),
288
+ createIntersectionObserver: (component, options) => driver.createIntersectionObserver(component, options),
289
+ createVideoContext: (videoId, component) => driver.createVideoContext(videoId, component),
215
290
  createSelectorQuery: () => {
216
291
  const requests = [];
217
292
  let scope;
@@ -270,12 +345,16 @@ function createHeadlessWx(driver) {
270
345
  return query;
271
346
  },
272
347
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
348
+ getFileInfo: (option) => invokeWxApi(() => driver.getFileInfo(option), option),
349
+ getImageInfo: (option) => invokeWxApi(() => driver.getImageInfo(option), option),
350
+ getVideoInfo: (option) => invokeWxApi(() => driver.getVideoInfo(option), option),
273
351
  getFileSystemManager: () => driver.getFileSystemManager(),
274
352
  getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
275
353
  getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
276
354
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
277
355
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
278
356
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
357
+ getClipboardData: (option) => invokeWxApi(() => driver.getClipboardData(), option),
279
358
  getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
280
359
  getNetworkType: (option) => invokeWxApi(() => driver.getNetworkType(), option),
281
360
  getStorageInfo: (option) => invokeWxApi(() => driver.getStorageInfoSync(), option),
@@ -301,9 +380,11 @@ function createHeadlessWx(driver) {
301
380
  nextTick: (callback) => driver.nextTick(callback),
302
381
  offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
303
382
  onNetworkStatusChange: (callback) => driver.onNetworkStatusChange(callback),
383
+ openDocument: (option) => invokeWxApi(() => driver.openDocument(option), option),
304
384
  pageScrollTo: (option) => invokeWxApi(() => {
305
385
  driver.pageScrollTo(option);
306
386
  }, option),
387
+ previewImage: (option) => invokeWxApi(() => driver.previewImage(option), option),
307
388
  reLaunch: (option) => invokeWxApi(() => {
308
389
  driver.reLaunch(option);
309
390
  }, option),
@@ -311,6 +392,8 @@ function createHeadlessWx(driver) {
311
392
  driver.redirectTo(option);
312
393
  }, option),
313
394
  removeSavedFile: (option) => invokeWxApi(() => driver.removeSavedFile(option), option),
395
+ saveImageToPhotosAlbum: (option) => invokeWxApi(() => driver.saveImageToPhotosAlbum(option), option),
396
+ saveVideoToPhotosAlbum: (option) => invokeWxApi(() => driver.saveVideoToPhotosAlbum(option), option),
314
397
  removeStorage: (option) => invokeWxApi(() => {
315
398
  driver.removeStorageSync(option.key);
316
399
  return { errMsg: "removeStorage:ok" };
@@ -320,6 +403,7 @@ function createHeadlessWx(driver) {
320
403
  saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
321
404
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
322
405
  setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
406
+ setClipboardData: (option) => invokeWxApi(() => driver.setClipboardData(option), option),
323
407
  setStorage: (option) => invokeWxApi(() => {
324
408
  driver.setStorageSync(option.key, option.data);
325
409
  return { errMsg: "setStorage:ok" };
@@ -339,6 +423,7 @@ function createHeadlessWx(driver) {
339
423
  showLoading: (option) => invokeWxApi(() => driver.showLoading(option), option),
340
424
  showModal: (option) => invokeWxApi(() => driver.showModal(option), option),
341
425
  showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
426
+ startPullDownRefresh: (option) => invokeWxApi(() => driver.startPullDownRefresh(), option),
342
427
  stopPullDownRefresh: () => driver.stopPullDownRefresh(),
343
428
  switchTab: (option) => invokeWxApi(() => {
344
429
  driver.switchTab(option);
@@ -561,6 +646,8 @@ function createBrowserProject(files, options = {}) {
561
646
  }
562
647
  //#endregion
563
648
  //#region src/runtime/componentInstance.ts
649
+ const ARRAY_INDEX_PATH_RE$1 = /\[(\d+)\]/g;
650
+ const ARRAY_INDEX_SEGMENT_RE$1 = /^\d+$/;
564
651
  function bindFunction$2(target, key, value) {
565
652
  if (typeof value !== "function") {
566
653
  target[key] = value;
@@ -577,10 +664,10 @@ function cloneValue(value) {
577
664
  return value;
578
665
  }
579
666
  function parseDataPath$1(path) {
580
- return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
667
+ return path.replace(ARRAY_INDEX_PATH_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
581
668
  }
582
669
  function isArrayIndexSegment$1(segment) {
583
- return /^\d+$/.test(segment);
670
+ return ARRAY_INDEX_SEGMENT_RE$1.test(segment);
584
671
  }
585
672
  function createContainerByNextSegment$1(nextSegment) {
586
673
  return isArrayIndexSegment$1(nextSegment ?? "") ? [] : {};
@@ -597,7 +684,7 @@ function assignByPath$1(target, path, value) {
597
684
  if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment$1(nextSegment);
598
685
  current = current[normalizedSegment];
599
686
  }
600
- const leafSegment = segments[segments.length - 1];
687
+ const leafSegment = segments.at(-1);
601
688
  const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
602
689
  current[normalizedLeafSegment] = value;
603
690
  }
@@ -717,7 +804,7 @@ function resolveInitialProperties(definition, properties) {
717
804
  const resolved = {};
718
805
  const propOptions = definition.properties;
719
806
  if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
720
- if (Object.prototype.hasOwnProperty.call(properties, key)) {
807
+ if (Object.hasOwn(properties, key)) {
721
808
  resolved[key] = coerceComponentPropertyValue(properties[key], option);
722
809
  continue;
723
810
  }
@@ -753,7 +840,7 @@ function resolveObservedValue(instance, pattern) {
753
840
  const segments = parseDataPath$1(pattern);
754
841
  if (segments.length === 0) return;
755
842
  const [rootSegment, ...restSegments] = segments;
756
- let current = (Object.prototype.hasOwnProperty.call(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
843
+ let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
757
844
  for (const segment of restSegments) {
758
845
  const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
759
846
  current = current?.[normalizedSegment];
@@ -851,7 +938,7 @@ const STRUCTURAL_ATTRS$1 = [
851
938
  "wx:key"
852
939
  ];
853
940
  const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
854
- const DATASET_NAME_RE$3 = /-([a-z])/g;
941
+ const DATASET_NAME_RE$4 = /-([a-z])/g;
855
942
  const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
856
943
  const CLASS_SPLIT_RE$1 = /\s+/;
857
944
  const JS_FILE_RE$1 = /\.js$/;
@@ -859,14 +946,14 @@ function isMustacheOnly$1(value) {
859
946
  const trimmed = value.trim();
860
947
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
861
948
  }
862
- function toDatasetKey$3(attributeName) {
863
- return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
949
+ function toDatasetKey$4(attributeName) {
950
+ return attributeName.slice(5).replace(DATASET_NAME_RE$4, (_match, char) => char.toUpperCase());
864
951
  }
865
- function collectDataset$3(node) {
952
+ function collectDataset$4(node) {
866
953
  const dataset = {};
867
954
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
868
955
  if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
869
- dataset[toDatasetKey$3(key)] = String(value);
956
+ dataset[toDatasetKey$4(key)] = String(value);
870
957
  }
871
958
  return dataset;
872
959
  }
@@ -1005,7 +1092,7 @@ function collectComponentEventBindings$1(hostNode) {
1005
1092
  return eventBindings;
1006
1093
  }
1007
1094
  function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1008
- const hostDataset = collectDataset$3(hostNode);
1095
+ const hostDataset = collectDataset$4(hostNode);
1009
1096
  const hostId = hostNode.attribs?.id ?? "";
1010
1097
  return (instance, eventName, detail, triggerOptions) => {
1011
1098
  const interactionTarget = instance.__lastInteractionEvent__?.target;
@@ -1186,6 +1273,8 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
1186
1273
  properties: nextProperties,
1187
1274
  triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1188
1275
  });
1276
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1277
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1189
1278
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1190
1279
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1191
1280
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
@@ -1201,7 +1290,7 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
1201
1290
  alias: clonedNode.name,
1202
1291
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1203
1292
  data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1204
- dataset: collectDataset$3(clonedNode),
1293
+ dataset: collectDataset$4(clonedNode),
1205
1294
  eventBindings: collectComponentEventBindings$1(clonedNode),
1206
1295
  getMethod: (methodName) => {
1207
1296
  const method = componentInstance?.[methodName];
@@ -1494,9 +1583,228 @@ const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1494
1583
  const TRAILING_SLASH_RE = /\/+$/;
1495
1584
  const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1496
1585
  const textEncoder = new TextEncoder();
1586
+ const IMAGE_EXTENSION_RE = /\.([^.?#/]+)(?:[?#].*)?$/;
1587
+ const LEADING_DOT_RE = /^\.+/;
1588
+ const IMAGE_FILE_EXTENSIONS = new Set([
1589
+ "bmp",
1590
+ "gif",
1591
+ "heic",
1592
+ "jpeg",
1593
+ "jpg",
1594
+ "png",
1595
+ "webp"
1596
+ ]);
1597
+ const VIDEO_FILE_EXTENSIONS = new Set([
1598
+ "avi",
1599
+ "m4v",
1600
+ "mov",
1601
+ "mp4",
1602
+ "mpeg",
1603
+ "mpg",
1604
+ "webm"
1605
+ ]);
1497
1606
  function byteLength(input) {
1498
1607
  return textEncoder.encode(input).byteLength;
1499
1608
  }
1609
+ function rotateLeft(value, bits) {
1610
+ return (value << bits | value >>> 32 - bits) >>> 0;
1611
+ }
1612
+ function toHexWordLittleEndian(value) {
1613
+ let output = "";
1614
+ for (let index = 0; index < 4; index += 1) output += (value >>> index * 8 & 255).toString(16).padStart(2, "0");
1615
+ return output;
1616
+ }
1617
+ function toHexWordBigEndian(value) {
1618
+ return value.toString(16).padStart(8, "0");
1619
+ }
1620
+ function computeMd5Digest(input) {
1621
+ const bytes = Array.from(textEncoder.encode(input));
1622
+ const bitLength = bytes.length * 8;
1623
+ const lowBits = bitLength >>> 0;
1624
+ const highBits = Math.floor(bitLength / 4294967296) >>> 0;
1625
+ bytes.push(128);
1626
+ while (bytes.length % 64 !== 56) bytes.push(0);
1627
+ for (let index = 0; index < 4; index += 1) bytes.push(lowBits >>> index * 8 & 255);
1628
+ for (let index = 0; index < 4; index += 1) bytes.push(highBits >>> index * 8 & 255);
1629
+ const shifts = [
1630
+ 7,
1631
+ 12,
1632
+ 17,
1633
+ 22,
1634
+ 7,
1635
+ 12,
1636
+ 17,
1637
+ 22,
1638
+ 7,
1639
+ 12,
1640
+ 17,
1641
+ 22,
1642
+ 7,
1643
+ 12,
1644
+ 17,
1645
+ 22,
1646
+ 5,
1647
+ 9,
1648
+ 14,
1649
+ 20,
1650
+ 5,
1651
+ 9,
1652
+ 14,
1653
+ 20,
1654
+ 5,
1655
+ 9,
1656
+ 14,
1657
+ 20,
1658
+ 5,
1659
+ 9,
1660
+ 14,
1661
+ 20,
1662
+ 4,
1663
+ 11,
1664
+ 16,
1665
+ 23,
1666
+ 4,
1667
+ 11,
1668
+ 16,
1669
+ 23,
1670
+ 4,
1671
+ 11,
1672
+ 16,
1673
+ 23,
1674
+ 4,
1675
+ 11,
1676
+ 16,
1677
+ 23,
1678
+ 6,
1679
+ 10,
1680
+ 15,
1681
+ 21,
1682
+ 6,
1683
+ 10,
1684
+ 15,
1685
+ 21,
1686
+ 6,
1687
+ 10,
1688
+ 15,
1689
+ 21,
1690
+ 6,
1691
+ 10,
1692
+ 15,
1693
+ 21
1694
+ ];
1695
+ const table = Array.from({ length: 64 }, (_, index) => Math.floor(Math.abs(Math.sin(index + 1)) * 4294967296) >>> 0);
1696
+ let a0 = 1732584193;
1697
+ let b0 = 4023233417;
1698
+ let c0 = 2562383102;
1699
+ let d0 = 271733878;
1700
+ for (let chunkOffset = 0; chunkOffset < bytes.length; chunkOffset += 64) {
1701
+ const words = Array.from({ length: 16 }, (_, index) => {
1702
+ const wordOffset = chunkOffset + index * 4;
1703
+ return (bytes[wordOffset] | bytes[wordOffset + 1] << 8 | bytes[wordOffset + 2] << 16 | bytes[wordOffset + 3] << 24) >>> 0;
1704
+ });
1705
+ let a = a0;
1706
+ let b = b0;
1707
+ let c = c0;
1708
+ let d = d0;
1709
+ for (let index = 0; index < 64; index += 1) {
1710
+ let f = 0;
1711
+ let g = 0;
1712
+ if (index < 16) {
1713
+ f = (b & c | ~b & d) >>> 0;
1714
+ g = index;
1715
+ } else if (index < 32) {
1716
+ f = (d & b | ~d & c) >>> 0;
1717
+ g = (5 * index + 1) % 16;
1718
+ } else if (index < 48) {
1719
+ f = (b ^ c ^ d) >>> 0;
1720
+ g = (3 * index + 5) % 16;
1721
+ } else {
1722
+ f = (c ^ (b | ~d)) >>> 0;
1723
+ g = 7 * index % 16;
1724
+ }
1725
+ const next = a + f + table[index] + words[g] >>> 0;
1726
+ a = d;
1727
+ d = c;
1728
+ c = b;
1729
+ b = b + rotateLeft(next, shifts[index]) >>> 0;
1730
+ }
1731
+ a0 = a0 + a >>> 0;
1732
+ b0 = b0 + b >>> 0;
1733
+ c0 = c0 + c >>> 0;
1734
+ d0 = d0 + d >>> 0;
1735
+ }
1736
+ return [
1737
+ toHexWordLittleEndian(a0),
1738
+ toHexWordLittleEndian(b0),
1739
+ toHexWordLittleEndian(c0),
1740
+ toHexWordLittleEndian(d0)
1741
+ ].join("");
1742
+ }
1743
+ function computeSha1Digest(input) {
1744
+ const bytes = Array.from(textEncoder.encode(input));
1745
+ const bitLength = bytes.length * 8;
1746
+ const lowBits = bitLength >>> 0;
1747
+ const highBits = Math.floor(bitLength / 4294967296) >>> 0;
1748
+ bytes.push(128);
1749
+ while (bytes.length % 64 !== 56) bytes.push(0);
1750
+ for (let index = 3; index >= 0; index -= 1) bytes.push(highBits >>> index * 8 & 255);
1751
+ for (let index = 3; index >= 0; index -= 1) bytes.push(lowBits >>> index * 8 & 255);
1752
+ let h0 = 1732584193;
1753
+ let h1 = 4023233417;
1754
+ let h2 = 2562383102;
1755
+ let h3 = 271733878;
1756
+ let h4 = 3285377520;
1757
+ for (let chunkOffset = 0; chunkOffset < bytes.length; chunkOffset += 64) {
1758
+ const words = Array.from({ length: 80 }, (_, index) => {
1759
+ if (index < 16) {
1760
+ const wordOffset = chunkOffset + index * 4;
1761
+ return (bytes[wordOffset] << 24 | bytes[wordOffset + 1] << 16 | bytes[wordOffset + 2] << 8 | bytes[wordOffset + 3]) >>> 0;
1762
+ }
1763
+ return 0;
1764
+ });
1765
+ for (let index = 16; index < 80; index += 1) words[index] = rotateLeft(words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16], 1);
1766
+ let a = h0;
1767
+ let b = h1;
1768
+ let c = h2;
1769
+ let d = h3;
1770
+ let e = h4;
1771
+ for (let index = 0; index < 80; index += 1) {
1772
+ let f = 0;
1773
+ let k = 0;
1774
+ if (index < 20) {
1775
+ f = (b & c | ~b & d) >>> 0;
1776
+ k = 1518500249;
1777
+ } else if (index < 40) {
1778
+ f = (b ^ c ^ d) >>> 0;
1779
+ k = 1859775393;
1780
+ } else if (index < 60) {
1781
+ f = (b & c | b & d | c & d) >>> 0;
1782
+ k = 2400959708;
1783
+ } else {
1784
+ f = (b ^ c ^ d) >>> 0;
1785
+ k = 3395469782;
1786
+ }
1787
+ const next = rotateLeft(a, 5) + f + e + k + words[index] >>> 0;
1788
+ e = d;
1789
+ d = c;
1790
+ c = rotateLeft(b, 30);
1791
+ b = a;
1792
+ a = next;
1793
+ }
1794
+ h0 = h0 + a >>> 0;
1795
+ h1 = h1 + b >>> 0;
1796
+ h2 = h2 + c >>> 0;
1797
+ h3 = h3 + d >>> 0;
1798
+ h4 = h4 + e >>> 0;
1799
+ }
1800
+ return [
1801
+ toHexWordBigEndian(h0),
1802
+ toHexWordBigEndian(h1),
1803
+ toHexWordBigEndian(h2),
1804
+ toHexWordBigEndian(h3),
1805
+ toHexWordBigEndian(h4)
1806
+ ].join("");
1807
+ }
1500
1808
  function cloneShareMenuSnapshot(snapshot) {
1501
1809
  return {
1502
1810
  isUpdatableMessage: snapshot.isUpdatableMessage,
@@ -1505,6 +1813,118 @@ function cloneShareMenuSnapshot(snapshot) {
1505
1813
  withShareTicket: snapshot.withShareTicket
1506
1814
  };
1507
1815
  }
1816
+ function normalizeImageType(type) {
1817
+ const normalized = (type ?? "").trim().toLowerCase();
1818
+ if (normalized === "jpg") return "jpeg";
1819
+ return normalized;
1820
+ }
1821
+ function normalizeFileExtension(extension) {
1822
+ return extension.trim().replace(LEADING_DOT_RE, "").toLowerCase();
1823
+ }
1824
+ function inferDocumentFileType(filePath) {
1825
+ const extensionMatch = filePath.match(IMAGE_EXTENSION_RE);
1826
+ return extensionMatch ? normalizeFileExtension(extensionMatch[1]) : "unknown";
1827
+ }
1828
+ function isImageFileExtension(extension) {
1829
+ return IMAGE_FILE_EXTENSIONS.has(normalizeFileExtension(extension));
1830
+ }
1831
+ function isVideoFileExtension(extension) {
1832
+ return VIDEO_FILE_EXTENSIONS.has(normalizeFileExtension(extension));
1833
+ }
1834
+ function resolveMessageFileExtensions(option) {
1835
+ const filteredExtensions = (Array.isArray(option.extension) ? option.extension.filter((item) => typeof item === "string").map(normalizeFileExtension).filter(Boolean) : []).filter((extension) => {
1836
+ if (option.type === "image") return isImageFileExtension(extension);
1837
+ if (option.type === "video") return isVideoFileExtension(extension);
1838
+ if (option.type === "file") return !isImageFileExtension(extension) && !isVideoFileExtension(extension);
1839
+ return true;
1840
+ });
1841
+ if (filteredExtensions.length > 0) return filteredExtensions;
1842
+ if (option.type === "image") return ["png", "jpg"];
1843
+ if (option.type === "video") return ["mp4"];
1844
+ if (option.type === "file") return [
1845
+ "txt",
1846
+ "pdf",
1847
+ "doc"
1848
+ ];
1849
+ return [
1850
+ "png",
1851
+ "pdf",
1852
+ "mp4"
1853
+ ];
1854
+ }
1855
+ function inferImageType(filePath, fileContent) {
1856
+ const extensionMatch = filePath.match(IMAGE_EXTENSION_RE);
1857
+ if (extensionMatch) return normalizeImageType(extensionMatch[1]);
1858
+ try {
1859
+ return normalizeImageType(JSON.parse(fileContent)?.config?.fileType) || "png";
1860
+ } catch {
1861
+ return "unknown";
1862
+ }
1863
+ }
1864
+ function inferImageSize(fileContent) {
1865
+ try {
1866
+ const config = JSON.parse(fileContent)?.config;
1867
+ const destHeight = config && "destHeight" in config ? config.destHeight : void 0;
1868
+ const destWidth = config && "destWidth" in config ? config.destWidth : void 0;
1869
+ return {
1870
+ height: destHeight ?? config?.height ?? 0,
1871
+ width: destWidth ?? config?.width ?? 0
1872
+ };
1873
+ } catch {
1874
+ return {
1875
+ height: 0,
1876
+ width: 0
1877
+ };
1878
+ }
1879
+ }
1880
+ function buildImageTempFilePayload(fileType, width, height, metadata = {}) {
1881
+ return JSON.stringify({ config: {
1882
+ fileType,
1883
+ height,
1884
+ quality: metadata.quality,
1885
+ sizeType: metadata.sizeType ?? [],
1886
+ sourceType: metadata.sourceType ?? [],
1887
+ width
1888
+ } });
1889
+ }
1890
+ function buildVideoTempFilePayload(width, height, duration, metadata = {}) {
1891
+ return JSON.stringify({ config: {
1892
+ bitrate: metadata.bitrate ?? 1500,
1893
+ compressed: metadata.compressed ?? true,
1894
+ duration,
1895
+ fps: metadata.fps ?? 30,
1896
+ height,
1897
+ maxDuration: metadata.maxDuration ?? duration,
1898
+ sourceType: metadata.sourceType ?? [],
1899
+ width
1900
+ } });
1901
+ }
1902
+ function inferVideoInfo(filePath, fileContent) {
1903
+ const size = byteLength(fileContent);
1904
+ const type = filePath.match(IMAGE_EXTENSION_RE)?.[1]?.toLowerCase() ?? "mp4";
1905
+ try {
1906
+ const payload = JSON.parse(fileContent);
1907
+ return {
1908
+ bitrate: payload.config.bitrate ?? 1500,
1909
+ duration: payload.config.duration ?? 0,
1910
+ fps: payload.config.fps ?? 30,
1911
+ height: payload.config.height ?? 0,
1912
+ size,
1913
+ type,
1914
+ width: payload.config.width ?? 0
1915
+ };
1916
+ } catch {
1917
+ return {
1918
+ bitrate: 1500,
1919
+ duration: 0,
1920
+ fps: 30,
1921
+ height: 0,
1922
+ size,
1923
+ type,
1924
+ width: 0
1925
+ };
1926
+ }
1927
+ }
1508
1928
  function createNetworkSnapshot(networkType) {
1509
1929
  return {
1510
1930
  isConnected: networkType !== "none",
@@ -1655,6 +2075,9 @@ function createHeadlessWxState() {
1655
2075
  let fileId = 0;
1656
2076
  let loading = null;
1657
2077
  let networkType = "wifi";
2078
+ let previewImage = null;
2079
+ let openedDocument = null;
2080
+ let clipboardData = "";
1658
2081
  let shareMenu = {
1659
2082
  isUpdatableMessage: false,
1660
2083
  menus: [],
@@ -1856,6 +2279,16 @@ function createHeadlessWxState() {
1856
2279
  size: savedFile.size
1857
2280
  };
1858
2281
  };
2282
+ const getFileInfo = (option) => {
2283
+ const normalizedPath = normalizeFsPath(option.filePath);
2284
+ const fileContent = files.get(normalizedPath);
2285
+ if (fileContent == null) throw new Error(`getFileInfo:fail no such file or directory, stat '${normalizedPath}'`);
2286
+ return {
2287
+ digest: (option.digestAlgorithm === "sha1" ? "sha1" : "md5") === "sha1" ? computeSha1Digest(fileContent) : computeMd5Digest(fileContent),
2288
+ errMsg: "getFileInfo:ok",
2289
+ size: byteLength(fileContent)
2290
+ };
2291
+ };
1859
2292
  const removeSavedFile = (filePath) => {
1860
2293
  const normalizedPath = normalizeFsPath(filePath);
1861
2294
  if (!savedFiles.has(normalizedPath)) throw new Error(`removeSavedFile:fail no such file or directory, unlink '${normalizedPath}'`);
@@ -2106,18 +2539,191 @@ function createHeadlessWxState() {
2106
2539
  getSavedFileInfo(option) {
2107
2540
  return getSavedFileInfo(option.filePath);
2108
2541
  },
2542
+ getFileInfo(option) {
2543
+ return getFileInfo(option);
2544
+ },
2109
2545
  getSavedFileList() {
2110
2546
  return getSavedFileList();
2111
2547
  },
2112
2548
  getFileText(filePath) {
2113
2549
  return files.get(filePath) ?? null;
2114
2550
  },
2551
+ createTempFile(fileContent, preferredPath) {
2552
+ const tempFilePath = allocateFilePath("temp", preferredPath);
2553
+ ensureDirectoryTree(tempFilePath);
2554
+ files.set(tempFilePath, String(fileContent));
2555
+ return tempFilePath;
2556
+ },
2557
+ chooseImage(option) {
2558
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(9, Math.trunc(option.count ?? 1))) : 9;
2559
+ const sizeType = Array.isArray(option.sizeType) && option.sizeType.length > 0 ? option.sizeType.filter((item) => typeof item === "string") : ["original"];
2560
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2561
+ const fileType = sizeType.includes("compressed") ? "jpg" : "png";
2562
+ const tempFiles = Array.from({ length: count }, (_, index) => {
2563
+ const payload = buildImageTempFilePayload(fileType, 160 + index * 12, 120 + index * 8, {
2564
+ sizeType: [...sizeType],
2565
+ sourceType: [...sourceType]
2566
+ });
2567
+ return {
2568
+ path: this.createTempFile(payload, `headless://wxfile/temp/chosen-image-${String(index + 1).padStart(2, "0")}.${fileType}`),
2569
+ size: payload.length
2570
+ };
2571
+ });
2572
+ return {
2573
+ errMsg: "chooseImage:ok",
2574
+ tempFilePaths: tempFiles.map((item) => item.path),
2575
+ tempFiles
2576
+ };
2577
+ },
2578
+ chooseMessageFile(option) {
2579
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(100, Math.trunc(option.count ?? 1))) : 1;
2580
+ const extensions = resolveMessageFileExtensions(option);
2581
+ return {
2582
+ errMsg: "chooseMessageFile:ok",
2583
+ tempFiles: Array.from({ length: count }, (_, index) => {
2584
+ const extension = extensions[index % extensions.length];
2585
+ const sequence = String(index + 1).padStart(2, "0");
2586
+ const fileName = `message-file-${sequence}.${extension}`;
2587
+ let fileContent = `headless message file ${fileName}`;
2588
+ if (isImageFileExtension(extension)) fileContent = buildImageTempFilePayload(extension, 160 + index * 12, 120 + index * 8, { sourceType: ["message"] });
2589
+ else if (isVideoFileExtension(extension)) fileContent = buildVideoTempFilePayload(640, 360, 18 + index, {
2590
+ compressed: true,
2591
+ sourceType: ["message"]
2592
+ });
2593
+ return {
2594
+ name: fileName,
2595
+ path: this.createTempFile(fileContent, `headless://wxfile/temp/chosen-message-file-${sequence}.${extension}`),
2596
+ size: byteLength(fileContent),
2597
+ time: 171e10 + index * 1e3,
2598
+ type: extension
2599
+ };
2600
+ })
2601
+ };
2602
+ },
2603
+ chooseMedia(option) {
2604
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(9, Math.trunc(option.count ?? 1))) : 1;
2605
+ const mediaTypes = Array.isArray(option.mediaType) && option.mediaType.length > 0 ? option.mediaType.filter((item) => item === "image" || item === "video") : ["image"];
2606
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2607
+ const sizeType = Array.isArray(option.sizeType) && option.sizeType.length > 0 ? option.sizeType.filter((item) => typeof item === "string") : ["compressed"];
2608
+ const maxDuration = Number.isFinite(option.maxDuration) ? Math.max(1, Math.trunc(option.maxDuration ?? 60)) : 60;
2609
+ return {
2610
+ errMsg: "chooseMedia:ok",
2611
+ tempFiles: Array.from({ length: count }, (_, index) => {
2612
+ if (mediaTypes[index % mediaTypes.length] === "video") {
2613
+ const duration = Math.min(maxDuration, 18 + index);
2614
+ const width = 640;
2615
+ const height = 360;
2616
+ const payload = buildVideoTempFilePayload(width, height, duration, {
2617
+ compressed: sizeType.includes("compressed"),
2618
+ maxDuration,
2619
+ sourceType: [...sourceType]
2620
+ });
2621
+ const tempFilePath = this.createTempFile(payload, `headless://wxfile/temp/chosen-media-video-${String(index + 1).padStart(2, "0")}.mp4`);
2622
+ const thumbPayload = buildImageTempFilePayload("jpg", 160, 90, {
2623
+ sizeType: ["compressed"],
2624
+ sourceType: [...sourceType]
2625
+ });
2626
+ const thumbTempFilePath = this.createTempFile(thumbPayload, `headless://wxfile/temp/chosen-media-video-thumb-${String(index + 1).padStart(2, "0")}.jpg`);
2627
+ return {
2628
+ duration,
2629
+ fileType: "video",
2630
+ height,
2631
+ size: payload.length,
2632
+ tempFilePath,
2633
+ thumbTempFilePath,
2634
+ width
2635
+ };
2636
+ }
2637
+ const width = 160 + index * 12;
2638
+ const height = 120 + index * 8;
2639
+ const fileType = sizeType.includes("compressed") ? "jpg" : "png";
2640
+ const payload = buildImageTempFilePayload(fileType, width, height, {
2641
+ sizeType: [...sizeType],
2642
+ sourceType: [...sourceType]
2643
+ });
2644
+ return {
2645
+ fileType: "image",
2646
+ height,
2647
+ size: payload.length,
2648
+ tempFilePath: this.createTempFile(payload, `headless://wxfile/temp/chosen-media-image-${String(index + 1).padStart(2, "0")}.${fileType}`),
2649
+ width
2650
+ };
2651
+ }),
2652
+ type: mediaTypes.length > 1 ? "mix" : mediaTypes[0] ?? "image"
2653
+ };
2654
+ },
2655
+ chooseVideo(option) {
2656
+ const compressed = option.compressed !== false;
2657
+ const maxDuration = Number.isFinite(option.maxDuration) ? Math.max(1, Math.trunc(option.maxDuration ?? 60)) : 60;
2658
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2659
+ const payload = JSON.stringify({ config: {
2660
+ compressed,
2661
+ duration: Math.min(maxDuration, compressed ? 18 : 36),
2662
+ height: compressed ? 360 : 720,
2663
+ maxDuration,
2664
+ sourceType: [...sourceType],
2665
+ width: compressed ? 640 : 1280
2666
+ } });
2667
+ const tempFilePath = this.createTempFile(payload, "headless://wxfile/temp/chosen-video-01.mp4");
2668
+ return {
2669
+ duration: Math.min(maxDuration, compressed ? 18 : 36),
2670
+ errMsg: "chooseVideo:ok",
2671
+ height: compressed ? 360 : 720,
2672
+ size: payload.length,
2673
+ tempFilePath,
2674
+ width: compressed ? 640 : 1280
2675
+ };
2676
+ },
2677
+ compressImage(option) {
2678
+ const fileContent = files.get(option.src);
2679
+ if (fileContent == null) throw new Error(`compressImage:fail file not found: ${option.src}`);
2680
+ const sourceSize = inferImageSize(fileContent);
2681
+ const sourceType = inferImageType(option.src, fileContent);
2682
+ const width = Number.isFinite(option.compressedWidth) ? Math.max(1, Math.trunc(option.compressedWidth ?? sourceSize.width)) : Math.max(1, sourceSize.width);
2683
+ const height = Number.isFinite(option.compressedHeight) ? Math.max(1, Math.trunc(option.compressedHeight ?? sourceSize.height)) : Math.max(1, sourceSize.height);
2684
+ const normalizedType = sourceType === "unknown" ? "jpg" : sourceType;
2685
+ const fileExtension = normalizedType === "jpeg" ? "jpg" : normalizedType;
2686
+ const payload = buildImageTempFilePayload(normalizedType, width, height, { quality: Number.isFinite(option.quality) ? Number(option.quality) : void 0 });
2687
+ return {
2688
+ errMsg: "compressImage:ok",
2689
+ tempFilePath: this.createTempFile(payload, `headless://wxfile/temp/compressed-image-${String(fileId + 1).padStart(2, "0")}.${fileExtension}`)
2690
+ };
2691
+ },
2115
2692
  getNetworkType() {
2116
2693
  return {
2117
2694
  errMsg: "getNetworkType:ok",
2118
2695
  networkType
2119
2696
  };
2120
2697
  },
2698
+ getImageInfo(option) {
2699
+ const fileContent = files.get(option.src);
2700
+ if (fileContent == null) throw new Error(`getImageInfo:fail file not found: ${option.src}`);
2701
+ const size = inferImageSize(fileContent);
2702
+ return {
2703
+ errMsg: "getImageInfo:ok",
2704
+ height: size.height,
2705
+ orientation: "up",
2706
+ path: option.src,
2707
+ type: inferImageType(option.src, fileContent),
2708
+ width: size.width
2709
+ };
2710
+ },
2711
+ getVideoInfo(option) {
2712
+ const fileContent = files.get(option.src);
2713
+ if (fileContent == null) throw new Error(`getVideoInfo:fail file not found: ${option.src}`);
2714
+ const info = inferVideoInfo(option.src, fileContent);
2715
+ return {
2716
+ bitrate: info.bitrate,
2717
+ duration: info.duration,
2718
+ errMsg: "getVideoInfo:ok",
2719
+ fps: info.fps,
2720
+ height: info.height,
2721
+ orientation: "up",
2722
+ size: info.size,
2723
+ type: info.type,
2724
+ width: info.width
2725
+ };
2726
+ },
2121
2727
  getModalLogs() {
2122
2728
  return modalLogs.map((entry) => ({
2123
2729
  ...entry,
@@ -2152,6 +2758,15 @@ function createHeadlessWxState() {
2152
2758
  getStorageSnapshot() {
2153
2759
  return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
2154
2760
  },
2761
+ getClipboardData() {
2762
+ return {
2763
+ data: clipboardData,
2764
+ errMsg: "getClipboardData:ok"
2765
+ };
2766
+ },
2767
+ getClipboardSnapshot() {
2768
+ return { data: clipboardData };
2769
+ },
2155
2770
  getStorageSync(key) {
2156
2771
  return cloneValue$1(storage.get(key));
2157
2772
  },
@@ -2161,6 +2776,21 @@ function createHeadlessWxState() {
2161
2776
  getLoading() {
2162
2777
  return loading ? { ...loading } : null;
2163
2778
  },
2779
+ getPreviewImage() {
2780
+ return previewImage ? {
2781
+ current: previewImage.current,
2782
+ urls: [...previewImage.urls],
2783
+ visible: previewImage.visible
2784
+ } : null;
2785
+ },
2786
+ getOpenedDocument() {
2787
+ return openedDocument ? {
2788
+ filePath: openedDocument.filePath,
2789
+ fileType: openedDocument.fileType,
2790
+ showMenu: openedDocument.showMenu,
2791
+ visible: openedDocument.visible
2792
+ } : null;
2793
+ },
2164
2794
  hideShareMenu() {
2165
2795
  shareMenu = {
2166
2796
  ...shareMenu,
@@ -2230,6 +2860,27 @@ function createHeadlessWxState() {
2230
2860
  onNetworkStatusChange(callback) {
2231
2861
  networkStatusChangeCallbacks.add(callback);
2232
2862
  },
2863
+ openDocument(option) {
2864
+ const normalizedPath = normalizeFsPath(option.filePath);
2865
+ if (!files.has(normalizedPath)) throw new Error(`openDocument:fail no such file or directory, open '${normalizedPath}'`);
2866
+ openedDocument = {
2867
+ filePath: normalizedPath,
2868
+ fileType: typeof option.fileType === "string" && option.fileType.trim() !== "" ? normalizeFileExtension(option.fileType) : inferDocumentFileType(normalizedPath),
2869
+ showMenu: option.showMenu !== false,
2870
+ visible: true
2871
+ };
2872
+ return { errMsg: "openDocument:ok" };
2873
+ },
2874
+ previewImage(option) {
2875
+ const urls = Array.isArray(option.urls) ? option.urls.filter((item) => typeof item === "string" && item.trim() !== "") : [];
2876
+ if (urls.length === 0) throw new Error("previewImage:fail invalid urls");
2877
+ previewImage = {
2878
+ current: typeof option.current === "string" && option.current.trim() !== "" ? option.current : urls[0],
2879
+ urls: [...urls],
2880
+ visible: true
2881
+ };
2882
+ return { errMsg: "previewImage:ok" };
2883
+ },
2233
2884
  removeStorageSync(key) {
2234
2885
  storage.delete(key);
2235
2886
  },
@@ -2277,6 +2928,14 @@ function createHeadlessWxState() {
2277
2928
  removeSavedFile(option) {
2278
2929
  return removeSavedFile(option.filePath);
2279
2930
  },
2931
+ saveImageToPhotosAlbum(option) {
2932
+ if (files.get(option.filePath) == null) throw new Error(`saveImageToPhotosAlbum:fail file not found: ${option.filePath}`);
2933
+ return { errMsg: "saveImageToPhotosAlbum:ok" };
2934
+ },
2935
+ saveVideoToPhotosAlbum(option) {
2936
+ if (files.get(option.filePath) == null) throw new Error(`saveVideoToPhotosAlbum:fail file not found: ${option.filePath}`);
2937
+ return { errMsg: "saveVideoToPhotosAlbum:ok" };
2938
+ },
2280
2939
  saveFile(option) {
2281
2940
  const fileContent = files.get(option.tempFilePath);
2282
2941
  if (fileContent == null) throw new Error(`saveFile:fail tempFilePath not found: ${option.tempFilePath}`);
@@ -2292,6 +2951,10 @@ function createHeadlessWxState() {
2292
2951
  setStorageSync(key, value) {
2293
2952
  storage.set(key, cloneValue$1(value));
2294
2953
  },
2954
+ setClipboardData(option) {
2955
+ clipboardData = String(option.data);
2956
+ return { errMsg: "setClipboardData:ok" };
2957
+ },
2295
2958
  setFile(filePath, fileContent) {
2296
2959
  const normalizedPath = normalizeFsPath(filePath);
2297
2960
  ensureDirectoryTree(normalizedPath);
@@ -2486,22 +3149,22 @@ function querySelectorAll(root, selector) {
2486
3149
  }
2487
3150
  //#endregion
2488
3151
  //#region src/view/nodeHandle.ts
2489
- const DATASET_NAME_RE$2 = /-([a-z])/g;
3152
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
2490
3153
  function escapeText$2(text) {
2491
3154
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2492
3155
  }
2493
- function toDatasetKey$2(attributeName) {
2494
- return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
3156
+ function toDatasetKey$3(attributeName) {
3157
+ return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
2495
3158
  }
2496
- function collectDataset$2(node) {
3159
+ function collectDataset$3(node) {
2497
3160
  const dataset = {};
2498
3161
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2499
3162
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2500
- dataset[toDatasetKey$2(key)] = value;
3163
+ dataset[toDatasetKey$3(key)] = value;
2501
3164
  }
2502
3165
  return dataset;
2503
3166
  }
2504
- function resolveEventBinding(node, eventName) {
3167
+ function resolveEventBinding$1(node, eventName) {
2505
3168
  const normalizedEventName = eventName.trim();
2506
3169
  if (!normalizedEventName) return null;
2507
3170
  const bindingAttrs = [
@@ -2516,8 +3179,8 @@ function resolveEventBinding(node, eventName) {
2516
3179
  }
2517
3180
  return null;
2518
3181
  }
2519
- function createEventPayload(node, eventName, event) {
2520
- const dataset = collectDataset$2(node);
3182
+ function createEventPayload$1(node, eventName, event) {
3183
+ const dataset = collectDataset$3(node);
2521
3184
  const nodeId = node.attribs?.id ?? "";
2522
3185
  return {
2523
3186
  bubbles: false,
@@ -2582,7 +3245,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2582
3245
  return this.node.attribs?.[name];
2583
3246
  }
2584
3247
  async dataset() {
2585
- return collectDataset$2(this.node);
3248
+ return collectDataset$3(this.node);
2586
3249
  }
2587
3250
  async scope() {
2588
3251
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
@@ -2612,9 +3275,9 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2612
3275
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2613
3276
  const normalizedEventName = eventName.trim();
2614
3277
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
2615
- const methodName = resolveEventBinding(this.node, normalizedEventName);
3278
+ const methodName = resolveEventBinding$1(this.node, normalizedEventName);
2616
3279
  if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
2617
- return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(this.node, normalizedEventName, event));
3280
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload$1(this.node, normalizedEventName, event));
2618
3281
  }
2619
3282
  async tap(event = {}) {
2620
3283
  return await this.trigger("tap", event);
@@ -2698,18 +3361,18 @@ function renderPageTree(project, page) {
2698
3361
  }
2699
3362
  //#endregion
2700
3363
  //#region src/view/selectorQuery.ts
2701
- const DATASET_NAME_RE$1 = /-([a-z])/g;
3364
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
2702
3365
  const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2703
3366
  const MARK_NAME_RE = /[:\-]([a-z])/g;
2704
- const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2705
- function toDatasetKey$1(attributeName) {
2706
- return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
3367
+ const NUMERIC_LIKE_VALUE_RE$1 = /-?\d+(?:\.\d+)?/;
3368
+ function toDatasetKey$2(attributeName) {
3369
+ return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
2707
3370
  }
2708
- function collectDataset$1(node) {
3371
+ function collectDataset$2(node) {
2709
3372
  const dataset = {};
2710
3373
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2711
3374
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2712
- dataset[toDatasetKey$1(key)] = value;
3375
+ dataset[toDatasetKey$2(key)] = value;
2713
3376
  }
2714
3377
  return dataset;
2715
3378
  }
@@ -2738,7 +3401,7 @@ function findNodeByScopeId(root, scopeId) {
2738
3401
  }
2739
3402
  return null;
2740
3403
  }
2741
- function parseStyleDeclarations(styleValue) {
3404
+ function parseStyleDeclarations$1(styleValue) {
2742
3405
  const declarations = {};
2743
3406
  if (!styleValue) return declarations;
2744
3407
  for (const declaration of styleValue.split(";")) {
@@ -2749,17 +3412,17 @@ function parseStyleDeclarations(styleValue) {
2749
3412
  }
2750
3413
  return declarations;
2751
3414
  }
2752
- function parseNumericLikeValue(value) {
3415
+ function parseNumericLikeValue$1(value) {
2753
3416
  if (!value) return 0;
2754
- const match = value.match(NUMERIC_LIKE_VALUE_RE);
3417
+ const match = value.match(NUMERIC_LIKE_VALUE_RE$1);
2755
3418
  return match ? Number(match[0]) : 0;
2756
3419
  }
2757
- function resolveRect(node) {
2758
- const style = parseStyleDeclarations(node.attribs?.style);
2759
- const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2760
- const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2761
- const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2762
- const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
3420
+ function resolveRect$1(node) {
3421
+ const style = parseStyleDeclarations$1(node.attribs?.style);
3422
+ const left = parseNumericLikeValue$1(node.attribs?.["data-sim-left"] ?? style.left);
3423
+ const top = parseNumericLikeValue$1(node.attribs?.["data-sim-top"] ?? style.top);
3424
+ const width = parseNumericLikeValue$1(node.attribs?.["data-sim-width"] ?? style.width);
3425
+ const height = parseNumericLikeValue$1(node.attribs?.["data-sim-height"] ?? style.height);
2763
3426
  return {
2764
3427
  bottom: top + height,
2765
3428
  height,
@@ -2773,12 +3436,12 @@ function resolveSelectorScrollTop(root, selector) {
2773
3436
  const normalizedSelector = selector?.trim();
2774
3437
  if (!normalizedSelector) return null;
2775
3438
  const match = querySelectorAll(root, normalizedSelector)[0];
2776
- return match ? resolveRect(match).top : null;
3439
+ return match ? resolveRect$1(match).top : null;
2777
3440
  }
2778
3441
  function resolveScrollOffset(node) {
2779
3442
  return {
2780
- scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2781
- scrollTop: parseNumericLikeValue(node.attribs?.["data-sim-scroll-top"])
3443
+ scrollLeft: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-left"]),
3444
+ scrollTop: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-top"])
2782
3445
  };
2783
3446
  }
2784
3447
  function resolvePropertyValue(node, propertyName) {
@@ -2786,7 +3449,7 @@ function resolvePropertyValue(node, propertyName) {
2786
3449
  if (!normalizedPropertyName) return;
2787
3450
  if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2788
3451
  if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2789
- if (normalizedPropertyName === "dataset") return collectDataset$1(node);
3452
+ if (normalizedPropertyName === "dataset") return collectDataset$2(node);
2790
3453
  return node.attribs?.[normalizedPropertyName];
2791
3454
  }
2792
3455
  function pickProperties(node, propertyNames) {
@@ -2795,18 +3458,18 @@ function pickProperties(node, propertyNames) {
2795
3458
  return result;
2796
3459
  }
2797
3460
  function pickComputedStyle(node, propertyNames) {
2798
- const style = parseStyleDeclarations(node.attribs?.style);
3461
+ const style = parseStyleDeclarations$1(node.attribs?.style);
2799
3462
  const result = {};
2800
3463
  for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2801
3464
  return result;
2802
3465
  }
2803
- function resolveFieldsResult(node, fields, _options) {
3466
+ function resolveFieldsResult(node, fields, options) {
2804
3467
  const result = {};
2805
3468
  if (fields.id) result.id = node.attribs?.id ?? "";
2806
- if (fields.dataset) result.dataset = collectDataset$1(node);
3469
+ if (fields.dataset) result.dataset = collectDataset$2(node);
2807
3470
  if (fields.mark) result.mark = collectMark(node);
2808
3471
  if (fields.rect || fields.size) {
2809
- const rect = resolveRect(node);
3472
+ const rect = resolveRect$1(node);
2810
3473
  if (fields.rect) Object.assign(result, rect);
2811
3474
  if (fields.size) {
2812
3475
  result.width = rect.width;
@@ -2816,7 +3479,7 @@ function resolveFieldsResult(node, fields, _options) {
2816
3479
  if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2817
3480
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2818
3481
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2819
- if (fields.context) result.context = { type: "unsupported-context" };
3482
+ if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
2820
3483
  if (fields.node) result.node = { type: node.name ?? "unknown" };
2821
3484
  return result;
2822
3485
  }
@@ -2859,6 +3522,749 @@ function resolveSelectorQueryScopeRoot(root, scopeId) {
2859
3522
  return scopedNode ? createScopedRoot(scopedNode) : root;
2860
3523
  }
2861
3524
  //#endregion
3525
+ //#region src/view/animation.ts
3526
+ const DEFAULT_STEP_OPTION = {
3527
+ delay: 0,
3528
+ duration: 400,
3529
+ timingFunction: "linear",
3530
+ transformOrigin: "50% 50% 0"
3531
+ };
3532
+ function normalizeStepOption(option) {
3533
+ return {
3534
+ delay: option?.delay ?? DEFAULT_STEP_OPTION.delay,
3535
+ duration: option?.duration ?? DEFAULT_STEP_OPTION.duration,
3536
+ timingFunction: option?.timingFunction ?? DEFAULT_STEP_OPTION.timingFunction,
3537
+ transformOrigin: option?.transformOrigin ?? DEFAULT_STEP_OPTION.transformOrigin
3538
+ };
3539
+ }
3540
+ function normalizeLength(value) {
3541
+ if (typeof value === "number") return `${value}px`;
3542
+ return value ?? "0px";
3543
+ }
3544
+ function createAction(type, args) {
3545
+ return {
3546
+ args,
3547
+ type
3548
+ };
3549
+ }
3550
+ function createHeadlessAnimation(defaultOption) {
3551
+ const baseOption = normalizeStepOption(defaultOption);
3552
+ let currentActions = [];
3553
+ let queue = [];
3554
+ let animation;
3555
+ const append = (type, args) => {
3556
+ currentActions.push(createAction(type, args));
3557
+ return animation;
3558
+ };
3559
+ animation = {
3560
+ backgroundColor(value) {
3561
+ return append("backgroundColor", [value]);
3562
+ },
3563
+ bottom(value) {
3564
+ return append("bottom", [normalizeLength(value)]);
3565
+ },
3566
+ export() {
3567
+ const exported = queue.map((item) => ({
3568
+ animates: item.animates.map((action) => ({
3569
+ args: [...action.args],
3570
+ type: action.type
3571
+ })),
3572
+ option: { ...item.option }
3573
+ }));
3574
+ queue = [];
3575
+ currentActions = [];
3576
+ return { actions: exported };
3577
+ },
3578
+ height(value) {
3579
+ return append("height", [normalizeLength(value)]);
3580
+ },
3581
+ left(value) {
3582
+ return append("left", [normalizeLength(value)]);
3583
+ },
3584
+ opacity(value) {
3585
+ return append("opacity", [value]);
3586
+ },
3587
+ right(value) {
3588
+ return append("right", [normalizeLength(value)]);
3589
+ },
3590
+ rotate(angle) {
3591
+ return append("rotate", [`${angle}deg`]);
3592
+ },
3593
+ scale(sx, sy) {
3594
+ return append("scale", [sx, sy ?? sx]);
3595
+ },
3596
+ step(option) {
3597
+ queue.push({
3598
+ animates: currentActions.map((action) => ({
3599
+ args: [...action.args],
3600
+ type: action.type
3601
+ })),
3602
+ option: {
3603
+ ...baseOption,
3604
+ ...option ?? {}
3605
+ }
3606
+ });
3607
+ currentActions = [];
3608
+ return animation;
3609
+ },
3610
+ top(value) {
3611
+ return append("top", [normalizeLength(value)]);
3612
+ },
3613
+ translate(tx, ty) {
3614
+ return append("translate", [normalizeLength(tx), normalizeLength(ty)]);
3615
+ },
3616
+ translate3d(tx, ty, tz) {
3617
+ return append("translate3d", [
3618
+ normalizeLength(tx),
3619
+ normalizeLength(ty),
3620
+ normalizeLength(tz)
3621
+ ]);
3622
+ },
3623
+ translateX(translation) {
3624
+ return append("translateX", [normalizeLength(translation)]);
3625
+ },
3626
+ translateY(translation) {
3627
+ return append("translateY", [normalizeLength(translation)]);
3628
+ },
3629
+ translateZ(translation) {
3630
+ return append("translateZ", [normalizeLength(translation)]);
3631
+ },
3632
+ width(value) {
3633
+ return append("width", [normalizeLength(value)]);
3634
+ }
3635
+ };
3636
+ return animation;
3637
+ }
3638
+ //#endregion
3639
+ //#region src/view/canvasContext.ts
3640
+ function findCanvasNode(root, canvasId) {
3641
+ if (root.type === "tag" && root.name === "canvas" && root.attribs?.["canvas-id"] === canvasId) return root;
3642
+ for (const child of root.children ?? []) {
3643
+ const match = findCanvasNode(child, canvasId);
3644
+ if (match) return match;
3645
+ }
3646
+ return null;
3647
+ }
3648
+ function cloneCall(call) {
3649
+ return {
3650
+ args: call.args.map((arg) => Array.isArray(arg) ? [...arg] : arg),
3651
+ type: call.type
3652
+ };
3653
+ }
3654
+ function createHeadlessCanvasContext(driver, canvasId, scope) {
3655
+ const defaultState = {
3656
+ fillStyle: "#000000",
3657
+ fontSize: 16,
3658
+ globalAlpha: 1,
3659
+ lineCap: "butt",
3660
+ lineDash: [],
3661
+ lineDashOffset: 0,
3662
+ lineJoin: "miter",
3663
+ miterLimit: 10,
3664
+ lineWidth: 1,
3665
+ shadowBlur: 0,
3666
+ shadowColor: "#000000",
3667
+ shadowOffsetX: 0,
3668
+ shadowOffsetY: 0,
3669
+ strokeStyle: "#000000",
3670
+ textAlign: "start",
3671
+ textBaseline: "alphabetic"
3672
+ };
3673
+ let state = { ...defaultState };
3674
+ let stateStack = [];
3675
+ let drawCalls = [];
3676
+ let snapshot = {
3677
+ canvasId,
3678
+ drawCalls: [],
3679
+ fillStyle: state.fillStyle,
3680
+ fontSize: state.fontSize,
3681
+ globalAlpha: state.globalAlpha,
3682
+ lineCap: state.lineCap,
3683
+ lineDash: [...state.lineDash],
3684
+ lineDashOffset: state.lineDashOffset,
3685
+ lineJoin: state.lineJoin,
3686
+ miterLimit: state.miterLimit,
3687
+ lineWidth: state.lineWidth,
3688
+ reserve: false,
3689
+ shadowBlur: state.shadowBlur,
3690
+ shadowColor: state.shadowColor,
3691
+ shadowOffsetX: state.shadowOffsetX,
3692
+ shadowOffsetY: state.shadowOffsetY,
3693
+ strokeStyle: state.strokeStyle,
3694
+ textAlign: state.textAlign,
3695
+ textBaseline: state.textBaseline
3696
+ };
3697
+ const resolveCanvas = () => {
3698
+ const scopeResolution = driver.resolveScope(scope);
3699
+ if (scopeResolution.kind === "missing") return null;
3700
+ const rendered = driver.renderCurrentPage();
3701
+ const root = scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root;
3702
+ return root ? findCanvasNode(root, canvasId) : null;
3703
+ };
3704
+ const ensureCanvas = () => {
3705
+ const node = resolveCanvas();
3706
+ if (!node) throw new Error(`Canvas with canvas-id "${canvasId}" was not found in headless runtime.`);
3707
+ return node;
3708
+ };
3709
+ const record = (type, args) => {
3710
+ ensureCanvas();
3711
+ drawCalls.push({
3712
+ args,
3713
+ type
3714
+ });
3715
+ };
3716
+ return {
3717
+ arc(x, y, r, sAngle, eAngle, counterclockwise) {
3718
+ record("arc", [
3719
+ x,
3720
+ y,
3721
+ r,
3722
+ sAngle,
3723
+ eAngle,
3724
+ Boolean(counterclockwise)
3725
+ ]);
3726
+ },
3727
+ arcTo(x1, y1, x2, y2, radius) {
3728
+ record("arcTo", [
3729
+ x1,
3730
+ y1,
3731
+ x2,
3732
+ y2,
3733
+ radius
3734
+ ]);
3735
+ },
3736
+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
3737
+ record("bezierCurveTo", [
3738
+ cp1x,
3739
+ cp1y,
3740
+ cp2x,
3741
+ cp2y,
3742
+ x,
3743
+ y
3744
+ ]);
3745
+ },
3746
+ __getSnapshot() {
3747
+ return {
3748
+ canvasId: snapshot.canvasId,
3749
+ drawCalls: snapshot.drawCalls.map(cloneCall),
3750
+ fillStyle: snapshot.fillStyle,
3751
+ fontSize: snapshot.fontSize,
3752
+ globalAlpha: snapshot.globalAlpha,
3753
+ lineCap: snapshot.lineCap,
3754
+ lineDash: [...snapshot.lineDash],
3755
+ lineDashOffset: snapshot.lineDashOffset,
3756
+ lineJoin: snapshot.lineJoin,
3757
+ miterLimit: snapshot.miterLimit,
3758
+ lineWidth: snapshot.lineWidth,
3759
+ reserve: snapshot.reserve,
3760
+ shadowBlur: snapshot.shadowBlur,
3761
+ shadowColor: snapshot.shadowColor,
3762
+ shadowOffsetX: snapshot.shadowOffsetX,
3763
+ shadowOffsetY: snapshot.shadowOffsetY,
3764
+ strokeStyle: snapshot.strokeStyle,
3765
+ textAlign: snapshot.textAlign,
3766
+ textBaseline: snapshot.textBaseline
3767
+ };
3768
+ },
3769
+ beginPath() {
3770
+ record("beginPath", []);
3771
+ },
3772
+ clearRect(x, y, width, height) {
3773
+ record("clearRect", [
3774
+ x,
3775
+ y,
3776
+ width,
3777
+ height
3778
+ ]);
3779
+ },
3780
+ clip(fillRule) {
3781
+ record("clip", fillRule == null ? [] : [fillRule]);
3782
+ },
3783
+ closePath() {
3784
+ record("closePath", []);
3785
+ },
3786
+ draw(reserve, callback) {
3787
+ ensureCanvas();
3788
+ snapshot = {
3789
+ canvasId,
3790
+ drawCalls: reserve ? [...snapshot.drawCalls.map(cloneCall), ...drawCalls.map(cloneCall)] : drawCalls.map(cloneCall),
3791
+ fillStyle: state.fillStyle,
3792
+ fontSize: state.fontSize,
3793
+ globalAlpha: state.globalAlpha,
3794
+ lineCap: state.lineCap,
3795
+ lineDash: [...state.lineDash],
3796
+ lineDashOffset: state.lineDashOffset,
3797
+ lineJoin: state.lineJoin,
3798
+ miterLimit: state.miterLimit,
3799
+ lineWidth: state.lineWidth,
3800
+ reserve: Boolean(reserve),
3801
+ shadowBlur: state.shadowBlur,
3802
+ shadowColor: state.shadowColor,
3803
+ shadowOffsetX: state.shadowOffsetX,
3804
+ shadowOffsetY: state.shadowOffsetY,
3805
+ strokeStyle: state.strokeStyle,
3806
+ textAlign: state.textAlign,
3807
+ textBaseline: state.textBaseline
3808
+ };
3809
+ drawCalls = [];
3810
+ state = { ...defaultState };
3811
+ stateStack = [];
3812
+ callback?.();
3813
+ },
3814
+ drawImage(image, ...args) {
3815
+ record("drawImage", [image, ...args]);
3816
+ },
3817
+ fill(fillRule) {
3818
+ record("fill", fillRule == null ? [] : [fillRule]);
3819
+ },
3820
+ fillRect(x, y, width, height) {
3821
+ record("fillRect", [
3822
+ x,
3823
+ y,
3824
+ width,
3825
+ height
3826
+ ]);
3827
+ },
3828
+ fillText(text, x, y, maxWidth) {
3829
+ record("fillText", maxWidth == null ? [
3830
+ text,
3831
+ x,
3832
+ y
3833
+ ] : [
3834
+ text,
3835
+ x,
3836
+ y,
3837
+ maxWidth
3838
+ ]);
3839
+ },
3840
+ lineTo(x, y) {
3841
+ record("lineTo", [x, y]);
3842
+ },
3843
+ measureText(text) {
3844
+ return { width: text.length * state.fontSize * .5 };
3845
+ },
3846
+ moveTo(x, y) {
3847
+ record("moveTo", [x, y]);
3848
+ },
3849
+ quadraticCurveTo(cpx, cpy, x, y) {
3850
+ record("quadraticCurveTo", [
3851
+ cpx,
3852
+ cpy,
3853
+ x,
3854
+ y
3855
+ ]);
3856
+ },
3857
+ rect(x, y, width, height) {
3858
+ record("rect", [
3859
+ x,
3860
+ y,
3861
+ width,
3862
+ height
3863
+ ]);
3864
+ },
3865
+ restore() {
3866
+ state = stateStack.pop() ?? { ...defaultState };
3867
+ record("restore", []);
3868
+ },
3869
+ rotate(rotate) {
3870
+ record("rotate", [rotate]);
3871
+ },
3872
+ save() {
3873
+ stateStack.push({ ...state });
3874
+ record("save", []);
3875
+ },
3876
+ scale(scaleWidth, scaleHeight) {
3877
+ record("scale", [scaleWidth, scaleHeight]);
3878
+ },
3879
+ setFillStyle(value) {
3880
+ state.fillStyle = String(value);
3881
+ record("setFillStyle", [value]);
3882
+ },
3883
+ setFontSize(fontSize) {
3884
+ state.fontSize = Number(fontSize);
3885
+ record("setFontSize", [fontSize]);
3886
+ },
3887
+ setGlobalAlpha(value) {
3888
+ state.globalAlpha = Number(value);
3889
+ record("setGlobalAlpha", [value]);
3890
+ },
3891
+ setLineCap(value) {
3892
+ state.lineCap = String(value);
3893
+ record("setLineCap", [value]);
3894
+ },
3895
+ setLineDash(pattern, offset) {
3896
+ state.lineDash = pattern.map((item) => Number(item));
3897
+ state.lineDashOffset = offset == null ? 0 : Number(offset);
3898
+ record("setLineDash", offset == null ? [pattern.map((item) => Number(item))] : [pattern.map((item) => Number(item)), Number(offset)]);
3899
+ },
3900
+ setLineJoin(value) {
3901
+ state.lineJoin = String(value);
3902
+ record("setLineJoin", [value]);
3903
+ },
3904
+ setMiterLimit(value) {
3905
+ state.miterLimit = Number(value);
3906
+ record("setMiterLimit", [value]);
3907
+ },
3908
+ setLineWidth(value) {
3909
+ state.lineWidth = Number(value);
3910
+ record("setLineWidth", [value]);
3911
+ },
3912
+ setShadow(offsetX, offsetY, blur, color) {
3913
+ state.shadowOffsetX = Number(offsetX);
3914
+ state.shadowOffsetY = Number(offsetY);
3915
+ state.shadowBlur = Number(blur);
3916
+ state.shadowColor = String(color);
3917
+ record("setShadow", [
3918
+ offsetX,
3919
+ offsetY,
3920
+ blur,
3921
+ color
3922
+ ]);
3923
+ },
3924
+ setStrokeStyle(value) {
3925
+ state.strokeStyle = String(value);
3926
+ record("setStrokeStyle", [value]);
3927
+ },
3928
+ setTextAlign(value) {
3929
+ state.textAlign = String(value);
3930
+ record("setTextAlign", [value]);
3931
+ },
3932
+ setTextBaseline(value) {
3933
+ state.textBaseline = String(value);
3934
+ record("setTextBaseline", [value]);
3935
+ },
3936
+ stroke() {
3937
+ record("stroke", []);
3938
+ },
3939
+ strokeRect(x, y, width, height) {
3940
+ record("strokeRect", [
3941
+ x,
3942
+ y,
3943
+ width,
3944
+ height
3945
+ ]);
3946
+ },
3947
+ strokeText(text, x, y, maxWidth) {
3948
+ record("strokeText", maxWidth == null ? [
3949
+ text,
3950
+ x,
3951
+ y
3952
+ ] : [
3953
+ text,
3954
+ x,
3955
+ y,
3956
+ maxWidth
3957
+ ]);
3958
+ },
3959
+ translate(x, y) {
3960
+ record("translate", [x, y]);
3961
+ }
3962
+ };
3963
+ }
3964
+ //#endregion
3965
+ //#region src/view/intersectionObserver.ts
3966
+ const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
3967
+ function normalizeMargins(margins) {
3968
+ return {
3969
+ bottom: Number(margins?.bottom) || 0,
3970
+ left: Number(margins?.left) || 0,
3971
+ right: Number(margins?.right) || 0,
3972
+ top: Number(margins?.top) || 0
3973
+ };
3974
+ }
3975
+ function parseStyleDeclarations(styleValue) {
3976
+ const declarations = {};
3977
+ if (!styleValue) return declarations;
3978
+ for (const declaration of styleValue.split(";")) {
3979
+ const [rawProperty, ...rawValueParts] = declaration.split(":");
3980
+ const property = rawProperty?.trim();
3981
+ if (!property) continue;
3982
+ declarations[property] = rawValueParts.join(":").trim();
3983
+ }
3984
+ return declarations;
3985
+ }
3986
+ function parseNumericLikeValue(value) {
3987
+ if (!value) return 0;
3988
+ const match = value.match(NUMERIC_LIKE_VALUE_RE);
3989
+ return match ? Number(match[0]) : 0;
3990
+ }
3991
+ function resolveRect(node) {
3992
+ const style = parseStyleDeclarations(node.attribs?.style);
3993
+ const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
3994
+ const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
3995
+ const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
3996
+ const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
3997
+ return {
3998
+ bottom: top + height,
3999
+ height,
4000
+ left,
4001
+ right: left + width,
4002
+ top,
4003
+ width
4004
+ };
4005
+ }
4006
+ function applyMargins(rect, margins) {
4007
+ const top = rect.top - (margins.top ?? 0);
4008
+ const left = rect.left - (margins.left ?? 0);
4009
+ const right = rect.right + (margins.right ?? 0);
4010
+ const bottom = rect.bottom + (margins.bottom ?? 0);
4011
+ return {
4012
+ bottom,
4013
+ height: Math.max(0, bottom - top),
4014
+ left,
4015
+ right,
4016
+ top,
4017
+ width: Math.max(0, right - left)
4018
+ };
4019
+ }
4020
+ function intersectRects(source, target) {
4021
+ const left = Math.max(source.left, target.left);
4022
+ const top = Math.max(source.top, target.top);
4023
+ const right = Math.min(source.right, target.right);
4024
+ const bottom = Math.min(source.bottom, target.bottom);
4025
+ if (right <= left || bottom <= top) return {
4026
+ bottom: top,
4027
+ height: 0,
4028
+ left,
4029
+ right: left,
4030
+ top,
4031
+ width: 0
4032
+ };
4033
+ return {
4034
+ bottom,
4035
+ height: bottom - top,
4036
+ left,
4037
+ right,
4038
+ top,
4039
+ width: right - left
4040
+ };
4041
+ }
4042
+ function resolveViewportRect(windowInfo) {
4043
+ return {
4044
+ bottom: windowInfo.windowHeight,
4045
+ height: windowInfo.windowHeight,
4046
+ left: 0,
4047
+ right: windowInfo.windowWidth,
4048
+ top: 0,
4049
+ width: windowInfo.windowWidth
4050
+ };
4051
+ }
4052
+ function createHeadlessIntersectionObserver(driver, scope, _options) {
4053
+ let active = true;
4054
+ let relativeTarget = {
4055
+ kind: "viewport",
4056
+ margins: normalizeMargins()
4057
+ };
4058
+ const resolveScopedRoot = () => {
4059
+ const scopeResolution = driver.resolveScope(scope);
4060
+ if (scopeResolution.kind === "missing") return null;
4061
+ const rendered = driver.renderCurrentPage();
4062
+ return scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root;
4063
+ };
4064
+ const resolveTargetNode = (selector) => {
4065
+ const scopedRoot = resolveScopedRoot();
4066
+ if (!scopedRoot) return null;
4067
+ return querySelectorAll(scopedRoot, selector)[0] ?? null;
4068
+ };
4069
+ const resolveRelativeRect = () => {
4070
+ if (relativeTarget.kind === "viewport") return applyMargins(resolveViewportRect(driver.getWindowInfo()), relativeTarget.margins);
4071
+ const relativeNode = resolveTargetNode(relativeTarget.selector);
4072
+ if (!relativeNode) return null;
4073
+ return applyMargins(resolveRect(relativeNode), relativeTarget.margins);
4074
+ };
4075
+ return {
4076
+ disconnect() {
4077
+ active = false;
4078
+ },
4079
+ observe(selector, callback) {
4080
+ if (!active) return;
4081
+ const targetNode = resolveTargetNode(selector);
4082
+ const relativeRect = resolveRelativeRect();
4083
+ if (!targetNode || !relativeRect) return;
4084
+ const boundingClientRect = resolveRect(targetNode);
4085
+ const intersectionRect = intersectRects(boundingClientRect, relativeRect);
4086
+ const targetArea = boundingClientRect.width * boundingClientRect.height;
4087
+ const intersectionArea = intersectionRect.width * intersectionRect.height;
4088
+ callback({
4089
+ boundingClientRect,
4090
+ id: targetNode.attribs?.id ?? "",
4091
+ intersectionRatio: targetArea > 0 ? intersectionArea / targetArea : 0,
4092
+ intersectionRect,
4093
+ relativeRect
4094
+ });
4095
+ },
4096
+ relativeTo(selector, margins) {
4097
+ relativeTarget = {
4098
+ kind: "selector",
4099
+ margins: normalizeMargins(margins),
4100
+ selector
4101
+ };
4102
+ return this;
4103
+ },
4104
+ relativeToViewport(margins) {
4105
+ relativeTarget = {
4106
+ kind: "viewport",
4107
+ margins: normalizeMargins(margins)
4108
+ };
4109
+ return this;
4110
+ }
4111
+ };
4112
+ }
4113
+ //#endregion
4114
+ //#region src/view/mediaQueryObserver.ts
4115
+ function resolveOrientation(windowInfo) {
4116
+ return windowInfo.windowWidth >= windowInfo.windowHeight ? "landscape" : "portrait";
4117
+ }
4118
+ function resolveMatches(descriptor, windowInfo) {
4119
+ if (descriptor.width != null && windowInfo.windowWidth !== descriptor.width) return false;
4120
+ if (descriptor.minWidth != null && windowInfo.windowWidth < descriptor.minWidth) return false;
4121
+ if (descriptor.maxWidth != null && windowInfo.windowWidth > descriptor.maxWidth) return false;
4122
+ if (descriptor.height != null && windowInfo.windowHeight !== descriptor.height) return false;
4123
+ if (descriptor.minHeight != null && windowInfo.windowHeight < descriptor.minHeight) return false;
4124
+ if (descriptor.maxHeight != null && windowInfo.windowHeight > descriptor.maxHeight) return false;
4125
+ if (descriptor.orientation != null && resolveOrientation(windowInfo) !== descriptor.orientation) return false;
4126
+ return true;
4127
+ }
4128
+ function createHeadlessMediaQueryObserver(driver, onDisconnect) {
4129
+ let active = true;
4130
+ let callback;
4131
+ let descriptor;
4132
+ let hasObserved = false;
4133
+ let lastMatches;
4134
+ const emit = (force) => {
4135
+ if (!active || !hasObserved || !callback || !descriptor) return;
4136
+ const matches = resolveMatches(descriptor, driver.getWindowInfo());
4137
+ if (!force && lastMatches === matches) return;
4138
+ lastMatches = matches;
4139
+ callback({ matches });
4140
+ };
4141
+ const observer = {
4142
+ disconnect() {
4143
+ if (!active) return;
4144
+ active = false;
4145
+ hasObserved = false;
4146
+ callback = void 0;
4147
+ descriptor = void 0;
4148
+ onDisconnect?.();
4149
+ },
4150
+ observe(nextDescriptor, nextCallback) {
4151
+ if (!active) return;
4152
+ descriptor = { ...nextDescriptor };
4153
+ callback = nextCallback;
4154
+ hasObserved = true;
4155
+ emit(true);
4156
+ }
4157
+ };
4158
+ return {
4159
+ disconnect: observer.disconnect,
4160
+ notify() {
4161
+ emit(false);
4162
+ },
4163
+ observer
4164
+ };
4165
+ }
4166
+ //#endregion
4167
+ //#region src/view/videoContext.ts
4168
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
4169
+ function toDatasetKey$1(attributeName) {
4170
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
4171
+ }
4172
+ function collectDataset$1(node) {
4173
+ const dataset = {};
4174
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
4175
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
4176
+ dataset[toDatasetKey$1(key)] = value;
4177
+ }
4178
+ return dataset;
4179
+ }
4180
+ function resolveEventBinding(node, eventName) {
4181
+ const normalizedEventName = eventName.trim();
4182
+ if (!normalizedEventName) return null;
4183
+ const bindingAttrs = [
4184
+ `bind${normalizedEventName}`,
4185
+ `bind:${normalizedEventName}`,
4186
+ `catch${normalizedEventName}`,
4187
+ `catch:${normalizedEventName}`
4188
+ ];
4189
+ for (const attributeName of bindingAttrs) {
4190
+ const methodName = node.attribs?.[attributeName]?.trim();
4191
+ if (methodName) return methodName;
4192
+ }
4193
+ return null;
4194
+ }
4195
+ function createEventPayload(node, eventName, detail) {
4196
+ const dataset = collectDataset$1(node);
4197
+ const nodeId = node.attribs?.id ?? "";
4198
+ return {
4199
+ bubbles: false,
4200
+ capturePhase: false,
4201
+ composed: false,
4202
+ currentTarget: {
4203
+ dataset,
4204
+ id: nodeId
4205
+ },
4206
+ detail,
4207
+ mark: void 0,
4208
+ target: {
4209
+ dataset,
4210
+ id: nodeId
4211
+ },
4212
+ type: eventName
4213
+ };
4214
+ }
4215
+ function createHeadlessVideoContext(driver, videoId, scope) {
4216
+ const state = {
4217
+ currentTime: 0,
4218
+ fullScreen: false,
4219
+ paused: true
4220
+ };
4221
+ const resolveNode = () => {
4222
+ const scopeResolution = driver.resolveScope(scope);
4223
+ if (scopeResolution.kind === "missing") return null;
4224
+ const rendered = driver.renderCurrentPage();
4225
+ return querySelectorAll(scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root, `#${videoId}`)[0] ?? null;
4226
+ };
4227
+ const dispatch = (eventName, detail) => {
4228
+ const node = resolveNode();
4229
+ if (!node) return;
4230
+ const methodName = resolveEventBinding(node, eventName);
4231
+ if (!methodName) return;
4232
+ driver.callScopeMethod(node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(node, eventName, detail));
4233
+ };
4234
+ return {
4235
+ exitFullScreen() {
4236
+ state.fullScreen = false;
4237
+ dispatch("fullscreenchange", {
4238
+ currentTime: state.currentTime,
4239
+ fullScreen: false
4240
+ });
4241
+ },
4242
+ pause() {
4243
+ state.paused = true;
4244
+ dispatch("pause", { currentTime: state.currentTime });
4245
+ },
4246
+ play() {
4247
+ state.paused = false;
4248
+ dispatch("play", { currentTime: state.currentTime });
4249
+ },
4250
+ requestFullScreen() {
4251
+ state.fullScreen = true;
4252
+ dispatch("fullscreenchange", {
4253
+ currentTime: state.currentTime,
4254
+ fullScreen: true
4255
+ });
4256
+ },
4257
+ seek(position) {
4258
+ state.currentTime = Number.isFinite(position) ? Number(position) : 0;
4259
+ },
4260
+ stop() {
4261
+ state.currentTime = 0;
4262
+ state.paused = true;
4263
+ dispatch("pause", { currentTime: state.currentTime });
4264
+ }
4265
+ };
4266
+ }
4267
+ //#endregion
2862
4268
  //#region src/browser/session.ts
2863
4269
  const LEADING_SLASH_RE$3 = /^\/+/;
2864
4270
  const PAGE_STACK_LIMIT$1 = 10;
@@ -2951,6 +4357,8 @@ var BrowserHeadlessSession = class {
2951
4357
  tabBarState = /* @__PURE__ */ new Map();
2952
4358
  tabBarVisible = false;
2953
4359
  systemInfo = createDefaultSystemInfo();
4360
+ mediaQueryObservers = /* @__PURE__ */ new Set();
4361
+ canvasContexts = /* @__PURE__ */ new Map();
2954
4362
  enterOptions = createAppLaunchOptions$1("", {});
2955
4363
  launchOptions = createAppLaunchOptions$1("", {});
2956
4364
  wxState = createHeadlessWxState();
@@ -2984,7 +4392,20 @@ var BrowserHeadlessSession = class {
2984
4392
  });
2985
4393
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2986
4394
  this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
4395
+ chooseImage: (option) => this.wxState.chooseImage(option ?? {}),
4396
+ chooseMessageFile: (option) => this.wxState.chooseMessageFile(option ?? {}),
4397
+ chooseMedia: (option) => this.wxState.chooseMedia(option ?? {}),
4398
+ chooseVideo: (option) => this.wxState.chooseVideo(option ?? {}),
4399
+ compressImage: (option) => this.wxState.compressImage(option),
4400
+ createAnimation: (option) => this.createAnimation(option),
4401
+ createCanvasContext: (canvasId, scope) => this.createCanvasContext(canvasId, scope),
4402
+ canvasToTempFilePath: (option) => this.canvasToTempFilePath(option),
4403
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4404
+ createVideoContext: (videoId, scope) => this.createVideoContext(videoId, scope),
2987
4405
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
4406
+ getFileInfo: (option) => this.wxState.getFileInfo(option),
4407
+ getImageInfo: (option) => this.wxState.getImageInfo(option),
4408
+ getVideoInfo: (option) => this.wxState.getVideoInfo(option),
2988
4409
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
2989
4410
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
2990
4411
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -3005,11 +4426,13 @@ var BrowserHeadlessSession = class {
3005
4426
  extraData: { ...this.launchOptions.referrerInfo.extraData }
3006
4427
  }
3007
4428
  }),
4429
+ getClipboardData: () => this.wxState.getClipboardData(),
3008
4430
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
3009
4431
  getNetworkType: () => this.wxState.getNetworkType(),
3010
4432
  navigateBack: (option) => this.navigateBack(option?.delta),
3011
4433
  navigateTo: (option) => this.navigateTo(option.url),
3012
4434
  pageScrollTo: (option) => this.pageScrollTo(option),
4435
+ openDocument: (option) => this.wxState.openDocument(option),
3013
4436
  clearStorageSync: () => this.wxState.clearStorageSync(),
3014
4437
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
3015
4438
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -3021,14 +4444,18 @@ var BrowserHeadlessSession = class {
3021
4444
  reLaunch: (option) => this.reLaunch(option.url),
3022
4445
  redirectTo: (option) => this.redirectTo(option.url),
3023
4446
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
4447
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
4448
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
3024
4449
  nextTick: (callback) => queueMicrotask(() => callback?.()),
3025
4450
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
3026
4451
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
3027
4452
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
4453
+ previewImage: (option) => this.wxState.previewImage(option),
3028
4454
  request: (option) => this.wxState.request(option),
3029
4455
  saveFile: (option) => this.wxState.saveFile(option),
3030
4456
  setBackgroundColor: (option) => this.setBackgroundColor(option),
3031
4457
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
4458
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
3032
4459
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
3033
4460
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
3034
4461
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -3044,6 +4471,7 @@ var BrowserHeadlessSession = class {
3044
4471
  showLoading: (option) => this.wxState.showLoading(option),
3045
4472
  showModal: (option) => this.wxState.showModal(option),
3046
4473
  showToast: (option) => this.wxState.showToast(option),
4474
+ startPullDownRefresh: () => this.startPullDownRefresh(),
3047
4475
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
3048
4476
  switchTab: (option) => this.switchTab(option.url),
3049
4477
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -3117,6 +4545,15 @@ var BrowserHeadlessSession = class {
3117
4545
  getStorageInfo() {
3118
4546
  return this.wxState.getStorageInfoSync();
3119
4547
  }
4548
+ getClipboardData() {
4549
+ return this.wxState.getClipboardSnapshot();
4550
+ }
4551
+ getPreviewImage() {
4552
+ return this.wxState.getPreviewImage();
4553
+ }
4554
+ getOpenedDocument() {
4555
+ return this.wxState.getOpenedDocument();
4556
+ }
3120
4557
  getPullDownRefreshState() {
3121
4558
  return { ...this.pullDownRefreshState };
3122
4559
  }
@@ -3350,16 +4787,12 @@ var BrowserHeadlessSession = class {
3350
4787
  if (!candidateScopeId.includes("/")) return false;
3351
4788
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
3352
4789
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
3353
- let partIndex = selectorParts.length - 1;
3354
- let currentScope = scope;
3355
- while (partIndex >= 0) {
3356
- if (!currentScope || !matchesComponentSelector$1(currentScope, selectorParts[partIndex])) {
3357
- currentScope = currentScope?.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
3358
- if (!currentScope) return false;
3359
- continue;
3360
- }
3361
- partIndex -= 1;
3362
- if (partIndex < 0) return true;
4790
+ const lastPart = selectorParts.at(-1);
4791
+ if (!lastPart || !matchesComponentSelector$1(scope, lastPart)) return false;
4792
+ let currentScope = scope.ownerScopeId ? this.componentScopes.get(scope.ownerScopeId) : void 0;
4793
+ for (let partIndex = selectorParts.length - 2; partIndex >= 0; partIndex -= 1) {
4794
+ while (currentScope && !matchesComponentSelector$1(currentScope, selectorParts[partIndex])) currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
4795
+ if (!currentScope) return false;
3363
4796
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
3364
4797
  }
3365
4798
  return true;
@@ -3375,6 +4808,8 @@ var BrowserHeadlessSession = class {
3375
4808
  moduleLoader: this.moduleLoader,
3376
4809
  project: this.project,
3377
4810
  session: {
4811
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4812
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3378
4813
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3379
4814
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3380
4815
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3413,6 +4848,7 @@ var BrowserHeadlessSession = class {
3413
4848
  }
3414
4849
  const instance = this.componentCache.get(normalizedScopeId);
3415
4850
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
4851
+ instance.__lastInteractionEvent__ = void 0;
3416
4852
  const method = instance[methodName];
3417
4853
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
3418
4854
  return method.apply(instance, args);
@@ -3561,6 +4997,8 @@ var BrowserHeadlessSession = class {
3561
4997
  moduleLoader: this.moduleLoader,
3562
4998
  project: this.project,
3563
4999
  session: {
5000
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5001
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3564
5002
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3565
5003
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3566
5004
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3578,6 +5016,10 @@ var BrowserHeadlessSession = class {
3578
5016
  current.onPullDownRefresh?.();
3579
5017
  return current;
3580
5018
  }
5019
+ startPullDownRefresh() {
5020
+ this.triggerPullDownRefresh();
5021
+ return { errMsg: "startPullDownRefresh:ok" };
5022
+ }
3581
5023
  triggerReachBottom() {
3582
5024
  const current = this.requireCurrentPage("triggerReachBottom()");
3583
5025
  current.onReachBottom?.();
@@ -3588,6 +5030,7 @@ var BrowserHeadlessSession = class {
3588
5030
  applyResizeToSystemInfo(this.systemInfo, options);
3589
5031
  current.onResize?.(options);
3590
5032
  this.runPageComponentLifetime(current.route, "resize", options);
5033
+ this.notifyMediaQueryObservers();
3591
5034
  return current;
3592
5035
  }
3593
5036
  triggerRouteDone(options = {}) {
@@ -3607,6 +5050,11 @@ var BrowserHeadlessSession = class {
3607
5050
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
3608
5051
  return executeSelectorQueryRequests(requests, {
3609
5052
  page: current,
5053
+ resolveContext: (node) => {
5054
+ if (node.name !== "canvas") return { type: "unsupported-context" };
5055
+ const canvasId = node.attribs?.["canvas-id"];
5056
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
5057
+ },
3610
5058
  root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
3611
5059
  changedPageKeys: current.__lastChangedKeys__ ?? [],
3612
5060
  componentCache: this.componentCache,
@@ -3615,6 +5063,8 @@ var BrowserHeadlessSession = class {
3615
5063
  moduleLoader: this.moduleLoader,
3616
5064
  project: this.project,
3617
5065
  session: {
5066
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5067
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3618
5068
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3619
5069
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3620
5070
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3632,6 +5082,8 @@ var BrowserHeadlessSession = class {
3632
5082
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3633
5083
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3634
5084
  });
5085
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
5086
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
3635
5087
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
3636
5088
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
3637
5089
  pageInstance.onLoad?.(target.query);
@@ -3681,10 +5133,12 @@ var BrowserHeadlessSession = class {
3681
5133
  this.tabPages.clear();
3682
5134
  this.componentCache.clear();
3683
5135
  this.componentScopes.clear();
5136
+ this.clearMediaQueryObservers();
3684
5137
  this.currentPageInstance = null;
3685
5138
  }
3686
5139
  unloadPage(page) {
3687
5140
  page.onUnload?.();
5141
+ this.clearMediaQueryObservers(page);
3688
5142
  this.detachPageComponents(page.route);
3689
5143
  this.tabPages.delete(stripLeadingSlash$1(page.route));
3690
5144
  }
@@ -3703,6 +5157,18 @@ var BrowserHeadlessSession = class {
3703
5157
  this.componentScopes.delete(scopeId);
3704
5158
  }
3705
5159
  }
5160
+ notifyMediaQueryObservers() {
5161
+ for (const entry of [...this.mediaQueryObservers]) {
5162
+ if (entry.ownerPage !== this.currentPageInstance) continue;
5163
+ entry.notify();
5164
+ }
5165
+ }
5166
+ clearMediaQueryObservers(ownerPage) {
5167
+ for (const entry of [...this.mediaQueryObservers]) {
5168
+ if (ownerPage && entry.ownerPage !== ownerPage) continue;
5169
+ entry.disconnect();
5170
+ }
5171
+ }
3706
5172
  runPageComponentLifetime(route, lifetimeName, payload) {
3707
5173
  const prefix = `page:${stripLeadingSlash$1(route)}`;
3708
5174
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -3714,6 +5180,100 @@ var BrowserHeadlessSession = class {
3714
5180
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
3715
5181
  return null;
3716
5182
  }
5183
+ createVideoContext(videoId, scope) {
5184
+ return createHeadlessVideoContext({
5185
+ callScopeMethod: (scopeId, methodName, event) => this.callScopeMethod(scopeId, methodName, event),
5186
+ renderCurrentPage: () => this.renderCurrentPage(),
5187
+ resolveScope: (value) => {
5188
+ const current = this.currentPageInstance;
5189
+ if (!value || value === current) return { kind: "page" };
5190
+ const scopeId = this.getScopeIdForComponent(value);
5191
+ if (!scopeId) return { kind: "missing" };
5192
+ return {
5193
+ kind: "component",
5194
+ scopeId
5195
+ };
5196
+ }
5197
+ }, videoId, scope);
5198
+ }
5199
+ createAnimation(option) {
5200
+ return createHeadlessAnimation(option);
5201
+ }
5202
+ resolveCanvasScopeKey(scope) {
5203
+ const current = this.currentPageInstance;
5204
+ if (!scope || scope === current) return "page";
5205
+ const scopeId = this.getScopeIdForComponent(scope);
5206
+ return scopeId ? `component:${scopeId}` : "missing";
5207
+ }
5208
+ createCanvasContext(canvasId, scope) {
5209
+ const context = createHeadlessCanvasContext({
5210
+ renderCurrentPage: () => this.renderCurrentPage(),
5211
+ resolveScope: (value) => {
5212
+ const current = this.currentPageInstance;
5213
+ if (!value || value === current) return { kind: "page" };
5214
+ const scopeId = this.getScopeIdForComponent(value);
5215
+ if (!scopeId) return { kind: "missing" };
5216
+ return {
5217
+ kind: "component",
5218
+ scopeId
5219
+ };
5220
+ }
5221
+ }, canvasId, scope);
5222
+ this.canvasContexts.set(`${this.resolveCanvasScopeKey(scope)}:${canvasId}`, context);
5223
+ return context;
5224
+ }
5225
+ canvasToTempFilePath(option) {
5226
+ const context = this.canvasContexts.get(`${this.resolveCanvasScopeKey(option.component)}:${option.canvasId}`);
5227
+ if (!context) throw new Error(`canvasToTempFilePath:fail canvas "${option.canvasId}" has not been drawn in browser runtime.`);
5228
+ return {
5229
+ errMsg: "canvasToTempFilePath:ok",
5230
+ tempFilePath: this.wxState.createTempFile(JSON.stringify({
5231
+ canvasId: option.canvasId,
5232
+ config: {
5233
+ destHeight: option.destHeight,
5234
+ destWidth: option.destWidth,
5235
+ fileType: option.fileType,
5236
+ height: option.height,
5237
+ quality: option.quality,
5238
+ width: option.width,
5239
+ x: option.x,
5240
+ y: option.y
5241
+ },
5242
+ snapshot: context.__getSnapshot()
5243
+ }))
5244
+ };
5245
+ }
5246
+ createIntersectionObserver(scope, options) {
5247
+ return createHeadlessIntersectionObserver({
5248
+ getWindowInfo: () => this.getWindowInfo(),
5249
+ renderCurrentPage: () => this.renderCurrentPage(),
5250
+ resolveScope: (value) => {
5251
+ const current = this.currentPageInstance;
5252
+ if (!value || value === current) return { kind: "page" };
5253
+ const scopeId = this.getScopeIdForComponent(value);
5254
+ if (!scopeId) return { kind: "missing" };
5255
+ return {
5256
+ kind: "component",
5257
+ scopeId
5258
+ };
5259
+ }
5260
+ }, scope, options);
5261
+ }
5262
+ createMediaQueryObserver(scope) {
5263
+ const current = this.requireCurrentPage("createMediaQueryObserver()");
5264
+ const ownerPage = scope === current || !scope ? current : this.currentPageInstance ?? current;
5265
+ let entry;
5266
+ const controller = createHeadlessMediaQueryObserver({ getWindowInfo: () => this.getWindowInfo() }, () => {
5267
+ this.mediaQueryObservers.delete(entry);
5268
+ });
5269
+ entry = {
5270
+ disconnect: controller.disconnect,
5271
+ notify: controller.notify,
5272
+ ownerPage
5273
+ };
5274
+ this.mediaQueryObservers.add(entry);
5275
+ return controller.observer;
5276
+ }
3717
5277
  };
3718
5278
  function createBrowserHeadlessSession(options) {
3719
5279
  return new BrowserHeadlessSession(options);
@@ -4137,6 +5697,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
4137
5697
  properties: nextProperties,
4138
5698
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
4139
5699
  });
5700
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5701
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
4140
5702
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
4141
5703
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
4142
5704
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
@@ -4396,6 +5958,8 @@ var HeadlessSession = class {
4396
5958
  tabBarState = /* @__PURE__ */ new Map();
4397
5959
  tabBarVisible = false;
4398
5960
  systemInfo = createDefaultSystemInfo();
5961
+ mediaQueryObservers = /* @__PURE__ */ new Set();
5962
+ canvasContexts = /* @__PURE__ */ new Map();
4399
5963
  enterOptions = createAppLaunchOptions("", {});
4400
5964
  launchOptions = createAppLaunchOptions("", {});
4401
5965
  wxState = createHeadlessWxState();
@@ -4428,7 +5992,20 @@ var HeadlessSession = class {
4428
5992
  });
4429
5993
  this.tabBarVisible = this.tabBarRoutes.size > 0;
4430
5994
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
5995
+ chooseImage: (option) => this.wxState.chooseImage(option ?? {}),
5996
+ chooseMessageFile: (option) => this.wxState.chooseMessageFile(option ?? {}),
5997
+ chooseMedia: (option) => this.wxState.chooseMedia(option ?? {}),
5998
+ chooseVideo: (option) => this.wxState.chooseVideo(option ?? {}),
5999
+ compressImage: (option) => this.wxState.compressImage(option),
6000
+ createAnimation: (option) => this.createAnimation(option),
6001
+ createCanvasContext: (canvasId, scope) => this.createCanvasContext(canvasId, scope),
6002
+ canvasToTempFilePath: (option) => this.canvasToTempFilePath(option),
6003
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6004
+ createVideoContext: (videoId, scope) => this.createVideoContext(videoId, scope),
4431
6005
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
6006
+ getFileInfo: (option) => this.wxState.getFileInfo(option),
6007
+ getImageInfo: (option) => this.wxState.getImageInfo(option),
6008
+ getVideoInfo: (option) => this.wxState.getVideoInfo(option),
4432
6009
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
4433
6010
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
4434
6011
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -4449,11 +6026,13 @@ var HeadlessSession = class {
4449
6026
  extraData: { ...this.launchOptions.referrerInfo.extraData }
4450
6027
  }
4451
6028
  }),
6029
+ getClipboardData: () => this.wxState.getClipboardData(),
4452
6030
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
4453
6031
  getNetworkType: () => this.wxState.getNetworkType(),
4454
6032
  navigateBack: (option) => this.navigateBack(option?.delta),
4455
6033
  navigateTo: (option) => this.navigateTo(option.url),
4456
6034
  pageScrollTo: (option) => this.pageScrollTo(option),
6035
+ openDocument: (option) => this.wxState.openDocument(option),
4457
6036
  clearStorageSync: () => this.wxState.clearStorageSync(),
4458
6037
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
4459
6038
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -4465,14 +6044,18 @@ var HeadlessSession = class {
4465
6044
  reLaunch: (option) => this.reLaunch(option.url),
4466
6045
  redirectTo: (option) => this.redirectTo(option.url),
4467
6046
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
6047
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6048
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
4468
6049
  nextTick: (callback) => queueMicrotask(() => callback?.()),
4469
6050
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
4470
6051
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
4471
6052
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
6053
+ previewImage: (option) => this.wxState.previewImage(option),
4472
6054
  request: (option) => this.wxState.request(option),
4473
6055
  saveFile: (option) => this.wxState.saveFile(option),
4474
6056
  setBackgroundColor: (option) => this.setBackgroundColor(option),
4475
6057
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
6058
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
4476
6059
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
4477
6060
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
4478
6061
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -4488,6 +6071,7 @@ var HeadlessSession = class {
4488
6071
  showLoading: (option) => this.wxState.showLoading(option),
4489
6072
  showModal: (option) => this.wxState.showModal(option),
4490
6073
  showToast: (option) => this.wxState.showToast(option),
6074
+ startPullDownRefresh: () => this.startPullDownRefresh(),
4491
6075
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
4492
6076
  switchTab: (option) => this.switchTab(option.url),
4493
6077
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -4546,6 +6130,8 @@ var HeadlessSession = class {
4546
6130
  moduleLoader: this.moduleLoader,
4547
6131
  project: this.project,
4548
6132
  session: {
6133
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6134
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
4549
6135
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4550
6136
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4551
6137
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -4613,6 +6199,7 @@ var HeadlessSession = class {
4613
6199
  }
4614
6200
  const instance = this.componentCache.get(normalizedScopeId);
4615
6201
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
6202
+ instance.__lastInteractionEvent__ = void 0;
4616
6203
  const method = instance[methodName];
4617
6204
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
4618
6205
  return method.apply(instance, args);
@@ -4662,6 +6249,15 @@ var HeadlessSession = class {
4662
6249
  getStorageInfo() {
4663
6250
  return this.wxState.getStorageInfoSync();
4664
6251
  }
6252
+ getClipboardData() {
6253
+ return this.wxState.getClipboardSnapshot();
6254
+ }
6255
+ getPreviewImage() {
6256
+ return this.wxState.getPreviewImage();
6257
+ }
6258
+ getOpenedDocument() {
6259
+ return this.wxState.getOpenedDocument();
6260
+ }
4665
6261
  getPullDownRefreshState() {
4666
6262
  return { ...this.pullDownRefreshState };
4667
6263
  }
@@ -4948,6 +6544,10 @@ var HeadlessSession = class {
4948
6544
  current.onPullDownRefresh?.();
4949
6545
  return current;
4950
6546
  }
6547
+ startPullDownRefresh() {
6548
+ this.triggerPullDownRefresh();
6549
+ return { errMsg: "startPullDownRefresh:ok" };
6550
+ }
4951
6551
  triggerReachBottom() {
4952
6552
  const current = this.requireCurrentPage("triggerReachBottom()");
4953
6553
  current.onReachBottom?.();
@@ -4958,6 +6558,7 @@ var HeadlessSession = class {
4958
6558
  applyResizeToSystemInfo(this.systemInfo, options);
4959
6559
  current.onResize?.(options);
4960
6560
  this.runPageComponentLifetime(current.route, "resize", options);
6561
+ this.notifyMediaQueryObservers();
4961
6562
  return current;
4962
6563
  }
4963
6564
  triggerRouteDone(options = {}) {
@@ -4978,6 +6579,11 @@ var HeadlessSession = class {
4978
6579
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4979
6580
  return executeSelectorQueryRequests(requests, {
4980
6581
  page: current,
6582
+ resolveContext: (node) => {
6583
+ if (node.name !== "canvas") return { type: "unsupported-context" };
6584
+ const canvasId = node.attribs?.["canvas-id"];
6585
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
6586
+ },
4981
6587
  root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4982
6588
  windowInfo: this.getWindowInfo()
4983
6589
  });
@@ -4991,6 +6597,8 @@ var HeadlessSession = class {
4991
6597
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4992
6598
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4993
6599
  });
6600
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
6601
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
4994
6602
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4995
6603
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
4996
6604
  pageInstance.onLoad?.(target.query);
@@ -5040,10 +6648,12 @@ var HeadlessSession = class {
5040
6648
  this.tabPages.clear();
5041
6649
  this.componentCache.clear();
5042
6650
  this.componentScopes.clear();
6651
+ this.clearMediaQueryObservers();
5043
6652
  this.currentPageInstance = null;
5044
6653
  }
5045
6654
  unloadPage(page) {
5046
6655
  page.onUnload?.();
6656
+ this.clearMediaQueryObservers(page);
5047
6657
  this.detachPageComponents(page.route);
5048
6658
  this.tabPages.delete(stripLeadingSlash(page.route));
5049
6659
  }
@@ -5060,16 +6670,12 @@ var HeadlessSession = class {
5060
6670
  if (!candidateScopeId.includes("/")) return false;
5061
6671
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
5062
6672
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
5063
- let partIndex = selectorParts.length - 1;
5064
- let currentScope = scope;
5065
- while (partIndex >= 0) {
5066
- if (!currentScope || !matchesComponentSelector(currentScope, selectorParts[partIndex])) {
5067
- currentScope = currentScope?.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
5068
- if (!currentScope) return false;
5069
- continue;
5070
- }
5071
- partIndex -= 1;
5072
- if (partIndex < 0) return true;
6673
+ const lastPart = selectorParts.at(-1);
6674
+ if (!lastPart || !matchesComponentSelector(scope, lastPart)) return false;
6675
+ let currentScope = scope.ownerScopeId ? this.componentScopes.get(scope.ownerScopeId) : void 0;
6676
+ for (let partIndex = selectorParts.length - 2; partIndex >= 0; partIndex -= 1) {
6677
+ while (currentScope && !matchesComponentSelector(currentScope, selectorParts[partIndex])) currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
6678
+ if (!currentScope) return false;
5073
6679
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
5074
6680
  }
5075
6681
  return true;
@@ -5084,6 +6690,18 @@ var HeadlessSession = class {
5084
6690
  this.componentScopes.delete(scopeId);
5085
6691
  }
5086
6692
  }
6693
+ notifyMediaQueryObservers() {
6694
+ for (const entry of [...this.mediaQueryObservers]) {
6695
+ if (entry.ownerPage !== this.currentPageInstance) continue;
6696
+ entry.notify();
6697
+ }
6698
+ }
6699
+ clearMediaQueryObservers(ownerPage) {
6700
+ for (const entry of [...this.mediaQueryObservers]) {
6701
+ if (ownerPage && entry.ownerPage !== ownerPage) continue;
6702
+ entry.disconnect();
6703
+ }
6704
+ }
5087
6705
  runPageComponentLifetime(route, lifetimeName, payload) {
5088
6706
  const prefix = `page:${stripLeadingSlash(route)}`;
5089
6707
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -5095,6 +6713,100 @@ var HeadlessSession = class {
5095
6713
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
5096
6714
  return null;
5097
6715
  }
6716
+ createVideoContext(videoId, scope) {
6717
+ return createHeadlessVideoContext({
6718
+ callScopeMethod: (scopeId, methodName, event) => this.callScopeMethod(scopeId, methodName, event),
6719
+ renderCurrentPage: () => this.renderCurrentPage(),
6720
+ resolveScope: (value) => {
6721
+ const current = this.currentPageInstance;
6722
+ if (!value || value === current) return { kind: "page" };
6723
+ const scopeId = this.getScopeIdForComponent(value);
6724
+ if (!scopeId) return { kind: "missing" };
6725
+ return {
6726
+ kind: "component",
6727
+ scopeId
6728
+ };
6729
+ }
6730
+ }, videoId, scope);
6731
+ }
6732
+ createAnimation(option) {
6733
+ return createHeadlessAnimation(option);
6734
+ }
6735
+ resolveCanvasScopeKey(scope) {
6736
+ const current = this.currentPageInstance;
6737
+ if (!scope || scope === current) return "page";
6738
+ const scopeId = this.getScopeIdForComponent(scope);
6739
+ return scopeId ? `component:${scopeId}` : "missing";
6740
+ }
6741
+ createCanvasContext(canvasId, scope) {
6742
+ const context = createHeadlessCanvasContext({
6743
+ renderCurrentPage: () => this.renderCurrentPage(),
6744
+ resolveScope: (value) => {
6745
+ const current = this.currentPageInstance;
6746
+ if (!value || value === current) return { kind: "page" };
6747
+ const scopeId = this.getScopeIdForComponent(value);
6748
+ if (!scopeId) return { kind: "missing" };
6749
+ return {
6750
+ kind: "component",
6751
+ scopeId
6752
+ };
6753
+ }
6754
+ }, canvasId, scope);
6755
+ this.canvasContexts.set(`${this.resolveCanvasScopeKey(scope)}:${canvasId}`, context);
6756
+ return context;
6757
+ }
6758
+ canvasToTempFilePath(option) {
6759
+ const context = this.canvasContexts.get(`${this.resolveCanvasScopeKey(option.component)}:${option.canvasId}`);
6760
+ if (!context) throw new Error(`canvasToTempFilePath:fail canvas "${option.canvasId}" has not been drawn in headless runtime.`);
6761
+ return {
6762
+ errMsg: "canvasToTempFilePath:ok",
6763
+ tempFilePath: this.wxState.createTempFile(JSON.stringify({
6764
+ canvasId: option.canvasId,
6765
+ config: {
6766
+ destHeight: option.destHeight,
6767
+ destWidth: option.destWidth,
6768
+ fileType: option.fileType,
6769
+ height: option.height,
6770
+ quality: option.quality,
6771
+ width: option.width,
6772
+ x: option.x,
6773
+ y: option.y
6774
+ },
6775
+ snapshot: context.__getSnapshot()
6776
+ }))
6777
+ };
6778
+ }
6779
+ createIntersectionObserver(scope, options) {
6780
+ return createHeadlessIntersectionObserver({
6781
+ getWindowInfo: () => this.getWindowInfo(),
6782
+ renderCurrentPage: () => this.renderCurrentPage(),
6783
+ resolveScope: (value) => {
6784
+ const current = this.currentPageInstance;
6785
+ if (!value || value === current) return { kind: "page" };
6786
+ const scopeId = this.getScopeIdForComponent(value);
6787
+ if (!scopeId) return { kind: "missing" };
6788
+ return {
6789
+ kind: "component",
6790
+ scopeId
6791
+ };
6792
+ }
6793
+ }, scope, options);
6794
+ }
6795
+ createMediaQueryObserver(scope) {
6796
+ const current = this.requireCurrentPage("createMediaQueryObserver()");
6797
+ const ownerPage = scope === current || !scope ? current : this.currentPageInstance ?? current;
6798
+ let entry;
6799
+ const controller = createHeadlessMediaQueryObserver({ getWindowInfo: () => this.getWindowInfo() }, () => {
6800
+ this.mediaQueryObservers.delete(entry);
6801
+ });
6802
+ entry = {
6803
+ disconnect: controller.disconnect,
6804
+ notify: controller.notify,
6805
+ ownerPage
6806
+ };
6807
+ this.mediaQueryObservers.add(entry);
6808
+ return controller.observer;
6809
+ }
5098
6810
  };
5099
6811
  function createHeadlessSession(options) {
5100
6812
  return new HeadlessSession(options);