@mpcore/simulator 0.0.3 → 0.1.1

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
@@ -63,6 +63,9 @@ function createHeadlessWx(driver) {
63
63
  clearStorage: true,
64
64
  clearStorageSync: true,
65
65
  createSelectorQuery: true,
66
+ getFileSystemManager: true,
67
+ getSavedFileInfo: true,
68
+ getSavedFileList: true,
66
69
  getAppBaseInfo: { return: {
67
70
  SDKVersion: true,
68
71
  enableDebug: true,
@@ -164,6 +167,7 @@ function createHeadlessWx(driver) {
164
167
  } },
165
168
  hideLoading: true,
166
169
  hideToast: true,
170
+ downloadFile: true,
167
171
  navigateBack: true,
168
172
  navigateTo: true,
169
173
  nextTick: true,
@@ -175,6 +179,7 @@ function createHeadlessWx(driver) {
175
179
  removeStorage: true,
176
180
  removeStorageSync: true,
177
181
  request: true,
182
+ saveFile: true,
178
183
  setBackgroundColor: true,
179
184
  setBackgroundTextStyle: true,
180
185
  setStorage: true,
@@ -195,6 +200,7 @@ function createHeadlessWx(driver) {
195
200
  showToast: true,
196
201
  stopPullDownRefresh: true,
197
202
  switchTab: true,
203
+ uploadFile: true,
198
204
  removeTabBarBadge: true,
199
205
  setTabBarBadge: true,
200
206
  updateShareMenu: true
@@ -264,6 +270,9 @@ function createHeadlessWx(driver) {
264
270
  return query;
265
271
  },
266
272
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
273
+ getFileSystemManager: () => driver.getFileSystemManager(),
274
+ getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
275
+ getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
267
276
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
268
277
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
269
278
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
@@ -282,6 +291,7 @@ function createHeadlessWx(driver) {
282
291
  getWindowInfoSync: () => driver.getWindowInfoSync(),
283
292
  hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
284
293
  hideToast: () => driver.hideToast(),
294
+ downloadFile: (option) => driver.downloadFile(option),
285
295
  navigateBack: (option) => invokeWxApi(() => {
286
296
  driver.navigateBack(option);
287
297
  }, option),
@@ -300,12 +310,14 @@ function createHeadlessWx(driver) {
300
310
  redirectTo: (option) => invokeWxApi(() => {
301
311
  driver.redirectTo(option);
302
312
  }, option),
313
+ removeSavedFile: (option) => invokeWxApi(() => driver.removeSavedFile(option), option),
303
314
  removeStorage: (option) => invokeWxApi(() => {
304
315
  driver.removeStorageSync(option.key);
305
316
  return { errMsg: "removeStorage:ok" };
306
317
  }, option),
307
318
  removeStorageSync: (key) => driver.removeStorageSync(key),
308
319
  request: (option) => driver.request(option),
320
+ saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
309
321
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
310
322
  setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
311
323
  setStorage: (option) => invokeWxApi(() => {
@@ -331,6 +343,7 @@ function createHeadlessWx(driver) {
331
343
  switchTab: (option) => invokeWxApi(() => {
332
344
  driver.switchTab(option);
333
345
  }, option),
346
+ uploadFile: (option) => driver.uploadFile(option),
334
347
  removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
335
348
  setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
336
349
  updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
@@ -465,10 +478,10 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
465
478
  //#endregion
466
479
  //#region src/project/resolveRoutes.ts
467
480
  const LEADING_SLASH_RE$6 = /^\/+/;
468
- const TRAILING_SLASH_RE = /\/+$/;
481
+ const TRAILING_SLASH_RE$1 = /\/+$/;
469
482
  const DUPLICATE_SLASH_RE = /\/{2,}/g;
470
483
  function normalizeSegment(value) {
471
- return value.replace(LEADING_SLASH_RE$6, "").replace(TRAILING_SLASH_RE, "");
484
+ return value.replace(LEADING_SLASH_RE$6, "").replace(TRAILING_SLASH_RE$1, "");
472
485
  }
473
486
  function pushRoute(records, seen, record) {
474
487
  if (!record.route || seen.has(record.route)) return;
@@ -1478,6 +1491,8 @@ const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1478
1491
  const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1479
1492
  const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
1480
1493
  const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1494
+ const TRAILING_SLASH_RE = /\/+$/;
1495
+ const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1481
1496
  const textEncoder = new TextEncoder();
1482
1497
  function byteLength(input) {
1483
1498
  return textEncoder.encode(input).byteLength;
@@ -1531,15 +1546,113 @@ function resolveRequestResponse(mock, option) {
1531
1546
  statusCode: mock.statusCode ?? 200
1532
1547
  };
1533
1548
  }
1549
+ function matchesSimpleUrlMock(mock, url) {
1550
+ if (typeof mock.url === "string") return mock.url === url;
1551
+ mock.url.lastIndex = 0;
1552
+ return mock.url.test(url);
1553
+ }
1554
+ function resolveDownloadFileResponse(mock, option, tempFilePath) {
1555
+ return {
1556
+ fileContent: typeof mock.fileContent === "function" ? mock.fileContent(option) : mock.fileContent,
1557
+ result: {
1558
+ errMsg: "downloadFile:ok",
1559
+ statusCode: mock.statusCode ?? 200,
1560
+ tempFilePath
1561
+ }
1562
+ };
1563
+ }
1564
+ function resolveUploadFileResponse(mock, option, fileContent) {
1565
+ const rawResponse = typeof mock.response === "function" ? mock.response({
1566
+ ...option,
1567
+ fileContent
1568
+ }) : mock.response;
1569
+ if (typeof rawResponse === "string") return {
1570
+ data: rawResponse,
1571
+ errMsg: "uploadFile:ok",
1572
+ statusCode: mock.statusCode ?? 200
1573
+ };
1574
+ return {
1575
+ data: rawResponse.data == null ? "" : String(rawResponse.data),
1576
+ errMsg: rawResponse.errMsg ?? "uploadFile:ok",
1577
+ statusCode: rawResponse.statusCode ?? mock.statusCode ?? 200
1578
+ };
1579
+ }
1580
+ function normalizeDelay(delay) {
1581
+ return Number.isFinite(delay) ? Math.max(0, Math.trunc(delay ?? 0)) : 0;
1582
+ }
1583
+ function createNoopTask() {
1584
+ return { abort() {} };
1585
+ }
1586
+ function normalizeEncoding(encoding) {
1587
+ const normalized = (encoding ?? "utf8").trim().toLowerCase();
1588
+ if (normalized === "utf8" || normalized === "utf-8") return "utf8";
1589
+ throw new Error(`Unsupported file encoding in headless runtime: ${encoding}`);
1590
+ }
1591
+ function isSavedFilePath(path) {
1592
+ return SAVED_FILE_PREFIXES.some((prefix) => path === prefix.slice(0, -1) || path.startsWith(prefix));
1593
+ }
1594
+ function normalizeFsPath(input) {
1595
+ const trimmed = input.trim();
1596
+ if (!trimmed) throw new Error("File path must be a non-empty string in headless runtime.");
1597
+ if (trimmed.length > 1 && trimmed.endsWith("/")) return trimmed.replace(TRAILING_SLASH_RE, "");
1598
+ return trimmed;
1599
+ }
1600
+ function splitFsPath(input) {
1601
+ const normalized = normalizeFsPath(input);
1602
+ const schemeIndex = normalized.indexOf("://");
1603
+ if (schemeIndex >= 0) {
1604
+ const afterScheme = schemeIndex + 3;
1605
+ const firstSlash = normalized.indexOf("/", afterScheme);
1606
+ if (firstSlash < 0) return {
1607
+ prefix: normalized,
1608
+ segments: []
1609
+ };
1610
+ return {
1611
+ prefix: normalized.slice(0, firstSlash),
1612
+ segments: normalized.slice(firstSlash + 1).split("/").filter(Boolean)
1613
+ };
1614
+ }
1615
+ return {
1616
+ prefix: normalized.startsWith("/") ? "/" : "",
1617
+ segments: normalized.split("/").filter(Boolean)
1618
+ };
1619
+ }
1620
+ function joinFsPath(prefix, segments) {
1621
+ if (segments.length === 0) return prefix || ".";
1622
+ if (!prefix) return segments.join("/");
1623
+ if (prefix === "/") return `/${segments.join("/")}`;
1624
+ return `${prefix}/${segments.join("/")}`;
1625
+ }
1626
+ function listParentDirectories(input) {
1627
+ const { prefix, segments } = splitFsPath(input);
1628
+ const parents = [];
1629
+ if (segments.length === 0) {
1630
+ if (prefix && prefix !== "/") parents.push(prefix);
1631
+ return parents;
1632
+ }
1633
+ for (let index = 0; index < segments.length; index += 1) {
1634
+ const parentPath = joinFsPath(prefix, segments.slice(0, index));
1635
+ if (parentPath !== "." && parentPath !== "/") parents.push(parentPath);
1636
+ }
1637
+ return parents;
1638
+ }
1534
1639
  function createHeadlessWxState() {
1535
1640
  const actionSheetLogs = [];
1536
1641
  const actionSheetMocks = [];
1642
+ const downloadFileLogs = [];
1643
+ const downloadFileMocks = [];
1537
1644
  const modalLogs = [];
1538
1645
  const networkStatusChangeCallbacks = /* @__PURE__ */ new Set();
1539
1646
  const modalMocks = [];
1540
1647
  const requestLogs = [];
1541
1648
  const requestMocks = [];
1542
1649
  const storage = /* @__PURE__ */ new Map();
1650
+ const uploadFileLogs = [];
1651
+ const uploadFileMocks = [];
1652
+ const files = /* @__PURE__ */ new Map();
1653
+ const savedFiles = /* @__PURE__ */ new Map();
1654
+ const directories = /* @__PURE__ */ new Set();
1655
+ let fileId = 0;
1543
1656
  let loading = null;
1544
1657
  let networkType = "wifi";
1545
1658
  let shareMenu = {
@@ -1549,10 +1662,424 @@ function createHeadlessWxState() {
1549
1662
  withShareTicket: false
1550
1663
  };
1551
1664
  let toast = null;
1665
+ const allocateFilePath = (bucket, preferredPath) => {
1666
+ if (typeof preferredPath === "string" && preferredPath.trim()) return preferredPath.trim();
1667
+ fileId += 1;
1668
+ return `headless://wxfile/${bucket}/${String(fileId).padStart(4, "0")}`;
1669
+ };
1670
+ const runDelayedTask = (delay, onSuccess, onFail, abortMessage) => {
1671
+ if (delay <= 0) {
1672
+ onSuccess(void 0);
1673
+ return createNoopTask();
1674
+ }
1675
+ let completed = false;
1676
+ const timer = setTimeout(() => {
1677
+ if (completed) return;
1678
+ completed = true;
1679
+ onSuccess(void 0);
1680
+ }, delay);
1681
+ return { abort() {
1682
+ if (completed) return;
1683
+ completed = true;
1684
+ clearTimeout(timer);
1685
+ onFail(new Error(abortMessage));
1686
+ } };
1687
+ };
1688
+ const ensureDirectoryTree = (targetPath) => {
1689
+ for (const directoryPath of listParentDirectories(targetPath)) directories.add(directoryPath);
1690
+ };
1691
+ const createStats = (isDirectory, size) => ({
1692
+ isDirectory: () => isDirectory,
1693
+ isFile: () => !isDirectory,
1694
+ size
1695
+ });
1696
+ const updateSavedFileMetadata = (normalizedPath, fileContent) => {
1697
+ const savedFile = savedFiles.get(normalizedPath);
1698
+ if (!savedFile) return;
1699
+ savedFiles.set(normalizedPath, {
1700
+ ...savedFile,
1701
+ size: fileContent.length
1702
+ });
1703
+ };
1704
+ const setSavedFileMetadata = (normalizedPath, fileContent, createTime = Date.now()) => {
1705
+ savedFiles.set(normalizedPath, {
1706
+ createTime,
1707
+ filePath: normalizedPath,
1708
+ size: fileContent.length
1709
+ });
1710
+ };
1711
+ const accessFile = (filePath) => {
1712
+ const normalizedPath = normalizeFsPath(filePath);
1713
+ if (!files.has(normalizedPath) && !directories.has(normalizedPath)) throw new Error(`access:fail no such file or directory, access '${normalizedPath}'`);
1714
+ return { errMsg: "access:ok" };
1715
+ };
1716
+ const readFile = (filePath, encoding) => {
1717
+ normalizeEncoding(encoding);
1718
+ const normalizedPath = normalizeFsPath(filePath);
1719
+ const fileContent = files.get(normalizedPath);
1720
+ if (fileContent == null) throw new Error(`readFile:fail no such file or directory, open '${normalizedPath}'`);
1721
+ return {
1722
+ data: fileContent,
1723
+ errMsg: "readFile:ok"
1724
+ };
1725
+ };
1726
+ const writeFile = (filePath, data, encoding) => {
1727
+ const normalizedPath = normalizeFsPath(filePath);
1728
+ normalizeEncoding(encoding);
1729
+ ensureDirectoryTree(normalizedPath);
1730
+ const fileContent = String(data);
1731
+ files.set(normalizedPath, fileContent);
1732
+ updateSavedFileMetadata(normalizedPath, fileContent);
1733
+ return { errMsg: "writeFile:ok" };
1734
+ };
1735
+ const appendFile = (filePath, data, encoding) => {
1736
+ const normalizedPath = normalizeFsPath(filePath);
1737
+ normalizeEncoding(encoding);
1738
+ ensureDirectoryTree(normalizedPath);
1739
+ const nextFileContent = `${files.get(normalizedPath) ?? ""}${String(data)}`;
1740
+ files.set(normalizedPath, nextFileContent);
1741
+ updateSavedFileMetadata(normalizedPath, nextFileContent);
1742
+ return { errMsg: "appendFile:ok" };
1743
+ };
1744
+ const copyFile = (srcPath, destPath) => {
1745
+ const normalizedSrcPath = normalizeFsPath(srcPath);
1746
+ const normalizedDestPath = normalizeFsPath(destPath);
1747
+ const fileContent = files.get(normalizedSrcPath);
1748
+ if (fileContent == null) throw new Error(`copyFile:fail no such file or directory, copyfile '${normalizedSrcPath}'`);
1749
+ ensureDirectoryTree(normalizedDestPath);
1750
+ files.set(normalizedDestPath, fileContent);
1751
+ if (savedFiles.has(normalizedDestPath)) setSavedFileMetadata(normalizedDestPath, fileContent, savedFiles.get(normalizedDestPath)?.createTime ?? Date.now());
1752
+ return { errMsg: "copyFile:ok" };
1753
+ };
1754
+ const renameFile = (oldPath, newPath) => {
1755
+ const normalizedOldPath = normalizeFsPath(oldPath);
1756
+ const normalizedNewPath = normalizeFsPath(newPath);
1757
+ const fileContent = files.get(normalizedOldPath);
1758
+ if (fileContent == null) throw new Error(`rename:fail no such file or directory, rename '${normalizedOldPath}'`);
1759
+ const targetSavedFile = savedFiles.get(normalizedNewPath);
1760
+ files.delete(normalizedOldPath);
1761
+ const savedFile = savedFiles.get(normalizedOldPath);
1762
+ if (savedFile) savedFiles.delete(normalizedOldPath);
1763
+ ensureDirectoryTree(normalizedNewPath);
1764
+ files.set(normalizedNewPath, fileContent);
1765
+ if (targetSavedFile) savedFiles.set(normalizedNewPath, {
1766
+ ...targetSavedFile,
1767
+ size: fileContent.length
1768
+ });
1769
+ else if (savedFile && isSavedFilePath(normalizedNewPath)) savedFiles.set(normalizedNewPath, {
1770
+ ...savedFile,
1771
+ filePath: normalizedNewPath,
1772
+ size: fileContent.length
1773
+ });
1774
+ return { errMsg: "rename:ok" };
1775
+ };
1776
+ const unlinkFile = (filePath) => {
1777
+ const normalizedPath = normalizeFsPath(filePath);
1778
+ if (!files.has(normalizedPath)) throw new Error(`unlink:fail no such file or directory, unlink '${normalizedPath}'`);
1779
+ files.delete(normalizedPath);
1780
+ savedFiles.delete(normalizedPath);
1781
+ return { errMsg: "unlink:ok" };
1782
+ };
1783
+ const mkdir = (dirPath, recursive = false) => {
1784
+ const normalizedPath = normalizeFsPath(dirPath);
1785
+ if (!recursive) {
1786
+ const directParent = listParentDirectories(normalizedPath).at(-1);
1787
+ if (directParent && !directories.has(directParent)) throw new Error(`mkdir:fail no such file or directory, mkdir '${normalizedPath}'`);
1788
+ }
1789
+ for (const directoryPath of [...listParentDirectories(normalizedPath), normalizedPath]) directories.add(directoryPath);
1790
+ return { errMsg: "mkdir:ok" };
1791
+ };
1792
+ const readdir = (dirPath) => {
1793
+ const normalizedPath = normalizeFsPath(dirPath);
1794
+ if (!directories.has(normalizedPath)) throw new Error(`readdir:fail no such file or directory, scandir '${normalizedPath}'`);
1795
+ const { prefix, segments } = splitFsPath(normalizedPath);
1796
+ const baseDepth = segments.length;
1797
+ const entries = /* @__PURE__ */ new Set();
1798
+ for (const directoryPath of directories) {
1799
+ if (directoryPath === normalizedPath) continue;
1800
+ const current = splitFsPath(directoryPath);
1801
+ if (current.prefix !== prefix || current.segments.length <= baseDepth) continue;
1802
+ if (current.segments.slice(0, baseDepth).join("/") !== segments.join("/")) continue;
1803
+ entries.add(current.segments[baseDepth]);
1804
+ }
1805
+ for (const filePath of files.keys()) {
1806
+ const current = splitFsPath(filePath);
1807
+ if (current.prefix !== prefix || current.segments.length <= baseDepth) continue;
1808
+ if (current.segments.slice(0, baseDepth).join("/") !== segments.join("/")) continue;
1809
+ entries.add(current.segments[baseDepth]);
1810
+ }
1811
+ return {
1812
+ errMsg: "readdir:ok",
1813
+ files: Array.from(entries).sort((a, b) => a.localeCompare(b))
1814
+ };
1815
+ };
1816
+ const rmdir = (dirPath, recursive = false) => {
1817
+ const normalizedPath = normalizeFsPath(dirPath);
1818
+ if (files.has(normalizedPath)) throw new Error(`rmdir:fail not a directory, rmdir '${normalizedPath}'`);
1819
+ if (!directories.has(normalizedPath)) throw new Error(`rmdir:fail no such file or directory, rmdir '${normalizedPath}'`);
1820
+ const childDirectoryPaths = Array.from(directories).filter((currentPath) => currentPath !== normalizedPath && currentPath.startsWith(`${normalizedPath}/`));
1821
+ const childFilePaths = Array.from(files.keys()).filter((currentPath) => currentPath.startsWith(`${normalizedPath}/`));
1822
+ if (!recursive && (childDirectoryPaths.length > 0 || childFilePaths.length > 0)) throw new Error(`rmdir:fail directory not empty, rmdir '${normalizedPath}'`);
1823
+ directories.delete(normalizedPath);
1824
+ childDirectoryPaths.forEach((currentPath) => directories.delete(currentPath));
1825
+ childFilePaths.forEach((currentPath) => {
1826
+ files.delete(currentPath);
1827
+ savedFiles.delete(currentPath);
1828
+ });
1829
+ return { errMsg: "rmdir:ok" };
1830
+ };
1831
+ const stat = (inputPath) => {
1832
+ const normalizedPath = normalizeFsPath(inputPath);
1833
+ if (files.has(normalizedPath)) return {
1834
+ errMsg: "stat:ok",
1835
+ stats: createStats(false, files.get(normalizedPath)?.length ?? 0)
1836
+ };
1837
+ if (directories.has(normalizedPath)) return {
1838
+ errMsg: "stat:ok",
1839
+ stats: createStats(true, 0)
1840
+ };
1841
+ throw new Error(`stat:fail no such file or directory, stat '${normalizedPath}'`);
1842
+ };
1843
+ const getSavedFileList = () => {
1844
+ return {
1845
+ errMsg: "getSavedFileList:ok",
1846
+ fileList: Array.from(savedFiles.values()).map((item) => ({ ...item })).sort((a, b) => a.filePath.localeCompare(b.filePath))
1847
+ };
1848
+ };
1849
+ const getSavedFileInfo = (filePath) => {
1850
+ const normalizedPath = normalizeFsPath(filePath);
1851
+ const savedFile = savedFiles.get(normalizedPath);
1852
+ if (!savedFile) throw new Error(`getSavedFileInfo:fail no such file or directory, stat '${normalizedPath}'`);
1853
+ return {
1854
+ createTime: savedFile.createTime,
1855
+ errMsg: "getSavedFileInfo:ok",
1856
+ size: savedFile.size
1857
+ };
1858
+ };
1859
+ const removeSavedFile = (filePath) => {
1860
+ const normalizedPath = normalizeFsPath(filePath);
1861
+ if (!savedFiles.has(normalizedPath)) throw new Error(`removeSavedFile:fail no such file or directory, unlink '${normalizedPath}'`);
1862
+ savedFiles.delete(normalizedPath);
1863
+ files.delete(normalizedPath);
1864
+ return { errMsg: "removeSavedFile:ok" };
1865
+ };
1866
+ const fileSystemManager = {
1867
+ access(option) {
1868
+ try {
1869
+ const result = accessFile(option.path);
1870
+ option.success?.(result);
1871
+ option.complete?.(result);
1872
+ return result;
1873
+ } catch (error) {
1874
+ option.fail?.(error);
1875
+ option.complete?.();
1876
+ return;
1877
+ }
1878
+ },
1879
+ accessSync(path) {
1880
+ accessFile(path);
1881
+ },
1882
+ appendFile(option) {
1883
+ try {
1884
+ const result = appendFile(option.filePath, option.data, option.encoding);
1885
+ option.success?.(result);
1886
+ option.complete?.(result);
1887
+ return result;
1888
+ } catch (error) {
1889
+ option.fail?.(error);
1890
+ option.complete?.();
1891
+ return;
1892
+ }
1893
+ },
1894
+ appendFileSync(filePath, data, encoding) {
1895
+ appendFile(filePath, data, encoding);
1896
+ },
1897
+ copyFile(option) {
1898
+ try {
1899
+ const result = copyFile(option.srcPath, option.destPath);
1900
+ option.success?.(result);
1901
+ option.complete?.(result);
1902
+ return result;
1903
+ } catch (error) {
1904
+ option.fail?.(error);
1905
+ option.complete?.();
1906
+ return;
1907
+ }
1908
+ },
1909
+ copyFileSync(srcPath, destPath) {
1910
+ copyFile(srcPath, destPath);
1911
+ },
1912
+ mkdir(option) {
1913
+ try {
1914
+ const result = mkdir(option.dirPath, option.recursive);
1915
+ option.success?.(result);
1916
+ option.complete?.(result);
1917
+ return result;
1918
+ } catch (error) {
1919
+ option.fail?.(error);
1920
+ option.complete?.();
1921
+ return;
1922
+ }
1923
+ },
1924
+ mkdirSync(dirPath, recursive) {
1925
+ mkdir(dirPath, recursive);
1926
+ },
1927
+ readFile(option) {
1928
+ try {
1929
+ const result = readFile(option.filePath, option.encoding);
1930
+ option.success?.(result);
1931
+ option.complete?.(result);
1932
+ return result;
1933
+ } catch (error) {
1934
+ option.fail?.(error);
1935
+ option.complete?.();
1936
+ return;
1937
+ }
1938
+ },
1939
+ readFileSync(filePath, encoding) {
1940
+ return readFile(filePath, encoding).data;
1941
+ },
1942
+ readdir(option) {
1943
+ try {
1944
+ const result = readdir(option.dirPath);
1945
+ option.success?.(result);
1946
+ option.complete?.(result);
1947
+ return result;
1948
+ } catch (error) {
1949
+ option.fail?.(error);
1950
+ option.complete?.();
1951
+ return;
1952
+ }
1953
+ },
1954
+ readdirSync(dirPath) {
1955
+ return readdir(dirPath).files;
1956
+ },
1957
+ rmdir(option) {
1958
+ try {
1959
+ const result = rmdir(option.dirPath, option.recursive);
1960
+ option.success?.(result);
1961
+ option.complete?.(result);
1962
+ return result;
1963
+ } catch (error) {
1964
+ option.fail?.(error);
1965
+ option.complete?.();
1966
+ return;
1967
+ }
1968
+ },
1969
+ rmdirSync(dirPath, recursive) {
1970
+ rmdir(dirPath, recursive);
1971
+ },
1972
+ rename(option) {
1973
+ try {
1974
+ const result = renameFile(option.oldPath, option.newPath);
1975
+ option.success?.(result);
1976
+ option.complete?.(result);
1977
+ return result;
1978
+ } catch (error) {
1979
+ option.fail?.(error);
1980
+ option.complete?.();
1981
+ return;
1982
+ }
1983
+ },
1984
+ renameSync(oldPath, newPath) {
1985
+ renameFile(oldPath, newPath);
1986
+ },
1987
+ stat(option) {
1988
+ try {
1989
+ const result = stat(option.path);
1990
+ option.success?.(result);
1991
+ option.complete?.(result);
1992
+ return result;
1993
+ } catch (error) {
1994
+ option.fail?.(error);
1995
+ option.complete?.();
1996
+ return;
1997
+ }
1998
+ },
1999
+ statSync(path) {
2000
+ return stat(path).stats;
2001
+ },
2002
+ unlink(option) {
2003
+ try {
2004
+ const result = unlinkFile(option.filePath);
2005
+ option.success?.(result);
2006
+ option.complete?.(result);
2007
+ return result;
2008
+ } catch (error) {
2009
+ option.fail?.(error);
2010
+ option.complete?.();
2011
+ return;
2012
+ }
2013
+ },
2014
+ unlinkSync(filePath) {
2015
+ unlinkFile(filePath);
2016
+ },
2017
+ writeFile(option) {
2018
+ try {
2019
+ const result = writeFile(option.filePath, option.data, option.encoding);
2020
+ option.success?.(result);
2021
+ option.complete?.(result);
2022
+ return result;
2023
+ } catch (error) {
2024
+ option.fail?.(error);
2025
+ option.complete?.();
2026
+ return;
2027
+ }
2028
+ },
2029
+ writeFileSync(filePath, data, encoding) {
2030
+ writeFile(filePath, data, encoding);
2031
+ }
2032
+ };
1552
2033
  return {
1553
2034
  clearStorageSync() {
1554
2035
  storage.clear();
1555
2036
  },
2037
+ downloadFile(option) {
2038
+ const matchedMock = downloadFileMocks.find((mock) => matchesSimpleUrlMock(mock, option.url));
2039
+ if (!matchedMock) {
2040
+ const logEntry = {
2041
+ header: { ...option.header ?? {} },
2042
+ matched: false,
2043
+ url: option.url
2044
+ };
2045
+ downloadFileLogs.push(logEntry);
2046
+ const error = /* @__PURE__ */ new Error(`No downloadFile mock matched in headless runtime: ${option.url}`);
2047
+ option.fail?.(error);
2048
+ option.complete?.();
2049
+ return createNoopTask();
2050
+ }
2051
+ const tempFilePath = allocateFilePath("temp", option.filePath);
2052
+ const delay = normalizeDelay(matchedMock.delay);
2053
+ const logEntry = {
2054
+ header: { ...option.header ?? {} },
2055
+ matched: true,
2056
+ response: {
2057
+ errMsg: "downloadFile:ok",
2058
+ statusCode: matchedMock.statusCode ?? 200,
2059
+ tempFilePath
2060
+ },
2061
+ tempFilePath,
2062
+ url: option.url
2063
+ };
2064
+ const commit = () => {
2065
+ const { fileContent, result } = resolveDownloadFileResponse(matchedMock, option, tempFilePath);
2066
+ ensureDirectoryTree(tempFilePath);
2067
+ files.set(tempFilePath, fileContent);
2068
+ logEntry.response = { ...result };
2069
+ downloadFileLogs.push(logEntry);
2070
+ option.success?.(result);
2071
+ option.complete?.(result);
2072
+ };
2073
+ const fail = (error) => {
2074
+ option.fail?.(error);
2075
+ option.complete?.();
2076
+ };
2077
+ if (delay <= 0) {
2078
+ commit();
2079
+ return createNoopTask();
2080
+ }
2081
+ return runDelayedTask(delay, commit, fail, "downloadFile:fail abort");
2082
+ },
1556
2083
  getActionSheetLogs() {
1557
2084
  return actionSheetLogs.map((entry) => ({
1558
2085
  ...entry,
@@ -1560,6 +2087,31 @@ function createHeadlessWxState() {
1560
2087
  result: entry.result ? { ...entry.result } : void 0
1561
2088
  }));
1562
2089
  },
2090
+ getDownloadFileLogs() {
2091
+ return downloadFileLogs.map((entry) => ({
2092
+ ...entry,
2093
+ header: { ...entry.header },
2094
+ response: entry.response ? { ...entry.response } : void 0
2095
+ }));
2096
+ },
2097
+ getFileSnapshot() {
2098
+ return Object.fromEntries(files.entries());
2099
+ },
2100
+ getDirectorySnapshot() {
2101
+ return Array.from(directories.values()).sort((a, b) => a.localeCompare(b));
2102
+ },
2103
+ getFileSystemManager() {
2104
+ return fileSystemManager;
2105
+ },
2106
+ getSavedFileInfo(option) {
2107
+ return getSavedFileInfo(option.filePath);
2108
+ },
2109
+ getSavedFileList() {
2110
+ return getSavedFileList();
2111
+ },
2112
+ getFileText(filePath) {
2113
+ return files.get(filePath) ?? null;
2114
+ },
1563
2115
  getNetworkType() {
1564
2116
  return {
1565
2117
  errMsg: "getNetworkType:ok",
@@ -1619,6 +2171,14 @@ function createHeadlessWxState() {
1619
2171
  getToast() {
1620
2172
  return toast ? { ...toast } : null;
1621
2173
  },
2174
+ getUploadFileLogs() {
2175
+ return uploadFileLogs.map((entry) => ({
2176
+ ...entry,
2177
+ formData: cloneValue$1(entry.formData),
2178
+ header: { ...entry.header },
2179
+ response: entry.response ? { ...entry.response } : void 0
2180
+ }));
2181
+ },
1622
2182
  hideLoading() {
1623
2183
  loading = null;
1624
2184
  return { errMsg: "hideLoading:ok" };
@@ -1641,12 +2201,26 @@ function createHeadlessWxState() {
1641
2201
  header: definition.header ? { ...definition.header } : void 0
1642
2202
  });
1643
2203
  },
2204
+ mockDownloadFile(definition) {
2205
+ downloadFileMocks.push({
2206
+ ...definition,
2207
+ delay: definition.delay,
2208
+ header: definition.header ? { ...definition.header } : void 0
2209
+ });
2210
+ },
1644
2211
  mockModal(definition = {}) {
1645
2212
  modalMocks.push({
1646
2213
  cancel: definition.cancel,
1647
2214
  confirm: definition.confirm
1648
2215
  });
1649
2216
  },
2217
+ mockUploadFile(definition) {
2218
+ uploadFileMocks.push({
2219
+ ...definition,
2220
+ delay: definition.delay,
2221
+ header: definition.header ? { ...definition.header } : void 0
2222
+ });
2223
+ },
1650
2224
  mockActionSheet(definition = {}) {
1651
2225
  actionSheetMocks.push({
1652
2226
  cancel: definition.cancel,
@@ -1673,7 +2247,7 @@ function createHeadlessWxState() {
1673
2247
  const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
1674
2248
  option.fail?.(error);
1675
2249
  option.complete?.();
1676
- return { abort() {} };
2250
+ return createNoopTask();
1677
2251
  }
1678
2252
  const response = resolveRequestResponse(matchedMock, option);
1679
2253
  const requestLogEntry = {
@@ -1689,28 +2263,40 @@ function createHeadlessWxState() {
1689
2263
  requestLogs.push(requestLogEntry);
1690
2264
  option.success?.(response);
1691
2265
  option.complete?.(response);
1692
- return { abort() {} };
2266
+ return createNoopTask();
1693
2267
  }
1694
- let completed = false;
1695
- const timer = setTimeout(() => {
1696
- if (completed) return;
1697
- completed = true;
2268
+ return runDelayedTask(delay, () => {
1698
2269
  requestLogs.push(requestLogEntry);
1699
2270
  option.success?.(response);
1700
2271
  option.complete?.(response);
1701
- }, delay);
1702
- return { abort() {
1703
- if (completed) return;
1704
- completed = true;
1705
- clearTimeout(timer);
1706
- const error = /* @__PURE__ */ new Error("request:fail abort");
2272
+ }, (error) => {
1707
2273
  option.fail?.(error);
1708
2274
  option.complete?.();
1709
- } };
2275
+ }, "request:fail abort");
2276
+ },
2277
+ removeSavedFile(option) {
2278
+ return removeSavedFile(option.filePath);
2279
+ },
2280
+ saveFile(option) {
2281
+ const fileContent = files.get(option.tempFilePath);
2282
+ if (fileContent == null) throw new Error(`saveFile:fail tempFilePath not found: ${option.tempFilePath}`);
2283
+ const savedFilePath = allocateFilePath("saved", option.filePath);
2284
+ ensureDirectoryTree(savedFilePath);
2285
+ files.set(savedFilePath, fileContent);
2286
+ setSavedFileMetadata(savedFilePath, fileContent, savedFiles.get(savedFilePath)?.createTime ?? Date.now());
2287
+ return {
2288
+ errMsg: "saveFile:ok",
2289
+ savedFilePath
2290
+ };
1710
2291
  },
1711
2292
  setStorageSync(key, value) {
1712
2293
  storage.set(key, cloneValue$1(value));
1713
2294
  },
2295
+ setFile(filePath, fileContent) {
2296
+ const normalizedPath = normalizeFsPath(filePath);
2297
+ ensureDirectoryTree(normalizedPath);
2298
+ files.set(normalizedPath, fileContent);
2299
+ },
1714
2300
  setNetworkType(nextNetworkType) {
1715
2301
  networkType = nextNetworkType;
1716
2302
  const snapshot = createNetworkSnapshot(networkType);
@@ -1792,6 +2378,50 @@ function createHeadlessWxState() {
1792
2378
  };
1793
2379
  return { errMsg: "showToast:ok" };
1794
2380
  },
2381
+ uploadFile(option) {
2382
+ const fileContent = files.get(option.filePath);
2383
+ if (fileContent == null) {
2384
+ const error = /* @__PURE__ */ new Error(`uploadFile:fail file not found: ${option.filePath}`);
2385
+ option.fail?.(error);
2386
+ option.complete?.();
2387
+ return createNoopTask();
2388
+ }
2389
+ const matchedMock = uploadFileMocks.find((mock) => matchesSimpleUrlMock(mock, option.url));
2390
+ const logEntry = {
2391
+ fileContent,
2392
+ fileName: option.fileName,
2393
+ filePath: option.filePath,
2394
+ formData: cloneValue$1(option.formData ?? {}),
2395
+ header: { ...option.header ?? {} },
2396
+ matched: Boolean(matchedMock),
2397
+ name: option.name,
2398
+ url: option.url
2399
+ };
2400
+ if (!matchedMock) {
2401
+ uploadFileLogs.push(logEntry);
2402
+ const error = /* @__PURE__ */ new Error(`No uploadFile mock matched in headless runtime: ${option.url}`);
2403
+ option.fail?.(error);
2404
+ option.complete?.();
2405
+ return createNoopTask();
2406
+ }
2407
+ const response = resolveUploadFileResponse(matchedMock, option, fileContent);
2408
+ const delay = normalizeDelay(matchedMock.delay);
2409
+ const commit = () => {
2410
+ logEntry.response = { ...response };
2411
+ uploadFileLogs.push(logEntry);
2412
+ option.success?.(response);
2413
+ option.complete?.(response);
2414
+ };
2415
+ const fail = (error) => {
2416
+ option.fail?.(error);
2417
+ option.complete?.();
2418
+ };
2419
+ if (delay <= 0) {
2420
+ commit();
2421
+ return createNoopTask();
2422
+ }
2423
+ return runDelayedTask(delay, commit, fail, "uploadFile:fail abort");
2424
+ },
1795
2425
  updateShareMenu(option = {}) {
1796
2426
  shareMenu = {
1797
2427
  isUpdatableMessage: option.isUpdatableMessage == null ? shareMenu.isUpdatableMessage : Boolean(option.isUpdatableMessage),
@@ -2315,6 +2945,9 @@ var BrowserHeadlessSession = class {
2315
2945
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2316
2946
  this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
2317
2947
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
2948
+ getFileSystemManager: () => this.wxState.getFileSystemManager(),
2949
+ getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
2950
+ getSavedFileList: () => this.wxState.getSavedFileList(),
2318
2951
  getEnterOptionsSync: () => ({
2319
2952
  ...this.enterOptions,
2320
2953
  query: { ...this.enterOptions.query },
@@ -2344,13 +2977,16 @@ var BrowserHeadlessSession = class {
2344
2977
  getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
2345
2978
  hideLoading: () => this.wxState.hideLoading(),
2346
2979
  hideToast: () => this.wxState.hideToast(),
2980
+ downloadFile: (option) => this.wxState.downloadFile(option),
2347
2981
  reLaunch: (option) => this.reLaunch(option.url),
2348
2982
  redirectTo: (option) => this.redirectTo(option.url),
2983
+ removeSavedFile: (option) => this.wxState.removeSavedFile(option),
2349
2984
  nextTick: (callback) => queueMicrotask(() => callback?.()),
2350
2985
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2351
2986
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
2352
2987
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
2353
2988
  request: (option) => this.wxState.request(option),
2989
+ saveFile: (option) => this.wxState.saveFile(option),
2354
2990
  setBackgroundColor: (option) => this.setBackgroundColor(option),
2355
2991
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
2356
2992
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
@@ -2370,6 +3006,7 @@ var BrowserHeadlessSession = class {
2370
3006
  showToast: (option) => this.wxState.showToast(option),
2371
3007
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
2372
3008
  switchTab: (option) => this.switchTab(option.url),
3009
+ uploadFile: (option) => this.wxState.uploadFile(option),
2373
3010
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
2374
3011
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
2375
3012
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
@@ -2398,6 +3035,24 @@ var BrowserHeadlessSession = class {
2398
3035
  getRequestLogs() {
2399
3036
  return this.wxState.getRequestLogs();
2400
3037
  }
3038
+ getDownloadFileLogs() {
3039
+ return this.wxState.getDownloadFileLogs();
3040
+ }
3041
+ getUploadFileLogs() {
3042
+ return this.wxState.getUploadFileLogs();
3043
+ }
3044
+ getFileSnapshot() {
3045
+ return this.wxState.getFileSnapshot();
3046
+ }
3047
+ getDirectorySnapshot() {
3048
+ return this.wxState.getDirectorySnapshot();
3049
+ }
3050
+ getFileText(filePath) {
3051
+ return this.wxState.getFileText(filePath);
3052
+ }
3053
+ getSavedFileListSnapshot() {
3054
+ return this.wxState.getSavedFileList().fileList;
3055
+ }
2401
3056
  getStorageSnapshot() {
2402
3057
  return this.wxState.getStorageSnapshot();
2403
3058
  }
@@ -2478,6 +3133,15 @@ var BrowserHeadlessSession = class {
2478
3133
  mockRequest(definition) {
2479
3134
  this.wxState.mockRequest(definition);
2480
3135
  }
3136
+ mockDownloadFile(definition) {
3137
+ this.wxState.mockDownloadFile(definition);
3138
+ }
3139
+ mockUploadFile(definition) {
3140
+ this.wxState.mockUploadFile(definition);
3141
+ }
3142
+ setFile(filePath, fileContent) {
3143
+ this.wxState.setFile(filePath, fileContent);
3144
+ }
2481
3145
  setNetworkType(networkType) {
2482
3146
  return this.wxState.setNetworkType(networkType);
2483
3147
  }
@@ -3684,6 +4348,9 @@ var HeadlessSession = class {
3684
4348
  this.tabBarVisible = this.tabBarRoutes.size > 0;
3685
4349
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
3686
4350
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
4351
+ getFileSystemManager: () => this.wxState.getFileSystemManager(),
4352
+ getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
4353
+ getSavedFileList: () => this.wxState.getSavedFileList(),
3687
4354
  getEnterOptionsSync: () => ({
3688
4355
  ...this.enterOptions,
3689
4356
  query: { ...this.enterOptions.query },
@@ -3713,13 +4380,16 @@ var HeadlessSession = class {
3713
4380
  getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
3714
4381
  hideLoading: () => this.wxState.hideLoading(),
3715
4382
  hideToast: () => this.wxState.hideToast(),
4383
+ downloadFile: (option) => this.wxState.downloadFile(option),
3716
4384
  reLaunch: (option) => this.reLaunch(option.url),
3717
4385
  redirectTo: (option) => this.redirectTo(option.url),
4386
+ removeSavedFile: (option) => this.wxState.removeSavedFile(option),
3718
4387
  nextTick: (callback) => queueMicrotask(() => callback?.()),
3719
4388
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
3720
4389
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
3721
4390
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
3722
4391
  request: (option) => this.wxState.request(option),
4392
+ saveFile: (option) => this.wxState.saveFile(option),
3723
4393
  setBackgroundColor: (option) => this.setBackgroundColor(option),
3724
4394
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
3725
4395
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
@@ -3739,6 +4409,7 @@ var HeadlessSession = class {
3739
4409
  showToast: (option) => this.wxState.showToast(option),
3740
4410
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
3741
4411
  switchTab: (option) => this.switchTab(option.url),
4412
+ uploadFile: (option) => this.wxState.uploadFile(option),
3742
4413
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
3743
4414
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
3744
4415
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
@@ -3767,6 +4438,24 @@ var HeadlessSession = class {
3767
4438
  getRequestLogs() {
3768
4439
  return this.wxState.getRequestLogs();
3769
4440
  }
4441
+ getDownloadFileLogs() {
4442
+ return this.wxState.getDownloadFileLogs();
4443
+ }
4444
+ getUploadFileLogs() {
4445
+ return this.wxState.getUploadFileLogs();
4446
+ }
4447
+ getFileSnapshot() {
4448
+ return this.wxState.getFileSnapshot();
4449
+ }
4450
+ getDirectorySnapshot() {
4451
+ return this.wxState.getDirectorySnapshot();
4452
+ }
4453
+ getFileText(filePath) {
4454
+ return this.wxState.getFileText(filePath);
4455
+ }
4456
+ getSavedFileListSnapshot() {
4457
+ return this.wxState.getSavedFileList().fileList;
4458
+ }
3770
4459
  renderCurrentPage() {
3771
4460
  const current = this.requireCurrentPage("renderCurrentPage()");
3772
4461
  return renderRuntimePageTree({
@@ -3948,6 +4637,15 @@ var HeadlessSession = class {
3948
4637
  mockRequest(definition) {
3949
4638
  this.wxState.mockRequest(definition);
3950
4639
  }
4640
+ mockDownloadFile(definition) {
4641
+ this.wxState.mockDownloadFile(definition);
4642
+ }
4643
+ mockUploadFile(definition) {
4644
+ this.wxState.mockUploadFile(definition);
4645
+ }
4646
+ setFile(filePath, fileContent) {
4647
+ this.wxState.setFile(filePath, fileContent);
4648
+ }
3951
4649
  setNetworkType(networkType) {
3952
4650
  return this.wxState.setNetworkType(networkType);
3953
4651
  }