@heybox/hb-sdk 0.8.1-alpha.2 → 0.8.1-alpha.6

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +58 -4
  3. package/dist/cli-chunks/{build-FQoALfGC.cjs → build-B0X9pazW.cjs} +16 -10
  4. package/dist/cli-chunks/{context-CA_Q1lyH.cjs → context-DVfWZ6d1.cjs} +8 -3
  5. package/dist/cli-chunks/{create-BjIl4hy4.cjs → create-CyQWVxCA.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-CiPQYsW_.cjs → dev-DP7WtQOo.cjs} +465 -117
  7. package/dist/cli-chunks/{doctor-CS6c3n-W.cjs → doctor-D6l-ONq-.cjs} +1 -1
  8. package/dist/cli-chunks/{index-BEn7WaqA.cjs → index-CDwwaNvP.cjs} +87 -15
  9. package/dist/cli-chunks/{index-CsP_x6y6.cjs → index-DvOPzPxS.cjs} +2 -2
  10. package/dist/cli-chunks/{index.esm-DeEc_-uV.cjs → index.esm-B8pX0BrZ.cjs} +9 -8
  11. package/dist/cli-chunks/{login-BENCVgaQ.cjs → login-Dt-FHzpL.cjs} +2 -2
  12. package/dist/cli-chunks/{project-vite-BO8oOfcs.cjs → project-vite-CE7kyqxl.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-IiVCXcSq.cjs → remote-Be6PeR-n.cjs} +41 -28
  14. package/dist/cli-chunks/{runtime-gate-BMSY22AL.cjs → runtime-gate-BWb8QIcX.cjs} +0 -107
  15. package/dist/cli-chunks/{runtime-permission-env-BPRwn4Yc.cjs → runtime-permission-env-DWSscWBT.cjs} +304 -23
  16. package/dist/cli-chunks/{session-C0eIKZ6V.cjs → session-DZXRQ4Dp.cjs} +1 -1
  17. package/dist/cli-chunks/{skill-DpInwbiA.cjs → skill-B8GWL2KT.cjs} +83 -27
  18. package/dist/cli-chunks/{version-BONZQWPR.cjs → version-D19lZmYN.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-Bb43BPMS.js +101 -0
  21. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DnPRjCa3.js +6 -0
  22. package/dist/devtools/browser-dev-host/assets/index-D-aNERAr.css +1 -0
  23. package/dist/devtools/browser-dev-host/assets/index-Dh5wRj5c.js +567 -0
  24. package/dist/devtools/browser-dev-host/index.html +3 -3
  25. package/dist/index.cjs.js +1893 -1562
  26. package/dist/index.esm.js +1893 -1563
  27. package/dist/miniapp-publish.cjs.js +61 -0
  28. package/dist/miniapp-publish.esm.js +59 -1
  29. package/dist/protocol.cjs.js +64 -13
  30. package/dist/protocol.esm.js +64 -13
  31. package/dist/templates/vanilla-vite-js/README.md.ejs +1 -1
  32. package/dist/templates/vanilla-vite-js/package.json.ejs +1 -0
  33. package/dist/templates/vanilla-vite-js/vite.config.js +1 -1
  34. package/dist/vite.cjs.js +1333 -18
  35. package/dist/vite.esm.js +1334 -20
  36. package/package.json +8 -8
  37. package/skill/SKILL.md +10 -5
  38. package/skill/references/api-protocol.md +3 -3
  39. package/skill/references/api-root.md +225 -210
  40. package/skill/references/cli.md +9 -3
  41. package/skill/references/examples.md +13 -1
  42. package/skill/references/recipes.md +161 -0
  43. package/skill/references/safety-boundaries.md +7 -1
  44. package/skill/skill.json +5 -5
  45. package/types/core/client.d.ts +2 -0
  46. package/types/core/sdk.d.ts +3 -0
  47. package/types/core/singleton.d.ts +3 -0
  48. package/types/devtools/device-logs.d.ts +48 -0
  49. package/types/index.d.ts +3 -1
  50. package/types/miniapp-manifest/companion-directory.d.ts +2 -0
  51. package/types/miniapp-manifest/companion-executable.d.ts +4 -0
  52. package/types/miniapp-manifest/companion-types.d.ts +38 -0
  53. package/types/miniapp-manifest/companions.d.ts +17 -0
  54. package/types/miniapp-manifest/index.d.ts +2 -0
  55. package/types/miniapp-manifest/node.d.ts +9 -0
  56. package/types/miniapp-manifest/permissions.d.ts +1 -1
  57. package/types/miniapp-manifest/schema.d.ts +5 -1
  58. package/types/miniapp-publish/index.d.ts +17 -2
  59. package/types/modules/companion/index.d.ts +57 -0
  60. package/types/protocol/dev-session.d.ts +6 -0
  61. package/types/vite/index.d.ts +11 -4
  62. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DzEst9n7.js +0 -99
  63. package/dist/devtools/browser-dev-host/assets/index-B-NHlLsr.js +0 -567
  64. package/dist/devtools/browser-dev-host/assets/index-P-ra4m1y.css +0 -1
  65. package/dist/devtools/browser-dev-host/assets/workbench-state-BwV7bm4n.js +0 -5
package/dist/index.esm.js CHANGED
@@ -560,6 +560,18 @@ function restoreMethod(history, name, patchedValue, original) {
560
560
  }
561
561
  }
562
562
 
563
+ const MINI_PROGRAM_MESSAGE_NAMESPACE = 'heybox:miniprogram';
564
+ const MINI_PROGRAM_MESSAGE_VERSION = 2;
565
+ const MINI_PROGRAM_BRIDGE_NONCE_PARAM = 'hb_mini_bridge_nonce';
566
+ const SDK_HANDSHAKE_METHOD = 'sdk.handshake';
567
+ const RUNTIME_LOCATION_PROBE_METHOD = 'runtime.location.probe';
568
+ const SDK_LOCATION_REPORT_METHOD = 'sdk.location.report';
569
+ const SDK_CSP_VIOLATION_METHOD = 'sdk.csp.violation';
570
+ const MINI_PROGRAM_OPERATION_PROGRESS_METHOD = 'operation.progress';
571
+ const COMPANION_SESSION_OUTPUT_EVENT = 'companion.session.output';
572
+ const COMPANION_SESSION_EXIT_EVENT = 'companion.session.exit';
573
+ const COMPANION_SESSION_OWNERSHIP_LOST_EVENT = 'companion.session.ownershipLost';
574
+
563
575
  const AUTH_LOGIN_METHOD = 'auth.login';
564
576
  const USER_GET_INFO_METHOD = 'user.getInfo';
565
577
  const USER_REVOKE_AUTHORIZATION_METHOD = 'user.revokeAuthorization';
@@ -601,15 +613,18 @@ const CLOUD_LEADERBOARD_GET_LIST_METHOD = 'cloud.leaderboard.getList';
601
613
  const CLOUD_LEADERBOARD_GET_CURRENT_USER_ENTRY_METHOD = 'cloud.leaderboard.getCurrentUserEntry';
602
614
  const CLOUD_LEADERBOARD_DELETE_CURRENT_USER_ENTRY_METHOD = 'cloud.leaderboard.deleteCurrentUserEntry';
603
615
  const CLOUD_LEADERBOARD_GET_INFO_METHOD = 'cloud.leaderboard.getInfo';
604
-
605
- const MINI_PROGRAM_MESSAGE_NAMESPACE = 'heybox:miniprogram';
606
- const MINI_PROGRAM_MESSAGE_VERSION = 2;
607
- const MINI_PROGRAM_BRIDGE_NONCE_PARAM = 'hb_mini_bridge_nonce';
608
- const SDK_HANDSHAKE_METHOD = 'sdk.handshake';
609
- const RUNTIME_LOCATION_PROBE_METHOD = 'runtime.location.probe';
610
- const SDK_LOCATION_REPORT_METHOD = 'sdk.location.report';
611
- const SDK_CSP_VIOLATION_METHOD = 'sdk.csp.violation';
612
- const MINI_PROGRAM_OPERATION_PROGRESS_METHOD = 'operation.progress';
616
+ const COMPANION_GET_INFO_METHOD = 'companion.getInfo';
617
+ const COMPANION_GET_PREPARATION_STATUS_METHOD = 'companion.getPreparationStatus';
618
+ const COMPANION_PREPARE_METHOD = 'companion.prepare';
619
+ const COMPANION_CANCEL_PREPARATION_METHOD = 'companion.cancelPreparation';
620
+ const COMPANION_GET_ACTIVE_SESSION_METHOD = 'companion.getActiveSession';
621
+ const COMPANION_LAUNCH_METHOD = 'companion.launch';
622
+ const COMPANION_SESSION_WRITE_METHOD = 'companion.session.write';
623
+ const COMPANION_SESSION_CLOSE_STDIN_METHOD = 'companion.session.closeStdin';
624
+ const COMPANION_SESSION_TERMINATE_METHOD = 'companion.session.terminate';
625
+ const COMPANION_SESSION_ACK_OUTPUT_METHOD = 'companion.session.ackOutput';
626
+ const COMPANION_OPEN_ATTACHMENT_METHOD = 'companion.openAttachment';
627
+ const COMPANION_SHOW_NOTIFICATION_METHOD = 'companion.showNotification';
613
628
 
614
629
  function isMiniProgramBridgeMessage(value) {
615
630
  if (!isRecord$1(value))
@@ -632,7 +647,7 @@ function isMiniProgramBridgeMessage(value) {
632
647
  if (!isNonEmptyString(value.method) || value.error !== undefined)
633
648
  return false;
634
649
  if (value.method === MINI_PROGRAM_OPERATION_PROGRESS_METHOD) {
635
- return value.version === 2 && isNonEmptyString(value.id) && isMiniProgramDownloadProgressPayload(value.payload);
650
+ return value.version === 2 && isNonEmptyString(value.id) && isMiniProgramOperationProgressPayload(value.payload);
636
651
  }
637
652
  return value.id === undefined || isNonEmptyString(value.id);
638
653
  }
@@ -670,7 +685,7 @@ function isMiniProgramDirectoryRef(value) {
670
685
  if (isNonEmptyString(value.handleId)) {
671
686
  return hasOnlyKeys(value, ['kind', 'handleId']);
672
687
  }
673
- return (isMiniProgramPathRootRef(value.root) && isMiniProgramRelativePath(value.relativePath) && hasOnlyKeys(value, ['kind', 'root', 'relativePath']));
688
+ return (isMiniProgramPathRootRef(value.root) && (value.relativePath === '.' || isMiniProgramRelativePath(value.relativePath)) && hasOnlyKeys(value, ['kind', 'root', 'relativePath']));
674
689
  }
675
690
  function isMiniProgramByteArray(value) {
676
691
  return value instanceof Uint8Array && value.buffer instanceof ArrayBuffer;
@@ -694,6 +709,24 @@ function isMiniProgramDownloadProgressPayload(value) {
694
709
  return value.total === undefined;
695
710
  return isNonNegativeSafeInteger(value.total) && value.loaded <= value.total;
696
711
  }
712
+ function isMiniProgramCompanionPrepareProgress(value) {
713
+ if (!isRecord$1(value))
714
+ return false;
715
+ if (value.phase === 'downloading') {
716
+ return (isNonNegativeSafeInteger(value.loaded) &&
717
+ (value.total === undefined || (isNonNegativeSafeInteger(value.total) && value.loaded <= value.total)) &&
718
+ hasOnlyKeys(value, ['phase', 'loaded', 'total']));
719
+ }
720
+ if (value.phase !== 'verifying' && value.phase !== 'extracting')
721
+ return false;
722
+ return (isNonNegativeSafeInteger(value.processed) &&
723
+ isNonNegativeSafeInteger(value.total) &&
724
+ value.processed <= value.total &&
725
+ hasOnlyKeys(value, ['phase', 'processed', 'total']));
726
+ }
727
+ function isMiniProgramOperationProgressPayload(value) {
728
+ return isMiniProgramDownloadProgressPayload(value) || isMiniProgramCompanionPrepareProgress(value);
729
+ }
697
730
  function isSDKHandshakePayload(value) {
698
731
  return isRecord$1(value) && isNonEmptyString(value.href) && typeof value.userAgent === 'string' && isNonEmptyString(value.sdkVersion);
699
732
  }
@@ -719,6 +752,8 @@ function isRecord$1(value) {
719
752
 
720
753
  /** 当前用户信息与登录能力支持的完整 scope 目录。 */
721
754
  const USER_INFO_AUTHORIZATION_SCOPES = ['identity', 'profile'];
755
+ /** Companion alias 的跨构建、Runtime 与 Host 规范。 */
756
+ const COMPANION_ALIAS_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
722
757
 
723
758
  const MINI_PROGRAM_PERMISSION_KEYS = [
724
759
  'userInfo',
@@ -729,6 +764,7 @@ const MINI_PROGRAM_PERMISSION_KEYS = [
729
764
  'clipboard',
730
765
  'leaderboard',
731
766
  'network',
767
+ 'companion',
732
768
  ];
733
769
  new Set(MINI_PROGRAM_PERMISSION_KEYS);
734
770
 
@@ -795,7 +831,7 @@ function createMessageId() {
795
831
  /** 构建时替换为当前发布包的实际版本。 */
796
832
  const HB_SDK_VERSION = typeof undefined === 'string'
797
833
  ? undefined
798
- : '0.8.1-alpha.2';
834
+ : '0.8.1-alpha.6';
799
835
 
800
836
  const RUNTIME_MODES = new Set(['production', 'preview', 'development', 'unknown']);
801
837
  const OPERATING_SYSTEM_NAMES = new Set(['android', 'ios', 'ohos', 'windows', 'macos', 'linux', 'unknown']);
@@ -968,11 +1004,23 @@ class MiniProgramBridgeClient {
968
1004
  method,
969
1005
  payload,
970
1006
  };
1007
+ const startedAt = Date.now();
1008
+ const report = (outcome, error) => {
1009
+ if (typeof false === 'undefined' || !false)
1010
+ return;
1011
+ try {
1012
+ const target = this.selfWindow;
1013
+ const errorCode = error instanceof HbMiniProgramSDKError ? error.code : undefined;
1014
+ target?.__hbSdkDeviceLog?.({ method, callId: id, outcome, durationMs: Date.now() - startedAt, errorCode });
1015
+ }
1016
+ catch { /* 调试输出不能改变 SDK 调用结果。 */ }
1017
+ };
971
1018
  return new Promise((resolve, reject) => {
972
1019
  const pending = {
973
1020
  resolve: resolve,
974
1021
  reject,
975
1022
  isOperation: !useTimeout,
1023
+ cancelOnAbort: options.cancelOnAbort !== false,
976
1024
  ...(options.onProgress ? { onProgress: options.onProgress } : {}),
977
1025
  ...(options.signal ? { signal: options.signal } : {}),
978
1026
  };
@@ -998,17 +1046,23 @@ class MiniProgramBridgeClient {
998
1046
  return;
999
1047
  }
1000
1048
  if (options.signal) {
1001
- pending.abortHandler = () => this.sendCancel(id);
1049
+ pending.abortHandler = () => {
1050
+ if (pending.cancelOnAbort)
1051
+ this.sendCancel(id);
1052
+ };
1002
1053
  options.signal.addEventListener('abort', pending.abortHandler, { once: true });
1003
1054
  if (options.signal.aborted) {
1004
1055
  pending.abortHandler();
1005
1056
  }
1006
1057
  }
1007
- });
1058
+ }).then(value => { report('success'); return value; }, error => { report('error', error); throw error; });
1008
1059
  }
1009
1060
  /** 销毁 SDK 实例,并拒绝尚未完成的请求。 */
1010
1061
  destroy() {
1011
- this.pendingRequests.forEach((_pending, id) => this.sendCancel(id));
1062
+ this.pendingRequests.forEach((pending, id) => {
1063
+ if (pending.cancelOnAbort)
1064
+ this.sendCancel(id);
1065
+ });
1012
1066
  this.destroyed = true;
1013
1067
  this.selfWindow?.removeEventListener('message', this.handleMessage);
1014
1068
  this.selfWindow?.removeEventListener('popstate', this.handlePopState);
@@ -1350,1648 +1404,1908 @@ function createCloudModule(requester) {
1350
1404
  };
1351
1405
  }
1352
1406
 
1353
- /**
1354
- * 复制当前小程序的通用分享链接。
1355
- *
1356
- * @param requester - 底层 bridge 请求能力。
1357
- * @param options - 分享扩展数据;不传时复制默认首页链接。
1358
- * @returns 已写入系统剪贴板的完整分享链接。
1359
- * @throws {@link HbMiniProgramSDKError} 当参数、bridge、父容器或剪贴板能力调用失败时抛出。
1360
- */
1361
- function copyLink(requester, options) {
1362
- return requester.request(SHARE_COPY_LINK_METHOD, options);
1407
+ const registries = new WeakMap();
1408
+ const brandedFileSystemValues = new WeakSet();
1409
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/;
1410
+ function invalidParams$1(message, data) {
1411
+ return createSDKError('INVALID_PARAMS', message, data);
1363
1412
  }
1364
-
1365
- // Integer Utility
1366
- var UINT32_MAX = 4294967295;
1367
- function setInt64(view, offset, value) {
1368
- var high = Math.floor(value / 4294967296);
1369
- var low = value; // high bits are truncated by DataView
1370
- view.setUint32(offset, high);
1371
- view.setUint32(offset + 4, low);
1413
+ function clonePathRootRef(ref) {
1414
+ return ref.kind === 'sandbox' ? Object.freeze({ kind: 'sandbox' }) : Object.freeze({ kind: 'directory', handleId: ref.handleId });
1372
1415
  }
1373
- function getInt64(view, offset) {
1374
- var high = view.getInt32(offset);
1375
- var low = view.getUint32(offset + 4);
1376
- return high * 4294967296 + low;
1416
+ function cloneFileRef(ref) {
1417
+ return 'handleId' in ref
1418
+ ? Object.freeze({ kind: 'file', handleId: ref.handleId })
1419
+ : Object.freeze({
1420
+ kind: 'file',
1421
+ root: clonePathRootRef(ref.root),
1422
+ relativePath: ref.relativePath,
1423
+ });
1377
1424
  }
1378
- function getUint64(view, offset) {
1379
- var high = view.getUint32(offset);
1380
- var low = view.getUint32(offset + 4);
1381
- return high * 4294967296 + low;
1425
+ function cloneDirectoryRef(ref) {
1426
+ return 'handleId' in ref
1427
+ ? Object.freeze({ kind: 'directory', handleId: ref.handleId })
1428
+ : Object.freeze({
1429
+ kind: 'directory',
1430
+ root: clonePathRootRef(ref.root),
1431
+ relativePath: ref.relativePath,
1432
+ });
1382
1433
  }
1383
-
1384
- var _a, _b, _c;
1385
- var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") &&
1386
- typeof TextEncoder !== "undefined" &&
1387
- typeof TextDecoder !== "undefined";
1388
- var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
1389
- !TEXT_ENCODING_AVAILABLE
1390
- ? UINT32_MAX
1391
- : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
1392
- ? 200
1393
- : 0;
1394
- function utf8EncodeTEencode(str, output, outputOffset) {
1395
- output.set(sharedTextEncoder.encode(str), outputOffset);
1434
+ function assertMode(mode) {
1435
+ if (mode !== 'read' && mode !== 'readwrite') {
1436
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件访问模式');
1437
+ }
1396
1438
  }
1397
- function utf8EncodeTEencodeInto(str, output, outputOffset) {
1398
- sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
1439
+ function assertName(name) {
1440
+ if (typeof name !== 'string' || name.length === 0 || name.includes('/') || name.includes('\\') || CONTROL_CHARACTER_PATTERN.test(name)) {
1441
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件名');
1442
+ }
1399
1443
  }
1400
- (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
1401
- var CHUNK_SIZE = 4096;
1402
- function utf8DecodeJs(bytes, inputOffset, byteLength) {
1403
- var offset = inputOffset;
1404
- var end = offset + byteLength;
1405
- var units = [];
1406
- var result = "";
1407
- while (offset < end) {
1408
- var byte1 = bytes[offset++];
1409
- if ((byte1 & 0x80) === 0) {
1410
- // 1 byte
1411
- units.push(byte1);
1412
- }
1413
- else if ((byte1 & 0xe0) === 0xc0) {
1414
- // 2 bytes
1415
- var byte2 = bytes[offset++] & 0x3f;
1416
- units.push(((byte1 & 0x1f) << 6) | byte2);
1417
- }
1418
- else if ((byte1 & 0xf0) === 0xe0) {
1419
- // 3 bytes
1420
- var byte2 = bytes[offset++] & 0x3f;
1421
- var byte3 = bytes[offset++] & 0x3f;
1422
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
1423
- }
1424
- else if ((byte1 & 0xf8) === 0xf0) {
1425
- // 4 bytes
1426
- var byte2 = bytes[offset++] & 0x3f;
1427
- var byte3 = bytes[offset++] & 0x3f;
1428
- var byte4 = bytes[offset++] & 0x3f;
1429
- var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
1430
- if (unit > 0xffff) {
1431
- unit -= 0x10000;
1432
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
1433
- unit = 0xdc00 | (unit & 0x3ff);
1434
- }
1435
- units.push(unit);
1436
- }
1437
- else {
1438
- units.push(byte1);
1439
- }
1440
- if (units.length >= CHUNK_SIZE) {
1441
- result += String.fromCharCode.apply(String, units);
1442
- units.length = 0;
1443
- }
1444
+ function assertFileRef(ref) {
1445
+ if (!isMiniProgramFileRef(ref)) {
1446
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 File handle');
1444
1447
  }
1445
- if (units.length > 0) {
1446
- result += String.fromCharCode.apply(String, units);
1448
+ }
1449
+ function assertDirectoryRef(ref) {
1450
+ if (!isMiniProgramDirectoryRef(ref)) {
1451
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 Directory handle');
1447
1452
  }
1448
- return result;
1449
1453
  }
1450
- var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
1451
- var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
1452
- ? UINT32_MAX
1453
- : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
1454
- ? 200
1455
- : 0;
1456
- function utf8DecodeTD(bytes, inputOffset, byteLength) {
1457
- var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
1458
- return sharedTextDecoder.decode(stringBytes);
1454
+ function defineReadonlyValue(target, key, value, enumerable = true) {
1455
+ Object.defineProperty(target, key, {
1456
+ value,
1457
+ enumerable,
1458
+ configurable: false,
1459
+ writable: false,
1460
+ });
1459
1461
  }
1460
-
1461
- /**
1462
- * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
1463
- */
1464
- var ExtData = /** @class */ (function () {
1465
- function ExtData(type, data) {
1466
- this.type = type;
1467
- this.data = data;
1462
+ function joinRelativePath(prefix, relativePath) {
1463
+ if (relativePath === '.')
1464
+ return prefix || '.';
1465
+ if (prefix === '.')
1466
+ return relativePath;
1467
+ return prefix ? `${prefix}/${relativePath}` : relativePath;
1468
+ }
1469
+ function basename(relativePath) {
1470
+ const segments = relativePath.split('/');
1471
+ return segments[segments.length - 1];
1472
+ }
1473
+ function assertWritable(mode) {
1474
+ if (mode !== 'readwrite') {
1475
+ throw createSDKError('FILE_ACCESS_DENIED', '当前文件句柄不允许写入');
1468
1476
  }
1469
- return ExtData;
1470
- }());
1471
-
1472
- var __extends = (undefined && undefined.__extends) || (function () {
1473
- var extendStatics = function (d, b) {
1474
- extendStatics = Object.setPrototypeOf ||
1475
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1476
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1477
- return extendStatics(d, b);
1478
- };
1479
- return function (d, b) {
1480
- if (typeof b !== "function" && b !== null)
1481
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1482
- extendStatics(d, b);
1483
- function __() { this.constructor = d; }
1484
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1477
+ }
1478
+ function assertSandboxRef(ref) {
1479
+ if ('handleId' in ref || ref.root.kind !== 'sandbox') {
1480
+ throw createSDKError('FILE_ACCESS_DENIED', '外部文件授权不允许删除');
1481
+ }
1482
+ }
1483
+ function normalizeCreateOptions(options) {
1484
+ if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
1485
+ throw invalidParams$1('create options 必须是对象');
1486
+ }
1487
+ if (options?.recursive !== undefined && typeof options.recursive !== 'boolean') {
1488
+ throw invalidParams$1('recursive 必须是 boolean');
1489
+ }
1490
+ if (options?.exclusive !== undefined && typeof options.exclusive !== 'boolean') {
1491
+ throw invalidParams$1('exclusive 必须是 boolean');
1492
+ }
1493
+ return {
1494
+ recursive: options?.recursive ?? false,
1495
+ exclusive: options?.exclusive ?? false,
1485
1496
  };
1486
- })();
1487
- var DecodeError = /** @class */ (function (_super) {
1488
- __extends(DecodeError, _super);
1489
- function DecodeError(message) {
1490
- var _this = _super.call(this, message) || this;
1491
- // fix the prototype chain in a cross-platform way
1492
- var proto = Object.create(DecodeError.prototype);
1493
- Object.setPrototypeOf(_this, proto);
1494
- Object.defineProperty(_this, "name", {
1495
- configurable: true,
1496
- enumerable: false,
1497
- value: DecodeError.name,
1498
- });
1499
- return _this;
1497
+ }
1498
+ function normalizeListOptions(options) {
1499
+ if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
1500
+ throw invalidParams$1('list options 必须是对象');
1500
1501
  }
1501
- return DecodeError;
1502
- }(Error));
1503
-
1504
- // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
1505
- var EXT_TIMESTAMP = -1;
1506
- var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
1507
- var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
1508
- function encodeTimeSpecToTimestamp(_a) {
1509
- var sec = _a.sec, nsec = _a.nsec;
1510
- if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
1511
- // Here sec >= 0 && nsec >= 0
1512
- if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
1513
- // timestamp 32 = { sec32 (unsigned) }
1514
- var rv = new Uint8Array(4);
1515
- var view = new DataView(rv.buffer);
1516
- view.setUint32(0, sec);
1517
- return rv;
1518
- }
1519
- else {
1520
- // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
1521
- var secHigh = sec / 0x100000000;
1522
- var secLow = sec & 0xffffffff;
1523
- var rv = new Uint8Array(8);
1524
- var view = new DataView(rv.buffer);
1525
- // nsec30 | secHigh2
1526
- view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
1527
- // secLow32
1528
- view.setUint32(4, secLow);
1529
- return rv;
1530
- }
1531
- }
1532
- else {
1533
- // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
1534
- var rv = new Uint8Array(12);
1535
- var view = new DataView(rv.buffer);
1536
- view.setUint32(0, nsec);
1537
- setInt64(view, 4, sec);
1538
- return rv;
1502
+ if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) {
1503
+ throw invalidParams$1('limit 必须是正的 safe integer');
1539
1504
  }
1505
+ return options?.limit;
1540
1506
  }
1541
- function encodeDateToTimeSpec(date) {
1542
- var msec = date.getTime();
1543
- var sec = Math.floor(msec / 1e3);
1544
- var nsec = (msec - sec * 1e3) * 1e6;
1545
- // Normalizes { sec, nsec } to ensure nsec is unsigned.
1546
- var nsecInSec = Math.floor(nsec / 1e9);
1547
- return {
1548
- sec: sec + nsecInSec,
1549
- nsec: nsec - nsecInSec * 1e9,
1550
- };
1551
- }
1552
- function encodeTimestampExtension(object) {
1553
- if (object instanceof Date) {
1554
- var timeSpec = encodeDateToTimeSpec(object);
1555
- return encodeTimeSpecToTimestamp(timeSpec);
1507
+ function normalizeRemoveOptions(options) {
1508
+ if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
1509
+ throw invalidParams$1('remove options 必须是对象');
1556
1510
  }
1557
- else {
1558
- return null;
1511
+ if (options?.recursive !== undefined && typeof options.recursive !== 'boolean') {
1512
+ throw invalidParams$1('recursive 必须是 boolean');
1559
1513
  }
1514
+ return { recursive: options?.recursive ?? false };
1560
1515
  }
1561
- function decodeTimestampToTimeSpec(data) {
1562
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1563
- // data may be 32, 64, or 96 bits
1564
- switch (data.byteLength) {
1565
- case 4: {
1566
- // timestamp 32 = { sec32 }
1567
- var sec = view.getUint32(0);
1568
- var nsec = 0;
1569
- return { sec: sec, nsec: nsec };
1570
- }
1571
- case 8: {
1572
- // timestamp 64 = { nsec30, sec34 }
1573
- var nsec30AndSecHigh2 = view.getUint32(0);
1574
- var secLow32 = view.getUint32(4);
1575
- var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
1576
- var nsec = nsec30AndSecHigh2 >>> 2;
1577
- return { sec: sec, nsec: nsec };
1578
- }
1579
- case 12: {
1580
- // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
1581
- var sec = getInt64(view, 4);
1582
- var nsec = view.getUint32(0);
1583
- return { sec: sec, nsec: nsec };
1584
- }
1585
- default:
1586
- throw new DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
1516
+ function cloneBytes$1(content) {
1517
+ if (!(content instanceof Uint8Array)) {
1518
+ throw invalidParams$1('content 必须是 Uint8Array');
1587
1519
  }
1520
+ if (typeof SharedArrayBuffer !== 'undefined' && content.buffer instanceof SharedArrayBuffer) {
1521
+ throw invalidParams$1('content 不能由 SharedArrayBuffer 承载');
1522
+ }
1523
+ return new Uint8Array(content);
1588
1524
  }
1589
- function decodeTimestampExtension(data) {
1590
- var timeSpec = decodeTimestampToTimeSpec(data);
1591
- return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
1592
- }
1593
- var timestampExtension = {
1594
- type: EXT_TIMESTAMP,
1595
- encode: encodeTimestampExtension,
1596
- decode: decodeTimestampExtension,
1597
- };
1598
-
1599
- // ExtensionCodec to handle MessagePack extensions
1600
- var ExtensionCodec = /** @class */ (function () {
1601
- function ExtensionCodec() {
1602
- // built-in extensions
1603
- this.builtInEncoders = [];
1604
- this.builtInDecoders = [];
1605
- // custom extensions
1606
- this.encoders = [];
1607
- this.decoders = [];
1608
- this.register(timestampExtension);
1525
+ function normalizeStat(stat) {
1526
+ if (!isMiniProgramFileStat(stat)) {
1527
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 FileStat');
1609
1528
  }
1610
- ExtensionCodec.prototype.register = function (_a) {
1611
- var type = _a.type, encode = _a.encode, decode = _a.decode;
1612
- if (type >= 0) {
1613
- // custom extensions
1614
- this.encoders[type] = encode;
1615
- this.decoders[type] = decode;
1616
- }
1617
- else {
1618
- // built-in extensions
1619
- var index = 1 + type;
1620
- this.builtInEncoders[index] = encode;
1621
- this.builtInDecoders[index] = decode;
1622
- }
1623
- };
1624
- ExtensionCodec.prototype.tryToEncode = function (object, context) {
1625
- // built-in extensions
1626
- for (var i = 0; i < this.builtInEncoders.length; i++) {
1627
- var encodeExt = this.builtInEncoders[i];
1628
- if (encodeExt != null) {
1629
- var data = encodeExt(object, context);
1630
- if (data != null) {
1631
- var type = -1 - i;
1632
- return new ExtData(type, data);
1633
- }
1634
- }
1635
- }
1636
- // custom extensions
1637
- for (var i = 0; i < this.encoders.length; i++) {
1638
- var encodeExt = this.encoders[i];
1639
- if (encodeExt != null) {
1640
- var data = encodeExt(object, context);
1641
- if (data != null) {
1642
- var type = i;
1643
- return new ExtData(type, data);
1644
- }
1645
- }
1646
- }
1647
- if (object instanceof ExtData) {
1648
- // to keep ExtData as is
1649
- return object;
1650
- }
1651
- return null;
1652
- };
1653
- ExtensionCodec.prototype.decode = function (data, type, context) {
1654
- var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
1655
- if (decodeExt) {
1656
- return decodeExt(data, type, context);
1657
- }
1658
- else {
1659
- // decode() does not fail, returns ExtData instead.
1660
- return new ExtData(type, data);
1661
- }
1529
+ return {
1530
+ kind: 'file',
1531
+ size: stat.size,
1532
+ ...(stat.modifiedAt === undefined ? {} : { modifiedAt: stat.modifiedAt }),
1533
+ ...(stat.createdAt === undefined ? {} : { createdAt: stat.createdAt }),
1662
1534
  };
1663
- ExtensionCodec.defaultCodec = new ExtensionCodec();
1664
- return ExtensionCodec;
1665
- }());
1666
-
1667
- function ensureUint8Array(buffer) {
1668
- if (buffer instanceof Uint8Array) {
1669
- return buffer;
1670
- }
1671
- else if (ArrayBuffer.isView(buffer)) {
1672
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1673
- }
1674
- else if (buffer instanceof ArrayBuffer) {
1675
- return new Uint8Array(buffer);
1676
- }
1677
- else {
1678
- // ArrayLike<number>
1679
- return Uint8Array.from(buffer);
1680
- }
1681
1535
  }
1682
- function createDataView(buffer) {
1683
- if (buffer instanceof ArrayBuffer) {
1684
- return new DataView(buffer);
1536
+ /** 校验并返回平台无关的 `/` 分隔逻辑相对路径。 */
1537
+ function normalizeRelativePath(value) {
1538
+ if (!isMiniProgramRelativePath(value)) {
1539
+ throw invalidParams$1('relativePath 必须是规范的 `/` 分隔逻辑相对路径');
1685
1540
  }
1686
- var bufferView = ensureUint8Array(buffer);
1687
- return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
1688
- }
1689
-
1690
- function prettyByte(byte) {
1691
- return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
1541
+ return value;
1692
1542
  }
1693
-
1694
- var DEFAULT_MAX_KEY_LENGTH = 16;
1695
- var DEFAULT_MAX_LENGTH_PER_KEY = 16;
1696
- var CachedKeyDecoder = /** @class */ (function () {
1697
- function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
1698
- if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
1699
- if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
1700
- this.maxKeyLength = maxKeyLength;
1701
- this.maxLengthPerKey = maxLengthPerKey;
1702
- this.hit = 0;
1703
- this.miss = 0;
1704
- // avoid `new Array(N)`, which makes a sparse array,
1705
- // because a sparse array is typically slower than a non-sparse array.
1706
- this.caches = [];
1707
- for (var i = 0; i < this.maxKeyLength; i++) {
1708
- this.caches.push([]);
1709
- }
1543
+ class MiniProgramFileHandleRegistry {
1544
+ requester;
1545
+ fileStates = new WeakMap();
1546
+ directoryStates = new WeakMap();
1547
+ pathRootStates = new WeakMap();
1548
+ sandboxRoot;
1549
+ constructor(requester) {
1550
+ this.requester = requester;
1710
1551
  }
1711
- CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
1712
- return byteLength > 0 && byteLength <= this.maxKeyLength;
1713
- };
1714
- CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
1715
- var records = this.caches[byteLength - 1];
1716
- FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
1717
- var record = records_1[_i];
1718
- var recordBytes = record.bytes;
1719
- for (var j = 0; j < byteLength; j++) {
1720
- if (recordBytes[j] !== bytes[inputOffset + j]) {
1721
- continue FIND_CHUNK;
1722
- }
1723
- }
1724
- return record.str;
1725
- }
1726
- return null;
1727
- };
1728
- CachedKeyDecoder.prototype.store = function (bytes, value) {
1729
- var records = this.caches[bytes.length - 1];
1730
- var record = { bytes: bytes, str: value };
1731
- if (records.length >= this.maxLengthPerKey) {
1732
- // `records` are full!
1733
- // Set `record` to an arbitrary position.
1734
- records[(Math.random() * records.length) | 0] = record;
1735
- }
1736
- else {
1737
- records.push(record);
1552
+ getSandbox() {
1553
+ if (this.sandboxRoot) {
1554
+ return this.sandboxRoot;
1738
1555
  }
1739
- };
1740
- CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
1741
- var cachedValue = this.find(bytes, inputOffset, byteLength);
1742
- if (cachedValue != null) {
1743
- this.hit++;
1744
- return cachedValue;
1745
- }
1746
- this.miss++;
1747
- var str = utf8DecodeJs(bytes, inputOffset, byteLength);
1748
- // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
1749
- var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
1750
- this.store(slicedCopyOfBytes, str);
1751
- return str;
1752
- };
1753
- return CachedKeyDecoder;
1754
- }());
1755
-
1756
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1757
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1758
- return new (P || (P = Promise))(function (resolve, reject) {
1759
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1760
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1761
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1762
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1763
- });
1764
- };
1765
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
1766
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1767
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1768
- function verb(n) { return function (v) { return step([n, v]); }; }
1769
- function step(op) {
1770
- if (f) throw new TypeError("Generator is already executing.");
1771
- while (_) try {
1772
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1773
- if (y = 0, t) op = [op[0] & 2, t.value];
1774
- switch (op[0]) {
1775
- case 0: case 1: t = op; break;
1776
- case 4: _.label++; return { value: op[1], done: false };
1777
- case 5: _.label++; y = op[1]; op = [0]; continue;
1778
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1779
- default:
1780
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1781
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1782
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1783
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1784
- if (t[2]) _.ops.pop();
1785
- _.trys.pop(); continue;
1786
- }
1787
- op = body.call(thisArg, _);
1788
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1789
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1556
+ const sandbox = {};
1557
+ const state = {
1558
+ root: Object.freeze({ kind: 'sandbox' }),
1559
+ prefix: '',
1560
+ mode: 'readwrite',
1561
+ };
1562
+ this.definePathRootMethods(sandbox, state);
1563
+ this.pathRootStates.set(sandbox, state);
1564
+ brandedFileSystemValues.add(sandbox);
1565
+ this.sandboxRoot = Object.freeze(sandbox);
1566
+ return this.sandboxRoot;
1790
1567
  }
1791
- };
1792
- var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
1793
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1794
- var m = o[Symbol.asyncIterator], i;
1795
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
1796
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
1797
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
1798
- };
1799
- var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); };
1800
- var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
1801
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1802
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
1803
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
1804
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
1805
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
1806
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
1807
- function fulfill(value) { resume("next", value); }
1808
- function reject(value) { resume("throw", value); }
1809
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
1810
- };
1811
- var isValidMapKeyType = function (key) {
1812
- var keyType = typeof key;
1813
- return keyType === "string" || keyType === "number";
1814
- };
1815
- var HEAD_BYTE_REQUIRED = -1;
1816
- var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
1817
- var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
1818
- // IE11: Hack to support IE11.
1819
- // IE11: Drop this hack and just use RangeError when IE11 is obsolete.
1820
- var DataViewIndexOutOfBoundsError = (function () {
1821
- try {
1822
- // IE11: The spec says it should throw RangeError,
1823
- // IE11: but in IE11 it throws TypeError.
1824
- EMPTY_VIEW.getInt8(0);
1568
+ createFile(descriptor) {
1569
+ this.assertFileDescriptor(descriptor);
1570
+ const ref = cloneFileRef(descriptor.ref);
1571
+ const state = { ref, mode: descriptor.mode };
1572
+ const handle = {};
1573
+ defineReadonlyValue(handle, 'kind', 'file');
1574
+ defineReadonlyValue(handle, 'name', descriptor.name);
1575
+ defineReadonlyValue(handle, 'mode', descriptor.mode);
1576
+ defineReadonlyValue(handle, 'create', async (options) => {
1577
+ assertWritable(state.mode);
1578
+ await this.requester.request(FILE_CREATE_METHOD, {
1579
+ target: state.ref,
1580
+ ...normalizeCreateOptions(options),
1581
+ });
1582
+ return handle;
1583
+ }, false);
1584
+ defineReadonlyValue(handle, 'remove', async () => {
1585
+ assertWritable(state.mode);
1586
+ assertSandboxRef(state.ref);
1587
+ await this.requester.request(FILE_REMOVE_METHOD, { target: state.ref });
1588
+ }, false);
1589
+ defineReadonlyValue(handle, 'exists', async () => {
1590
+ const result = await this.requester.request(FILE_EXISTS_METHOD, { target: state.ref });
1591
+ if (typeof result !== 'boolean') {
1592
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 exists 结果');
1593
+ }
1594
+ return result;
1595
+ }, false);
1596
+ defineReadonlyValue(handle, 'readText', async () => {
1597
+ const result = await this.requester.request(FILE_READ_TEXT_METHOD, { target: state.ref });
1598
+ if (typeof result !== 'string') {
1599
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文本内容');
1600
+ }
1601
+ return result;
1602
+ }, false);
1603
+ defineReadonlyValue(handle, 'writeText', async (content) => {
1604
+ assertWritable(state.mode);
1605
+ if (typeof content !== 'string') {
1606
+ throw invalidParams$1('content 必须是 string');
1607
+ }
1608
+ await this.requester.request(FILE_WRITE_TEXT_METHOD, { target: state.ref, content });
1609
+ }, false);
1610
+ defineReadonlyValue(handle, 'readBytes', async () => {
1611
+ const result = await this.requester.request(FILE_READ_BYTES_METHOD, { target: state.ref });
1612
+ if (!isMiniProgramByteArray(result)) {
1613
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的二进制内容');
1614
+ }
1615
+ return new Uint8Array(result);
1616
+ }, false);
1617
+ defineReadonlyValue(handle, 'writeBytes', async (content) => {
1618
+ assertWritable(state.mode);
1619
+ const snapshot = cloneBytes$1(content);
1620
+ await this.requester.request(FILE_WRITE_BYTES_METHOD, { target: state.ref, content: snapshot });
1621
+ }, false);
1622
+ defineReadonlyValue(handle, 'stat', async () => {
1623
+ const result = await this.requester.request(FILE_STAT_METHOD, { target: state.ref });
1624
+ return normalizeStat(result);
1625
+ }, false);
1626
+ this.fileStates.set(handle, state);
1627
+ brandedFileSystemValues.add(handle);
1628
+ return Object.freeze(handle);
1825
1629
  }
1826
- catch (e) {
1827
- return e.constructor;
1630
+ createDirectFile(descriptor) {
1631
+ this.assertFileDescriptor(descriptor);
1632
+ if (!('handleId' in descriptor.ref)) {
1633
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回的 File 不是精确文件授权');
1634
+ }
1635
+ return this.createFile(descriptor);
1828
1636
  }
1829
- throw new Error("never reached");
1830
- })();
1831
- var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
1832
- var sharedCachedKeyDecoder = new CachedKeyDecoder();
1833
- var Decoder = /** @class */ (function () {
1834
- function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
1835
- if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }
1836
- if (context === void 0) { context = undefined; }
1837
- if (maxStrLength === void 0) { maxStrLength = UINT32_MAX; }
1838
- if (maxBinLength === void 0) { maxBinLength = UINT32_MAX; }
1839
- if (maxArrayLength === void 0) { maxArrayLength = UINT32_MAX; }
1840
- if (maxMapLength === void 0) { maxMapLength = UINT32_MAX; }
1841
- if (maxExtLength === void 0) { maxExtLength = UINT32_MAX; }
1842
- if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }
1843
- this.extensionCodec = extensionCodec;
1844
- this.context = context;
1845
- this.maxStrLength = maxStrLength;
1846
- this.maxBinLength = maxBinLength;
1847
- this.maxArrayLength = maxArrayLength;
1848
- this.maxMapLength = maxMapLength;
1849
- this.maxExtLength = maxExtLength;
1850
- this.keyDecoder = keyDecoder;
1851
- this.totalPos = 0;
1852
- this.pos = 0;
1853
- this.view = EMPTY_VIEW;
1854
- this.bytes = EMPTY_BYTES;
1855
- this.headByte = HEAD_BYTE_REQUIRED;
1856
- this.stack = [];
1637
+ createDirectory(descriptor) {
1638
+ this.assertDirectoryDescriptor(descriptor);
1639
+ const ref = cloneDirectoryRef(descriptor.ref);
1640
+ const state = { ref, mode: descriptor.mode };
1641
+ const pathRootState = 'handleId' in ref ? { root: ref, prefix: '', mode: descriptor.mode } : { root: ref.root, prefix: ref.relativePath, mode: descriptor.mode };
1642
+ const handle = {};
1643
+ defineReadonlyValue(handle, 'kind', 'directory');
1644
+ defineReadonlyValue(handle, 'name', descriptor.name);
1645
+ defineReadonlyValue(handle, 'mode', descriptor.mode);
1646
+ this.definePathRootMethods(handle, pathRootState);
1647
+ defineReadonlyValue(handle, 'create', async (options) => {
1648
+ assertWritable(state.mode);
1649
+ await this.requester.request(DIRECTORY_CREATE_METHOD, {
1650
+ target: state.ref,
1651
+ ...normalizeCreateOptions(options),
1652
+ });
1653
+ return handle;
1654
+ }, false);
1655
+ defineReadonlyValue(handle, 'remove', async (options) => {
1656
+ assertWritable(state.mode);
1657
+ assertSandboxRef(state.ref);
1658
+ await this.requester.request(DIRECTORY_REMOVE_METHOD, {
1659
+ target: state.ref,
1660
+ ...normalizeRemoveOptions(options),
1661
+ });
1662
+ }, false);
1663
+ defineReadonlyValue(handle, 'exists', async () => {
1664
+ const result = await this.requester.request(DIRECTORY_EXISTS_METHOD, { target: state.ref });
1665
+ if (typeof result !== 'boolean') {
1666
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 exists 结果');
1667
+ }
1668
+ return result;
1669
+ }, false);
1670
+ defineReadonlyValue(handle, 'list', async (options) => {
1671
+ const limit = normalizeListOptions(options);
1672
+ const result = await this.requester.request(DIRECTORY_LIST_METHOD, {
1673
+ target: state.ref,
1674
+ ...(limit === undefined ? {} : { limit }),
1675
+ });
1676
+ if (!Array.isArray(result)) {
1677
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的目录列表');
1678
+ }
1679
+ if (result.some((entry) => entry?.mode !== state.mode)) {
1680
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回的目录项未继承父目录 mode');
1681
+ }
1682
+ return result.map((entry) => this.createEntity(entry));
1683
+ }, false);
1684
+ this.directoryStates.set(handle, state);
1685
+ this.pathRootStates.set(handle, pathRootState);
1686
+ brandedFileSystemValues.add(handle);
1687
+ return Object.freeze(handle);
1857
1688
  }
1858
- Decoder.prototype.reinitializeState = function () {
1859
- this.totalPos = 0;
1860
- this.headByte = HEAD_BYTE_REQUIRED;
1861
- this.stack.length = 0;
1862
- // view, bytes, and pos will be re-initialized in setBuffer()
1863
- };
1864
- Decoder.prototype.setBuffer = function (buffer) {
1865
- this.bytes = ensureUint8Array(buffer);
1866
- this.view = createDataView(this.bytes);
1867
- this.pos = 0;
1868
- };
1869
- Decoder.prototype.appendBuffer = function (buffer) {
1870
- if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
1871
- this.setBuffer(buffer);
1689
+ createDirectDirectory(descriptor) {
1690
+ this.assertDirectoryDescriptor(descriptor);
1691
+ if (!('handleId' in descriptor.ref)) {
1692
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回的 Directory 不是精确目录授权');
1872
1693
  }
1873
- else {
1874
- var remainingData = this.bytes.subarray(this.pos);
1875
- var newData = ensureUint8Array(buffer);
1876
- // concat remainingData + newData
1877
- var newBuffer = new Uint8Array(remainingData.length + newData.length);
1878
- newBuffer.set(remainingData);
1879
- newBuffer.set(newData, remainingData.length);
1880
- this.setBuffer(newBuffer);
1694
+ return this.createDirectory(descriptor);
1695
+ }
1696
+ createEntity(descriptor) {
1697
+ if (descriptor?.kind === 'file') {
1698
+ return this.createFile(descriptor);
1881
1699
  }
1882
- };
1883
- Decoder.prototype.hasRemaining = function (size) {
1884
- return this.view.byteLength - this.pos >= size;
1885
- };
1886
- Decoder.prototype.createExtraByteError = function (posToShow) {
1887
- var _a = this, view = _a.view, pos = _a.pos;
1888
- return new RangeError("Extra ".concat(view.byteLength - pos, " of ").concat(view.byteLength, " byte(s) found at buffer[").concat(posToShow, "]"));
1889
- };
1890
- /**
1891
- * @throws {@link DecodeError}
1892
- * @throws {@link RangeError}
1893
- */
1894
- Decoder.prototype.decode = function (buffer) {
1895
- this.reinitializeState();
1896
- this.setBuffer(buffer);
1897
- var object = this.doDecodeSync();
1898
- if (this.hasRemaining(1)) {
1899
- throw this.createExtraByteError(this.pos);
1700
+ if (descriptor?.kind === 'directory') {
1701
+ return this.createDirectory(descriptor);
1900
1702
  }
1901
- return object;
1902
- };
1903
- Decoder.prototype.decodeMulti = function (buffer) {
1904
- return __generator(this, function (_a) {
1905
- switch (_a.label) {
1906
- case 0:
1907
- this.reinitializeState();
1908
- this.setBuffer(buffer);
1909
- _a.label = 1;
1910
- case 1:
1911
- if (!this.hasRemaining(1)) return [3 /*break*/, 3];
1912
- return [4 /*yield*/, this.doDecodeSync()];
1913
- case 2:
1914
- _a.sent();
1915
- return [3 /*break*/, 1];
1916
- case 3: return [2 /*return*/];
1917
- }
1703
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件实体');
1704
+ }
1705
+ requireFile(handle) {
1706
+ const state = handle && typeof handle === 'object' ? this.fileStates.get(handle) : undefined;
1707
+ if (!state) {
1708
+ throw invalidParams$1('to 必须是当前 SDK session 创建的 FileHandle');
1709
+ }
1710
+ return state;
1711
+ }
1712
+ requireDirectory(handle) {
1713
+ const state = handle && typeof handle === 'object' ? this.directoryStates.get(handle) : undefined;
1714
+ if (!state) {
1715
+ throw invalidParams$1('to 必须是当前 SDK session 创建的 DirectoryHandle');
1716
+ }
1717
+ return state;
1718
+ }
1719
+ definePathRootMethods(target, state) {
1720
+ defineReadonlyValue(target, 'file', (relativePath) => {
1721
+ const normalized = normalizeRelativePath(relativePath);
1722
+ const fullPath = joinRelativePath(state.prefix, normalized);
1723
+ return this.createFile({
1724
+ kind: 'file',
1725
+ name: basename(normalized),
1726
+ mode: state.mode,
1727
+ ref: {
1728
+ kind: 'file',
1729
+ root: state.root,
1730
+ relativePath: fullPath,
1731
+ },
1732
+ });
1733
+ }, false);
1734
+ defineReadonlyValue(target, 'directory', (relativePath) => {
1735
+ const normalized = relativePath === '.' ? '.' : normalizeRelativePath(relativePath);
1736
+ const fullPath = joinRelativePath(state.prefix, normalized);
1737
+ return this.createDirectory({
1738
+ kind: 'directory',
1739
+ name: basename(normalized),
1740
+ mode: state.mode,
1741
+ ref: {
1742
+ kind: 'directory',
1743
+ root: state.root,
1744
+ relativePath: fullPath,
1745
+ },
1746
+ });
1747
+ }, false);
1748
+ }
1749
+ assertFileDescriptor(descriptor) {
1750
+ if (!descriptor || descriptor.kind !== 'file') {
1751
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 File descriptor');
1752
+ }
1753
+ assertName(descriptor.name);
1754
+ assertMode(descriptor.mode);
1755
+ assertFileRef(descriptor.ref);
1756
+ }
1757
+ assertDirectoryDescriptor(descriptor) {
1758
+ if (!descriptor || descriptor.kind !== 'directory') {
1759
+ throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 Directory descriptor');
1760
+ }
1761
+ assertName(descriptor.name);
1762
+ assertMode(descriptor.mode);
1763
+ assertDirectoryRef(descriptor.ref);
1764
+ }
1765
+ }
1766
+ function getFileHandleRegistry(requester) {
1767
+ let registry = registries.get(requester);
1768
+ if (!registry) {
1769
+ registry = new MiniProgramFileHandleRegistry(requester);
1770
+ registries.set(requester, registry);
1771
+ }
1772
+ return registry;
1773
+ }
1774
+ function isMiniProgramFileSystemValue(value) {
1775
+ return !!value && typeof value === 'object' && brandedFileSystemValues.has(value);
1776
+ }
1777
+
1778
+ function normalizeAlias(alias) {
1779
+ if (typeof alias !== 'string' || !COMPANION_ALIAS_PATTERN.test(alias)) {
1780
+ throw createSDKError('INVALID_PARAMS', 'alias 必须是规范的 Companion alias');
1781
+ }
1782
+ return alias;
1783
+ }
1784
+ function cloneBytes(data) {
1785
+ if (!isMiniProgramByteArray(data)) {
1786
+ throw createSDKError('INVALID_PARAMS', 'data 必须是 Uint8Array');
1787
+ }
1788
+ return new Uint8Array(data);
1789
+ }
1790
+ function assertPrepareOptions(options) {
1791
+ if (options === undefined)
1792
+ return;
1793
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
1794
+ throw createSDKError('INVALID_PARAMS', 'prepare options 必须是对象');
1795
+ }
1796
+ if (options.onProgress !== undefined && typeof options.onProgress !== 'function') {
1797
+ throw createSDKError('INVALID_PARAMS', 'onProgress 必须是函数');
1798
+ }
1799
+ if (options.signal !== undefined &&
1800
+ (typeof options.signal !== 'object' ||
1801
+ typeof options.signal.aborted !== 'boolean' ||
1802
+ typeof options.signal.addEventListener !== 'function' ||
1803
+ typeof options.signal.removeEventListener !== 'function')) {
1804
+ throw createSDKError('INVALID_PARAMS', 'signal 必须是 AbortSignal');
1805
+ }
1806
+ }
1807
+ class CompanionSessionProxy {
1808
+ requester;
1809
+ snapshot;
1810
+ id;
1811
+ alias;
1812
+ target;
1813
+ capabilities;
1814
+ stdio;
1815
+ attachments;
1816
+ notifications;
1817
+ stdoutHandlers = new Set();
1818
+ stderrHandlers = new Set();
1819
+ stateHandlers = new Set();
1820
+ exitHandlers = new Set();
1821
+ ownershipLostHandlers = new Set();
1822
+ exitPromise;
1823
+ resolveExit;
1824
+ exit;
1825
+ ownsController = true;
1826
+ lastOutputSequence = { stdout: -1, stderr: -1 };
1827
+ constructor(requester, snapshot) {
1828
+ this.requester = requester;
1829
+ this.snapshot = snapshot;
1830
+ this.id = snapshot.id;
1831
+ this.alias = snapshot.alias;
1832
+ this.target = snapshot.target;
1833
+ this.capabilities = Object.freeze([...snapshot.capabilities]);
1834
+ this.exitPromise = new Promise((resolve) => {
1835
+ this.resolveExit = resolve;
1918
1836
  });
1919
- };
1920
- Decoder.prototype.decodeAsync = function (stream) {
1921
- var stream_1, stream_1_1;
1922
- var e_1, _a;
1923
- return __awaiter(this, void 0, void 0, function () {
1924
- var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
1925
- return __generator(this, function (_c) {
1926
- switch (_c.label) {
1927
- case 0:
1928
- decoded = false;
1929
- _c.label = 1;
1930
- case 1:
1931
- _c.trys.push([1, 6, 7, 12]);
1932
- stream_1 = __asyncValues(stream);
1933
- _c.label = 2;
1934
- case 2: return [4 /*yield*/, stream_1.next()];
1935
- case 3:
1936
- if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];
1937
- buffer = stream_1_1.value;
1938
- if (decoded) {
1939
- throw this.createExtraByteError(this.totalPos);
1940
- }
1941
- this.appendBuffer(buffer);
1942
- try {
1943
- object = this.doDecodeSync();
1944
- decoded = true;
1945
- }
1946
- catch (e) {
1947
- if (!(e instanceof DataViewIndexOutOfBoundsError)) {
1948
- throw e; // rethrow
1949
- }
1950
- // fallthrough
1951
- }
1952
- this.totalPos += this.pos;
1953
- _c.label = 4;
1954
- case 4: return [3 /*break*/, 2];
1955
- case 5: return [3 /*break*/, 12];
1956
- case 6:
1957
- e_1_1 = _c.sent();
1958
- e_1 = { error: e_1_1 };
1959
- return [3 /*break*/, 12];
1960
- case 7:
1961
- _c.trys.push([7, , 10, 11]);
1962
- if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];
1963
- return [4 /*yield*/, _a.call(stream_1)];
1964
- case 8:
1965
- _c.sent();
1966
- _c.label = 9;
1967
- case 9: return [3 /*break*/, 11];
1968
- case 10:
1969
- if (e_1) throw e_1.error;
1970
- return [7 /*endfinally*/];
1971
- case 11: return [7 /*endfinally*/];
1972
- case 12:
1973
- if (decoded) {
1974
- if (this.hasRemaining(1)) {
1975
- throw this.createExtraByteError(this.totalPos);
1976
- }
1977
- return [2 /*return*/, object];
1978
- }
1979
- _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
1980
- throw new RangeError("Insufficient data in parsing ".concat(prettyByte(headByte), " at ").concat(totalPos, " (").concat(pos, " in the current buffer)"));
1837
+ if (snapshot.capabilities.includes('stdio')) {
1838
+ const stdio = {
1839
+ write: (data) => this.write(data),
1840
+ closeStdin: () => this.closeStdin(),
1841
+ onStdout: (handler) => this.onOutput('stdout', handler),
1842
+ onStderr: (handler) => this.onOutput('stderr', handler),
1843
+ };
1844
+ this.stdio = Object.freeze(stdio);
1845
+ }
1846
+ if (snapshot.capabilities.includes('attachments')) {
1847
+ const attachments = { open: (id) => this.openAttachment(id) };
1848
+ this.attachments = Object.freeze(attachments);
1849
+ }
1850
+ if (snapshot.capabilities.includes('notifications')) {
1851
+ const notifications = {
1852
+ show: (input) => this.showNotification(input),
1853
+ };
1854
+ this.notifications = Object.freeze(notifications);
1855
+ }
1856
+ }
1857
+ get state() {
1858
+ return this.exit ? 'exited' : 'running';
1859
+ }
1860
+ updateController(snapshot) {
1861
+ if (snapshot.controllerGeneration < this.snapshot.controllerGeneration)
1862
+ return;
1863
+ if (snapshot.alias !== this.alias || snapshot.target !== this.target ||
1864
+ snapshot.capabilities.length !== this.capabilities.length ||
1865
+ [...snapshot.capabilities].sort().some((capability, index) => capability !== [...this.capabilities].sort()[index])) {
1866
+ throw createSDKError('COMPANION_SESSION_VERSION_MISMATCH', 'Companion Session 版本不匹配');
1867
+ }
1868
+ if (snapshot.controllerGeneration === this.snapshot.controllerGeneration)
1869
+ return;
1870
+ this.snapshot = snapshot;
1871
+ this.ownsController = true;
1872
+ this.lastOutputSequence.stdout = -1;
1873
+ this.lastOutputSequence.stderr = -1;
1874
+ }
1875
+ async terminate() {
1876
+ await this.requestController(COMPANION_SESSION_TERMINATE_METHOD);
1877
+ }
1878
+ waitForExit() {
1879
+ return this.exitPromise;
1880
+ }
1881
+ onStateChange(handler) {
1882
+ if (typeof handler !== 'function')
1883
+ throw createSDKError('INVALID_PARAMS', 'state handler 必须是函数');
1884
+ this.stateHandlers.add(handler);
1885
+ return () => this.stateHandlers.delete(handler);
1886
+ }
1887
+ onExit(handler) {
1888
+ if (typeof handler !== 'function')
1889
+ throw createSDKError('INVALID_PARAMS', 'exit handler 必须是函数');
1890
+ if (this.exit) {
1891
+ handler(this.exit);
1892
+ return () => undefined;
1893
+ }
1894
+ this.exitHandlers.add(handler);
1895
+ return () => this.exitHandlers.delete(handler);
1896
+ }
1897
+ onOwnershipLost(handler) {
1898
+ if (typeof handler !== 'function')
1899
+ throw createSDKError('INVALID_PARAMS', 'ownership handler 必须是函数');
1900
+ this.ownershipLostHandlers.add(handler);
1901
+ return () => this.ownershipLostHandlers.delete(handler);
1902
+ }
1903
+ handleOutput(payload) {
1904
+ if (this.exit || !this.ownsController || payload.controllerGeneration !== this.snapshot.controllerGeneration ||
1905
+ !isMiniProgramByteArray(payload.data) || !Number.isSafeInteger(payload.sequence) || payload.sequence < 0)
1906
+ return;
1907
+ const duplicate = payload.sequence <= this.lastOutputSequence[payload.stream];
1908
+ if (!duplicate)
1909
+ this.lastOutputSequence[payload.stream] = payload.sequence;
1910
+ const handlers = payload.stream === 'stdout' ? this.stdoutHandlers : this.stderrHandlers;
1911
+ if (!duplicate) {
1912
+ handlers.forEach((handler) => {
1913
+ try {
1914
+ handler(new Uint8Array(payload.data));
1915
+ }
1916
+ catch {
1917
+ // 单个业务 handler 失败不能阻止其他 handler 或 Host ack。
1981
1918
  }
1982
1919
  });
1983
- });
1984
- };
1985
- Decoder.prototype.decodeArrayStream = function (stream) {
1986
- return this.decodeMultiAsync(stream, true);
1920
+ }
1921
+ void this.requester
1922
+ .request(COMPANION_SESSION_ACK_OUTPUT_METHOD, {
1923
+ ...this.controllerPayload(),
1924
+ stream: payload.stream,
1925
+ sequence: payload.sequence,
1926
+ })
1927
+ .catch(() => undefined);
1928
+ }
1929
+ handleExit(exit) {
1930
+ if (this.exit)
1931
+ return;
1932
+ this.exit = Object.freeze({ ...exit });
1933
+ this.ownsController = false;
1934
+ this.resolveExit(this.exit);
1935
+ this.stateHandlers.forEach((handler) => handler('exited'));
1936
+ this.exitHandlers.forEach((handler) => handler(this.exit));
1937
+ this.exitHandlers.clear();
1938
+ this.stateHandlers.clear();
1939
+ this.stdoutHandlers.clear();
1940
+ this.stderrHandlers.clear();
1941
+ }
1942
+ handleOwnershipLost(controllerGeneration) {
1943
+ if (controllerGeneration !== this.snapshot.controllerGeneration || !this.ownsController)
1944
+ return;
1945
+ this.ownsController = false;
1946
+ this.ownershipLostHandlers.forEach((handler) => handler());
1947
+ }
1948
+ onOutput(stream, handler) {
1949
+ if (typeof handler !== 'function')
1950
+ throw createSDKError('INVALID_PARAMS', 'output handler 必须是函数');
1951
+ const handlers = stream === 'stdout' ? this.stdoutHandlers : this.stderrHandlers;
1952
+ handlers.add(handler);
1953
+ return () => handlers.delete(handler);
1954
+ }
1955
+ async write(data) {
1956
+ this.assertController();
1957
+ await this.requester.request(COMPANION_SESSION_WRITE_METHOD, { ...this.controllerPayload(), data: cloneBytes(data) });
1958
+ }
1959
+ async closeStdin() {
1960
+ await this.requestController(COMPANION_SESSION_CLOSE_STDIN_METHOD);
1961
+ }
1962
+ async openAttachment(id) {
1963
+ this.assertController();
1964
+ if (typeof id !== 'string' || id.length === 0)
1965
+ throw createSDKError('INVALID_PARAMS', 'attachment id 必须是非空字符串');
1966
+ const descriptor = await this.requester.request(COMPANION_OPEN_ATTACHMENT_METHOD, { ...this.controllerPayload(), id });
1967
+ return getFileHandleRegistry(this.requester).createDirectFile(descriptor);
1968
+ }
1969
+ async showNotification(input) {
1970
+ this.assertController();
1971
+ if (!input || typeof input !== 'object' || Array.isArray(input) || !['completed', 'failed', 'stopped', 'attention'].includes(input.category)) {
1972
+ throw createSDKError('INVALID_PARAMS', 'notification category 不合法');
1973
+ }
1974
+ await this.requester.request(COMPANION_SHOW_NOTIFICATION_METHOD, { ...this.controllerPayload(), category: input.category });
1975
+ }
1976
+ async requestController(method) {
1977
+ this.assertController();
1978
+ await this.requester.request(method, this.controllerPayload());
1979
+ }
1980
+ controllerPayload() {
1981
+ return { sessionId: this.snapshot.id, controllerGeneration: this.snapshot.controllerGeneration };
1982
+ }
1983
+ assertController() {
1984
+ if (this.exit)
1985
+ throw createSDKError('COMPANION_SESSION_EXITED', 'Companion Session 已退出');
1986
+ if (!this.ownsController)
1987
+ throw createSDKError('COMPANION_SESSION_OWNERSHIP_LOST', 'Companion Session 控制权已转移');
1988
+ }
1989
+ }
1990
+ /** 创建当前 SDK session 的 companion 模块。 */
1991
+ function createCompanionModule(requester) {
1992
+ const sessions = new Map();
1993
+ const getSession = (snapshot) => {
1994
+ const current = sessions.get(snapshot.id);
1995
+ if (current) {
1996
+ current.updateController(snapshot);
1997
+ return current;
1998
+ }
1999
+ const session = new CompanionSessionProxy(requester, snapshot);
2000
+ sessions.set(snapshot.id, session);
2001
+ return session;
1987
2002
  };
1988
- Decoder.prototype.decodeStream = function (stream) {
1989
- return this.decodeMultiAsync(stream, false);
2003
+ requester.on(COMPANION_SESSION_OUTPUT_EVENT, (payload) => sessions.get(payload.sessionId)?.handleOutput(payload));
2004
+ requester.on(COMPANION_SESSION_EXIT_EVENT, (payload) => sessions.get(payload.sessionId)?.handleExit(payload.exit));
2005
+ requester.on(COMPANION_SESSION_OWNERSHIP_LOST_EVENT, (payload) => sessions.get(payload.sessionId)?.handleOwnershipLost(payload.controllerGeneration));
2006
+ const module = {
2007
+ getInfo: (alias) => requester.request(COMPANION_GET_INFO_METHOD, { alias: normalizeAlias(alias) }),
2008
+ getPreparationStatus: (alias) => requester.request(COMPANION_GET_PREPARATION_STATUS_METHOD, { alias: normalizeAlias(alias) }),
2009
+ prepare(alias, options) {
2010
+ assertPrepareOptions(options);
2011
+ const normalizedAlias = normalizeAlias(alias);
2012
+ const cancel = () => {
2013
+ void requester.request(COMPANION_CANCEL_PREPARATION_METHOD, { alias: normalizedAlias }).catch(() => undefined);
2014
+ };
2015
+ options?.signal?.addEventListener('abort', cancel, { once: true });
2016
+ return requester.requestOperation(COMPANION_PREPARE_METHOD, { alias: normalizedAlias }, {
2017
+ ...options,
2018
+ cancelOnAbort: false,
2019
+ createAbortError: () => createSDKError('COMPANION_PREPARATION_CANCELLED', 'Companion 准备已取消'),
2020
+ }).finally(() => options?.signal?.removeEventListener('abort', cancel));
2021
+ },
2022
+ cancelPreparation: (alias) => requester.request(COMPANION_CANCEL_PREPARATION_METHOD, { alias: normalizeAlias(alias) }),
2023
+ async launch(alias) {
2024
+ return getSession(await requester.requestOperation(COMPANION_LAUNCH_METHOD, { alias: normalizeAlias(alias) }));
2025
+ },
2026
+ async getActiveSession(alias) {
2027
+ const snapshot = await requester.request(COMPANION_GET_ACTIVE_SESSION_METHOD, { alias: normalizeAlias(alias) });
2028
+ return snapshot ? getSession(snapshot) : undefined;
2029
+ },
1990
2030
  };
1991
- Decoder.prototype.decodeMultiAsync = function (stream, isArray) {
1992
- return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
1993
- var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
1994
- var e_3, _a;
1995
- return __generator(this, function (_b) {
1996
- switch (_b.label) {
1997
- case 0:
1998
- isArrayHeaderRequired = isArray;
1999
- arrayItemsLeft = -1;
2000
- _b.label = 1;
2001
- case 1:
2002
- _b.trys.push([1, 13, 14, 19]);
2003
- stream_2 = __asyncValues(stream);
2004
- _b.label = 2;
2005
- case 2: return [4 /*yield*/, __await(stream_2.next())];
2006
- case 3:
2007
- if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];
2008
- buffer = stream_2_1.value;
2009
- if (isArray && arrayItemsLeft === 0) {
2010
- throw this.createExtraByteError(this.totalPos);
2011
- }
2012
- this.appendBuffer(buffer);
2013
- if (isArrayHeaderRequired) {
2014
- arrayItemsLeft = this.readArraySize();
2015
- isArrayHeaderRequired = false;
2016
- this.complete();
2017
- }
2018
- _b.label = 4;
2019
- case 4:
2020
- _b.trys.push([4, 9, , 10]);
2021
- _b.label = 5;
2022
- case 5:
2023
- return [4 /*yield*/, __await(this.doDecodeSync())];
2024
- case 6: return [4 /*yield*/, _b.sent()];
2025
- case 7:
2026
- _b.sent();
2027
- if (--arrayItemsLeft === 0) {
2028
- return [3 /*break*/, 8];
2029
- }
2030
- return [3 /*break*/, 5];
2031
- case 8: return [3 /*break*/, 10];
2032
- case 9:
2033
- e_2 = _b.sent();
2034
- if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {
2035
- throw e_2; // rethrow
2036
- }
2037
- return [3 /*break*/, 10];
2038
- case 10:
2039
- this.totalPos += this.pos;
2040
- _b.label = 11;
2041
- case 11: return [3 /*break*/, 2];
2042
- case 12: return [3 /*break*/, 19];
2043
- case 13:
2044
- e_3_1 = _b.sent();
2045
- e_3 = { error: e_3_1 };
2046
- return [3 /*break*/, 19];
2047
- case 14:
2048
- _b.trys.push([14, , 17, 18]);
2049
- if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];
2050
- return [4 /*yield*/, __await(_a.call(stream_2))];
2051
- case 15:
2052
- _b.sent();
2053
- _b.label = 16;
2054
- case 16: return [3 /*break*/, 18];
2055
- case 17:
2056
- if (e_3) throw e_3.error;
2057
- return [7 /*endfinally*/];
2058
- case 18: return [7 /*endfinally*/];
2059
- case 19: return [2 /*return*/];
2060
- }
2061
- });
2062
- });
2063
- };
2064
- Decoder.prototype.doDecodeSync = function () {
2065
- DECODE: while (true) {
2066
- var headByte = this.readHeadByte();
2067
- var object = void 0;
2068
- if (headByte >= 0xe0) {
2069
- // negative fixint (111x xxxx) 0xe0 - 0xff
2070
- object = headByte - 0x100;
2071
- }
2072
- else if (headByte < 0xc0) {
2073
- if (headByte < 0x80) {
2074
- // positive fixint (0xxx xxxx) 0x00 - 0x7f
2075
- object = headByte;
2076
- }
2077
- else if (headByte < 0x90) {
2078
- // fixmap (1000 xxxx) 0x80 - 0x8f
2079
- var size = headByte - 0x80;
2080
- if (size !== 0) {
2081
- this.pushMapState(size);
2082
- this.complete();
2083
- continue DECODE;
2084
- }
2085
- else {
2086
- object = {};
2087
- }
2088
- }
2089
- else if (headByte < 0xa0) {
2090
- // fixarray (1001 xxxx) 0x90 - 0x9f
2091
- var size = headByte - 0x90;
2092
- if (size !== 0) {
2093
- this.pushArrayState(size);
2094
- this.complete();
2095
- continue DECODE;
2096
- }
2097
- else {
2098
- object = [];
2099
- }
2100
- }
2101
- else {
2102
- // fixstr (101x xxxx) 0xa0 - 0xbf
2103
- var byteLength = headByte - 0xa0;
2104
- object = this.decodeUtf8String(byteLength, 0);
2105
- }
2106
- }
2107
- else if (headByte === 0xc0) {
2108
- // nil
2109
- object = null;
2110
- }
2111
- else if (headByte === 0xc2) {
2112
- // false
2113
- object = false;
2114
- }
2115
- else if (headByte === 0xc3) {
2116
- // true
2117
- object = true;
2118
- }
2119
- else if (headByte === 0xca) {
2120
- // float 32
2121
- object = this.readF32();
2122
- }
2123
- else if (headByte === 0xcb) {
2124
- // float 64
2125
- object = this.readF64();
2126
- }
2127
- else if (headByte === 0xcc) {
2128
- // uint 8
2129
- object = this.readU8();
2130
- }
2131
- else if (headByte === 0xcd) {
2132
- // uint 16
2133
- object = this.readU16();
2134
- }
2135
- else if (headByte === 0xce) {
2136
- // uint 32
2137
- object = this.readU32();
2138
- }
2139
- else if (headByte === 0xcf) {
2140
- // uint 64
2141
- object = this.readU64();
2142
- }
2143
- else if (headByte === 0xd0) {
2144
- // int 8
2145
- object = this.readI8();
2146
- }
2147
- else if (headByte === 0xd1) {
2148
- // int 16
2149
- object = this.readI16();
2150
- }
2151
- else if (headByte === 0xd2) {
2152
- // int 32
2153
- object = this.readI32();
2154
- }
2155
- else if (headByte === 0xd3) {
2156
- // int 64
2157
- object = this.readI64();
2158
- }
2159
- else if (headByte === 0xd9) {
2160
- // str 8
2161
- var byteLength = this.lookU8();
2162
- object = this.decodeUtf8String(byteLength, 1);
2163
- }
2164
- else if (headByte === 0xda) {
2165
- // str 16
2166
- var byteLength = this.lookU16();
2167
- object = this.decodeUtf8String(byteLength, 2);
2168
- }
2169
- else if (headByte === 0xdb) {
2170
- // str 32
2171
- var byteLength = this.lookU32();
2172
- object = this.decodeUtf8String(byteLength, 4);
2173
- }
2174
- else if (headByte === 0xdc) {
2175
- // array 16
2176
- var size = this.readU16();
2177
- if (size !== 0) {
2178
- this.pushArrayState(size);
2179
- this.complete();
2180
- continue DECODE;
2181
- }
2182
- else {
2183
- object = [];
2184
- }
2185
- }
2186
- else if (headByte === 0xdd) {
2187
- // array 32
2188
- var size = this.readU32();
2189
- if (size !== 0) {
2190
- this.pushArrayState(size);
2191
- this.complete();
2192
- continue DECODE;
2193
- }
2194
- else {
2195
- object = [];
2196
- }
2197
- }
2198
- else if (headByte === 0xde) {
2199
- // map 16
2200
- var size = this.readU16();
2201
- if (size !== 0) {
2202
- this.pushMapState(size);
2203
- this.complete();
2204
- continue DECODE;
2205
- }
2206
- else {
2207
- object = {};
2208
- }
2209
- }
2210
- else if (headByte === 0xdf) {
2211
- // map 32
2212
- var size = this.readU32();
2213
- if (size !== 0) {
2214
- this.pushMapState(size);
2215
- this.complete();
2216
- continue DECODE;
2217
- }
2218
- else {
2219
- object = {};
2220
- }
2221
- }
2222
- else if (headByte === 0xc4) {
2223
- // bin 8
2224
- var size = this.lookU8();
2225
- object = this.decodeBinary(size, 1);
2226
- }
2227
- else if (headByte === 0xc5) {
2228
- // bin 16
2229
- var size = this.lookU16();
2230
- object = this.decodeBinary(size, 2);
2231
- }
2232
- else if (headByte === 0xc6) {
2233
- // bin 32
2234
- var size = this.lookU32();
2235
- object = this.decodeBinary(size, 4);
2236
- }
2237
- else if (headByte === 0xd4) {
2238
- // fixext 1
2239
- object = this.decodeExtension(1, 0);
2240
- }
2241
- else if (headByte === 0xd5) {
2242
- // fixext 2
2243
- object = this.decodeExtension(2, 0);
2244
- }
2245
- else if (headByte === 0xd6) {
2246
- // fixext 4
2247
- object = this.decodeExtension(4, 0);
2248
- }
2249
- else if (headByte === 0xd7) {
2250
- // fixext 8
2251
- object = this.decodeExtension(8, 0);
2252
- }
2253
- else if (headByte === 0xd8) {
2254
- // fixext 16
2255
- object = this.decodeExtension(16, 0);
2256
- }
2257
- else if (headByte === 0xc7) {
2258
- // ext 8
2259
- var size = this.lookU8();
2260
- object = this.decodeExtension(size, 1);
2261
- }
2262
- else if (headByte === 0xc8) {
2263
- // ext 16
2264
- var size = this.lookU16();
2265
- object = this.decodeExtension(size, 2);
2266
- }
2267
- else if (headByte === 0xc9) {
2268
- // ext 32
2269
- var size = this.lookU32();
2270
- object = this.decodeExtension(size, 4);
2271
- }
2272
- else {
2273
- throw new DecodeError("Unrecognized type byte: ".concat(prettyByte(headByte)));
2274
- }
2275
- this.complete();
2276
- var stack = this.stack;
2277
- while (stack.length > 0) {
2278
- // arrays and maps
2279
- var state = stack[stack.length - 1];
2280
- if (state.type === 0 /* State.ARRAY */) {
2281
- state.array[state.position] = object;
2282
- state.position++;
2283
- if (state.position === state.size) {
2284
- stack.pop();
2285
- object = state.array;
2286
- }
2287
- else {
2288
- continue DECODE;
2289
- }
2290
- }
2291
- else if (state.type === 1 /* State.MAP_KEY */) {
2292
- if (!isValidMapKeyType(object)) {
2293
- throw new DecodeError("The type of key must be string or number but " + typeof object);
2294
- }
2295
- if (object === "__proto__") {
2296
- throw new DecodeError("The key __proto__ is not allowed");
2297
- }
2298
- state.key = object;
2299
- state.type = 2 /* State.MAP_VALUE */;
2300
- continue DECODE;
2301
- }
2302
- else {
2303
- // it must be `state.type === State.MAP_VALUE` here
2304
- state.map[state.key] = object;
2305
- state.readCount++;
2306
- if (state.readCount === state.size) {
2307
- stack.pop();
2308
- object = state.map;
2309
- }
2310
- else {
2311
- state.key = null;
2312
- state.type = 1 /* State.MAP_KEY */;
2313
- continue DECODE;
2314
- }
2315
- }
2316
- }
2317
- return object;
2318
- }
2319
- };
2320
- Decoder.prototype.readHeadByte = function () {
2321
- if (this.headByte === HEAD_BYTE_REQUIRED) {
2322
- this.headByte = this.readU8();
2323
- // console.log("headByte", prettyByte(this.headByte));
2324
- }
2325
- return this.headByte;
2326
- };
2327
- Decoder.prototype.complete = function () {
2328
- this.headByte = HEAD_BYTE_REQUIRED;
2329
- };
2330
- Decoder.prototype.readArraySize = function () {
2331
- var headByte = this.readHeadByte();
2332
- switch (headByte) {
2333
- case 0xdc:
2334
- return this.readU16();
2335
- case 0xdd:
2336
- return this.readU32();
2337
- default: {
2338
- if (headByte < 0xa0) {
2339
- return headByte - 0x90;
2340
- }
2341
- else {
2342
- throw new DecodeError("Unrecognized array type byte: ".concat(prettyByte(headByte)));
2343
- }
2344
- }
2345
- }
2346
- };
2347
- Decoder.prototype.pushMapState = function (size) {
2348
- if (size > this.maxMapLength) {
2349
- throw new DecodeError("Max length exceeded: map length (".concat(size, ") > maxMapLengthLength (").concat(this.maxMapLength, ")"));
2350
- }
2351
- this.stack.push({
2352
- type: 1 /* State.MAP_KEY */,
2353
- size: size,
2354
- key: null,
2355
- readCount: 0,
2356
- map: {},
2357
- });
2358
- };
2359
- Decoder.prototype.pushArrayState = function (size) {
2360
- if (size > this.maxArrayLength) {
2361
- throw new DecodeError("Max length exceeded: array length (".concat(size, ") > maxArrayLength (").concat(this.maxArrayLength, ")"));
2362
- }
2363
- this.stack.push({
2364
- type: 0 /* State.ARRAY */,
2365
- size: size,
2366
- array: new Array(size),
2367
- position: 0,
2368
- });
2369
- };
2370
- Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {
2371
- var _a;
2372
- if (byteLength > this.maxStrLength) {
2373
- throw new DecodeError("Max length exceeded: UTF-8 byte length (".concat(byteLength, ") > maxStrLength (").concat(this.maxStrLength, ")"));
2374
- }
2375
- if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
2376
- throw MORE_DATA;
2377
- }
2378
- var offset = this.pos + headerOffset;
2379
- var object;
2380
- if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {
2381
- object = this.keyDecoder.decode(this.bytes, offset, byteLength);
2382
- }
2383
- else if (byteLength > TEXT_DECODER_THRESHOLD) {
2384
- object = utf8DecodeTD(this.bytes, offset, byteLength);
2385
- }
2386
- else {
2387
- object = utf8DecodeJs(this.bytes, offset, byteLength);
2388
- }
2389
- this.pos += headerOffset + byteLength;
2390
- return object;
2391
- };
2392
- Decoder.prototype.stateIsMapKey = function () {
2393
- if (this.stack.length > 0) {
2394
- var state = this.stack[this.stack.length - 1];
2395
- return state.type === 1 /* State.MAP_KEY */;
2396
- }
2397
- return false;
2398
- };
2399
- Decoder.prototype.decodeBinary = function (byteLength, headOffset) {
2400
- if (byteLength > this.maxBinLength) {
2401
- throw new DecodeError("Max length exceeded: bin length (".concat(byteLength, ") > maxBinLength (").concat(this.maxBinLength, ")"));
2402
- }
2403
- if (!this.hasRemaining(byteLength + headOffset)) {
2404
- throw MORE_DATA;
2405
- }
2406
- var offset = this.pos + headOffset;
2407
- var object = this.bytes.subarray(offset, offset + byteLength);
2408
- this.pos += headOffset + byteLength;
2409
- return object;
2410
- };
2411
- Decoder.prototype.decodeExtension = function (size, headOffset) {
2412
- if (size > this.maxExtLength) {
2413
- throw new DecodeError("Max length exceeded: ext length (".concat(size, ") > maxExtLength (").concat(this.maxExtLength, ")"));
2414
- }
2415
- var extType = this.view.getInt8(this.pos + headOffset);
2416
- var data = this.decodeBinary(size, headOffset + 1 /* extType */);
2417
- return this.extensionCodec.decode(data, extType, this.context);
2418
- };
2419
- Decoder.prototype.lookU8 = function () {
2420
- return this.view.getUint8(this.pos);
2421
- };
2422
- Decoder.prototype.lookU16 = function () {
2423
- return this.view.getUint16(this.pos);
2424
- };
2425
- Decoder.prototype.lookU32 = function () {
2426
- return this.view.getUint32(this.pos);
2427
- };
2428
- Decoder.prototype.readU8 = function () {
2429
- var value = this.view.getUint8(this.pos);
2430
- this.pos++;
2431
- return value;
2432
- };
2433
- Decoder.prototype.readI8 = function () {
2434
- var value = this.view.getInt8(this.pos);
2435
- this.pos++;
2436
- return value;
2437
- };
2438
- Decoder.prototype.readU16 = function () {
2439
- var value = this.view.getUint16(this.pos);
2440
- this.pos += 2;
2441
- return value;
2442
- };
2443
- Decoder.prototype.readI16 = function () {
2444
- var value = this.view.getInt16(this.pos);
2445
- this.pos += 2;
2446
- return value;
2447
- };
2448
- Decoder.prototype.readU32 = function () {
2449
- var value = this.view.getUint32(this.pos);
2450
- this.pos += 4;
2451
- return value;
2452
- };
2453
- Decoder.prototype.readI32 = function () {
2454
- var value = this.view.getInt32(this.pos);
2455
- this.pos += 4;
2456
- return value;
2457
- };
2458
- Decoder.prototype.readU64 = function () {
2459
- var value = getUint64(this.view, this.pos);
2460
- this.pos += 8;
2461
- return value;
2462
- };
2463
- Decoder.prototype.readI64 = function () {
2464
- var value = getInt64(this.view, this.pos);
2465
- this.pos += 8;
2466
- return value;
2467
- };
2468
- Decoder.prototype.readF32 = function () {
2469
- var value = this.view.getFloat32(this.pos);
2470
- this.pos += 4;
2471
- return value;
2472
- };
2473
- Decoder.prototype.readF64 = function () {
2474
- var value = this.view.getFloat64(this.pos);
2475
- this.pos += 8;
2476
- return value;
2477
- };
2478
- return Decoder;
2479
- }());
2031
+ return Object.freeze(module);
2032
+ }
2480
2033
 
2481
- var defaultDecodeOptions = {};
2482
2034
  /**
2483
- * It decodes a single MessagePack object in a buffer.
2484
- *
2485
- * This is a synchronous decoding function.
2486
- * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
2035
+ * 复制当前小程序的通用分享链接。
2487
2036
  *
2488
- * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
2489
- * @throws {@link DecodeError} if the buffer contains invalid data.
2037
+ * @param requester - 底层 bridge 请求能力。
2038
+ * @param options - 分享扩展数据;不传时复制默认首页链接。
2039
+ * @returns 已写入系统剪贴板的完整分享链接。
2040
+ * @throws {@link HbMiniProgramSDKError} 当参数、bridge、父容器或剪贴板能力调用失败时抛出。
2490
2041
  */
2491
- function decode(buffer, options) {
2492
- if (options === void 0) { options = defaultDecodeOptions; }
2493
- var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
2494
- return decoder.decode(buffer);
2042
+ function copyLink(requester, options) {
2043
+ return requester.request(SHARE_COPY_LINK_METHOD, options);
2495
2044
  }
2496
2045
 
2497
- /** 读取小程序启动时携带的分享数据。 */
2498
- function readMiniProgramShareExtra(launchHref) {
2499
- if (!launchHref)
2500
- return undefined;
2501
- try {
2502
- const value = new URL(launchHref).searchParams.get('extra');
2503
- if (!value || value.length > 256 || value.length % 4 === 1 || !/^[A-Za-z0-9_-]+$/.test(value)) {
2504
- return undefined;
2505
- }
2506
- const bytes = decodeBase64Url(value);
2507
- if (bytes.byteLength > 128)
2508
- return undefined;
2509
- const decoded = decode(bytes);
2510
- assertExtraValue(decoded);
2511
- return decoded;
2512
- }
2513
- catch {
2514
- return undefined;
2515
- }
2046
+ // Integer Utility
2047
+ var UINT32_MAX = 4294967295;
2048
+ function setInt64(view, offset, value) {
2049
+ var high = Math.floor(value / 4294967296);
2050
+ var low = value; // high bits are truncated by DataView
2051
+ view.setUint32(offset, high);
2052
+ view.setUint32(offset + 4, low);
2516
2053
  }
2517
- function assertExtraValue(value, depth = 0, seen = new WeakSet()) {
2518
- if (depth > 8)
2519
- throw new Error('extra nesting depth exceeded');
2520
- if (value === null || typeof value === 'string' || typeof value === 'boolean')
2521
- return;
2522
- if (typeof value === 'number') {
2523
- if (Number.isFinite(value))
2524
- return;
2525
- throw new Error('extra number must be finite');
2526
- }
2527
- if (typeof value !== 'object')
2528
- throw new Error('extra value must be JSON-compatible');
2529
- if (seen.has(value))
2530
- throw new Error('extra value must not contain cycles');
2531
- seen.add(value);
2532
- if (Array.isArray(value)) {
2533
- if (value.length > 64)
2534
- throw new Error('extra array is too large');
2535
- for (const item of value)
2536
- assertExtraValue(item, depth + 1, seen);
2537
- seen.delete(value);
2538
- return;
2539
- }
2540
- const prototype = Object.getPrototypeOf(value);
2541
- if (prototype !== Object.prototype && prototype !== null)
2542
- throw new Error('extra object must be a plain object');
2543
- const values = Object.values(value);
2544
- if (values.length > 64)
2545
- throw new Error('extra object has too many fields');
2546
- for (const item of values)
2547
- assertExtraValue(item, depth + 1, seen);
2548
- seen.delete(value);
2054
+ function getInt64(view, offset) {
2055
+ var high = view.getInt32(offset);
2056
+ var low = view.getUint32(offset + 4);
2057
+ return high * 4294967296 + low;
2058
+ }
2059
+ function getUint64(view, offset) {
2060
+ var high = view.getUint32(offset);
2061
+ var low = view.getUint32(offset + 4);
2062
+ return high * 4294967296 + low;
2063
+ }
2064
+
2065
+ var _a, _b, _c;
2066
+ var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") &&
2067
+ typeof TextEncoder !== "undefined" &&
2068
+ typeof TextDecoder !== "undefined";
2069
+ var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
2070
+ !TEXT_ENCODING_AVAILABLE
2071
+ ? UINT32_MAX
2072
+ : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
2073
+ ? 200
2074
+ : 0;
2075
+ function utf8EncodeTEencode(str, output, outputOffset) {
2076
+ output.set(sharedTextEncoder.encode(str), outputOffset);
2077
+ }
2078
+ function utf8EncodeTEencodeInto(str, output, outputOffset) {
2079
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
2080
+ }
2081
+ (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
2082
+ var CHUNK_SIZE = 4096;
2083
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
2084
+ var offset = inputOffset;
2085
+ var end = offset + byteLength;
2086
+ var units = [];
2087
+ var result = "";
2088
+ while (offset < end) {
2089
+ var byte1 = bytes[offset++];
2090
+ if ((byte1 & 0x80) === 0) {
2091
+ // 1 byte
2092
+ units.push(byte1);
2093
+ }
2094
+ else if ((byte1 & 0xe0) === 0xc0) {
2095
+ // 2 bytes
2096
+ var byte2 = bytes[offset++] & 0x3f;
2097
+ units.push(((byte1 & 0x1f) << 6) | byte2);
2098
+ }
2099
+ else if ((byte1 & 0xf0) === 0xe0) {
2100
+ // 3 bytes
2101
+ var byte2 = bytes[offset++] & 0x3f;
2102
+ var byte3 = bytes[offset++] & 0x3f;
2103
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
2104
+ }
2105
+ else if ((byte1 & 0xf8) === 0xf0) {
2106
+ // 4 bytes
2107
+ var byte2 = bytes[offset++] & 0x3f;
2108
+ var byte3 = bytes[offset++] & 0x3f;
2109
+ var byte4 = bytes[offset++] & 0x3f;
2110
+ var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
2111
+ if (unit > 0xffff) {
2112
+ unit -= 0x10000;
2113
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
2114
+ unit = 0xdc00 | (unit & 0x3ff);
2115
+ }
2116
+ units.push(unit);
2117
+ }
2118
+ else {
2119
+ units.push(byte1);
2120
+ }
2121
+ if (units.length >= CHUNK_SIZE) {
2122
+ result += String.fromCharCode.apply(String, units);
2123
+ units.length = 0;
2124
+ }
2125
+ }
2126
+ if (units.length > 0) {
2127
+ result += String.fromCharCode.apply(String, units);
2128
+ }
2129
+ return result;
2549
2130
  }
2550
- function decodeBase64Url(value) {
2551
- const normalized = value.replaceAll('-', '+').replaceAll('_', '/');
2552
- const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=');
2553
- return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
2131
+ var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
2132
+ var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
2133
+ ? UINT32_MAX
2134
+ : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
2135
+ ? 200
2136
+ : 0;
2137
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
2138
+ var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
2139
+ return sharedTextDecoder.decode(stringBytes);
2554
2140
  }
2555
2141
 
2556
2142
  /**
2557
- * 截图并唤起分享。
2558
- *
2559
- * @param requester - 底层 bridge 请求能力。
2560
- * @param options - 截图区域、延迟与保存相册等配置。
2561
- * @returns 由宿主客户端协议决定的结果。
2562
- * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
2143
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
2563
2144
  */
2564
- function screenshot(requester, options) {
2565
- return requester.request(SHARE_SCREENSHOT_METHOD, options);
2566
- }
2145
+ var ExtData = /** @class */ (function () {
2146
+ function ExtData(type, data) {
2147
+ this.type = type;
2148
+ this.data = data;
2149
+ }
2150
+ return ExtData;
2151
+ }());
2567
2152
 
2568
- /**
2569
- * 展示以当前小程序通用分享页为落地页的基础分享面板。
2570
- *
2571
- * @param requester - 底层 bridge 请求能力。
2572
- * @param options - 基础分享参数。
2573
- * @returns 由宿主客户端协议决定的结果。
2574
- * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
2575
- */
2576
- function showShareMenu(requester, options) {
2577
- return requester.request(SHARE_SHOW_SHARE_MENU_METHOD, options);
2578
- }
2153
+ var __extends = (undefined && undefined.__extends) || (function () {
2154
+ var extendStatics = function (d, b) {
2155
+ extendStatics = Object.setPrototypeOf ||
2156
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2157
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
2158
+ return extendStatics(d, b);
2159
+ };
2160
+ return function (d, b) {
2161
+ if (typeof b !== "function" && b !== null)
2162
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2163
+ extendStatics(d, b);
2164
+ function __() { this.constructor = d; }
2165
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2166
+ };
2167
+ })();
2168
+ var DecodeError = /** @class */ (function (_super) {
2169
+ __extends(DecodeError, _super);
2170
+ function DecodeError(message) {
2171
+ var _this = _super.call(this, message) || this;
2172
+ // fix the prototype chain in a cross-platform way
2173
+ var proto = Object.create(DecodeError.prototype);
2174
+ Object.setPrototypeOf(_this, proto);
2175
+ Object.defineProperty(_this, "name", {
2176
+ configurable: true,
2177
+ enumerable: false,
2178
+ value: DecodeError.name,
2179
+ });
2180
+ return _this;
2181
+ }
2182
+ return DecodeError;
2183
+ }(Error));
2579
2184
 
2580
- /**
2581
- * 创建分享模块。
2582
- *
2583
- * @param requester - 底层 bridge 请求能力。
2584
- * @returns 面向业务层的分享模块对象。
2585
- */
2586
- function createShareModule(requester, launchHref) {
2185
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
2186
+ var EXT_TIMESTAMP = -1;
2187
+ var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
2188
+ var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
2189
+ function encodeTimeSpecToTimestamp(_a) {
2190
+ var sec = _a.sec, nsec = _a.nsec;
2191
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
2192
+ // Here sec >= 0 && nsec >= 0
2193
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
2194
+ // timestamp 32 = { sec32 (unsigned) }
2195
+ var rv = new Uint8Array(4);
2196
+ var view = new DataView(rv.buffer);
2197
+ view.setUint32(0, sec);
2198
+ return rv;
2199
+ }
2200
+ else {
2201
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
2202
+ var secHigh = sec / 0x100000000;
2203
+ var secLow = sec & 0xffffffff;
2204
+ var rv = new Uint8Array(8);
2205
+ var view = new DataView(rv.buffer);
2206
+ // nsec30 | secHigh2
2207
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
2208
+ // secLow32
2209
+ view.setUint32(4, secLow);
2210
+ return rv;
2211
+ }
2212
+ }
2213
+ else {
2214
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
2215
+ var rv = new Uint8Array(12);
2216
+ var view = new DataView(rv.buffer);
2217
+ view.setUint32(0, nsec);
2218
+ setInt64(view, 4, sec);
2219
+ return rv;
2220
+ }
2221
+ }
2222
+ function encodeDateToTimeSpec(date) {
2223
+ var msec = date.getTime();
2224
+ var sec = Math.floor(msec / 1e3);
2225
+ var nsec = (msec - sec * 1e3) * 1e6;
2226
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
2227
+ var nsecInSec = Math.floor(nsec / 1e9);
2587
2228
  return {
2588
- copyLink: (options) => copyLink(requester, options),
2589
- getExtra: () => readMiniProgramShareExtra(launchHref),
2590
- showShareMenu: (options) => showShareMenu(requester, options),
2591
- screenshot: (options) => screenshot(requester, options),
2229
+ sec: sec + nsecInSec,
2230
+ nsec: nsec - nsecInSec * 1e9,
2592
2231
  };
2593
2232
  }
2594
-
2595
- /**
2596
- * 获取小程序隔离 storage。
2597
- *
2598
- * @param requester - 底层 bridge 请求能力。
2599
- * @param options - 读取的 storage key。
2600
- * @returns 对应 key 的标准化读取结果。
2601
- * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
2602
- */
2603
- function getStorage(requester, options) {
2604
- return requester.request(STORAGE_GET_STORAGE_METHOD, options);
2233
+ function encodeTimestampExtension(object) {
2234
+ if (object instanceof Date) {
2235
+ var timeSpec = encodeDateToTimeSpec(object);
2236
+ return encodeTimeSpecToTimestamp(timeSpec);
2237
+ }
2238
+ else {
2239
+ return null;
2240
+ }
2605
2241
  }
2606
- /**
2607
- * 写入小程序隔离 storage。
2608
- *
2609
- * @param requester - 底层 bridge 请求能力。
2610
- * @param options - 要写入的 storage key 与数据。
2611
- * @returns 当写入完成后 resolve。
2612
- * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
2613
- */
2614
- function setStorage(requester, options) {
2615
- return requester.request(STORAGE_SET_STORAGE_METHOD, options);
2242
+ function decodeTimestampToTimeSpec(data) {
2243
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
2244
+ // data may be 32, 64, or 96 bits
2245
+ switch (data.byteLength) {
2246
+ case 4: {
2247
+ // timestamp 32 = { sec32 }
2248
+ var sec = view.getUint32(0);
2249
+ var nsec = 0;
2250
+ return { sec: sec, nsec: nsec };
2251
+ }
2252
+ case 8: {
2253
+ // timestamp 64 = { nsec30, sec34 }
2254
+ var nsec30AndSecHigh2 = view.getUint32(0);
2255
+ var secLow32 = view.getUint32(4);
2256
+ var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
2257
+ var nsec = nsec30AndSecHigh2 >>> 2;
2258
+ return { sec: sec, nsec: nsec };
2259
+ }
2260
+ case 12: {
2261
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
2262
+ var sec = getInt64(view, 4);
2263
+ var nsec = view.getUint32(0);
2264
+ return { sec: sec, nsec: nsec };
2265
+ }
2266
+ default:
2267
+ throw new DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
2268
+ }
2616
2269
  }
2617
- /**
2618
- * 创建 storage 模块。
2619
- *
2620
- * @param requester - 底层 bridge 请求能力。
2621
- * @returns 面向业务层的 storage 模块对象。
2622
- */
2623
- function createStorageModule(requester) {
2624
- return {
2625
- getStorage: (options) => getStorage(requester, options),
2626
- setStorage: (options) => setStorage(requester, options),
2270
+ function decodeTimestampExtension(data) {
2271
+ var timeSpec = decodeTimestampToTimeSpec(data);
2272
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
2273
+ }
2274
+ var timestampExtension = {
2275
+ type: EXT_TIMESTAMP,
2276
+ encode: encodeTimestampExtension,
2277
+ decode: decodeTimestampExtension,
2278
+ };
2279
+
2280
+ // ExtensionCodec to handle MessagePack extensions
2281
+ var ExtensionCodec = /** @class */ (function () {
2282
+ function ExtensionCodec() {
2283
+ // built-in extensions
2284
+ this.builtInEncoders = [];
2285
+ this.builtInDecoders = [];
2286
+ // custom extensions
2287
+ this.encoders = [];
2288
+ this.decoders = [];
2289
+ this.register(timestampExtension);
2290
+ }
2291
+ ExtensionCodec.prototype.register = function (_a) {
2292
+ var type = _a.type, encode = _a.encode, decode = _a.decode;
2293
+ if (type >= 0) {
2294
+ // custom extensions
2295
+ this.encoders[type] = encode;
2296
+ this.decoders[type] = decode;
2297
+ }
2298
+ else {
2299
+ // built-in extensions
2300
+ var index = 1 + type;
2301
+ this.builtInEncoders[index] = encode;
2302
+ this.builtInDecoders[index] = decode;
2303
+ }
2304
+ };
2305
+ ExtensionCodec.prototype.tryToEncode = function (object, context) {
2306
+ // built-in extensions
2307
+ for (var i = 0; i < this.builtInEncoders.length; i++) {
2308
+ var encodeExt = this.builtInEncoders[i];
2309
+ if (encodeExt != null) {
2310
+ var data = encodeExt(object, context);
2311
+ if (data != null) {
2312
+ var type = -1 - i;
2313
+ return new ExtData(type, data);
2314
+ }
2315
+ }
2316
+ }
2317
+ // custom extensions
2318
+ for (var i = 0; i < this.encoders.length; i++) {
2319
+ var encodeExt = this.encoders[i];
2320
+ if (encodeExt != null) {
2321
+ var data = encodeExt(object, context);
2322
+ if (data != null) {
2323
+ var type = i;
2324
+ return new ExtData(type, data);
2325
+ }
2326
+ }
2327
+ }
2328
+ if (object instanceof ExtData) {
2329
+ // to keep ExtData as is
2330
+ return object;
2331
+ }
2332
+ return null;
2627
2333
  };
2628
- }
2334
+ ExtensionCodec.prototype.decode = function (data, type, context) {
2335
+ var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
2336
+ if (decodeExt) {
2337
+ return decodeExt(data, type, context);
2338
+ }
2339
+ else {
2340
+ // decode() does not fail, returns ExtData instead.
2341
+ return new ExtData(type, data);
2342
+ }
2343
+ };
2344
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
2345
+ return ExtensionCodec;
2346
+ }());
2629
2347
 
2630
- const registries = new WeakMap();
2631
- const brandedFileSystemValues = new WeakSet();
2632
- const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/;
2633
- function invalidParams$1(message, data) {
2634
- return createSDKError('INVALID_PARAMS', message, data);
2635
- }
2636
- function clonePathRootRef(ref) {
2637
- return ref.kind === 'sandbox' ? Object.freeze({ kind: 'sandbox' }) : Object.freeze({ kind: 'directory', handleId: ref.handleId });
2638
- }
2639
- function cloneFileRef(ref) {
2640
- return 'handleId' in ref
2641
- ? Object.freeze({ kind: 'file', handleId: ref.handleId })
2642
- : Object.freeze({
2643
- kind: 'file',
2644
- root: clonePathRootRef(ref.root),
2645
- relativePath: ref.relativePath,
2646
- });
2647
- }
2648
- function cloneDirectoryRef(ref) {
2649
- return 'handleId' in ref
2650
- ? Object.freeze({ kind: 'directory', handleId: ref.handleId })
2651
- : Object.freeze({
2652
- kind: 'directory',
2653
- root: clonePathRootRef(ref.root),
2654
- relativePath: ref.relativePath,
2655
- });
2656
- }
2657
- function assertMode(mode) {
2658
- if (mode !== 'read' && mode !== 'readwrite') {
2659
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件访问模式');
2348
+ function ensureUint8Array(buffer) {
2349
+ if (buffer instanceof Uint8Array) {
2350
+ return buffer;
2660
2351
  }
2661
- }
2662
- function assertName(name) {
2663
- if (typeof name !== 'string' || name.length === 0 || name.includes('/') || name.includes('\\') || CONTROL_CHARACTER_PATTERN.test(name)) {
2664
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件名');
2352
+ else if (ArrayBuffer.isView(buffer)) {
2353
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2665
2354
  }
2666
- }
2667
- function assertFileRef(ref) {
2668
- if (!isMiniProgramFileRef(ref)) {
2669
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 File handle');
2355
+ else if (buffer instanceof ArrayBuffer) {
2356
+ return new Uint8Array(buffer);
2670
2357
  }
2671
- }
2672
- function assertDirectoryRef(ref) {
2673
- if (!isMiniProgramDirectoryRef(ref)) {
2674
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 Directory handle');
2358
+ else {
2359
+ // ArrayLike<number>
2360
+ return Uint8Array.from(buffer);
2675
2361
  }
2676
2362
  }
2677
- function defineReadonlyValue(target, key, value, enumerable = true) {
2678
- Object.defineProperty(target, key, {
2679
- value,
2680
- enumerable,
2681
- configurable: false,
2682
- writable: false,
2683
- });
2684
- }
2685
- function joinRelativePath(prefix, relativePath) {
2686
- return prefix ? `${prefix}/${relativePath}` : relativePath;
2687
- }
2688
- function basename(relativePath) {
2689
- const segments = relativePath.split('/');
2690
- return segments[segments.length - 1];
2691
- }
2692
- function assertWritable(mode) {
2693
- if (mode !== 'readwrite') {
2694
- throw createSDKError('FILE_ACCESS_DENIED', '当前文件句柄不允许写入');
2363
+ function createDataView(buffer) {
2364
+ if (buffer instanceof ArrayBuffer) {
2365
+ return new DataView(buffer);
2695
2366
  }
2367
+ var bufferView = ensureUint8Array(buffer);
2368
+ return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
2696
2369
  }
2697
- function assertSandboxRef(ref) {
2698
- if ('handleId' in ref || ref.root.kind !== 'sandbox') {
2699
- throw createSDKError('FILE_ACCESS_DENIED', '外部文件授权不允许删除');
2700
- }
2370
+
2371
+ function prettyByte(byte) {
2372
+ return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
2701
2373
  }
2702
- function normalizeCreateOptions(options) {
2703
- if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
2704
- throw invalidParams$1('create options 必须是对象');
2705
- }
2706
- if (options?.recursive !== undefined && typeof options.recursive !== 'boolean') {
2707
- throw invalidParams$1('recursive 必须是 boolean');
2708
- }
2709
- if (options?.exclusive !== undefined && typeof options.exclusive !== 'boolean') {
2710
- throw invalidParams$1('exclusive 必须是 boolean');
2374
+
2375
+ var DEFAULT_MAX_KEY_LENGTH = 16;
2376
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
2377
+ var CachedKeyDecoder = /** @class */ (function () {
2378
+ function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
2379
+ if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
2380
+ if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
2381
+ this.maxKeyLength = maxKeyLength;
2382
+ this.maxLengthPerKey = maxLengthPerKey;
2383
+ this.hit = 0;
2384
+ this.miss = 0;
2385
+ // avoid `new Array(N)`, which makes a sparse array,
2386
+ // because a sparse array is typically slower than a non-sparse array.
2387
+ this.caches = [];
2388
+ for (var i = 0; i < this.maxKeyLength; i++) {
2389
+ this.caches.push([]);
2390
+ }
2711
2391
  }
2712
- return {
2713
- recursive: options?.recursive ?? false,
2714
- exclusive: options?.exclusive ?? false,
2392
+ CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
2393
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
2715
2394
  };
2716
- }
2717
- function normalizeListOptions(options) {
2718
- if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
2719
- throw invalidParams$1('list options 必须是对象');
2720
- }
2721
- if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) {
2722
- throw invalidParams$1('limit 必须是正的 safe integer');
2723
- }
2724
- return options?.limit;
2725
- }
2726
- function normalizeRemoveOptions(options) {
2727
- if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {
2728
- throw invalidParams$1('remove options 必须是对象');
2729
- }
2730
- if (options?.recursive !== undefined && typeof options.recursive !== 'boolean') {
2731
- throw invalidParams$1('recursive 必须是 boolean');
2395
+ CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
2396
+ var records = this.caches[byteLength - 1];
2397
+ FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
2398
+ var record = records_1[_i];
2399
+ var recordBytes = record.bytes;
2400
+ for (var j = 0; j < byteLength; j++) {
2401
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
2402
+ continue FIND_CHUNK;
2403
+ }
2404
+ }
2405
+ return record.str;
2406
+ }
2407
+ return null;
2408
+ };
2409
+ CachedKeyDecoder.prototype.store = function (bytes, value) {
2410
+ var records = this.caches[bytes.length - 1];
2411
+ var record = { bytes: bytes, str: value };
2412
+ if (records.length >= this.maxLengthPerKey) {
2413
+ // `records` are full!
2414
+ // Set `record` to an arbitrary position.
2415
+ records[(Math.random() * records.length) | 0] = record;
2416
+ }
2417
+ else {
2418
+ records.push(record);
2419
+ }
2420
+ };
2421
+ CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
2422
+ var cachedValue = this.find(bytes, inputOffset, byteLength);
2423
+ if (cachedValue != null) {
2424
+ this.hit++;
2425
+ return cachedValue;
2426
+ }
2427
+ this.miss++;
2428
+ var str = utf8DecodeJs(bytes, inputOffset, byteLength);
2429
+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
2430
+ var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
2431
+ this.store(slicedCopyOfBytes, str);
2432
+ return str;
2433
+ };
2434
+ return CachedKeyDecoder;
2435
+ }());
2436
+
2437
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2438
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2439
+ return new (P || (P = Promise))(function (resolve, reject) {
2440
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2441
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2442
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2443
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2444
+ });
2445
+ };
2446
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
2447
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2448
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2449
+ function verb(n) { return function (v) { return step([n, v]); }; }
2450
+ function step(op) {
2451
+ if (f) throw new TypeError("Generator is already executing.");
2452
+ while (_) try {
2453
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2454
+ if (y = 0, t) op = [op[0] & 2, t.value];
2455
+ switch (op[0]) {
2456
+ case 0: case 1: t = op; break;
2457
+ case 4: _.label++; return { value: op[1], done: false };
2458
+ case 5: _.label++; y = op[1]; op = [0]; continue;
2459
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
2460
+ default:
2461
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2462
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2463
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2464
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2465
+ if (t[2]) _.ops.pop();
2466
+ _.trys.pop(); continue;
2467
+ }
2468
+ op = body.call(thisArg, _);
2469
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2470
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2732
2471
  }
2733
- return { recursive: options?.recursive ?? false };
2734
- }
2735
- function cloneBytes(content) {
2736
- if (!(content instanceof Uint8Array)) {
2737
- throw invalidParams$1('content 必须是 Uint8Array');
2472
+ };
2473
+ var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
2474
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2475
+ var m = o[Symbol.asyncIterator], i;
2476
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
2477
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
2478
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
2479
+ };
2480
+ var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); };
2481
+ var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
2482
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2483
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
2484
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
2485
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
2486
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
2487
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
2488
+ function fulfill(value) { resume("next", value); }
2489
+ function reject(value) { resume("throw", value); }
2490
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
2491
+ };
2492
+ var isValidMapKeyType = function (key) {
2493
+ var keyType = typeof key;
2494
+ return keyType === "string" || keyType === "number";
2495
+ };
2496
+ var HEAD_BYTE_REQUIRED = -1;
2497
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
2498
+ var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
2499
+ // IE11: Hack to support IE11.
2500
+ // IE11: Drop this hack and just use RangeError when IE11 is obsolete.
2501
+ var DataViewIndexOutOfBoundsError = (function () {
2502
+ try {
2503
+ // IE11: The spec says it should throw RangeError,
2504
+ // IE11: but in IE11 it throws TypeError.
2505
+ EMPTY_VIEW.getInt8(0);
2738
2506
  }
2739
- if (typeof SharedArrayBuffer !== 'undefined' && content.buffer instanceof SharedArrayBuffer) {
2740
- throw invalidParams$1('content 不能由 SharedArrayBuffer 承载');
2507
+ catch (e) {
2508
+ return e.constructor;
2741
2509
  }
2742
- return new Uint8Array(content);
2743
- }
2744
- function normalizeStat(stat) {
2745
- if (!isMiniProgramFileStat(stat)) {
2746
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 FileStat');
2510
+ throw new Error("never reached");
2511
+ })();
2512
+ var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
2513
+ var sharedCachedKeyDecoder = new CachedKeyDecoder();
2514
+ var Decoder = /** @class */ (function () {
2515
+ function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
2516
+ if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }
2517
+ if (context === void 0) { context = undefined; }
2518
+ if (maxStrLength === void 0) { maxStrLength = UINT32_MAX; }
2519
+ if (maxBinLength === void 0) { maxBinLength = UINT32_MAX; }
2520
+ if (maxArrayLength === void 0) { maxArrayLength = UINT32_MAX; }
2521
+ if (maxMapLength === void 0) { maxMapLength = UINT32_MAX; }
2522
+ if (maxExtLength === void 0) { maxExtLength = UINT32_MAX; }
2523
+ if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }
2524
+ this.extensionCodec = extensionCodec;
2525
+ this.context = context;
2526
+ this.maxStrLength = maxStrLength;
2527
+ this.maxBinLength = maxBinLength;
2528
+ this.maxArrayLength = maxArrayLength;
2529
+ this.maxMapLength = maxMapLength;
2530
+ this.maxExtLength = maxExtLength;
2531
+ this.keyDecoder = keyDecoder;
2532
+ this.totalPos = 0;
2533
+ this.pos = 0;
2534
+ this.view = EMPTY_VIEW;
2535
+ this.bytes = EMPTY_BYTES;
2536
+ this.headByte = HEAD_BYTE_REQUIRED;
2537
+ this.stack = [];
2747
2538
  }
2748
- return {
2749
- kind: 'file',
2750
- size: stat.size,
2751
- ...(stat.modifiedAt === undefined ? {} : { modifiedAt: stat.modifiedAt }),
2752
- ...(stat.createdAt === undefined ? {} : { createdAt: stat.createdAt }),
2539
+ Decoder.prototype.reinitializeState = function () {
2540
+ this.totalPos = 0;
2541
+ this.headByte = HEAD_BYTE_REQUIRED;
2542
+ this.stack.length = 0;
2543
+ // view, bytes, and pos will be re-initialized in setBuffer()
2753
2544
  };
2754
- }
2755
- /** 校验并返回平台无关的 `/` 分隔逻辑相对路径。 */
2756
- function normalizeRelativePath(value) {
2757
- if (!isMiniProgramRelativePath(value)) {
2758
- throw invalidParams$1('relativePath 必须是规范的 `/` 分隔逻辑相对路径');
2759
- }
2760
- return value;
2761
- }
2762
- class MiniProgramFileHandleRegistry {
2763
- requester;
2764
- fileStates = new WeakMap();
2765
- directoryStates = new WeakMap();
2766
- pathRootStates = new WeakMap();
2767
- sandboxRoot;
2768
- constructor(requester) {
2769
- this.requester = requester;
2770
- }
2771
- getSandbox() {
2772
- if (this.sandboxRoot) {
2773
- return this.sandboxRoot;
2545
+ Decoder.prototype.setBuffer = function (buffer) {
2546
+ this.bytes = ensureUint8Array(buffer);
2547
+ this.view = createDataView(this.bytes);
2548
+ this.pos = 0;
2549
+ };
2550
+ Decoder.prototype.appendBuffer = function (buffer) {
2551
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
2552
+ this.setBuffer(buffer);
2774
2553
  }
2775
- const sandbox = {};
2776
- const state = {
2777
- root: Object.freeze({ kind: 'sandbox' }),
2778
- prefix: '',
2779
- mode: 'readwrite',
2780
- };
2781
- this.definePathRootMethods(sandbox, state);
2782
- this.pathRootStates.set(sandbox, state);
2783
- brandedFileSystemValues.add(sandbox);
2784
- this.sandboxRoot = Object.freeze(sandbox);
2785
- return this.sandboxRoot;
2786
- }
2787
- createFile(descriptor) {
2788
- this.assertFileDescriptor(descriptor);
2789
- const ref = cloneFileRef(descriptor.ref);
2790
- const state = { ref, mode: descriptor.mode };
2791
- const handle = {};
2792
- defineReadonlyValue(handle, 'kind', 'file');
2793
- defineReadonlyValue(handle, 'name', descriptor.name);
2794
- defineReadonlyValue(handle, 'mode', descriptor.mode);
2795
- defineReadonlyValue(handle, 'create', async (options) => {
2796
- assertWritable(state.mode);
2797
- await this.requester.request(FILE_CREATE_METHOD, {
2798
- target: state.ref,
2799
- ...normalizeCreateOptions(options),
2554
+ else {
2555
+ var remainingData = this.bytes.subarray(this.pos);
2556
+ var newData = ensureUint8Array(buffer);
2557
+ // concat remainingData + newData
2558
+ var newBuffer = new Uint8Array(remainingData.length + newData.length);
2559
+ newBuffer.set(remainingData);
2560
+ newBuffer.set(newData, remainingData.length);
2561
+ this.setBuffer(newBuffer);
2562
+ }
2563
+ };
2564
+ Decoder.prototype.hasRemaining = function (size) {
2565
+ return this.view.byteLength - this.pos >= size;
2566
+ };
2567
+ Decoder.prototype.createExtraByteError = function (posToShow) {
2568
+ var _a = this, view = _a.view, pos = _a.pos;
2569
+ return new RangeError("Extra ".concat(view.byteLength - pos, " of ").concat(view.byteLength, " byte(s) found at buffer[").concat(posToShow, "]"));
2570
+ };
2571
+ /**
2572
+ * @throws {@link DecodeError}
2573
+ * @throws {@link RangeError}
2574
+ */
2575
+ Decoder.prototype.decode = function (buffer) {
2576
+ this.reinitializeState();
2577
+ this.setBuffer(buffer);
2578
+ var object = this.doDecodeSync();
2579
+ if (this.hasRemaining(1)) {
2580
+ throw this.createExtraByteError(this.pos);
2581
+ }
2582
+ return object;
2583
+ };
2584
+ Decoder.prototype.decodeMulti = function (buffer) {
2585
+ return __generator(this, function (_a) {
2586
+ switch (_a.label) {
2587
+ case 0:
2588
+ this.reinitializeState();
2589
+ this.setBuffer(buffer);
2590
+ _a.label = 1;
2591
+ case 1:
2592
+ if (!this.hasRemaining(1)) return [3 /*break*/, 3];
2593
+ return [4 /*yield*/, this.doDecodeSync()];
2594
+ case 2:
2595
+ _a.sent();
2596
+ return [3 /*break*/, 1];
2597
+ case 3: return [2 /*return*/];
2598
+ }
2599
+ });
2600
+ };
2601
+ Decoder.prototype.decodeAsync = function (stream) {
2602
+ var stream_1, stream_1_1;
2603
+ var e_1, _a;
2604
+ return __awaiter(this, void 0, void 0, function () {
2605
+ var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
2606
+ return __generator(this, function (_c) {
2607
+ switch (_c.label) {
2608
+ case 0:
2609
+ decoded = false;
2610
+ _c.label = 1;
2611
+ case 1:
2612
+ _c.trys.push([1, 6, 7, 12]);
2613
+ stream_1 = __asyncValues(stream);
2614
+ _c.label = 2;
2615
+ case 2: return [4 /*yield*/, stream_1.next()];
2616
+ case 3:
2617
+ if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];
2618
+ buffer = stream_1_1.value;
2619
+ if (decoded) {
2620
+ throw this.createExtraByteError(this.totalPos);
2621
+ }
2622
+ this.appendBuffer(buffer);
2623
+ try {
2624
+ object = this.doDecodeSync();
2625
+ decoded = true;
2626
+ }
2627
+ catch (e) {
2628
+ if (!(e instanceof DataViewIndexOutOfBoundsError)) {
2629
+ throw e; // rethrow
2630
+ }
2631
+ // fallthrough
2632
+ }
2633
+ this.totalPos += this.pos;
2634
+ _c.label = 4;
2635
+ case 4: return [3 /*break*/, 2];
2636
+ case 5: return [3 /*break*/, 12];
2637
+ case 6:
2638
+ e_1_1 = _c.sent();
2639
+ e_1 = { error: e_1_1 };
2640
+ return [3 /*break*/, 12];
2641
+ case 7:
2642
+ _c.trys.push([7, , 10, 11]);
2643
+ if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];
2644
+ return [4 /*yield*/, _a.call(stream_1)];
2645
+ case 8:
2646
+ _c.sent();
2647
+ _c.label = 9;
2648
+ case 9: return [3 /*break*/, 11];
2649
+ case 10:
2650
+ if (e_1) throw e_1.error;
2651
+ return [7 /*endfinally*/];
2652
+ case 11: return [7 /*endfinally*/];
2653
+ case 12:
2654
+ if (decoded) {
2655
+ if (this.hasRemaining(1)) {
2656
+ throw this.createExtraByteError(this.totalPos);
2657
+ }
2658
+ return [2 /*return*/, object];
2659
+ }
2660
+ _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
2661
+ throw new RangeError("Insufficient data in parsing ".concat(prettyByte(headByte), " at ").concat(totalPos, " (").concat(pos, " in the current buffer)"));
2662
+ }
2663
+ });
2664
+ });
2665
+ };
2666
+ Decoder.prototype.decodeArrayStream = function (stream) {
2667
+ return this.decodeMultiAsync(stream, true);
2668
+ };
2669
+ Decoder.prototype.decodeStream = function (stream) {
2670
+ return this.decodeMultiAsync(stream, false);
2671
+ };
2672
+ Decoder.prototype.decodeMultiAsync = function (stream, isArray) {
2673
+ return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
2674
+ var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
2675
+ var e_3, _a;
2676
+ return __generator(this, function (_b) {
2677
+ switch (_b.label) {
2678
+ case 0:
2679
+ isArrayHeaderRequired = isArray;
2680
+ arrayItemsLeft = -1;
2681
+ _b.label = 1;
2682
+ case 1:
2683
+ _b.trys.push([1, 13, 14, 19]);
2684
+ stream_2 = __asyncValues(stream);
2685
+ _b.label = 2;
2686
+ case 2: return [4 /*yield*/, __await(stream_2.next())];
2687
+ case 3:
2688
+ if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];
2689
+ buffer = stream_2_1.value;
2690
+ if (isArray && arrayItemsLeft === 0) {
2691
+ throw this.createExtraByteError(this.totalPos);
2692
+ }
2693
+ this.appendBuffer(buffer);
2694
+ if (isArrayHeaderRequired) {
2695
+ arrayItemsLeft = this.readArraySize();
2696
+ isArrayHeaderRequired = false;
2697
+ this.complete();
2698
+ }
2699
+ _b.label = 4;
2700
+ case 4:
2701
+ _b.trys.push([4, 9, , 10]);
2702
+ _b.label = 5;
2703
+ case 5:
2704
+ return [4 /*yield*/, __await(this.doDecodeSync())];
2705
+ case 6: return [4 /*yield*/, _b.sent()];
2706
+ case 7:
2707
+ _b.sent();
2708
+ if (--arrayItemsLeft === 0) {
2709
+ return [3 /*break*/, 8];
2710
+ }
2711
+ return [3 /*break*/, 5];
2712
+ case 8: return [3 /*break*/, 10];
2713
+ case 9:
2714
+ e_2 = _b.sent();
2715
+ if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {
2716
+ throw e_2; // rethrow
2717
+ }
2718
+ return [3 /*break*/, 10];
2719
+ case 10:
2720
+ this.totalPos += this.pos;
2721
+ _b.label = 11;
2722
+ case 11: return [3 /*break*/, 2];
2723
+ case 12: return [3 /*break*/, 19];
2724
+ case 13:
2725
+ e_3_1 = _b.sent();
2726
+ e_3 = { error: e_3_1 };
2727
+ return [3 /*break*/, 19];
2728
+ case 14:
2729
+ _b.trys.push([14, , 17, 18]);
2730
+ if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];
2731
+ return [4 /*yield*/, __await(_a.call(stream_2))];
2732
+ case 15:
2733
+ _b.sent();
2734
+ _b.label = 16;
2735
+ case 16: return [3 /*break*/, 18];
2736
+ case 17:
2737
+ if (e_3) throw e_3.error;
2738
+ return [7 /*endfinally*/];
2739
+ case 18: return [7 /*endfinally*/];
2740
+ case 19: return [2 /*return*/];
2741
+ }
2800
2742
  });
2801
- return handle;
2802
- }, false);
2803
- defineReadonlyValue(handle, 'remove', async () => {
2804
- assertWritable(state.mode);
2805
- assertSandboxRef(state.ref);
2806
- await this.requester.request(FILE_REMOVE_METHOD, { target: state.ref });
2807
- }, false);
2808
- defineReadonlyValue(handle, 'exists', async () => {
2809
- const result = await this.requester.request(FILE_EXISTS_METHOD, { target: state.ref });
2810
- if (typeof result !== 'boolean') {
2811
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 exists 结果');
2743
+ });
2744
+ };
2745
+ Decoder.prototype.doDecodeSync = function () {
2746
+ DECODE: while (true) {
2747
+ var headByte = this.readHeadByte();
2748
+ var object = void 0;
2749
+ if (headByte >= 0xe0) {
2750
+ // negative fixint (111x xxxx) 0xe0 - 0xff
2751
+ object = headByte - 0x100;
2812
2752
  }
2813
- return result;
2814
- }, false);
2815
- defineReadonlyValue(handle, 'readText', async () => {
2816
- const result = await this.requester.request(FILE_READ_TEXT_METHOD, { target: state.ref });
2817
- if (typeof result !== 'string') {
2818
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文本内容');
2753
+ else if (headByte < 0xc0) {
2754
+ if (headByte < 0x80) {
2755
+ // positive fixint (0xxx xxxx) 0x00 - 0x7f
2756
+ object = headByte;
2757
+ }
2758
+ else if (headByte < 0x90) {
2759
+ // fixmap (1000 xxxx) 0x80 - 0x8f
2760
+ var size = headByte - 0x80;
2761
+ if (size !== 0) {
2762
+ this.pushMapState(size);
2763
+ this.complete();
2764
+ continue DECODE;
2765
+ }
2766
+ else {
2767
+ object = {};
2768
+ }
2769
+ }
2770
+ else if (headByte < 0xa0) {
2771
+ // fixarray (1001 xxxx) 0x90 - 0x9f
2772
+ var size = headByte - 0x90;
2773
+ if (size !== 0) {
2774
+ this.pushArrayState(size);
2775
+ this.complete();
2776
+ continue DECODE;
2777
+ }
2778
+ else {
2779
+ object = [];
2780
+ }
2781
+ }
2782
+ else {
2783
+ // fixstr (101x xxxx) 0xa0 - 0xbf
2784
+ var byteLength = headByte - 0xa0;
2785
+ object = this.decodeUtf8String(byteLength, 0);
2786
+ }
2787
+ }
2788
+ else if (headByte === 0xc0) {
2789
+ // nil
2790
+ object = null;
2791
+ }
2792
+ else if (headByte === 0xc2) {
2793
+ // false
2794
+ object = false;
2795
+ }
2796
+ else if (headByte === 0xc3) {
2797
+ // true
2798
+ object = true;
2799
+ }
2800
+ else if (headByte === 0xca) {
2801
+ // float 32
2802
+ object = this.readF32();
2803
+ }
2804
+ else if (headByte === 0xcb) {
2805
+ // float 64
2806
+ object = this.readF64();
2807
+ }
2808
+ else if (headByte === 0xcc) {
2809
+ // uint 8
2810
+ object = this.readU8();
2811
+ }
2812
+ else if (headByte === 0xcd) {
2813
+ // uint 16
2814
+ object = this.readU16();
2815
+ }
2816
+ else if (headByte === 0xce) {
2817
+ // uint 32
2818
+ object = this.readU32();
2819
+ }
2820
+ else if (headByte === 0xcf) {
2821
+ // uint 64
2822
+ object = this.readU64();
2823
+ }
2824
+ else if (headByte === 0xd0) {
2825
+ // int 8
2826
+ object = this.readI8();
2827
+ }
2828
+ else if (headByte === 0xd1) {
2829
+ // int 16
2830
+ object = this.readI16();
2831
+ }
2832
+ else if (headByte === 0xd2) {
2833
+ // int 32
2834
+ object = this.readI32();
2835
+ }
2836
+ else if (headByte === 0xd3) {
2837
+ // int 64
2838
+ object = this.readI64();
2839
+ }
2840
+ else if (headByte === 0xd9) {
2841
+ // str 8
2842
+ var byteLength = this.lookU8();
2843
+ object = this.decodeUtf8String(byteLength, 1);
2844
+ }
2845
+ else if (headByte === 0xda) {
2846
+ // str 16
2847
+ var byteLength = this.lookU16();
2848
+ object = this.decodeUtf8String(byteLength, 2);
2849
+ }
2850
+ else if (headByte === 0xdb) {
2851
+ // str 32
2852
+ var byteLength = this.lookU32();
2853
+ object = this.decodeUtf8String(byteLength, 4);
2854
+ }
2855
+ else if (headByte === 0xdc) {
2856
+ // array 16
2857
+ var size = this.readU16();
2858
+ if (size !== 0) {
2859
+ this.pushArrayState(size);
2860
+ this.complete();
2861
+ continue DECODE;
2862
+ }
2863
+ else {
2864
+ object = [];
2865
+ }
2866
+ }
2867
+ else if (headByte === 0xdd) {
2868
+ // array 32
2869
+ var size = this.readU32();
2870
+ if (size !== 0) {
2871
+ this.pushArrayState(size);
2872
+ this.complete();
2873
+ continue DECODE;
2874
+ }
2875
+ else {
2876
+ object = [];
2877
+ }
2878
+ }
2879
+ else if (headByte === 0xde) {
2880
+ // map 16
2881
+ var size = this.readU16();
2882
+ if (size !== 0) {
2883
+ this.pushMapState(size);
2884
+ this.complete();
2885
+ continue DECODE;
2886
+ }
2887
+ else {
2888
+ object = {};
2889
+ }
2890
+ }
2891
+ else if (headByte === 0xdf) {
2892
+ // map 32
2893
+ var size = this.readU32();
2894
+ if (size !== 0) {
2895
+ this.pushMapState(size);
2896
+ this.complete();
2897
+ continue DECODE;
2898
+ }
2899
+ else {
2900
+ object = {};
2901
+ }
2902
+ }
2903
+ else if (headByte === 0xc4) {
2904
+ // bin 8
2905
+ var size = this.lookU8();
2906
+ object = this.decodeBinary(size, 1);
2907
+ }
2908
+ else if (headByte === 0xc5) {
2909
+ // bin 16
2910
+ var size = this.lookU16();
2911
+ object = this.decodeBinary(size, 2);
2912
+ }
2913
+ else if (headByte === 0xc6) {
2914
+ // bin 32
2915
+ var size = this.lookU32();
2916
+ object = this.decodeBinary(size, 4);
2917
+ }
2918
+ else if (headByte === 0xd4) {
2919
+ // fixext 1
2920
+ object = this.decodeExtension(1, 0);
2921
+ }
2922
+ else if (headByte === 0xd5) {
2923
+ // fixext 2
2924
+ object = this.decodeExtension(2, 0);
2925
+ }
2926
+ else if (headByte === 0xd6) {
2927
+ // fixext 4
2928
+ object = this.decodeExtension(4, 0);
2929
+ }
2930
+ else if (headByte === 0xd7) {
2931
+ // fixext 8
2932
+ object = this.decodeExtension(8, 0);
2933
+ }
2934
+ else if (headByte === 0xd8) {
2935
+ // fixext 16
2936
+ object = this.decodeExtension(16, 0);
2937
+ }
2938
+ else if (headByte === 0xc7) {
2939
+ // ext 8
2940
+ var size = this.lookU8();
2941
+ object = this.decodeExtension(size, 1);
2819
2942
  }
2820
- return result;
2821
- }, false);
2822
- defineReadonlyValue(handle, 'writeText', async (content) => {
2823
- assertWritable(state.mode);
2824
- if (typeof content !== 'string') {
2825
- throw invalidParams$1('content 必须是 string');
2943
+ else if (headByte === 0xc8) {
2944
+ // ext 16
2945
+ var size = this.lookU16();
2946
+ object = this.decodeExtension(size, 2);
2826
2947
  }
2827
- await this.requester.request(FILE_WRITE_TEXT_METHOD, { target: state.ref, content });
2828
- }, false);
2829
- defineReadonlyValue(handle, 'readBytes', async () => {
2830
- const result = await this.requester.request(FILE_READ_BYTES_METHOD, { target: state.ref });
2831
- if (!isMiniProgramByteArray(result)) {
2832
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的二进制内容');
2948
+ else if (headByte === 0xc9) {
2949
+ // ext 32
2950
+ var size = this.lookU32();
2951
+ object = this.decodeExtension(size, 4);
2833
2952
  }
2834
- return new Uint8Array(result);
2835
- }, false);
2836
- defineReadonlyValue(handle, 'writeBytes', async (content) => {
2837
- assertWritable(state.mode);
2838
- const snapshot = cloneBytes(content);
2839
- await this.requester.request(FILE_WRITE_BYTES_METHOD, { target: state.ref, content: snapshot });
2840
- }, false);
2841
- defineReadonlyValue(handle, 'stat', async () => {
2842
- const result = await this.requester.request(FILE_STAT_METHOD, { target: state.ref });
2843
- return normalizeStat(result);
2844
- }, false);
2845
- this.fileStates.set(handle, state);
2846
- brandedFileSystemValues.add(handle);
2847
- return Object.freeze(handle);
2848
- }
2849
- createDirectFile(descriptor) {
2850
- this.assertFileDescriptor(descriptor);
2851
- if (!('handleId' in descriptor.ref)) {
2852
- throw createSDKError('FILE_IO_FAILED', 'Host 返回的 File 不是精确文件授权');
2853
- }
2854
- return this.createFile(descriptor);
2855
- }
2856
- createDirectory(descriptor) {
2857
- this.assertDirectoryDescriptor(descriptor);
2858
- const ref = cloneDirectoryRef(descriptor.ref);
2859
- const state = { ref, mode: descriptor.mode };
2860
- const pathRootState = 'handleId' in ref ? { root: ref, prefix: '', mode: descriptor.mode } : { root: ref.root, prefix: ref.relativePath, mode: descriptor.mode };
2861
- const handle = {};
2862
- defineReadonlyValue(handle, 'kind', 'directory');
2863
- defineReadonlyValue(handle, 'name', descriptor.name);
2864
- defineReadonlyValue(handle, 'mode', descriptor.mode);
2865
- this.definePathRootMethods(handle, pathRootState);
2866
- defineReadonlyValue(handle, 'create', async (options) => {
2867
- assertWritable(state.mode);
2868
- await this.requester.request(DIRECTORY_CREATE_METHOD, {
2869
- target: state.ref,
2870
- ...normalizeCreateOptions(options),
2871
- });
2872
- return handle;
2873
- }, false);
2874
- defineReadonlyValue(handle, 'remove', async (options) => {
2875
- assertWritable(state.mode);
2876
- assertSandboxRef(state.ref);
2877
- await this.requester.request(DIRECTORY_REMOVE_METHOD, {
2878
- target: state.ref,
2879
- ...normalizeRemoveOptions(options),
2880
- });
2881
- }, false);
2882
- defineReadonlyValue(handle, 'exists', async () => {
2883
- const result = await this.requester.request(DIRECTORY_EXISTS_METHOD, { target: state.ref });
2884
- if (typeof result !== 'boolean') {
2885
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 exists 结果');
2953
+ else {
2954
+ throw new DecodeError("Unrecognized type byte: ".concat(prettyByte(headByte)));
2886
2955
  }
2887
- return result;
2888
- }, false);
2889
- defineReadonlyValue(handle, 'list', async (options) => {
2890
- const limit = normalizeListOptions(options);
2891
- const result = await this.requester.request(DIRECTORY_LIST_METHOD, {
2892
- target: state.ref,
2893
- ...(limit === undefined ? {} : { limit }),
2894
- });
2895
- if (!Array.isArray(result)) {
2896
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的目录列表');
2956
+ this.complete();
2957
+ var stack = this.stack;
2958
+ while (stack.length > 0) {
2959
+ // arrays and maps
2960
+ var state = stack[stack.length - 1];
2961
+ if (state.type === 0 /* State.ARRAY */) {
2962
+ state.array[state.position] = object;
2963
+ state.position++;
2964
+ if (state.position === state.size) {
2965
+ stack.pop();
2966
+ object = state.array;
2967
+ }
2968
+ else {
2969
+ continue DECODE;
2970
+ }
2971
+ }
2972
+ else if (state.type === 1 /* State.MAP_KEY */) {
2973
+ if (!isValidMapKeyType(object)) {
2974
+ throw new DecodeError("The type of key must be string or number but " + typeof object);
2975
+ }
2976
+ if (object === "__proto__") {
2977
+ throw new DecodeError("The key __proto__ is not allowed");
2978
+ }
2979
+ state.key = object;
2980
+ state.type = 2 /* State.MAP_VALUE */;
2981
+ continue DECODE;
2982
+ }
2983
+ else {
2984
+ // it must be `state.type === State.MAP_VALUE` here
2985
+ state.map[state.key] = object;
2986
+ state.readCount++;
2987
+ if (state.readCount === state.size) {
2988
+ stack.pop();
2989
+ object = state.map;
2990
+ }
2991
+ else {
2992
+ state.key = null;
2993
+ state.type = 1 /* State.MAP_KEY */;
2994
+ continue DECODE;
2995
+ }
2996
+ }
2897
2997
  }
2898
- if (result.some((entry) => entry?.mode !== state.mode)) {
2899
- throw createSDKError('FILE_IO_FAILED', 'Host 返回的目录项未继承父目录 mode');
2998
+ return object;
2999
+ }
3000
+ };
3001
+ Decoder.prototype.readHeadByte = function () {
3002
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
3003
+ this.headByte = this.readU8();
3004
+ // console.log("headByte", prettyByte(this.headByte));
3005
+ }
3006
+ return this.headByte;
3007
+ };
3008
+ Decoder.prototype.complete = function () {
3009
+ this.headByte = HEAD_BYTE_REQUIRED;
3010
+ };
3011
+ Decoder.prototype.readArraySize = function () {
3012
+ var headByte = this.readHeadByte();
3013
+ switch (headByte) {
3014
+ case 0xdc:
3015
+ return this.readU16();
3016
+ case 0xdd:
3017
+ return this.readU32();
3018
+ default: {
3019
+ if (headByte < 0xa0) {
3020
+ return headByte - 0x90;
3021
+ }
3022
+ else {
3023
+ throw new DecodeError("Unrecognized array type byte: ".concat(prettyByte(headByte)));
3024
+ }
2900
3025
  }
2901
- return result.map((entry) => this.createEntity(entry));
2902
- }, false);
2903
- this.directoryStates.set(handle, state);
2904
- this.pathRootStates.set(handle, pathRootState);
2905
- brandedFileSystemValues.add(handle);
2906
- return Object.freeze(handle);
2907
- }
2908
- createDirectDirectory(descriptor) {
2909
- this.assertDirectoryDescriptor(descriptor);
2910
- if (!('handleId' in descriptor.ref)) {
2911
- throw createSDKError('FILE_IO_FAILED', 'Host 返回的 Directory 不是精确目录授权');
2912
3026
  }
2913
- return this.createDirectory(descriptor);
2914
- }
2915
- createEntity(descriptor) {
2916
- if (descriptor?.kind === 'file') {
2917
- return this.createFile(descriptor);
3027
+ };
3028
+ Decoder.prototype.pushMapState = function (size) {
3029
+ if (size > this.maxMapLength) {
3030
+ throw new DecodeError("Max length exceeded: map length (".concat(size, ") > maxMapLengthLength (").concat(this.maxMapLength, ")"));
2918
3031
  }
2919
- if (descriptor?.kind === 'directory') {
2920
- return this.createDirectory(descriptor);
3032
+ this.stack.push({
3033
+ type: 1 /* State.MAP_KEY */,
3034
+ size: size,
3035
+ key: null,
3036
+ readCount: 0,
3037
+ map: {},
3038
+ });
3039
+ };
3040
+ Decoder.prototype.pushArrayState = function (size) {
3041
+ if (size > this.maxArrayLength) {
3042
+ throw new DecodeError("Max length exceeded: array length (".concat(size, ") > maxArrayLength (").concat(this.maxArrayLength, ")"));
2921
3043
  }
2922
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的文件实体');
2923
- }
2924
- requireFile(handle) {
2925
- const state = handle && typeof handle === 'object' ? this.fileStates.get(handle) : undefined;
2926
- if (!state) {
2927
- throw invalidParams$1('to 必须是当前 SDK session 创建的 FileHandle');
3044
+ this.stack.push({
3045
+ type: 0 /* State.ARRAY */,
3046
+ size: size,
3047
+ array: new Array(size),
3048
+ position: 0,
3049
+ });
3050
+ };
3051
+ Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {
3052
+ var _a;
3053
+ if (byteLength > this.maxStrLength) {
3054
+ throw new DecodeError("Max length exceeded: UTF-8 byte length (".concat(byteLength, ") > maxStrLength (").concat(this.maxStrLength, ")"));
2928
3055
  }
2929
- return state;
2930
- }
2931
- requireDirectory(handle) {
2932
- const state = handle && typeof handle === 'object' ? this.directoryStates.get(handle) : undefined;
2933
- if (!state) {
2934
- throw invalidParams$1('to 必须是当前 SDK session 创建的 DirectoryHandle');
3056
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
3057
+ throw MORE_DATA;
3058
+ }
3059
+ var offset = this.pos + headerOffset;
3060
+ var object;
3061
+ if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {
3062
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
3063
+ }
3064
+ else if (byteLength > TEXT_DECODER_THRESHOLD) {
3065
+ object = utf8DecodeTD(this.bytes, offset, byteLength);
3066
+ }
3067
+ else {
3068
+ object = utf8DecodeJs(this.bytes, offset, byteLength);
3069
+ }
3070
+ this.pos += headerOffset + byteLength;
3071
+ return object;
3072
+ };
3073
+ Decoder.prototype.stateIsMapKey = function () {
3074
+ if (this.stack.length > 0) {
3075
+ var state = this.stack[this.stack.length - 1];
3076
+ return state.type === 1 /* State.MAP_KEY */;
3077
+ }
3078
+ return false;
3079
+ };
3080
+ Decoder.prototype.decodeBinary = function (byteLength, headOffset) {
3081
+ if (byteLength > this.maxBinLength) {
3082
+ throw new DecodeError("Max length exceeded: bin length (".concat(byteLength, ") > maxBinLength (").concat(this.maxBinLength, ")"));
3083
+ }
3084
+ if (!this.hasRemaining(byteLength + headOffset)) {
3085
+ throw MORE_DATA;
3086
+ }
3087
+ var offset = this.pos + headOffset;
3088
+ var object = this.bytes.subarray(offset, offset + byteLength);
3089
+ this.pos += headOffset + byteLength;
3090
+ return object;
3091
+ };
3092
+ Decoder.prototype.decodeExtension = function (size, headOffset) {
3093
+ if (size > this.maxExtLength) {
3094
+ throw new DecodeError("Max length exceeded: ext length (".concat(size, ") > maxExtLength (").concat(this.maxExtLength, ")"));
3095
+ }
3096
+ var extType = this.view.getInt8(this.pos + headOffset);
3097
+ var data = this.decodeBinary(size, headOffset + 1 /* extType */);
3098
+ return this.extensionCodec.decode(data, extType, this.context);
3099
+ };
3100
+ Decoder.prototype.lookU8 = function () {
3101
+ return this.view.getUint8(this.pos);
3102
+ };
3103
+ Decoder.prototype.lookU16 = function () {
3104
+ return this.view.getUint16(this.pos);
3105
+ };
3106
+ Decoder.prototype.lookU32 = function () {
3107
+ return this.view.getUint32(this.pos);
3108
+ };
3109
+ Decoder.prototype.readU8 = function () {
3110
+ var value = this.view.getUint8(this.pos);
3111
+ this.pos++;
3112
+ return value;
3113
+ };
3114
+ Decoder.prototype.readI8 = function () {
3115
+ var value = this.view.getInt8(this.pos);
3116
+ this.pos++;
3117
+ return value;
3118
+ };
3119
+ Decoder.prototype.readU16 = function () {
3120
+ var value = this.view.getUint16(this.pos);
3121
+ this.pos += 2;
3122
+ return value;
3123
+ };
3124
+ Decoder.prototype.readI16 = function () {
3125
+ var value = this.view.getInt16(this.pos);
3126
+ this.pos += 2;
3127
+ return value;
3128
+ };
3129
+ Decoder.prototype.readU32 = function () {
3130
+ var value = this.view.getUint32(this.pos);
3131
+ this.pos += 4;
3132
+ return value;
3133
+ };
3134
+ Decoder.prototype.readI32 = function () {
3135
+ var value = this.view.getInt32(this.pos);
3136
+ this.pos += 4;
3137
+ return value;
3138
+ };
3139
+ Decoder.prototype.readU64 = function () {
3140
+ var value = getUint64(this.view, this.pos);
3141
+ this.pos += 8;
3142
+ return value;
3143
+ };
3144
+ Decoder.prototype.readI64 = function () {
3145
+ var value = getInt64(this.view, this.pos);
3146
+ this.pos += 8;
3147
+ return value;
3148
+ };
3149
+ Decoder.prototype.readF32 = function () {
3150
+ var value = this.view.getFloat32(this.pos);
3151
+ this.pos += 4;
3152
+ return value;
3153
+ };
3154
+ Decoder.prototype.readF64 = function () {
3155
+ var value = this.view.getFloat64(this.pos);
3156
+ this.pos += 8;
3157
+ return value;
3158
+ };
3159
+ return Decoder;
3160
+ }());
3161
+
3162
+ var defaultDecodeOptions = {};
3163
+ /**
3164
+ * It decodes a single MessagePack object in a buffer.
3165
+ *
3166
+ * This is a synchronous decoding function.
3167
+ * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
3168
+ *
3169
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
3170
+ * @throws {@link DecodeError} if the buffer contains invalid data.
3171
+ */
3172
+ function decode(buffer, options) {
3173
+ if (options === void 0) { options = defaultDecodeOptions; }
3174
+ var decoder = new Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
3175
+ return decoder.decode(buffer);
3176
+ }
3177
+
3178
+ /** 读取小程序启动时携带的分享数据。 */
3179
+ function readMiniProgramShareExtra(launchHref) {
3180
+ if (!launchHref)
3181
+ return undefined;
3182
+ try {
3183
+ const value = new URL(launchHref).searchParams.get('extra');
3184
+ if (!value || value.length > 256 || value.length % 4 === 1 || !/^[A-Za-z0-9_-]+$/.test(value)) {
3185
+ return undefined;
2935
3186
  }
2936
- return state;
3187
+ const bytes = decodeBase64Url(value);
3188
+ if (bytes.byteLength > 128)
3189
+ return undefined;
3190
+ const decoded = decode(bytes);
3191
+ assertExtraValue(decoded);
3192
+ return decoded;
2937
3193
  }
2938
- definePathRootMethods(target, state) {
2939
- defineReadonlyValue(target, 'file', (relativePath) => {
2940
- const normalized = normalizeRelativePath(relativePath);
2941
- const fullPath = joinRelativePath(state.prefix, normalized);
2942
- return this.createFile({
2943
- kind: 'file',
2944
- name: basename(normalized),
2945
- mode: state.mode,
2946
- ref: {
2947
- kind: 'file',
2948
- root: state.root,
2949
- relativePath: fullPath,
2950
- },
2951
- });
2952
- }, false);
2953
- defineReadonlyValue(target, 'directory', (relativePath) => {
2954
- const normalized = normalizeRelativePath(relativePath);
2955
- const fullPath = joinRelativePath(state.prefix, normalized);
2956
- return this.createDirectory({
2957
- kind: 'directory',
2958
- name: basename(normalized),
2959
- mode: state.mode,
2960
- ref: {
2961
- kind: 'directory',
2962
- root: state.root,
2963
- relativePath: fullPath,
2964
- },
2965
- });
2966
- }, false);
3194
+ catch {
3195
+ return undefined;
2967
3196
  }
2968
- assertFileDescriptor(descriptor) {
2969
- if (!descriptor || descriptor.kind !== 'file') {
2970
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 File descriptor');
2971
- }
2972
- assertName(descriptor.name);
2973
- assertMode(descriptor.mode);
2974
- assertFileRef(descriptor.ref);
3197
+ }
3198
+ function assertExtraValue(value, depth = 0, seen = new WeakSet()) {
3199
+ if (depth > 8)
3200
+ throw new Error('extra nesting depth exceeded');
3201
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
3202
+ return;
3203
+ if (typeof value === 'number') {
3204
+ if (Number.isFinite(value))
3205
+ return;
3206
+ throw new Error('extra number must be finite');
2975
3207
  }
2976
- assertDirectoryDescriptor(descriptor) {
2977
- if (!descriptor || descriptor.kind !== 'directory') {
2978
- throw createSDKError('FILE_IO_FAILED', 'Host 返回了无效的 Directory descriptor');
2979
- }
2980
- assertName(descriptor.name);
2981
- assertMode(descriptor.mode);
2982
- assertDirectoryRef(descriptor.ref);
3208
+ if (typeof value !== 'object')
3209
+ throw new Error('extra value must be JSON-compatible');
3210
+ if (seen.has(value))
3211
+ throw new Error('extra value must not contain cycles');
3212
+ seen.add(value);
3213
+ if (Array.isArray(value)) {
3214
+ if (value.length > 64)
3215
+ throw new Error('extra array is too large');
3216
+ for (const item of value)
3217
+ assertExtraValue(item, depth + 1, seen);
3218
+ seen.delete(value);
3219
+ return;
2983
3220
  }
3221
+ const prototype = Object.getPrototypeOf(value);
3222
+ if (prototype !== Object.prototype && prototype !== null)
3223
+ throw new Error('extra object must be a plain object');
3224
+ const values = Object.values(value);
3225
+ if (values.length > 64)
3226
+ throw new Error('extra object has too many fields');
3227
+ for (const item of values)
3228
+ assertExtraValue(item, depth + 1, seen);
3229
+ seen.delete(value);
2984
3230
  }
2985
- function getFileHandleRegistry(requester) {
2986
- let registry = registries.get(requester);
2987
- if (!registry) {
2988
- registry = new MiniProgramFileHandleRegistry(requester);
2989
- registries.set(requester, registry);
2990
- }
2991
- return registry;
3231
+ function decodeBase64Url(value) {
3232
+ const normalized = value.replaceAll('-', '+').replaceAll('_', '/');
3233
+ const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), '=');
3234
+ return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
2992
3235
  }
2993
- function isMiniProgramFileSystemValue(value) {
2994
- return !!value && typeof value === 'object' && brandedFileSystemValues.has(value);
3236
+
3237
+ /**
3238
+ * 截图并唤起分享。
3239
+ *
3240
+ * @param requester - 底层 bridge 请求能力。
3241
+ * @param options - 截图区域、延迟与保存相册等配置。
3242
+ * @returns 由宿主客户端协议决定的结果。
3243
+ * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
3244
+ */
3245
+ function screenshot(requester, options) {
3246
+ return requester.request(SHARE_SCREENSHOT_METHOD, options);
3247
+ }
3248
+
3249
+ /**
3250
+ * 展示以当前小程序通用分享页为落地页的基础分享面板。
3251
+ *
3252
+ * @param requester - 底层 bridge 请求能力。
3253
+ * @param options - 基础分享参数。
3254
+ * @returns 由宿主客户端协议决定的结果。
3255
+ * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
3256
+ */
3257
+ function showShareMenu(requester, options) {
3258
+ return requester.request(SHARE_SHOW_SHARE_MENU_METHOD, options);
3259
+ }
3260
+
3261
+ /**
3262
+ * 创建分享模块。
3263
+ *
3264
+ * @param requester - 底层 bridge 请求能力。
3265
+ * @returns 面向业务层的分享模块对象。
3266
+ */
3267
+ function createShareModule(requester, launchHref) {
3268
+ return {
3269
+ copyLink: (options) => copyLink(requester, options),
3270
+ getExtra: () => readMiniProgramShareExtra(launchHref),
3271
+ showShareMenu: (options) => showShareMenu(requester, options),
3272
+ screenshot: (options) => screenshot(requester, options),
3273
+ };
3274
+ }
3275
+
3276
+ /**
3277
+ * 获取小程序隔离 storage。
3278
+ *
3279
+ * @param requester - 底层 bridge 请求能力。
3280
+ * @param options - 读取的 storage key。
3281
+ * @returns 对应 key 的标准化读取结果。
3282
+ * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
3283
+ */
3284
+ function getStorage(requester, options) {
3285
+ return requester.request(STORAGE_GET_STORAGE_METHOD, options);
3286
+ }
3287
+ /**
3288
+ * 写入小程序隔离 storage。
3289
+ *
3290
+ * @param requester - 底层 bridge 请求能力。
3291
+ * @param options - 要写入的 storage key 与数据。
3292
+ * @returns 当写入完成后 resolve。
3293
+ * @throws {@link HbMiniProgramSDKError} 当 bridge、父容器或宿主能力调用失败时抛出。
3294
+ */
3295
+ function setStorage(requester, options) {
3296
+ return requester.request(STORAGE_SET_STORAGE_METHOD, options);
3297
+ }
3298
+ /**
3299
+ * 创建 storage 模块。
3300
+ *
3301
+ * @param requester - 底层 bridge 请求能力。
3302
+ * @returns 面向业务层的 storage 模块对象。
3303
+ */
3304
+ function createStorageModule(requester) {
3305
+ return {
3306
+ getStorage: (options) => getStorage(requester, options),
3307
+ setStorage: (options) => setStorage(requester, options),
3308
+ };
2995
3309
  }
2996
3310
 
2997
3311
  const LOG_PREFIX = '[hb-sdk][network.request]';
@@ -3758,6 +4072,8 @@ class MiniProgramSDK {
3758
4072
  navigation;
3759
4073
  /** 云端数据相关开放能力。 */
3760
4074
  cloud;
4075
+ /** 受管桌面程序能力。 */
4076
+ companion;
3761
4077
  /** 当前实例的环境信息。 */
3762
4078
  environment;
3763
4079
  constructor(options) {
@@ -3774,6 +4090,7 @@ class MiniProgramSDK {
3774
4090
  this.device = createDeviceModule(this.client);
3775
4091
  this.navigation = createNavigationModule(this.client);
3776
4092
  this.cloud = createCloudModule(this.client);
4093
+ this.companion = createCompanionModule(this.client);
3777
4094
  this.environment = createEnvironmentModule(this.client);
3778
4095
  }
3779
4096
  /** 获取当前握手状态。 */
@@ -3913,6 +4230,9 @@ function installMiniDevConsoleForwarding(consoleRef = console) {
3913
4230
  }
3914
4231
 
3915
4232
  let defaultSDK = createMiniProgramSDK();
4233
+ if (typeof false !== 'undefined' && false && typeof window !== 'undefined') {
4234
+ window.__hbSdkSandboxList = async (path) => (await getDefaultSDK().files.sandbox.directory(path).list({ limit: 200 })).map(entry => ({ name: entry.name, kind: entry.kind }));
4235
+ }
3916
4236
  // 开发期调试台 console 捕获:双条件门控(vite serve 注入 define + 调试 iframe 标记),
3917
4237
  // 生产构建被死代码消除,正式环境无副作用。失败静默,绝不影响 SDK 初始化。
3918
4238
  try {
@@ -4073,6 +4393,15 @@ const cloud = {
4073
4393
  getInfo: (options) => getDefaultSDK().cloud.leaderboard.getInfo(options),
4074
4394
  },
4075
4395
  };
4396
+ /** 默认 SDK 实例的受管桌面程序模块。 */
4397
+ const companion = {
4398
+ getInfo: (alias) => getDefaultSDK().companion.getInfo(alias),
4399
+ getPreparationStatus: (alias) => getDefaultSDK().companion.getPreparationStatus(alias),
4400
+ prepare: (alias, options) => getDefaultSDK().companion.prepare(alias, options),
4401
+ cancelPreparation: (alias) => getDefaultSDK().companion.cancelPreparation(alias),
4402
+ launch: (alias) => getDefaultSDK().companion.launch(alias),
4403
+ getActiveSession: (alias) => getDefaultSDK().companion.getActiveSession(alias),
4404
+ };
4076
4405
  /** 默认 SDK 实例的 environment 模块。 */
4077
4406
  const environment = {
4078
4407
  getInfo: () => getDefaultSDK().environment.getInfo(),
@@ -4096,6 +4425,7 @@ const hbSDK = {
4096
4425
  environment,
4097
4426
  navigation,
4098
4427
  cloud,
4428
+ companion,
4099
4429
  };
4100
4430
 
4101
- export { HbMiniProgramNetworkError, HbMiniProgramSDKError, USER_INFO_AUTHORIZATION_SCOPES, auth, cloud, hbSDK as default, device, environment, files, getHandshakeState, navigation, network, off, on, onHandshakeStateChange, share, storage, ui, user, viewport };
4431
+ export { HbMiniProgramNetworkError, HbMiniProgramSDKError, USER_INFO_AUTHORIZATION_SCOPES, auth, cloud, companion, hbSDK as default, device, environment, files, getHandshakeState, navigation, network, off, on, onHandshakeStateChange, share, storage, ui, user, viewport };