@heybox/hb-sdk 0.7.4 → 0.8.0-alpha

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 (54) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +14 -14
  3. package/dist/cli-chunks/{build-CVPqGQY3.cjs → build-DJWFSM1B.cjs} +6 -5
  4. package/dist/cli-chunks/{context-C1nTGr-R.cjs → context-DV2UK1Nz.cjs} +2 -2
  5. package/dist/cli-chunks/{create-C5qrLLvv.cjs → create-2HfoB48V.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-U5BlN4ei.cjs → dev-Dgt2zS9k.cjs} +8 -8
  7. package/dist/cli-chunks/{doctor-DxqHMTbm.cjs → doctor-C95gIao_.cjs} +1 -1
  8. package/dist/cli-chunks/{index-BfR6OZeU.cjs → index-BjoSXl8C.cjs} +2 -2
  9. package/dist/cli-chunks/{index-DLrcC_ij.cjs → index-D62ANeBv.cjs} +14 -14
  10. package/dist/cli-chunks/{index.esm-DbbyeU1z.cjs → index.esm-CigcxJ2B.cjs} +6 -6
  11. package/dist/cli-chunks/{login-DQkArK14.cjs → login-Cumknwdx.cjs} +2 -2
  12. package/dist/cli-chunks/{project-vite-c13CKUUl.cjs → project-vite-CcE-HMmd.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-816SyJyA.cjs → remote-DDdP3xcE.cjs} +10 -8
  14. package/dist/cli-chunks/{runtime-gate-CtV7rWyX.cjs → runtime-gate-DFjw66kF.cjs} +20 -1
  15. package/dist/cli-chunks/{runtime-permission-env-D-8_jPG3.cjs → runtime-permission-env-CjsCe5bp.cjs} +13 -13
  16. package/dist/cli-chunks/{session-ySUU0fVq.cjs → session-BDi_AZSv.cjs} +1 -1
  17. package/dist/cli.cjs +1 -1
  18. package/dist/devtools/browser-dev-host/main.js +654 -472
  19. package/dist/index.cjs.js +714 -639
  20. package/dist/index.esm.js +714 -639
  21. package/dist/miniapp-publish.cjs.js +13 -13
  22. package/dist/miniapp-publish.esm.js +13 -13
  23. package/dist/templates/vue3-vite-ts/README.md.ejs +2 -0
  24. package/dist/templates/vue3-vite-ts/vite.config.ts +1 -1
  25. package/dist/vite.cjs.js +31 -4
  26. package/dist/vite.esm.js +31 -5
  27. package/package.json +11 -8
  28. package/skill/references/api-protocol.md +14 -2
  29. package/skill/references/api-root.md +42 -21
  30. package/skill/references/examples.md +1 -1
  31. package/skill/references/safety-boundaries.md +1 -1
  32. package/skill/scripts/sync-references.mjs +3 -1
  33. package/skill/skill.json +4 -4
  34. package/types/core/errors.d.ts +5 -5
  35. package/types/core/sdk.d.ts +5 -5
  36. package/types/core/singleton.d.ts +56 -6
  37. package/types/miniapp-manifest/schema.d.ts +5 -0
  38. package/types/miniapp-publish/index.d.ts +8 -8
  39. package/types/modules/auth/index.d.ts +15 -1
  40. package/types/modules/cloud/index.d.ts +75 -5
  41. package/types/modules/device/index.d.ts +31 -3
  42. package/types/modules/navigation/index.d.ts +46 -4
  43. package/types/modules/network/index.d.ts +22 -11
  44. package/types/modules/share/copy-link.d.ts +3 -3
  45. package/types/modules/share/index.d.ts +61 -5
  46. package/types/modules/share/screenshot.d.ts +3 -3
  47. package/types/modules/share/show-share-menu.d.ts +3 -3
  48. package/types/modules/storage/index.d.ts +38 -10
  49. package/types/modules/ui/index.d.ts +46 -4
  50. package/types/modules/user/get-info.d.ts +1 -1
  51. package/types/modules/user/index.d.ts +46 -4
  52. package/types/modules/user/steam-game-list.d.ts +2 -2
  53. package/types/modules/viewport/index.d.ts +36 -8
  54. package/types/vite/index.d.ts +15 -7
@@ -251,6 +251,10 @@ class MiniProgramBridgeServer {
251
251
  this.dispatcher = options.dispatcher;
252
252
  this.targetOrigin = options.targetOrigin || '*';
253
253
  }
254
+ /** 返回当前已完成握手的协议版本。 */
255
+ get protocolVersion() {
256
+ return this.handshaken ? this.bridgeVersion : undefined;
257
+ }
254
258
  /** 开始监听 iframe 内 SDK 消息。 */
255
259
  start() {
256
260
  if (this.started) {
@@ -342,9 +346,10 @@ class MiniProgramBridgeServer {
342
346
  isTrustedMiniProgramMessage(event) {
343
347
  return (event.source === this.iframe.contentWindow &&
344
348
  isMiniProgramBridgeMessage(event.data) &&
349
+ (!this.handshaken || event.data.version === this.bridgeVersion) &&
345
350
  // 历史 v1 小程序可能在启动后跳转到不同的合法文档 origin;source 与 nonce
346
351
  // 仍然绑定到当前 iframe 实例,v2 继续执行严格 origin 校验。
347
- (event.data.version === 1 || this.targetOrigin === '*' || event.origin === this.targetOrigin) &&
352
+ ((this.handshaken ? this.bridgeVersion : event.data.version) === 1 || this.targetOrigin === '*' || event.origin === this.targetOrigin) &&
348
353
  event.data.nonce === this.nonce);
349
354
  }
350
355
  handleHandshake(payload, version, origin) {
@@ -747,20 +752,6 @@ function parseLoginResponse(response) {
747
752
  }
748
753
  return { ...envelope, result: mapped };
749
754
  }
750
- function parseLocalIdentityBeginResponse(response) {
751
- const envelope = parseAPIResponse(response, '小程序本地身份接口响应异常');
752
- const result = envelope.result;
753
- const mapped = {};
754
- if (result.local_identity && typeof result.local_identity === 'object') {
755
- mapped.localIdentity = {
756
- appUserId: result.local_identity.app_user_id,
757
- };
758
- }
759
- if (result.consent_challenge && typeof result.consent_challenge === 'object') {
760
- mapped.consentChallenge = mapChallenge(result.consent_challenge);
761
- }
762
- return { ...envelope, result: mapped };
763
- }
764
755
 
765
756
  const userMiniprogramAuthorizationCancelEndpoint = {
766
757
  auth: 'none',
@@ -786,29 +777,17 @@ const userMiniprogramAuthorizationRevokeEndpoint = {
786
777
  parse: (response) => parseAPIResponse(response, '小程序授权撤销接口响应异常'),
787
778
  };
788
779
 
789
- const userMiniprogramLocalIdentityBeginEndpoint = {
780
+ const userMiniprogramLocalIdentityEndpoint = {
790
781
  auth: 'none',
791
782
  bodyEncoding: 'form',
792
783
  channel: 'api',
793
784
  failurePresentation: 'none',
794
- id: 'heybox.user_miniprogram.runtime.auth.local_identity.begin.post',
785
+ id: 'heybox.user_miniprogram.runtime.local_identity.post',
795
786
  method: 'POST',
796
- path: '/user_miniprogram/runtime/auth/local_identity/begin',
787
+ path: '/user_miniprogram/runtime/local_identity',
797
788
  body: (input) => runtimeContextBody(input.runtimeContext),
798
- parse: (response) => parseLocalIdentityBeginResponse(response),
799
- };
800
-
801
- const userMiniprogramLocalIdentityConfirmEndpoint = {
802
- auth: 'none',
803
- bodyEncoding: 'form',
804
- channel: 'api',
805
- failurePresentation: 'none',
806
- id: 'heybox.user_miniprogram.runtime.auth.local_identity.confirm.post',
807
- method: 'POST',
808
- path: '/user_miniprogram/runtime/auth/local_identity/confirm',
809
- body: (input) => ({ ...runtimeContextBody(input.runtimeContext), challenge: input.challenge }),
810
789
  parse(response) {
811
- const envelope = parseAPIResponse(response, '小程序本地身份确认接口响应异常');
790
+ const envelope = parseAPIResponse(response, '小程序隔离身份接口响应异常');
812
791
  return { ...envelope, result: { appUserId: envelope.result.app_user_id } };
813
792
  },
814
793
  };
@@ -1323,35 +1302,11 @@ function createAuthorizationCoordinator(options) {
1323
1302
  }
1324
1303
  async function requestLocalIdentity(userId, miniProgramId) {
1325
1304
  const expectedGeneration = generation;
1326
- const beginEnvelope = await request(userMiniprogramLocalIdentityBeginEndpoint, {
1305
+ const envelope = await request(userMiniprogramLocalIdentityEndpoint, {
1327
1306
  runtimeContext: { miniProgramId },
1328
1307
  });
1329
1308
  await assertAuthorizationContext(userId, expectedGeneration);
1330
- const begin = readSuccessfulResult$3(beginEnvelope, '用户本地身份');
1331
- const hasIdentity = hasOwn(begin, 'localIdentity');
1332
- const hasChallenge = hasOwn(begin, 'consentChallenge');
1333
- if (hasIdentity === hasChallenge) {
1334
- throw createCapabilityBridgeError('INVALID_RESPONSE', '用户本地身份 begin 必须返回 exact oneof');
1335
- }
1336
- let localIdentity;
1337
- if (hasIdentity) {
1338
- localIdentity = validateLocalIdentity(begin.localIdentity);
1339
- }
1340
- else {
1341
- const identityChallenge = validateConsentChallenge(begin.consentChallenge);
1342
- if (identityChallenge.requestedScopes.length !== 1 ||
1343
- identityChallenge.requestedScopes[0] !== 'identity' ||
1344
- identityChallenge.displayedScopes.length !== 1 ||
1345
- identityChallenge.displayedScopes[0] !== 'identity') {
1346
- throw createCapabilityBridgeError('INVALID_RESPONSE', '用户本地身份 challenge 必须仅包含 identity scope');
1347
- }
1348
- const confirmEnvelope = await request(userMiniprogramLocalIdentityConfirmEndpoint, {
1349
- runtimeContext: { miniProgramId },
1350
- challenge: identityChallenge.challenge,
1351
- });
1352
- await assertAuthorizationContext(userId, expectedGeneration);
1353
- localIdentity = validateLocalIdentity(readSuccessfulResult$3(confirmEnvelope, '用户本地身份确认'));
1354
- }
1309
+ const localIdentity = validateLocalIdentity(readSuccessfulResult$3(envelope, '用户本地身份'));
1355
1310
  for (const scope of USER_INFO_AUTHORIZATION_SCOPES)
1356
1311
  grantedScopes.add(scope);
1357
1312
  emit('user_info_authorization_change', authorizationFromScopes(grantedScopes));
@@ -2884,12 +2839,38 @@ function bridgeError$2(code, message) {
2884
2839
  return { code, message };
2885
2840
  }
2886
2841
 
2842
+ // Integer Utility
2843
+ var UINT32_MAX = 4294967295;
2844
+ // DataView extension to handle int64 / uint64,
2845
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
2846
+ function setUint64(view, offset, value) {
2847
+ var high = value / 4294967296;
2848
+ var low = value; // high bits are truncated by DataView
2849
+ view.setUint32(offset, high);
2850
+ view.setUint32(offset + 4, low);
2851
+ }
2852
+ function setInt64(view, offset, value) {
2853
+ var high = Math.floor(value / 4294967296);
2854
+ var low = value; // high bits are truncated by DataView
2855
+ view.setUint32(offset, high);
2856
+ view.setUint32(offset + 4, low);
2857
+ }
2858
+ function getInt64(view, offset) {
2859
+ var high = view.getInt32(offset);
2860
+ var low = view.getUint32(offset + 4);
2861
+ return high * 4294967296 + low;
2862
+ }
2863
+
2864
+ var _a, _b, _c;
2865
+ 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") &&
2866
+ typeof TextEncoder !== "undefined" &&
2867
+ typeof TextDecoder !== "undefined";
2887
2868
  function utf8Count(str) {
2888
- const strLength = str.length;
2889
- let byteLength = 0;
2890
- let pos = 0;
2869
+ var strLength = str.length;
2870
+ var byteLength = 0;
2871
+ var pos = 0;
2891
2872
  while (pos < strLength) {
2892
- let value = str.charCodeAt(pos++);
2873
+ var value = str.charCodeAt(pos++);
2893
2874
  if ((value & 0xffffff80) === 0) {
2894
2875
  // 1-byte
2895
2876
  byteLength++;
@@ -2904,7 +2885,7 @@ function utf8Count(str) {
2904
2885
  if (value >= 0xd800 && value <= 0xdbff) {
2905
2886
  // high surrogate
2906
2887
  if (pos < strLength) {
2907
- const extra = str.charCodeAt(pos);
2888
+ var extra = str.charCodeAt(pos);
2908
2889
  if ((extra & 0xfc00) === 0xdc00) {
2909
2890
  ++pos;
2910
2891
  value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
@@ -2924,11 +2905,11 @@ function utf8Count(str) {
2924
2905
  return byteLength;
2925
2906
  }
2926
2907
  function utf8EncodeJs(str, output, outputOffset) {
2927
- const strLength = str.length;
2928
- let offset = outputOffset;
2929
- let pos = 0;
2908
+ var strLength = str.length;
2909
+ var offset = outputOffset;
2910
+ var pos = 0;
2930
2911
  while (pos < strLength) {
2931
- let value = str.charCodeAt(pos++);
2912
+ var value = str.charCodeAt(pos++);
2932
2913
  if ((value & 0xffffff80) === 0) {
2933
2914
  // 1-byte
2934
2915
  output[offset++] = value;
@@ -2943,7 +2924,7 @@ function utf8EncodeJs(str, output, outputOffset) {
2943
2924
  if (value >= 0xd800 && value <= 0xdbff) {
2944
2925
  // high surrogate
2945
2926
  if (pos < strLength) {
2946
- const extra = str.charCodeAt(pos);
2927
+ var extra = str.charCodeAt(pos);
2947
2928
  if ((extra & 0xfc00) === 0xdc00) {
2948
2929
  ++pos;
2949
2930
  value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
@@ -2965,56 +2946,48 @@ function utf8EncodeJs(str, output, outputOffset) {
2965
2946
  output[offset++] = (value & 0x3f) | 0x80;
2966
2947
  }
2967
2948
  }
2968
- // TextEncoder and TextDecoder are standardized in whatwg encoding:
2969
- // https://encoding.spec.whatwg.org/
2970
- // and available in all the modern browsers:
2971
- // https://caniuse.com/textencoder
2972
- // They are available in Node.js since v12 LTS as well:
2973
- // https://nodejs.org/api/globals.html#textencoder
2974
- const sharedTextEncoder = new TextEncoder();
2975
- // This threshold should be determined by benchmarking, which might vary in engines and input data.
2976
- // Run `npx ts-node benchmark/encode-string.ts` for details.
2977
- const TEXT_ENCODER_THRESHOLD = 50;
2978
- function utf8EncodeTE(str, output, outputOffset) {
2979
- sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
2949
+ var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
2950
+ var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
2951
+ ? UINT32_MAX
2952
+ : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
2953
+ ? 200
2954
+ : 0;
2955
+ function utf8EncodeTEencode(str, output, outputOffset) {
2956
+ output.set(sharedTextEncoder.encode(str), outputOffset);
2980
2957
  }
2981
- function utf8Encode(str, output, outputOffset) {
2982
- if (str.length > TEXT_ENCODER_THRESHOLD) {
2983
- utf8EncodeTE(str, output, outputOffset);
2984
- }
2985
- else {
2986
- utf8EncodeJs(str, output, outputOffset);
2987
- }
2958
+ function utf8EncodeTEencodeInto(str, output, outputOffset) {
2959
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
2988
2960
  }
2989
- const CHUNK_SIZE = 4096;
2961
+ var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
2962
+ var CHUNK_SIZE = 4096;
2990
2963
  function utf8DecodeJs(bytes, inputOffset, byteLength) {
2991
- let offset = inputOffset;
2992
- const end = offset + byteLength;
2993
- const units = [];
2994
- let result = "";
2964
+ var offset = inputOffset;
2965
+ var end = offset + byteLength;
2966
+ var units = [];
2967
+ var result = "";
2995
2968
  while (offset < end) {
2996
- const byte1 = bytes[offset++];
2969
+ var byte1 = bytes[offset++];
2997
2970
  if ((byte1 & 0x80) === 0) {
2998
2971
  // 1 byte
2999
2972
  units.push(byte1);
3000
2973
  }
3001
2974
  else if ((byte1 & 0xe0) === 0xc0) {
3002
2975
  // 2 bytes
3003
- const byte2 = bytes[offset++] & 0x3f;
2976
+ var byte2 = bytes[offset++] & 0x3f;
3004
2977
  units.push(((byte1 & 0x1f) << 6) | byte2);
3005
2978
  }
3006
2979
  else if ((byte1 & 0xf0) === 0xe0) {
3007
2980
  // 3 bytes
3008
- const byte2 = bytes[offset++] & 0x3f;
3009
- const byte3 = bytes[offset++] & 0x3f;
2981
+ var byte2 = bytes[offset++] & 0x3f;
2982
+ var byte3 = bytes[offset++] & 0x3f;
3010
2983
  units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
3011
2984
  }
3012
2985
  else if ((byte1 & 0xf8) === 0xf0) {
3013
2986
  // 4 bytes
3014
- const byte2 = bytes[offset++] & 0x3f;
3015
- const byte3 = bytes[offset++] & 0x3f;
3016
- const byte4 = bytes[offset++] & 0x3f;
3017
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
2987
+ var byte2 = bytes[offset++] & 0x3f;
2988
+ var byte3 = bytes[offset++] & 0x3f;
2989
+ var byte4 = bytes[offset++] & 0x3f;
2990
+ var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
3018
2991
  if (unit > 0xffff) {
3019
2992
  unit -= 0x10000;
3020
2993
  units.push(((unit >>> 10) & 0x3ff) | 0xd800);
@@ -3026,84 +2999,86 @@ function utf8DecodeJs(bytes, inputOffset, byteLength) {
3026
2999
  units.push(byte1);
3027
3000
  }
3028
3001
  if (units.length >= CHUNK_SIZE) {
3029
- result += String.fromCharCode(...units);
3002
+ result += String.fromCharCode.apply(String, units);
3030
3003
  units.length = 0;
3031
3004
  }
3032
3005
  }
3033
3006
  if (units.length > 0) {
3034
- result += String.fromCharCode(...units);
3007
+ result += String.fromCharCode.apply(String, units);
3035
3008
  }
3036
3009
  return result;
3037
3010
  }
3038
- new TextDecoder();
3011
+ TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
3012
+ !TEXT_ENCODING_AVAILABLE
3013
+ ? UINT32_MAX
3014
+ : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
3015
+ ? 200
3016
+ : 0;
3039
3017
 
3040
3018
  /**
3041
3019
  * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
3042
3020
  */
3043
- class ExtData {
3044
- type;
3045
- data;
3046
- constructor(type, data) {
3021
+ var ExtData = /** @class */ (function () {
3022
+ function ExtData(type, data) {
3047
3023
  this.type = type;
3048
3024
  this.data = data;
3049
3025
  }
3050
- }
3026
+ return ExtData;
3027
+ }());
3051
3028
 
3052
- class DecodeError extends Error {
3053
- constructor(message) {
3054
- super(message);
3029
+ var __extends = (undefined && undefined.__extends) || (function () {
3030
+ var extendStatics = function (d, b) {
3031
+ extendStatics = Object.setPrototypeOf ||
3032
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
3033
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
3034
+ return extendStatics(d, b);
3035
+ };
3036
+ return function (d, b) {
3037
+ if (typeof b !== "function" && b !== null)
3038
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
3039
+ extendStatics(d, b);
3040
+ function __() { this.constructor = d; }
3041
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
3042
+ };
3043
+ })();
3044
+ var DecodeError = /** @class */ (function (_super) {
3045
+ __extends(DecodeError, _super);
3046
+ function DecodeError(message) {
3047
+ var _this = _super.call(this, message) || this;
3055
3048
  // fix the prototype chain in a cross-platform way
3056
- const proto = Object.create(DecodeError.prototype);
3057
- Object.setPrototypeOf(this, proto);
3058
- Object.defineProperty(this, "name", {
3049
+ var proto = Object.create(DecodeError.prototype);
3050
+ Object.setPrototypeOf(_this, proto);
3051
+ Object.defineProperty(_this, "name", {
3059
3052
  configurable: true,
3060
3053
  enumerable: false,
3061
3054
  value: DecodeError.name,
3062
3055
  });
3056
+ return _this;
3063
3057
  }
3064
- }
3065
-
3066
- // Integer Utility
3067
- // DataView extension to handle int64 / uint64,
3068
- // where the actual range is 53-bits integer (a.k.a. safe integer)
3069
- function setUint64(view, offset, value) {
3070
- const high = value / 4294967296;
3071
- const low = value; // high bits are truncated by DataView
3072
- view.setUint32(offset, high);
3073
- view.setUint32(offset + 4, low);
3074
- }
3075
- function setInt64(view, offset, value) {
3076
- const high = Math.floor(value / 4294967296);
3077
- const low = value; // high bits are truncated by DataView
3078
- view.setUint32(offset, high);
3079
- view.setUint32(offset + 4, low);
3080
- }
3081
- function getInt64(view, offset) {
3082
- const high = view.getInt32(offset);
3083
- const low = view.getUint32(offset + 4);
3084
- return high * 4294967296 + low;
3085
- }
3058
+ return DecodeError;
3059
+ }(Error));
3086
3060
 
3087
3061
  // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
3088
- const EXT_TIMESTAMP = -1;
3089
- const TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
3090
- const TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
3091
- function encodeTimeSpecToTimestamp({ sec, nsec }) {
3062
+ var EXT_TIMESTAMP = -1;
3063
+ var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
3064
+ var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
3065
+ function encodeTimeSpecToTimestamp(_a) {
3066
+ var sec = _a.sec, nsec = _a.nsec;
3092
3067
  if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
3093
3068
  // Here sec >= 0 && nsec >= 0
3094
3069
  if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
3095
3070
  // timestamp 32 = { sec32 (unsigned) }
3096
- const rv = new Uint8Array(4);
3097
- const view = new DataView(rv.buffer);
3071
+ var rv = new Uint8Array(4);
3072
+ var view = new DataView(rv.buffer);
3098
3073
  view.setUint32(0, sec);
3099
3074
  return rv;
3100
3075
  }
3101
3076
  else {
3102
3077
  // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
3103
- const secHigh = sec / 0x100000000;
3104
- const secLow = sec & 0xffffffff;
3105
- const rv = new Uint8Array(8);
3106
- const view = new DataView(rv.buffer);
3078
+ var secHigh = sec / 0x100000000;
3079
+ var secLow = sec & 0xffffffff;
3080
+ var rv = new Uint8Array(8);
3081
+ var view = new DataView(rv.buffer);
3107
3082
  // nsec30 | secHigh2
3108
3083
  view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
3109
3084
  // secLow32
@@ -3113,19 +3088,19 @@ function encodeTimeSpecToTimestamp({ sec, nsec }) {
3113
3088
  }
3114
3089
  else {
3115
3090
  // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3116
- const rv = new Uint8Array(12);
3117
- const view = new DataView(rv.buffer);
3091
+ var rv = new Uint8Array(12);
3092
+ var view = new DataView(rv.buffer);
3118
3093
  view.setUint32(0, nsec);
3119
3094
  setInt64(view, 4, sec);
3120
3095
  return rv;
3121
3096
  }
3122
3097
  }
3123
3098
  function encodeDateToTimeSpec(date) {
3124
- const msec = date.getTime();
3125
- const sec = Math.floor(msec / 1e3);
3126
- const nsec = (msec - sec * 1e3) * 1e6;
3099
+ var msec = date.getTime();
3100
+ var sec = Math.floor(msec / 1e3);
3101
+ var nsec = (msec - sec * 1e3) * 1e6;
3127
3102
  // Normalizes { sec, nsec } to ensure nsec is unsigned.
3128
- const nsecInSec = Math.floor(nsec / 1e9);
3103
+ var nsecInSec = Math.floor(nsec / 1e9);
3129
3104
  return {
3130
3105
  sec: sec + nsecInSec,
3131
3106
  nsec: nsec - nsecInSec * 1e9,
@@ -3133,7 +3108,7 @@ function encodeDateToTimeSpec(date) {
3133
3108
  }
3134
3109
  function encodeTimestampExtension(object) {
3135
3110
  if (object instanceof Date) {
3136
- const timeSpec = encodeDateToTimeSpec(object);
3111
+ var timeSpec = encodeDateToTimeSpec(object);
3137
3112
  return encodeTimeSpecToTimestamp(timeSpec);
3138
3113
  }
3139
3114
  else {
@@ -3141,60 +3116,56 @@ function encodeTimestampExtension(object) {
3141
3116
  }
3142
3117
  }
3143
3118
  function decodeTimestampToTimeSpec(data) {
3144
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3119
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3145
3120
  // data may be 32, 64, or 96 bits
3146
3121
  switch (data.byteLength) {
3147
3122
  case 4: {
3148
3123
  // timestamp 32 = { sec32 }
3149
- const sec = view.getUint32(0);
3150
- const nsec = 0;
3151
- return { sec, nsec };
3124
+ var sec = view.getUint32(0);
3125
+ var nsec = 0;
3126
+ return { sec: sec, nsec: nsec };
3152
3127
  }
3153
3128
  case 8: {
3154
3129
  // timestamp 64 = { nsec30, sec34 }
3155
- const nsec30AndSecHigh2 = view.getUint32(0);
3156
- const secLow32 = view.getUint32(4);
3157
- const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
3158
- const nsec = nsec30AndSecHigh2 >>> 2;
3159
- return { sec, nsec };
3130
+ var nsec30AndSecHigh2 = view.getUint32(0);
3131
+ var secLow32 = view.getUint32(4);
3132
+ var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
3133
+ var nsec = nsec30AndSecHigh2 >>> 2;
3134
+ return { sec: sec, nsec: nsec };
3160
3135
  }
3161
3136
  case 12: {
3162
3137
  // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3163
- const sec = getInt64(view, 4);
3164
- const nsec = view.getUint32(0);
3165
- return { sec, nsec };
3138
+ var sec = getInt64(view, 4);
3139
+ var nsec = view.getUint32(0);
3140
+ return { sec: sec, nsec: nsec };
3166
3141
  }
3167
3142
  default:
3168
- throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
3143
+ throw new DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
3169
3144
  }
3170
3145
  }
3171
3146
  function decodeTimestampExtension(data) {
3172
- const timeSpec = decodeTimestampToTimeSpec(data);
3147
+ var timeSpec = decodeTimestampToTimeSpec(data);
3173
3148
  return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
3174
3149
  }
3175
- const timestampExtension = {
3150
+ var timestampExtension = {
3176
3151
  type: EXT_TIMESTAMP,
3177
3152
  encode: encodeTimestampExtension,
3178
3153
  decode: decodeTimestampExtension,
3179
3154
  };
3180
3155
 
3181
3156
  // ExtensionCodec to handle MessagePack extensions
3182
- class ExtensionCodec {
3183
- static defaultCodec = new ExtensionCodec();
3184
- // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
3185
- // this will make type errors a lot more clear
3186
- // eslint-disable-next-line @typescript-eslint/naming-convention
3187
- __brand;
3188
- // built-in extensions
3189
- builtInEncoders = [];
3190
- builtInDecoders = [];
3191
- // custom extensions
3192
- encoders = [];
3193
- decoders = [];
3194
- constructor() {
3157
+ var ExtensionCodec = /** @class */ (function () {
3158
+ function ExtensionCodec() {
3159
+ // built-in extensions
3160
+ this.builtInEncoders = [];
3161
+ this.builtInDecoders = [];
3162
+ // custom extensions
3163
+ this.encoders = [];
3164
+ this.decoders = [];
3195
3165
  this.register(timestampExtension);
3196
3166
  }
3197
- register({ type, encode, decode, }) {
3167
+ ExtensionCodec.prototype.register = function (_a) {
3168
+ var type = _a.type, encode = _a.encode, decode = _a.decode;
3198
3169
  if (type >= 0) {
3199
3170
  // custom extensions
3200
3171
  this.encoders[type] = encode;
@@ -3202,30 +3173,30 @@ class ExtensionCodec {
3202
3173
  }
3203
3174
  else {
3204
3175
  // built-in extensions
3205
- const index = -1 - type;
3176
+ var index = 1 + type;
3206
3177
  this.builtInEncoders[index] = encode;
3207
3178
  this.builtInDecoders[index] = decode;
3208
3179
  }
3209
- }
3210
- tryToEncode(object, context) {
3180
+ };
3181
+ ExtensionCodec.prototype.tryToEncode = function (object, context) {
3211
3182
  // built-in extensions
3212
- for (let i = 0; i < this.builtInEncoders.length; i++) {
3213
- const encodeExt = this.builtInEncoders[i];
3183
+ for (var i = 0; i < this.builtInEncoders.length; i++) {
3184
+ var encodeExt = this.builtInEncoders[i];
3214
3185
  if (encodeExt != null) {
3215
- const data = encodeExt(object, context);
3186
+ var data = encodeExt(object, context);
3216
3187
  if (data != null) {
3217
- const type = -1 - i;
3188
+ var type = -1 - i;
3218
3189
  return new ExtData(type, data);
3219
3190
  }
3220
3191
  }
3221
3192
  }
3222
3193
  // custom extensions
3223
- for (let i = 0; i < this.encoders.length; i++) {
3224
- const encodeExt = this.encoders[i];
3194
+ for (var i = 0; i < this.encoders.length; i++) {
3195
+ var encodeExt = this.encoders[i];
3225
3196
  if (encodeExt != null) {
3226
- const data = encodeExt(object, context);
3197
+ var data = encodeExt(object, context);
3227
3198
  if (data != null) {
3228
- const type = i;
3199
+ var type = i;
3229
3200
  return new ExtData(type, data);
3230
3201
  }
3231
3202
  }
@@ -3235,9 +3206,9 @@ class ExtensionCodec {
3235
3206
  return object;
3236
3207
  }
3237
3208
  return null;
3238
- }
3239
- decode(data, type, context) {
3240
- const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
3209
+ };
3210
+ ExtensionCodec.prototype.decode = function (data, type, context) {
3211
+ var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
3241
3212
  if (decodeExt) {
3242
3213
  return decodeExt(data, type, context);
3243
3214
  }
@@ -3245,12 +3216,11 @@ class ExtensionCodec {
3245
3216
  // decode() does not fail, returns ExtData instead.
3246
3217
  return new ExtData(type, data);
3247
3218
  }
3248
- }
3249
- }
3219
+ };
3220
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
3221
+ return ExtensionCodec;
3222
+ }());
3250
3223
 
3251
- function isArrayBufferLike(buffer) {
3252
- return (buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer));
3253
- }
3254
3224
  function ensureUint8Array(buffer) {
3255
3225
  if (buffer instanceof Uint8Array) {
3256
3226
  return buffer;
@@ -3258,7 +3228,7 @@ function ensureUint8Array(buffer) {
3258
3228
  else if (ArrayBuffer.isView(buffer)) {
3259
3229
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
3260
3230
  }
3261
- else if (isArrayBufferLike(buffer)) {
3231
+ else if (buffer instanceof ArrayBuffer) {
3262
3232
  return new Uint8Array(buffer);
3263
3233
  }
3264
3234
  else {
@@ -3267,96 +3237,54 @@ function ensureUint8Array(buffer) {
3267
3237
  }
3268
3238
  }
3269
3239
 
3270
- const DEFAULT_MAX_DEPTH = 100;
3271
- const DEFAULT_INITIAL_BUFFER_SIZE = 2048;
3272
- class Encoder {
3273
- extensionCodec;
3274
- context;
3275
- useBigInt64;
3276
- maxDepth;
3277
- initialBufferSize;
3278
- sortKeys;
3279
- forceFloat32;
3280
- ignoreUndefined;
3281
- forceIntegerToFloat;
3282
- pos;
3283
- view;
3284
- bytes;
3285
- entered = false;
3286
- constructor(options) {
3287
- this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
3288
- this.context = options?.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined
3289
- this.useBigInt64 = options?.useBigInt64 ?? false;
3290
- this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;
3291
- this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;
3292
- this.sortKeys = options?.sortKeys ?? false;
3293
- this.forceFloat32 = options?.forceFloat32 ?? false;
3294
- this.ignoreUndefined = options?.ignoreUndefined ?? false;
3295
- this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
3240
+ var DEFAULT_MAX_DEPTH = 100;
3241
+ var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
3242
+ var Encoder = /** @class */ (function () {
3243
+ function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {
3244
+ if (extensionCodec === void 0) { extensionCodec = ExtensionCodec.defaultCodec; }
3245
+ if (context === void 0) { context = undefined; }
3246
+ if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }
3247
+ if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }
3248
+ if (sortKeys === void 0) { sortKeys = false; }
3249
+ if (forceFloat32 === void 0) { forceFloat32 = false; }
3250
+ if (ignoreUndefined === void 0) { ignoreUndefined = false; }
3251
+ if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }
3252
+ this.extensionCodec = extensionCodec;
3253
+ this.context = context;
3254
+ this.maxDepth = maxDepth;
3255
+ this.initialBufferSize = initialBufferSize;
3256
+ this.sortKeys = sortKeys;
3257
+ this.forceFloat32 = forceFloat32;
3258
+ this.ignoreUndefined = ignoreUndefined;
3259
+ this.forceIntegerToFloat = forceIntegerToFloat;
3296
3260
  this.pos = 0;
3297
3261
  this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
3298
3262
  this.bytes = new Uint8Array(this.view.buffer);
3299
3263
  }
3300
- clone() {
3301
- // Because of slightly special argument `context`,
3302
- // type assertion is needed.
3303
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
3304
- return new Encoder({
3305
- extensionCodec: this.extensionCodec,
3306
- context: this.context,
3307
- useBigInt64: this.useBigInt64,
3308
- maxDepth: this.maxDepth,
3309
- initialBufferSize: this.initialBufferSize,
3310
- sortKeys: this.sortKeys,
3311
- forceFloat32: this.forceFloat32,
3312
- ignoreUndefined: this.ignoreUndefined,
3313
- forceIntegerToFloat: this.forceIntegerToFloat,
3314
- });
3315
- }
3316
- reinitializeState() {
3264
+ Encoder.prototype.reinitializeState = function () {
3317
3265
  this.pos = 0;
3318
- }
3266
+ };
3319
3267
  /**
3320
3268
  * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
3321
3269
  *
3322
3270
  * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
3323
3271
  */
3324
- encodeSharedRef(object) {
3325
- if (this.entered) {
3326
- const instance = this.clone();
3327
- return instance.encodeSharedRef(object);
3328
- }
3329
- try {
3330
- this.entered = true;
3331
- this.reinitializeState();
3332
- this.doEncode(object, 1);
3333
- return this.bytes.subarray(0, this.pos);
3334
- }
3335
- finally {
3336
- this.entered = false;
3337
- }
3338
- }
3272
+ Encoder.prototype.encodeSharedRef = function (object) {
3273
+ this.reinitializeState();
3274
+ this.doEncode(object, 1);
3275
+ return this.bytes.subarray(0, this.pos);
3276
+ };
3339
3277
  /**
3340
3278
  * @returns Encodes the object and returns a copy of the encoder's internal buffer.
3341
3279
  */
3342
- encode(object) {
3343
- if (this.entered) {
3344
- const instance = this.clone();
3345
- return instance.encode(object);
3346
- }
3347
- try {
3348
- this.entered = true;
3349
- this.reinitializeState();
3350
- this.doEncode(object, 1);
3351
- return this.bytes.slice(0, this.pos);
3352
- }
3353
- finally {
3354
- this.entered = false;
3355
- }
3356
- }
3357
- doEncode(object, depth) {
3280
+ Encoder.prototype.encode = function (object) {
3281
+ this.reinitializeState();
3282
+ this.doEncode(object, 1);
3283
+ return this.bytes.slice(0, this.pos);
3284
+ };
3285
+ Encoder.prototype.doEncode = function (object, depth) {
3358
3286
  if (depth > this.maxDepth) {
3359
- throw new Error(`Too deep objects in depth ${depth}`);
3287
+ throw new Error("Too deep objects in depth ".concat(depth));
3360
3288
  }
3361
3289
  if (object == null) {
3362
3290
  this.encodeNil();
@@ -3365,50 +3293,42 @@ class Encoder {
3365
3293
  this.encodeBoolean(object);
3366
3294
  }
3367
3295
  else if (typeof object === "number") {
3368
- if (!this.forceIntegerToFloat) {
3369
- this.encodeNumber(object);
3370
- }
3371
- else {
3372
- this.encodeNumberAsFloat(object);
3373
- }
3296
+ this.encodeNumber(object);
3374
3297
  }
3375
3298
  else if (typeof object === "string") {
3376
3299
  this.encodeString(object);
3377
3300
  }
3378
- else if (this.useBigInt64 && typeof object === "bigint") {
3379
- this.encodeBigInt64(object);
3380
- }
3381
3301
  else {
3382
3302
  this.encodeObject(object, depth);
3383
3303
  }
3384
- }
3385
- ensureBufferSizeToWrite(sizeToWrite) {
3386
- const requiredSize = this.pos + sizeToWrite;
3304
+ };
3305
+ Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {
3306
+ var requiredSize = this.pos + sizeToWrite;
3387
3307
  if (this.view.byteLength < requiredSize) {
3388
3308
  this.resizeBuffer(requiredSize * 2);
3389
3309
  }
3390
- }
3391
- resizeBuffer(newSize) {
3392
- const newBuffer = new ArrayBuffer(newSize);
3393
- const newBytes = new Uint8Array(newBuffer);
3394
- const newView = new DataView(newBuffer);
3310
+ };
3311
+ Encoder.prototype.resizeBuffer = function (newSize) {
3312
+ var newBuffer = new ArrayBuffer(newSize);
3313
+ var newBytes = new Uint8Array(newBuffer);
3314
+ var newView = new DataView(newBuffer);
3395
3315
  newBytes.set(this.bytes);
3396
3316
  this.view = newView;
3397
3317
  this.bytes = newBytes;
3398
- }
3399
- encodeNil() {
3318
+ };
3319
+ Encoder.prototype.encodeNil = function () {
3400
3320
  this.writeU8(0xc0);
3401
- }
3402
- encodeBoolean(object) {
3321
+ };
3322
+ Encoder.prototype.encodeBoolean = function (object) {
3403
3323
  if (object === false) {
3404
3324
  this.writeU8(0xc2);
3405
3325
  }
3406
3326
  else {
3407
3327
  this.writeU8(0xc3);
3408
3328
  }
3409
- }
3410
- encodeNumber(object) {
3411
- if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
3329
+ };
3330
+ Encoder.prototype.encodeNumber = function (object) {
3331
+ if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {
3412
3332
  if (object >= 0) {
3413
3333
  if (object < 0x80) {
3414
3334
  // positive fixint
@@ -3429,14 +3349,11 @@ class Encoder {
3429
3349
  this.writeU8(0xce);
3430
3350
  this.writeU32(object);
3431
3351
  }
3432
- else if (!this.useBigInt64) {
3352
+ else {
3433
3353
  // uint 64
3434
3354
  this.writeU8(0xcf);
3435
3355
  this.writeU64(object);
3436
3356
  }
3437
- else {
3438
- this.encodeNumberAsFloat(object);
3439
- }
3440
3357
  }
3441
3358
  else {
3442
3359
  if (object >= -32) {
@@ -3458,45 +3375,28 @@ class Encoder {
3458
3375
  this.writeU8(0xd2);
3459
3376
  this.writeI32(object);
3460
3377
  }
3461
- else if (!this.useBigInt64) {
3378
+ else {
3462
3379
  // int 64
3463
3380
  this.writeU8(0xd3);
3464
3381
  this.writeI64(object);
3465
3382
  }
3466
- else {
3467
- this.encodeNumberAsFloat(object);
3468
- }
3469
3383
  }
3470
3384
  }
3471
3385
  else {
3472
- this.encodeNumberAsFloat(object);
3473
- }
3474
- }
3475
- encodeNumberAsFloat(object) {
3476
- if (this.forceFloat32) {
3477
- // float 32
3478
- this.writeU8(0xca);
3479
- this.writeF32(object);
3480
- }
3481
- else {
3482
- // float 64
3483
- this.writeU8(0xcb);
3484
- this.writeF64(object);
3485
- }
3486
- }
3487
- encodeBigInt64(object) {
3488
- if (object >= BigInt(0)) {
3489
- // uint 64
3490
- this.writeU8(0xcf);
3491
- this.writeBigUint64(object);
3492
- }
3493
- else {
3494
- // int 64
3495
- this.writeU8(0xd3);
3496
- this.writeBigInt64(object);
3386
+ // non-integer numbers
3387
+ if (this.forceFloat32) {
3388
+ // float 32
3389
+ this.writeU8(0xca);
3390
+ this.writeF32(object);
3391
+ }
3392
+ else {
3393
+ // float 64
3394
+ this.writeU8(0xcb);
3395
+ this.writeF64(object);
3396
+ }
3497
3397
  }
3498
- }
3499
- writeStringHeader(byteLength) {
3398
+ };
3399
+ Encoder.prototype.writeStringHeader = function (byteLength) {
3500
3400
  if (byteLength < 32) {
3501
3401
  // fixstr
3502
3402
  this.writeU8(0xa0 + byteLength);
@@ -3517,20 +3417,30 @@ class Encoder {
3517
3417
  this.writeU32(byteLength);
3518
3418
  }
3519
3419
  else {
3520
- throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
3420
+ throw new Error("Too long string: ".concat(byteLength, " bytes in UTF-8"));
3521
3421
  }
3522
- }
3523
- encodeString(object) {
3524
- const maxHeaderSize = 1 + 4;
3525
- const byteLength = utf8Count(object);
3526
- this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3527
- this.writeStringHeader(byteLength);
3528
- utf8Encode(object, this.bytes, this.pos);
3529
- this.pos += byteLength;
3530
- }
3531
- encodeObject(object, depth) {
3422
+ };
3423
+ Encoder.prototype.encodeString = function (object) {
3424
+ var maxHeaderSize = 1 + 4;
3425
+ var strLength = object.length;
3426
+ if (strLength > TEXT_ENCODER_THRESHOLD) {
3427
+ var byteLength = utf8Count(object);
3428
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3429
+ this.writeStringHeader(byteLength);
3430
+ utf8EncodeTE(object, this.bytes, this.pos);
3431
+ this.pos += byteLength;
3432
+ }
3433
+ else {
3434
+ var byteLength = utf8Count(object);
3435
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3436
+ this.writeStringHeader(byteLength);
3437
+ utf8EncodeJs(object, this.bytes, this.pos);
3438
+ this.pos += byteLength;
3439
+ }
3440
+ };
3441
+ Encoder.prototype.encodeObject = function (object, depth) {
3532
3442
  // try to encode objects with custom codec first of non-primitives
3533
- const ext = this.extensionCodec.tryToEncode(object, this.context);
3443
+ var ext = this.extensionCodec.tryToEncode(object, this.context);
3534
3444
  if (ext != null) {
3535
3445
  this.encodeExtension(ext);
3536
3446
  }
@@ -3545,11 +3455,11 @@ class Encoder {
3545
3455
  }
3546
3456
  else {
3547
3457
  // symbol, function and other special object come here unless extensionCodec handles them.
3548
- throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
3458
+ throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
3549
3459
  }
3550
- }
3551
- encodeBinary(object) {
3552
- const size = object.byteLength;
3460
+ };
3461
+ Encoder.prototype.encodeBinary = function (object) {
3462
+ var size = object.byteLength;
3553
3463
  if (size < 0x100) {
3554
3464
  // bin 8
3555
3465
  this.writeU8(0xc4);
@@ -3566,13 +3476,13 @@ class Encoder {
3566
3476
  this.writeU32(size);
3567
3477
  }
3568
3478
  else {
3569
- throw new Error(`Too large binary: ${size}`);
3479
+ throw new Error("Too large binary: ".concat(size));
3570
3480
  }
3571
- const bytes = ensureUint8Array(object);
3481
+ var bytes = ensureUint8Array(object);
3572
3482
  this.writeU8a(bytes);
3573
- }
3574
- encodeArray(object, depth) {
3575
- const size = object.length;
3483
+ };
3484
+ Encoder.prototype.encodeArray = function (object, depth) {
3485
+ var size = object.length;
3576
3486
  if (size < 16) {
3577
3487
  // fixarray
3578
3488
  this.writeU8(0x90 + size);
@@ -3588,27 +3498,29 @@ class Encoder {
3588
3498
  this.writeU32(size);
3589
3499
  }
3590
3500
  else {
3591
- throw new Error(`Too large array: ${size}`);
3501
+ throw new Error("Too large array: ".concat(size));
3592
3502
  }
3593
- for (const item of object) {
3503
+ for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
3504
+ var item = object_1[_i];
3594
3505
  this.doEncode(item, depth + 1);
3595
3506
  }
3596
- }
3597
- countWithoutUndefined(object, keys) {
3598
- let count = 0;
3599
- for (const key of keys) {
3507
+ };
3508
+ Encoder.prototype.countWithoutUndefined = function (object, keys) {
3509
+ var count = 0;
3510
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3511
+ var key = keys_1[_i];
3600
3512
  if (object[key] !== undefined) {
3601
3513
  count++;
3602
3514
  }
3603
3515
  }
3604
3516
  return count;
3605
- }
3606
- encodeMap(object, depth) {
3607
- const keys = Object.keys(object);
3517
+ };
3518
+ Encoder.prototype.encodeMap = function (object, depth) {
3519
+ var keys = Object.keys(object);
3608
3520
  if (this.sortKeys) {
3609
3521
  keys.sort();
3610
3522
  }
3611
- const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
3523
+ var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
3612
3524
  if (size < 16) {
3613
3525
  // fixmap
3614
3526
  this.writeU8(0x80 + size);
@@ -3624,30 +3536,19 @@ class Encoder {
3624
3536
  this.writeU32(size);
3625
3537
  }
3626
3538
  else {
3627
- throw new Error(`Too large map object: ${size}`);
3539
+ throw new Error("Too large map object: ".concat(size));
3628
3540
  }
3629
- for (const key of keys) {
3630
- const value = object[key];
3541
+ for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
3542
+ var key = keys_2[_i];
3543
+ var value = object[key];
3631
3544
  if (!(this.ignoreUndefined && value === undefined)) {
3632
3545
  this.encodeString(key);
3633
3546
  this.doEncode(value, depth + 1);
3634
3547
  }
3635
3548
  }
3636
- }
3637
- encodeExtension(ext) {
3638
- if (typeof ext.data === "function") {
3639
- const data = ext.data(this.pos + 6);
3640
- const size = data.length;
3641
- if (size >= 0x100000000) {
3642
- throw new Error(`Too large extension object: ${size}`);
3643
- }
3644
- this.writeU8(0xc9);
3645
- this.writeU32(size);
3646
- this.writeI8(ext.type);
3647
- this.writeU8a(data);
3648
- return;
3649
- }
3650
- const size = ext.data.length;
3549
+ };
3550
+ Encoder.prototype.encodeExtension = function (ext) {
3551
+ var size = ext.data.length;
3651
3552
  if (size === 1) {
3652
3553
  // fixext 1
3653
3554
  this.writeU8(0xd4);
@@ -3684,79 +3585,71 @@ class Encoder {
3684
3585
  this.writeU32(size);
3685
3586
  }
3686
3587
  else {
3687
- throw new Error(`Too large extension object: ${size}`);
3588
+ throw new Error("Too large extension object: ".concat(size));
3688
3589
  }
3689
3590
  this.writeI8(ext.type);
3690
3591
  this.writeU8a(ext.data);
3691
- }
3692
- writeU8(value) {
3592
+ };
3593
+ Encoder.prototype.writeU8 = function (value) {
3693
3594
  this.ensureBufferSizeToWrite(1);
3694
3595
  this.view.setUint8(this.pos, value);
3695
3596
  this.pos++;
3696
- }
3697
- writeU8a(values) {
3698
- const size = values.length;
3597
+ };
3598
+ Encoder.prototype.writeU8a = function (values) {
3599
+ var size = values.length;
3699
3600
  this.ensureBufferSizeToWrite(size);
3700
3601
  this.bytes.set(values, this.pos);
3701
3602
  this.pos += size;
3702
- }
3703
- writeI8(value) {
3603
+ };
3604
+ Encoder.prototype.writeI8 = function (value) {
3704
3605
  this.ensureBufferSizeToWrite(1);
3705
3606
  this.view.setInt8(this.pos, value);
3706
3607
  this.pos++;
3707
- }
3708
- writeU16(value) {
3608
+ };
3609
+ Encoder.prototype.writeU16 = function (value) {
3709
3610
  this.ensureBufferSizeToWrite(2);
3710
3611
  this.view.setUint16(this.pos, value);
3711
3612
  this.pos += 2;
3712
- }
3713
- writeI16(value) {
3613
+ };
3614
+ Encoder.prototype.writeI16 = function (value) {
3714
3615
  this.ensureBufferSizeToWrite(2);
3715
3616
  this.view.setInt16(this.pos, value);
3716
3617
  this.pos += 2;
3717
- }
3718
- writeU32(value) {
3618
+ };
3619
+ Encoder.prototype.writeU32 = function (value) {
3719
3620
  this.ensureBufferSizeToWrite(4);
3720
3621
  this.view.setUint32(this.pos, value);
3721
3622
  this.pos += 4;
3722
- }
3723
- writeI32(value) {
3623
+ };
3624
+ Encoder.prototype.writeI32 = function (value) {
3724
3625
  this.ensureBufferSizeToWrite(4);
3725
3626
  this.view.setInt32(this.pos, value);
3726
3627
  this.pos += 4;
3727
- }
3728
- writeF32(value) {
3628
+ };
3629
+ Encoder.prototype.writeF32 = function (value) {
3729
3630
  this.ensureBufferSizeToWrite(4);
3730
3631
  this.view.setFloat32(this.pos, value);
3731
3632
  this.pos += 4;
3732
- }
3733
- writeF64(value) {
3633
+ };
3634
+ Encoder.prototype.writeF64 = function (value) {
3734
3635
  this.ensureBufferSizeToWrite(8);
3735
3636
  this.view.setFloat64(this.pos, value);
3736
3637
  this.pos += 8;
3737
- }
3738
- writeU64(value) {
3638
+ };
3639
+ Encoder.prototype.writeU64 = function (value) {
3739
3640
  this.ensureBufferSizeToWrite(8);
3740
3641
  setUint64(this.view, this.pos, value);
3741
3642
  this.pos += 8;
3742
- }
3743
- writeI64(value) {
3643
+ };
3644
+ Encoder.prototype.writeI64 = function (value) {
3744
3645
  this.ensureBufferSizeToWrite(8);
3745
3646
  setInt64(this.view, this.pos, value);
3746
3647
  this.pos += 8;
3747
- }
3748
- writeBigUint64(value) {
3749
- this.ensureBufferSizeToWrite(8);
3750
- this.view.setBigUint64(this.pos, value);
3751
- this.pos += 8;
3752
- }
3753
- writeBigInt64(value) {
3754
- this.ensureBufferSizeToWrite(8);
3755
- this.view.setBigInt64(this.pos, value);
3756
- this.pos += 8;
3757
- }
3758
- }
3648
+ };
3649
+ return Encoder;
3650
+ }());
3759
3651
 
3652
+ var defaultEncodeOptions = {};
3760
3653
  /**
3761
3654
  * It encodes `value` in the MessagePack format and
3762
3655
  * returns a byte buffer.
@@ -3764,36 +3657,37 @@ class Encoder {
3764
3657
  * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
3765
3658
  */
3766
3659
  function encode(value, options) {
3767
- const encoder = new Encoder(options);
3660
+ if (options === void 0) { options = defaultEncodeOptions; }
3661
+ var encoder = new Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);
3768
3662
  return encoder.encodeSharedRef(value);
3769
3663
  }
3770
3664
 
3771
- const DEFAULT_MAX_KEY_LENGTH = 16;
3772
- const DEFAULT_MAX_LENGTH_PER_KEY = 16;
3773
- class CachedKeyDecoder {
3774
- hit = 0;
3775
- miss = 0;
3776
- caches;
3777
- maxKeyLength;
3778
- maxLengthPerKey;
3779
- constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
3665
+ var DEFAULT_MAX_KEY_LENGTH = 16;
3666
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
3667
+ var CachedKeyDecoder = /** @class */ (function () {
3668
+ function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
3669
+ if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
3670
+ if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
3780
3671
  this.maxKeyLength = maxKeyLength;
3781
3672
  this.maxLengthPerKey = maxLengthPerKey;
3673
+ this.hit = 0;
3674
+ this.miss = 0;
3782
3675
  // avoid `new Array(N)`, which makes a sparse array,
3783
3676
  // because a sparse array is typically slower than a non-sparse array.
3784
3677
  this.caches = [];
3785
- for (let i = 0; i < this.maxKeyLength; i++) {
3678
+ for (var i = 0; i < this.maxKeyLength; i++) {
3786
3679
  this.caches.push([]);
3787
3680
  }
3788
3681
  }
3789
- canBeCached(byteLength) {
3682
+ CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
3790
3683
  return byteLength > 0 && byteLength <= this.maxKeyLength;
3791
- }
3792
- find(bytes, inputOffset, byteLength) {
3793
- const records = this.caches[byteLength - 1];
3794
- FIND_CHUNK: for (const record of records) {
3795
- const recordBytes = record.bytes;
3796
- for (let j = 0; j < byteLength; j++) {
3684
+ };
3685
+ CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
3686
+ var records = this.caches[byteLength - 1];
3687
+ FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
3688
+ var record = records_1[_i];
3689
+ var recordBytes = record.bytes;
3690
+ for (var j = 0; j < byteLength; j++) {
3797
3691
  if (recordBytes[j] !== bytes[inputOffset + j]) {
3798
3692
  continue FIND_CHUNK;
3799
3693
  }
@@ -3801,10 +3695,10 @@ class CachedKeyDecoder {
3801
3695
  return record.str;
3802
3696
  }
3803
3697
  return null;
3804
- }
3805
- store(bytes, value) {
3806
- const records = this.caches[bytes.length - 1];
3807
- const record = { bytes, str: value };
3698
+ };
3699
+ CachedKeyDecoder.prototype.store = function (bytes, value) {
3700
+ var records = this.caches[bytes.length - 1];
3701
+ var record = { bytes: bytes, str: value };
3808
3702
  if (records.length >= this.maxLengthPerKey) {
3809
3703
  // `records` are full!
3810
3704
  // Set `record` to an arbitrary position.
@@ -3813,36 +3707,174 @@ class CachedKeyDecoder {
3813
3707
  else {
3814
3708
  records.push(record);
3815
3709
  }
3816
- }
3817
- decode(bytes, inputOffset, byteLength) {
3818
- const cachedValue = this.find(bytes, inputOffset, byteLength);
3710
+ };
3711
+ CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
3712
+ var cachedValue = this.find(bytes, inputOffset, byteLength);
3819
3713
  if (cachedValue != null) {
3820
3714
  this.hit++;
3821
3715
  return cachedValue;
3822
3716
  }
3823
3717
  this.miss++;
3824
- const str = utf8DecodeJs(bytes, inputOffset, byteLength);
3825
- // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
3826
- const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
3718
+ var str = utf8DecodeJs(bytes, inputOffset, byteLength);
3719
+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
3720
+ var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
3827
3721
  this.store(slicedCopyOfBytes, str);
3828
3722
  return str;
3723
+ };
3724
+ return CachedKeyDecoder;
3725
+ }());
3726
+
3727
+ (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
3728
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3729
+ return new (P || (P = Promise))(function (resolve, reject) {
3730
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3731
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3732
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
3733
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3734
+ });
3735
+ };
3736
+ (undefined && undefined.__generator) || function (thisArg, body) {
3737
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3738
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
3739
+ function verb(n) { return function (v) { return step([n, v]); }; }
3740
+ function step(op) {
3741
+ if (f) throw new TypeError("Generator is already executing.");
3742
+ while (_) try {
3743
+ 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;
3744
+ if (y = 0, t) op = [op[0] & 2, t.value];
3745
+ switch (op[0]) {
3746
+ case 0: case 1: t = op; break;
3747
+ case 4: _.label++; return { value: op[1], done: false };
3748
+ case 5: _.label++; y = op[1]; op = [0]; continue;
3749
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
3750
+ default:
3751
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
3752
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
3753
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
3754
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
3755
+ if (t[2]) _.ops.pop();
3756
+ _.trys.pop(); continue;
3757
+ }
3758
+ op = body.call(thisArg, _);
3759
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
3760
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
3829
3761
  }
3830
- }
3831
-
3832
- const EMPTY_VIEW = new DataView(new ArrayBuffer(0));
3762
+ };
3763
+ (undefined && undefined.__asyncValues) || function (o) {
3764
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3765
+ var m = o[Symbol.asyncIterator], i;
3766
+ 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);
3767
+ 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); }); }; }
3768
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
3769
+ };
3770
+ var __await$1 = (undefined && undefined.__await) || function (v) { return this instanceof __await$1 ? (this.v = v, this) : new __await$1(v); };
3771
+ (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
3772
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3773
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
3774
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
3775
+ 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); }); }; }
3776
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
3777
+ function step(r) { r.value instanceof __await$1 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
3778
+ function fulfill(value) { resume("next", value); }
3779
+ function reject(value) { resume("throw", value); }
3780
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
3781
+ };
3782
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
3833
3783
  new Uint8Array(EMPTY_VIEW.buffer);
3834
- try {
3835
- // IE11: The spec says it should throw RangeError,
3836
- // IE11: but in IE11 it throws TypeError.
3837
- EMPTY_VIEW.getInt8(0);
3838
- }
3839
- catch (e) {
3840
- if (!(e instanceof RangeError)) {
3841
- throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
3784
+ // IE11: Hack to support IE11.
3785
+ // IE11: Drop this hack and just use RangeError when IE11 is obsolete.
3786
+ var DataViewIndexOutOfBoundsError = (function () {
3787
+ try {
3788
+ // IE11: The spec says it should throw RangeError,
3789
+ // IE11: but in IE11 it throws TypeError.
3790
+ EMPTY_VIEW.getInt8(0);
3842
3791
  }
3843
- }
3792
+ catch (e) {
3793
+ return e.constructor;
3794
+ }
3795
+ throw new Error("never reached");
3796
+ })();
3797
+ new DataViewIndexOutOfBoundsError("Insufficient data");
3844
3798
  new CachedKeyDecoder();
3845
3799
 
3800
+ // utility for whatwg streams
3801
+ (undefined && undefined.__generator) || function (thisArg, body) {
3802
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3803
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
3804
+ function verb(n) { return function (v) { return step([n, v]); }; }
3805
+ function step(op) {
3806
+ if (f) throw new TypeError("Generator is already executing.");
3807
+ while (_) try {
3808
+ 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;
3809
+ if (y = 0, t) op = [op[0] & 2, t.value];
3810
+ switch (op[0]) {
3811
+ case 0: case 1: t = op; break;
3812
+ case 4: _.label++; return { value: op[1], done: false };
3813
+ case 5: _.label++; y = op[1]; op = [0]; continue;
3814
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
3815
+ default:
3816
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
3817
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
3818
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
3819
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
3820
+ if (t[2]) _.ops.pop();
3821
+ _.trys.pop(); continue;
3822
+ }
3823
+ op = body.call(thisArg, _);
3824
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
3825
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
3826
+ }
3827
+ };
3828
+ var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); };
3829
+ (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
3830
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3831
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
3832
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
3833
+ 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); }); }; }
3834
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
3835
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
3836
+ function fulfill(value) { resume("next", value); }
3837
+ function reject(value) { resume("throw", value); }
3838
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
3839
+ };
3840
+
3841
+ (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
3842
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3843
+ return new (P || (P = Promise))(function (resolve, reject) {
3844
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3845
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3846
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
3847
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3848
+ });
3849
+ };
3850
+ (undefined && undefined.__generator) || function (thisArg, body) {
3851
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3852
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
3853
+ function verb(n) { return function (v) { return step([n, v]); }; }
3854
+ function step(op) {
3855
+ if (f) throw new TypeError("Generator is already executing.");
3856
+ while (_) try {
3857
+ 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;
3858
+ if (y = 0, t) op = [op[0] & 2, t.value];
3859
+ switch (op[0]) {
3860
+ case 0: case 1: t = op; break;
3861
+ case 4: _.label++; return { value: op[1], done: false };
3862
+ case 5: _.label++; y = op[1]; op = [0]; continue;
3863
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
3864
+ default:
3865
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
3866
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
3867
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
3868
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
3869
+ if (t[2]) _.ops.pop();
3870
+ _.trys.pop(); continue;
3871
+ }
3872
+ op = body.call(thisArg, _);
3873
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
3874
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
3875
+ }
3876
+ };
3877
+
3846
3878
  function encodeMiniProgramShareExtra(value) {
3847
3879
  assertExtraValue(value);
3848
3880
  const bytes = encode(value);
@@ -5670,6 +5702,9 @@ class MiniProgramRuntimeImpl {
5670
5702
  this.probeSequence = 0;
5671
5703
  this.hostVisible = true;
5672
5704
  this.awaitingControlledDocumentLoad = false;
5705
+ this.documentRevalidationPending = false;
5706
+ this.documentRevalidationGeneration = 0;
5707
+ this.iframeHiddenForRevalidation = false;
5673
5708
  this.runtimePermissions = undefined;
5674
5709
  this.options = options;
5675
5710
  this.iframe = options.iframe;
@@ -5699,13 +5734,22 @@ class MiniProgramRuntimeImpl {
5699
5734
  this.iframeLoadListener = () => {
5700
5735
  if (this.awaitingControlledDocumentLoad) {
5701
5736
  this.awaitingControlledDocumentLoad = false;
5737
+ if (this.stateValue === 'ready' && this.bridgeServer?.protocolVersion === 2 && this.sdkVersionDecision?.heartbeatEnabled) {
5738
+ this.beginDocumentRevalidation();
5739
+ return;
5740
+ }
5702
5741
  if (this.compatibilityWithoutSdk && !this.readyContext) {
5703
5742
  this.completeCompatibilityLaunch();
5704
5743
  }
5705
5744
  return;
5706
5745
  }
5707
5746
  if (this.stateValue === 'ready') {
5708
- this.scheduleUnexpectedDocumentLoadFailure();
5747
+ if (this.bridgeServer?.protocolVersion === 2 && this.sdkVersionDecision?.heartbeatEnabled) {
5748
+ this.beginDocumentRevalidation();
5749
+ }
5750
+ else {
5751
+ this.scheduleUnexpectedDocumentLoadFailure();
5752
+ }
5709
5753
  }
5710
5754
  };
5711
5755
  this.iframe.addEventListener('error', this.iframeErrorListener);
@@ -5753,14 +5797,34 @@ class MiniProgramRuntimeImpl {
5753
5797
  this.hostVisible = true;
5754
5798
  this.emitLifecycleEvent('show');
5755
5799
  if (!wasVisible && this.stateValue === 'ready' && this.sdkVersionDecision?.heartbeatEnabled) {
5756
- this.sendLocationProbe();
5800
+ if (this.documentRevalidationPending) {
5801
+ this.armDocumentRevalidationTimer(this.documentRevalidationGeneration);
5802
+ this.resendDocumentRevalidationProbe();
5803
+ }
5804
+ else {
5805
+ this.sendLocationProbe();
5806
+ }
5757
5807
  }
5758
5808
  }
5759
5809
  hide() {
5760
5810
  this.hostVisible = false;
5761
5811
  this.clearHeartbeat();
5812
+ this.clearDocumentRevalidationTimer();
5762
5813
  this.emitLifecycleEvent('hide');
5763
5814
  }
5815
+ prepareForHistoryTraversal() {
5816
+ if (this.stateValue !== 'ready' || this.bridgeServer?.protocolVersion !== 2 || !this.sdkVersionDecision?.heartbeatEnabled) {
5817
+ return () => undefined;
5818
+ }
5819
+ const generation = this.beginDocumentRevalidation({ deferProbe: true });
5820
+ this.preparedHistoryTraversalGeneration = generation;
5821
+ return () => {
5822
+ if (this.preparedHistoryTraversalGeneration !== generation) {
5823
+ return;
5824
+ }
5825
+ this.cancelPreparedHistoryTraversal();
5826
+ };
5827
+ }
5764
5828
  createReadyPromise() {
5765
5829
  return new Promise((resolve, reject) => {
5766
5830
  this.resolveReady = resolve;
@@ -5857,11 +5921,7 @@ class MiniProgramRuntimeImpl {
5857
5921
  this.handleBridgeReady();
5858
5922
  },
5859
5923
  onDuplicateHandshake: () => {
5860
- this.trace({
5861
- runtimeId: this.nonce,
5862
- timestamp: Date.now(),
5863
- type: 'duplicate_handshake',
5864
- });
5924
+ this.handleDuplicateBridgeHandshake();
5865
5925
  },
5866
5926
  onInternalEvent: (message) => {
5867
5927
  this.handleInternalBridgeEvent(message);
@@ -6102,7 +6162,7 @@ class MiniProgramRuntimeImpl {
6102
6162
  }
6103
6163
  }
6104
6164
  sendLocationProbe() {
6105
- if (this.isInactive() || !this.hostVisible || !this.sdkVersionDecision?.heartbeatEnabled) {
6165
+ if (this.isInactive() || !this.hostVisible || !this.sdkVersionDecision?.heartbeatEnabled || this.documentRevalidationPending) {
6106
6166
  return;
6107
6167
  }
6108
6168
  if (this.pendingProbeId) {
@@ -6137,6 +6197,123 @@ class MiniProgramRuntimeImpl {
6137
6197
  this.pendingProbeId = undefined;
6138
6198
  this.consecutiveHeartbeatMisses = 0;
6139
6199
  }
6200
+ beginDocumentRevalidation(options = {}) {
6201
+ this.clearUnexpectedDocumentLoadFailure();
6202
+ this.clearHeartbeat();
6203
+ this.clearDocumentRevalidationTimer();
6204
+ this.preparedHistoryTraversalGeneration = undefined;
6205
+ this.documentRevalidationPending = true;
6206
+ const generation = ++this.documentRevalidationGeneration;
6207
+ if (!this.iframeHiddenForRevalidation) {
6208
+ this.iframeVisibilityBeforeRevalidation = this.iframe.style.visibility;
6209
+ this.iframe.style.visibility = 'hidden';
6210
+ this.iframeHiddenForRevalidation = true;
6211
+ }
6212
+ this.armDocumentRevalidationTimer(generation);
6213
+ if (!options.deferProbe) {
6214
+ this.sendDocumentRevalidationProbe();
6215
+ }
6216
+ return generation;
6217
+ }
6218
+ sendDocumentRevalidationProbe() {
6219
+ if (this.isInactive() || !this.hostVisible || !this.documentRevalidationPending || !this.sdkVersionDecision?.heartbeatEnabled) {
6220
+ return;
6221
+ }
6222
+ const probeId = `${Date.now().toString(36)}_${++this.probeSequence}`;
6223
+ this.pendingProbeId = probeId;
6224
+ this.postLocationProbe(probeId);
6225
+ }
6226
+ resendDocumentRevalidationProbe() {
6227
+ if (this.isInactive() || !this.hostVisible || !this.documentRevalidationPending || !this.sdkVersionDecision?.heartbeatEnabled) {
6228
+ return;
6229
+ }
6230
+ if (!this.pendingProbeId) {
6231
+ this.sendDocumentRevalidationProbe();
6232
+ return;
6233
+ }
6234
+ this.postLocationProbe(this.pendingProbeId);
6235
+ }
6236
+ postLocationProbe(probeId) {
6237
+ this.bridgeServer?.postInternalRequest(RUNTIME_LOCATION_PROBE_METHOD, probeId, {
6238
+ probeId,
6239
+ timestamp: Date.now(),
6240
+ });
6241
+ this.trace({
6242
+ runtimeId: this.nonce,
6243
+ timestamp: Date.now(),
6244
+ type: 'location_probe',
6245
+ method: RUNTIME_LOCATION_PROBE_METHOD,
6246
+ });
6247
+ }
6248
+ armDocumentRevalidationTimer(generation) {
6249
+ if (!this.hostVisible) {
6250
+ return;
6251
+ }
6252
+ this.documentRevalidationTimer = setTimeout(() => {
6253
+ this.documentRevalidationTimer = undefined;
6254
+ if (this.isInactive() || !this.documentRevalidationPending || generation !== this.documentRevalidationGeneration) {
6255
+ return;
6256
+ }
6257
+ this.emitUrlSecurityViolation('UNEXPECTED_DOCUMENT_LOAD', this.launchUrl);
6258
+ this.failRuntime(createBridgeError('UNEXPECTED_DOCUMENT_LOAD', '小程序 iframe 文档再验证超时'));
6259
+ }, HEARTBEAT_INTERVAL);
6260
+ }
6261
+ clearDocumentRevalidationTimer() {
6262
+ if (this.documentRevalidationTimer) {
6263
+ clearTimeout(this.documentRevalidationTimer);
6264
+ this.documentRevalidationTimer = undefined;
6265
+ }
6266
+ }
6267
+ completeDocumentRevalidation() {
6268
+ this.clearDocumentRevalidationTimer();
6269
+ this.documentRevalidationPending = false;
6270
+ this.preparedHistoryTraversalGeneration = undefined;
6271
+ this.pendingProbeId = undefined;
6272
+ this.consecutiveHeartbeatMisses = 0;
6273
+ if (this.iframeHiddenForRevalidation && this.iframe.style.visibility === 'hidden') {
6274
+ this.iframe.style.visibility = this.iframeVisibilityBeforeRevalidation ?? '';
6275
+ }
6276
+ this.iframeVisibilityBeforeRevalidation = undefined;
6277
+ this.iframeHiddenForRevalidation = false;
6278
+ if (this.hostVisible && this.sdkVersionDecision?.heartbeatEnabled) {
6279
+ this.heartbeatTimer = setTimeout(() => {
6280
+ this.heartbeatTimer = undefined;
6281
+ this.sendLocationProbe();
6282
+ }, HEARTBEAT_INTERVAL);
6283
+ }
6284
+ }
6285
+ clearDocumentRevalidation() {
6286
+ this.clearDocumentRevalidationTimer();
6287
+ this.documentRevalidationPending = false;
6288
+ this.preparedHistoryTraversalGeneration = undefined;
6289
+ this.iframeVisibilityBeforeRevalidation = undefined;
6290
+ this.iframeHiddenForRevalidation = false;
6291
+ }
6292
+ cancelPreparedHistoryTraversal() {
6293
+ this.clearDocumentRevalidationTimer();
6294
+ this.documentRevalidationPending = false;
6295
+ this.preparedHistoryTraversalGeneration = undefined;
6296
+ this.pendingProbeId = undefined;
6297
+ this.consecutiveHeartbeatMisses = 0;
6298
+ if (this.iframeHiddenForRevalidation && this.iframe.style.visibility === 'hidden') {
6299
+ this.iframe.style.visibility = this.iframeVisibilityBeforeRevalidation ?? '';
6300
+ }
6301
+ this.iframeVisibilityBeforeRevalidation = undefined;
6302
+ this.iframeHiddenForRevalidation = false;
6303
+ if (this.hostVisible && this.sdkVersionDecision?.heartbeatEnabled) {
6304
+ this.sendLocationProbe();
6305
+ }
6306
+ }
6307
+ handleDuplicateBridgeHandshake() {
6308
+ this.trace({
6309
+ runtimeId: this.nonce,
6310
+ timestamp: Date.now(),
6311
+ type: 'duplicate_handshake',
6312
+ });
6313
+ if (this.documentRevalidationPending) {
6314
+ this.resendDocumentRevalidationProbe();
6315
+ }
6316
+ }
6140
6317
  handleInternalBridgeEvent(message) {
6141
6318
  if (message.method === SDK_CSP_VIOLATION_METHOD) {
6142
6319
  this.handleCspViolation(message.payload);
@@ -6168,12 +6345,16 @@ class MiniProgramRuntimeImpl {
6168
6345
  this.failRuntime(createBridgeError('URL_OUT_OF_SCOPE', '小程序页面地址超出允许范围'));
6169
6346
  return;
6170
6347
  }
6171
- if (report.trigger === 'hashchange') {
6172
- this.clearUnexpectedDocumentLoadFailure();
6173
- }
6174
6348
  if (report.probeId !== undefined) {
6175
6349
  this.pendingProbeId = undefined;
6176
6350
  this.consecutiveHeartbeatMisses = 0;
6351
+ if (this.documentRevalidationPending) {
6352
+ this.completeDocumentRevalidation();
6353
+ }
6354
+ }
6355
+ else if (this.documentRevalidationPending && !this.pendingProbeId) {
6356
+ this.preparedHistoryTraversalGeneration = undefined;
6357
+ this.sendDocumentRevalidationProbe();
6177
6358
  }
6178
6359
  }
6179
6360
  handleCspViolation(payload) {
@@ -6283,6 +6464,7 @@ class MiniProgramRuntimeImpl {
6283
6464
  this.clearHandshakeTimeout();
6284
6465
  this.clearHeartbeat();
6285
6466
  this.clearUnexpectedDocumentLoadFailure();
6467
+ this.clearDocumentRevalidation();
6286
6468
  this.destroyBridgeServer();
6287
6469
  this.capabilityGraph?.dispose();
6288
6470
  this.capabilityGraph = undefined;