@heybox/hb-sdk 0.8.0 → 0.8.1-alpha.10

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