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