@heybox/hb-sdk 0.7.4-alpha.1 → 0.7.4-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +17 -1
- package/dist/cli-chunks/{build-Cej8ObyY.cjs → build-C-ufarA6.cjs} +2 -2
- package/dist/cli-chunks/{context-DATgeHkI.cjs → context-C839--TH.cjs} +1 -1
- package/dist/cli-chunks/{create-LXHV_lW5.cjs → create-CNcII_CB.cjs} +1 -1
- package/dist/cli-chunks/{dev-CDuVyGm9.cjs → dev-MpESCaMm.cjs} +5 -5
- package/dist/cli-chunks/{doctor-BqmQrPaV.cjs → doctor-bhfQwyYU.cjs} +1 -1
- package/dist/cli-chunks/{index-Ck7X1LRP.cjs → index-B_qJzSFo.cjs} +1 -1
- package/dist/cli-chunks/{index-BCd2vU5D.cjs → index-CT94XzyO.cjs} +14 -14
- package/dist/cli-chunks/{login-BLTILOf-.cjs → login-hYrDJ3dR.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-BtIYxLkt.cjs → project-vite-zaw68V1G.cjs} +1 -1
- package/dist/cli-chunks/{remote-Bp9SK8C3.cjs → remote-DQZRAAHh.cjs} +4 -4
- package/dist/cli-chunks/{session-9ZWPGpqB.cjs → session-D692TU5N.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/main.js +1256 -46
- package/dist/index.cjs.js +1187 -3
- package/dist/index.esm.js +1187 -3
- package/dist/protocol.cjs.js +3 -0
- package/dist/protocol.esm.js +3 -1
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/package.json +5 -4
- package/skill/SKILL.md +1 -0
- package/skill/references/api-protocol.md +5 -2
- package/skill/references/api-root.md +6 -2
- package/skill/references/recipes.md +39 -0
- package/skill/skill.json +4 -4
- package/types/index.d.ts +1 -1
- package/types/modules/share/copy-link.d.ts +16 -0
- package/types/modules/share/extra.d.ts +3 -0
- package/types/modules/share/index.d.ts +8 -2
- package/types/modules/share/types.d.ts +11 -0
- package/types/protocol/capabilities.d.ts +1 -1
- package/types/protocol.d.ts +2 -2
|
@@ -2,6 +2,7 @@ const AUTH_LOGIN_METHOD = 'auth.login';
|
|
|
2
2
|
const USER_GET_INFO_METHOD = 'user.getInfo';
|
|
3
3
|
const USER_REVOKE_AUTHORIZATION_METHOD = 'user.revokeAuthorization';
|
|
4
4
|
const USER_GET_STEAM_GAME_LIST_METHOD = 'user.getSteamGameList';
|
|
5
|
+
const SHARE_COPY_LINK_METHOD = 'share.copyLink';
|
|
5
6
|
const SHARE_SHOW_SHARE_MENU_METHOD = 'share.showShareMenu';
|
|
6
7
|
const SHARE_SCREENSHOT_METHOD = 'share.screenshot';
|
|
7
8
|
const VIEWPORT_GET_WINDOW_INFO_METHOD = 'viewport.getWindowInfo';
|
|
@@ -39,6 +40,7 @@ const MINI_PROGRAM_PROTOCOL_CAPABILITIES = [
|
|
|
39
40
|
permission: 'user.platformAccount.steam',
|
|
40
41
|
risk: 'high',
|
|
41
42
|
},
|
|
43
|
+
{ method: SHARE_COPY_LINK_METHOD, module: 'share', capability: SHARE_COPY_LINK_METHOD, permission: 'share.copyLink', risk: 'medium' },
|
|
42
44
|
{ method: SHARE_SHOW_SHARE_MENU_METHOD, module: 'share', capability: SHARE_SHOW_SHARE_MENU_METHOD, permission: 'share.basic', risk: 'low' },
|
|
43
45
|
{ method: SHARE_SCREENSHOT_METHOD, module: 'share', capability: SHARE_SCREENSHOT_METHOD, permission: 'share.screenshot', risk: 'medium' },
|
|
44
46
|
{
|
|
@@ -216,11 +218,18 @@ function readBrowserEnvironment() {
|
|
|
216
218
|
return { activeElement: null };
|
|
217
219
|
}
|
|
218
220
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
221
|
+
const USER_GESTURE_TTL_MS = 1000;
|
|
222
|
+
/** 优先使用 User Activation;旧版 WebView 使用带时效的 iframe 焦点回退。 */
|
|
223
|
+
function computeTrustedIframeUserGesture(iframe, environment = readBrowserEnvironment()) {
|
|
224
|
+
if (environment.userActivation) {
|
|
225
|
+
return environment.userActivation.isActive === true;
|
|
226
|
+
}
|
|
227
|
+
const lastUserInteractionAt = environment.lastUserInteractionAt;
|
|
228
|
+
const now = environment.now ?? Date.now();
|
|
229
|
+
return (environment.activeElement === iframe
|
|
230
|
+
&& lastUserInteractionAt !== undefined
|
|
231
|
+
&& now >= lastUserInteractionAt
|
|
232
|
+
&& now - lastUserInteractionAt <= USER_GESTURE_TTL_MS);
|
|
224
233
|
}
|
|
225
234
|
|
|
226
235
|
const RUNTIME_GATE_PROBE_METHOD = 'runtime.gate.probe';
|
|
@@ -238,6 +247,7 @@ class MiniProgramBridgeServer {
|
|
|
238
247
|
this.onDuplicateHandshake = options.onDuplicateHandshake;
|
|
239
248
|
this.onInternalEvent = options.onInternalEvent;
|
|
240
249
|
this.handleMessage = this.onMessage.bind(this);
|
|
250
|
+
this.handleUserInteraction = this.onUserInteraction.bind(this);
|
|
241
251
|
this.dispatcher = options.dispatcher;
|
|
242
252
|
this.targetOrigin = options.targetOrigin || '*';
|
|
243
253
|
}
|
|
@@ -248,6 +258,9 @@ class MiniProgramBridgeServer {
|
|
|
248
258
|
}
|
|
249
259
|
this.started = true;
|
|
250
260
|
window.addEventListener('message', this.handleMessage);
|
|
261
|
+
for (const eventName of ['pointerdown', 'touchend', 'mousedown', 'keydown']) {
|
|
262
|
+
window.addEventListener(eventName, this.handleUserInteraction, true);
|
|
263
|
+
}
|
|
251
264
|
}
|
|
252
265
|
/** 设置发送给 iframe 的 targetOrigin。 */
|
|
253
266
|
setTargetOrigin(targetOrigin) {
|
|
@@ -263,6 +276,10 @@ class MiniProgramBridgeServer {
|
|
|
263
276
|
timestamp: Date.now(),
|
|
264
277
|
});
|
|
265
278
|
window.removeEventListener('message', this.handleMessage);
|
|
279
|
+
for (const eventName of ['pointerdown', 'touchend', 'mousedown', 'keydown']) {
|
|
280
|
+
window.removeEventListener(eventName, this.handleUserInteraction, true);
|
|
281
|
+
}
|
|
282
|
+
this.lastUserInteractionAt = undefined;
|
|
266
283
|
}
|
|
267
284
|
/** 向 iframe 内小程序派发生命周期或业务事件。 */
|
|
268
285
|
postEvent(eventName, payload) {
|
|
@@ -297,13 +314,31 @@ class MiniProgramBridgeServer {
|
|
|
297
314
|
return;
|
|
298
315
|
}
|
|
299
316
|
if (message.type === 'request') {
|
|
300
|
-
|
|
317
|
+
let trustedUserGesture = false;
|
|
318
|
+
try {
|
|
319
|
+
trustedUserGesture = computeTrustedIframeUserGesture(this.iframe, {
|
|
320
|
+
activeElement: document.activeElement,
|
|
321
|
+
userActivation: navigator.userActivation,
|
|
322
|
+
lastUserInteractionAt: this.lastUserInteractionAt,
|
|
323
|
+
now: Date.now(),
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
trustedUserGesture = false;
|
|
328
|
+
}
|
|
329
|
+
this.handleRequest(message, trustedUserGesture);
|
|
301
330
|
return;
|
|
302
331
|
}
|
|
303
332
|
if (message.type === 'event' && this.handshaken) {
|
|
304
333
|
this.onInternalEvent?.(message);
|
|
305
334
|
}
|
|
306
335
|
}
|
|
336
|
+
onUserInteraction(event) {
|
|
337
|
+
const path = typeof event.composedPath === 'function' ? event.composedPath() : [];
|
|
338
|
+
if (event.target === this.iframe || path.includes(this.iframe)) {
|
|
339
|
+
this.lastUserInteractionAt = Date.now();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
307
342
|
isTrustedMiniProgramMessage(event) {
|
|
308
343
|
return (event.source === this.iframe.contentWindow &&
|
|
309
344
|
isMiniProgramBridgeMessage(event.data) &&
|
|
@@ -412,6 +447,7 @@ const HOST_METHOD_PRIMITIVE_REQUIREMENTS = {
|
|
|
412
447
|
[USER_GET_INFO_METHOD]: ['account.getCurrentUserId', 'account.onChange', 'network.request'],
|
|
413
448
|
[USER_REVOKE_AUTHORIZATION_METHOD]: ['account.getCurrentUserId', 'account.onChange', 'network.request'],
|
|
414
449
|
[USER_GET_STEAM_GAME_LIST_METHOD]: ['account.getCurrentUserId', 'account.onChange', 'network.request'],
|
|
450
|
+
[SHARE_COPY_LINK_METHOD]: ['presentation.setClipboard'],
|
|
415
451
|
[SHARE_SHOW_SHARE_MENU_METHOD]: ['presentation.showShareMenu'],
|
|
416
452
|
[SHARE_SCREENSHOT_METHOD]: ['presentation.getViewportMetrics', 'presentation.captureAndShare'],
|
|
417
453
|
[VIEWPORT_GET_WINDOW_INFO_METHOD]: ['presentation.getViewportMetrics', 'presentation.getNavigationBarHeight'],
|
|
@@ -624,6 +660,64 @@ function parseAPIResponse(response, fallbackMessage) {
|
|
|
624
660
|
return data;
|
|
625
661
|
}
|
|
626
662
|
|
|
663
|
+
/**
|
|
664
|
+
* @packageDocumentation
|
|
665
|
+
* 定义 AccountUserBaseInfo 接口的 Runtime endpoint 契约。
|
|
666
|
+
*/
|
|
667
|
+
/**
|
|
668
|
+
* AccountUserBaseInfo 原始信封 endpoint。
|
|
669
|
+
*
|
|
670
|
+
* @remarks
|
|
671
|
+
* 供需要区分 `login`、`relogin` 等认证状态的领域服务使用;调用输入仍为 `void`,
|
|
672
|
+
* wire path 只由本 API contract owner 维护。
|
|
673
|
+
*/
|
|
674
|
+
const accountUserBaseInfoEnvelopeEndpoint = {
|
|
675
|
+
auth: 'optional',
|
|
676
|
+
channel: 'api',
|
|
677
|
+
id: 'heybox.account.user_base_info.envelope.get',
|
|
678
|
+
method: 'GET',
|
|
679
|
+
path: '/account/get_user_base_info',
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* @packageDocumentation
|
|
684
|
+
* 定义 UserMiniprogramPublicDetail 接口的 Runtime endpoint 契约。
|
|
685
|
+
*/
|
|
686
|
+
/** 用户侧工坊小程序详情 endpoint。 */
|
|
687
|
+
const userMiniprogramPublicDetailEndpoint = {
|
|
688
|
+
auth: 'optional',
|
|
689
|
+
channel: 'api',
|
|
690
|
+
failurePresentation: 'none',
|
|
691
|
+
id: 'heybox.user_miniprogram.public.detail.get',
|
|
692
|
+
method: 'GET',
|
|
693
|
+
path: '/user_miniprogram/public/detail',
|
|
694
|
+
/**
|
|
695
|
+
* 把业务输入映射为接口 query。
|
|
696
|
+
*
|
|
697
|
+
* @param input - 已由调用方提供的接口输入。
|
|
698
|
+
*/
|
|
699
|
+
query(input) {
|
|
700
|
+
return {
|
|
701
|
+
mini_program_id: input.mini_program_id,
|
|
702
|
+
...(input.miniprogram_version ? { miniprogram_version: input.miniprogram_version } : {}),
|
|
703
|
+
...(input.preview_token ? { preview_token: input.preview_token } : {}),
|
|
704
|
+
...(input.local_dev_launch_token ? { local_dev_launch_token: input.local_dev_launch_token } : {}),
|
|
705
|
+
...(input.entry ? { entry: input.entry } : {}),
|
|
706
|
+
...(input.h_src_parent ? { h_src_parent: input.h_src_parent } : {}),
|
|
707
|
+
...(input.extra !== undefined ? { extra: input.extra } : {}),
|
|
708
|
+
};
|
|
709
|
+
},
|
|
710
|
+
/**
|
|
711
|
+
* 保留标准响应信封,由迁移页维持旧 `status` 分支语义。
|
|
712
|
+
*
|
|
713
|
+
* @param response - Runtime request pipeline 返回的 transport 响应。
|
|
714
|
+
* @param _input - 当前 endpoint 输入;解析响应时无需读取。
|
|
715
|
+
*/
|
|
716
|
+
parse(response, _input) {
|
|
717
|
+
return parseAPIResponse(response, '工坊小程序详情加载失败');
|
|
718
|
+
},
|
|
719
|
+
};
|
|
720
|
+
|
|
627
721
|
function runtimeContextBody(runtimeContext) {
|
|
628
722
|
return { mini_program_id: runtimeContext.miniProgramId };
|
|
629
723
|
}
|
|
@@ -964,6 +1058,7 @@ async function requestEndpoint(network, endpoint, input, context) {
|
|
|
964
1058
|
}
|
|
965
1059
|
|
|
966
1060
|
const USER_INFO_AUTHORIZATION_SCOPE_SET = new Set(USER_INFO_AUTHORIZATION_SCOPES);
|
|
1061
|
+
const AUTHORIZATION_PRESENTATION_DETAILS_TIMEOUT_MS = 1000;
|
|
967
1062
|
function createAuthorizationCoordinator(options) {
|
|
968
1063
|
const listeners = new Set();
|
|
969
1064
|
const localIdentityCache = new Map();
|
|
@@ -972,13 +1067,18 @@ function createAuthorizationCoordinator(options) {
|
|
|
972
1067
|
let generation = 0;
|
|
973
1068
|
let disposed = false;
|
|
974
1069
|
let presentationQueue = Promise.resolve();
|
|
1070
|
+
let activePresentationController;
|
|
975
1071
|
const unsubscribeAccount = options.account.onChange((userId) => {
|
|
1072
|
+
invalidateAuthorizationContext();
|
|
1073
|
+
emit('heybox_app_login_change', { isHeyboxAppLoggedIn: Boolean(userId) });
|
|
1074
|
+
});
|
|
1075
|
+
function invalidateAuthorizationContext() {
|
|
976
1076
|
generation += 1;
|
|
1077
|
+
activePresentationController?.abort();
|
|
977
1078
|
localIdentityCache.clear();
|
|
978
1079
|
localIdentityInflight.clear();
|
|
979
1080
|
grantedScopes.clear();
|
|
980
|
-
|
|
981
|
-
});
|
|
1081
|
+
}
|
|
982
1082
|
function emit(name, payload) {
|
|
983
1083
|
for (const listener of listeners) {
|
|
984
1084
|
try {
|
|
@@ -1036,12 +1136,14 @@ function createAuthorizationCoordinator(options) {
|
|
|
1036
1136
|
}
|
|
1037
1137
|
return userId;
|
|
1038
1138
|
}
|
|
1039
|
-
async function request(endpoint, input) {
|
|
1139
|
+
async function request(endpoint, input, signal = options.operationContext.signal) {
|
|
1040
1140
|
try {
|
|
1041
|
-
|
|
1141
|
+
if (signal.aborted)
|
|
1142
|
+
throw createAbortError$3();
|
|
1143
|
+
return await waitForAbortableOperation(requestEndpoint(options.network, endpoint, input, {
|
|
1042
1144
|
credentials: 'heybox-session',
|
|
1043
|
-
signal
|
|
1044
|
-
});
|
|
1145
|
+
signal,
|
|
1146
|
+
}), signal);
|
|
1045
1147
|
}
|
|
1046
1148
|
catch (error) {
|
|
1047
1149
|
if (options.operationContext.signal.aborted) {
|
|
@@ -1071,7 +1173,19 @@ function createAuthorizationCoordinator(options) {
|
|
|
1071
1173
|
}).catch(() => undefined);
|
|
1072
1174
|
}
|
|
1073
1175
|
function runPresentation(operation) {
|
|
1074
|
-
const
|
|
1176
|
+
const run = async () => {
|
|
1177
|
+
const controller = createLinkedAbortController(options.operationContext.signal);
|
|
1178
|
+
activePresentationController = controller;
|
|
1179
|
+
try {
|
|
1180
|
+
return await operation(controller.signal);
|
|
1181
|
+
}
|
|
1182
|
+
finally {
|
|
1183
|
+
if (activePresentationController === controller)
|
|
1184
|
+
activePresentationController = undefined;
|
|
1185
|
+
controller.abort();
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
const result = presentationQueue.then(run, run);
|
|
1075
1189
|
presentationQueue = result.then(() => undefined, () => undefined);
|
|
1076
1190
|
return result;
|
|
1077
1191
|
}
|
|
@@ -1084,14 +1198,17 @@ function createAuthorizationCoordinator(options) {
|
|
|
1084
1198
|
await cancelAuthorization(miniProgramId, challengeValue.challenge);
|
|
1085
1199
|
throw createCapabilityBridgeError('AUTHORIZATION_PRESENTATION_UNAVAILABLE', '授权确认界面不可用');
|
|
1086
1200
|
}
|
|
1087
|
-
return runPresentation(async () => {
|
|
1201
|
+
return runPresentation(async (presentationSignal) => {
|
|
1202
|
+
await assertAuthorizationContext(expectedUserId, expectedGeneration);
|
|
1203
|
+
const presentationDetails = await loadAuthorizationPresentationDetails(miniProgramId, challengeValue.displayedScopes, presentationSignal);
|
|
1088
1204
|
await assertAuthorizationContext(expectedUserId, expectedGeneration);
|
|
1089
1205
|
let decision;
|
|
1090
1206
|
try {
|
|
1091
1207
|
decision = await options.authPresentation.confirmAuthorization({
|
|
1092
1208
|
miniProgramId,
|
|
1093
1209
|
scopes: challengeValue.displayedScopes,
|
|
1094
|
-
|
|
1210
|
+
...presentationDetails,
|
|
1211
|
+
signal: presentationSignal,
|
|
1095
1212
|
});
|
|
1096
1213
|
}
|
|
1097
1214
|
catch (error) {
|
|
@@ -1115,6 +1232,53 @@ function createAuthorizationCoordinator(options) {
|
|
|
1115
1232
|
return selectedScopes;
|
|
1116
1233
|
});
|
|
1117
1234
|
}
|
|
1235
|
+
async function loadAuthorizationPresentationDetails(miniProgramId, displayedScopes, presentationSignal) {
|
|
1236
|
+
const detailController = createLinkedAbortController(presentationSignal);
|
|
1237
|
+
const timeout = setTimeout(() => detailController.abort(), AUTHORIZATION_PRESENTATION_DETAILS_TIMEOUT_MS);
|
|
1238
|
+
try {
|
|
1239
|
+
const trustedMiniProgram = normalizeMiniProgramPresentation(options.miniProgramPresentation);
|
|
1240
|
+
const [miniProgram, userProfile] = await Promise.all([
|
|
1241
|
+
trustedMiniProgram ? Promise.resolve(trustedMiniProgram) : loadMiniProgramPresentation(miniProgramId, detailController.signal),
|
|
1242
|
+
displayedScopes.includes('profile') ? loadUserProfilePresentation(detailController.signal) : Promise.resolve(undefined),
|
|
1243
|
+
]);
|
|
1244
|
+
return {
|
|
1245
|
+
...(miniProgram ? { miniProgram } : {}),
|
|
1246
|
+
...(userProfile ? { userProfile } : {}),
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
finally {
|
|
1250
|
+
clearTimeout(timeout);
|
|
1251
|
+
detailController.abort();
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async function loadMiniProgramPresentation(miniProgramId, signal) {
|
|
1255
|
+
try {
|
|
1256
|
+
const version = options.identity.get()?.version?.trim();
|
|
1257
|
+
const envelope = await request(userMiniprogramPublicDetailEndpoint, {
|
|
1258
|
+
mini_program_id: miniProgramId,
|
|
1259
|
+
...(version ? { miniprogram_version: version } : {}),
|
|
1260
|
+
}, signal);
|
|
1261
|
+
const result = readSuccessfulResult$3(envelope, '小程序公开资料');
|
|
1262
|
+
const name = readOptionalPresentationText(result.name);
|
|
1263
|
+
const avatarUrl = readOptionalPresentationText(result.icon_url);
|
|
1264
|
+
return name || avatarUrl ? { ...(name ? { name } : {}), ...(avatarUrl ? { avatarUrl } : {}) } : undefined;
|
|
1265
|
+
}
|
|
1266
|
+
catch {
|
|
1267
|
+
return undefined;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
async function loadUserProfilePresentation(signal) {
|
|
1271
|
+
try {
|
|
1272
|
+
const envelope = await request(accountUserBaseInfoEnvelopeEndpoint, undefined, signal);
|
|
1273
|
+
const result = readSuccessfulResult$3(envelope, '账号基础信息');
|
|
1274
|
+
const nickname = readOptionalPresentationText(result.display_username);
|
|
1275
|
+
const avatar = readOptionalPresentationText(result.display_avatar);
|
|
1276
|
+
return nickname || avatar ? { ...(nickname ? { nickname } : {}), ...(avatar ? { avatar } : {}) } : undefined;
|
|
1277
|
+
}
|
|
1278
|
+
catch {
|
|
1279
|
+
return undefined;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1118
1282
|
async function login(scopes, trustedUserGesture) {
|
|
1119
1283
|
const miniProgramId = requireCanonicalMiniProgramId();
|
|
1120
1284
|
const userId = await requireAuthenticatedUser(trustedUserGesture);
|
|
@@ -1231,10 +1395,7 @@ function createAuthorizationCoordinator(options) {
|
|
|
1231
1395
|
});
|
|
1232
1396
|
await assertAuthorizationContext(userId, expectedGeneration);
|
|
1233
1397
|
readSuccessfulResult$3(envelope, '用户授权撤销');
|
|
1234
|
-
|
|
1235
|
-
localIdentityCache.clear();
|
|
1236
|
-
localIdentityInflight.clear();
|
|
1237
|
-
grantedScopes.clear();
|
|
1398
|
+
invalidateAuthorizationContext();
|
|
1238
1399
|
emit('user_info_authorization_change', { identity: 'denied', profile: 'denied' });
|
|
1239
1400
|
return undefined;
|
|
1240
1401
|
}
|
|
@@ -1251,11 +1412,8 @@ function createAuthorizationCoordinator(options) {
|
|
|
1251
1412
|
if (disposed)
|
|
1252
1413
|
return;
|
|
1253
1414
|
disposed = true;
|
|
1254
|
-
|
|
1415
|
+
invalidateAuthorizationContext();
|
|
1255
1416
|
unsubscribeAccount();
|
|
1256
|
-
localIdentityCache.clear();
|
|
1257
|
-
localIdentityInflight.clear();
|
|
1258
|
-
grantedScopes.clear();
|
|
1259
1417
|
listeners.clear();
|
|
1260
1418
|
},
|
|
1261
1419
|
};
|
|
@@ -1339,6 +1497,46 @@ function validateSelectedScopes(scopes, displayedScopes) {
|
|
|
1339
1497
|
}
|
|
1340
1498
|
return selected;
|
|
1341
1499
|
}
|
|
1500
|
+
function readOptionalPresentationText(value) {
|
|
1501
|
+
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
|
1502
|
+
}
|
|
1503
|
+
function normalizeMiniProgramPresentation(value) {
|
|
1504
|
+
const name = readOptionalPresentationText(value?.name);
|
|
1505
|
+
const avatarUrl = readOptionalPresentationText(value?.avatarUrl);
|
|
1506
|
+
return name || avatarUrl ? { ...(name ? { name } : {}), ...(avatarUrl ? { avatarUrl } : {}) } : undefined;
|
|
1507
|
+
}
|
|
1508
|
+
function createLinkedAbortController(parent) {
|
|
1509
|
+
const controller = new AbortController();
|
|
1510
|
+
if (parent.aborted) {
|
|
1511
|
+
controller.abort(parent.reason);
|
|
1512
|
+
}
|
|
1513
|
+
else {
|
|
1514
|
+
parent.addEventListener('abort', () => controller.abort(parent.reason), { once: true, signal: controller.signal });
|
|
1515
|
+
}
|
|
1516
|
+
return controller;
|
|
1517
|
+
}
|
|
1518
|
+
function waitForAbortableOperation(operation, signal) {
|
|
1519
|
+
if (signal.aborted)
|
|
1520
|
+
return Promise.reject(createAbortError$3());
|
|
1521
|
+
return new Promise((resolve, reject) => {
|
|
1522
|
+
let settled = false;
|
|
1523
|
+
const settle = (callback) => {
|
|
1524
|
+
if (settled)
|
|
1525
|
+
return;
|
|
1526
|
+
settled = true;
|
|
1527
|
+
signal.removeEventListener('abort', onAbort);
|
|
1528
|
+
callback();
|
|
1529
|
+
};
|
|
1530
|
+
const onAbort = () => settle(() => reject(createAbortError$3()));
|
|
1531
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
1532
|
+
operation.then((value) => settle(() => resolve(value)), (error) => settle(() => reject(error)));
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
function createAbortError$3() {
|
|
1536
|
+
const error = new Error('The operation was aborted');
|
|
1537
|
+
error.name = 'AbortError';
|
|
1538
|
+
return error;
|
|
1539
|
+
}
|
|
1342
1540
|
function validateScopeArray(value, label) {
|
|
1343
1541
|
if (!Array.isArray(value) ||
|
|
1344
1542
|
value.some((scope) => typeof scope !== 'string' || !USER_INFO_AUTHORIZATION_SCOPE_SET.has(scope)) ||
|
|
@@ -2686,6 +2884,1009 @@ function bridgeError$2(code, message) {
|
|
|
2686
2884
|
return { code, message };
|
|
2687
2885
|
}
|
|
2688
2886
|
|
|
2887
|
+
function utf8Count(str) {
|
|
2888
|
+
const strLength = str.length;
|
|
2889
|
+
let byteLength = 0;
|
|
2890
|
+
let pos = 0;
|
|
2891
|
+
while (pos < strLength) {
|
|
2892
|
+
let value = str.charCodeAt(pos++);
|
|
2893
|
+
if ((value & 0xffffff80) === 0) {
|
|
2894
|
+
// 1-byte
|
|
2895
|
+
byteLength++;
|
|
2896
|
+
continue;
|
|
2897
|
+
}
|
|
2898
|
+
else if ((value & 0xfffff800) === 0) {
|
|
2899
|
+
// 2-bytes
|
|
2900
|
+
byteLength += 2;
|
|
2901
|
+
}
|
|
2902
|
+
else {
|
|
2903
|
+
// handle surrogate pair
|
|
2904
|
+
if (value >= 0xd800 && value <= 0xdbff) {
|
|
2905
|
+
// high surrogate
|
|
2906
|
+
if (pos < strLength) {
|
|
2907
|
+
const extra = str.charCodeAt(pos);
|
|
2908
|
+
if ((extra & 0xfc00) === 0xdc00) {
|
|
2909
|
+
++pos;
|
|
2910
|
+
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
if ((value & 0xffff0000) === 0) {
|
|
2915
|
+
// 3-byte
|
|
2916
|
+
byteLength += 3;
|
|
2917
|
+
}
|
|
2918
|
+
else {
|
|
2919
|
+
// 4-byte
|
|
2920
|
+
byteLength += 4;
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
}
|
|
2924
|
+
return byteLength;
|
|
2925
|
+
}
|
|
2926
|
+
function utf8EncodeJs(str, output, outputOffset) {
|
|
2927
|
+
const strLength = str.length;
|
|
2928
|
+
let offset = outputOffset;
|
|
2929
|
+
let pos = 0;
|
|
2930
|
+
while (pos < strLength) {
|
|
2931
|
+
let value = str.charCodeAt(pos++);
|
|
2932
|
+
if ((value & 0xffffff80) === 0) {
|
|
2933
|
+
// 1-byte
|
|
2934
|
+
output[offset++] = value;
|
|
2935
|
+
continue;
|
|
2936
|
+
}
|
|
2937
|
+
else if ((value & 0xfffff800) === 0) {
|
|
2938
|
+
// 2-bytes
|
|
2939
|
+
output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
|
|
2940
|
+
}
|
|
2941
|
+
else {
|
|
2942
|
+
// handle surrogate pair
|
|
2943
|
+
if (value >= 0xd800 && value <= 0xdbff) {
|
|
2944
|
+
// high surrogate
|
|
2945
|
+
if (pos < strLength) {
|
|
2946
|
+
const extra = str.charCodeAt(pos);
|
|
2947
|
+
if ((extra & 0xfc00) === 0xdc00) {
|
|
2948
|
+
++pos;
|
|
2949
|
+
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
if ((value & 0xffff0000) === 0) {
|
|
2954
|
+
// 3-byte
|
|
2955
|
+
output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
|
|
2956
|
+
output[offset++] = ((value >> 6) & 0x3f) | 0x80;
|
|
2957
|
+
}
|
|
2958
|
+
else {
|
|
2959
|
+
// 4-byte
|
|
2960
|
+
output[offset++] = ((value >> 18) & 0x07) | 0xf0;
|
|
2961
|
+
output[offset++] = ((value >> 12) & 0x3f) | 0x80;
|
|
2962
|
+
output[offset++] = ((value >> 6) & 0x3f) | 0x80;
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
output[offset++] = (value & 0x3f) | 0x80;
|
|
2966
|
+
}
|
|
2967
|
+
}
|
|
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));
|
|
2980
|
+
}
|
|
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
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
const CHUNK_SIZE = 4096;
|
|
2990
|
+
function utf8DecodeJs(bytes, inputOffset, byteLength) {
|
|
2991
|
+
let offset = inputOffset;
|
|
2992
|
+
const end = offset + byteLength;
|
|
2993
|
+
const units = [];
|
|
2994
|
+
let result = "";
|
|
2995
|
+
while (offset < end) {
|
|
2996
|
+
const byte1 = bytes[offset++];
|
|
2997
|
+
if ((byte1 & 0x80) === 0) {
|
|
2998
|
+
// 1 byte
|
|
2999
|
+
units.push(byte1);
|
|
3000
|
+
}
|
|
3001
|
+
else if ((byte1 & 0xe0) === 0xc0) {
|
|
3002
|
+
// 2 bytes
|
|
3003
|
+
const byte2 = bytes[offset++] & 0x3f;
|
|
3004
|
+
units.push(((byte1 & 0x1f) << 6) | byte2);
|
|
3005
|
+
}
|
|
3006
|
+
else if ((byte1 & 0xf0) === 0xe0) {
|
|
3007
|
+
// 3 bytes
|
|
3008
|
+
const byte2 = bytes[offset++] & 0x3f;
|
|
3009
|
+
const byte3 = bytes[offset++] & 0x3f;
|
|
3010
|
+
units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
|
|
3011
|
+
}
|
|
3012
|
+
else if ((byte1 & 0xf8) === 0xf0) {
|
|
3013
|
+
// 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;
|
|
3018
|
+
if (unit > 0xffff) {
|
|
3019
|
+
unit -= 0x10000;
|
|
3020
|
+
units.push(((unit >>> 10) & 0x3ff) | 0xd800);
|
|
3021
|
+
unit = 0xdc00 | (unit & 0x3ff);
|
|
3022
|
+
}
|
|
3023
|
+
units.push(unit);
|
|
3024
|
+
}
|
|
3025
|
+
else {
|
|
3026
|
+
units.push(byte1);
|
|
3027
|
+
}
|
|
3028
|
+
if (units.length >= CHUNK_SIZE) {
|
|
3029
|
+
result += String.fromCharCode(...units);
|
|
3030
|
+
units.length = 0;
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
if (units.length > 0) {
|
|
3034
|
+
result += String.fromCharCode(...units);
|
|
3035
|
+
}
|
|
3036
|
+
return result;
|
|
3037
|
+
}
|
|
3038
|
+
new TextDecoder();
|
|
3039
|
+
|
|
3040
|
+
/**
|
|
3041
|
+
* ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
|
|
3042
|
+
*/
|
|
3043
|
+
class ExtData {
|
|
3044
|
+
type;
|
|
3045
|
+
data;
|
|
3046
|
+
constructor(type, data) {
|
|
3047
|
+
this.type = type;
|
|
3048
|
+
this.data = data;
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
class DecodeError extends Error {
|
|
3053
|
+
constructor(message) {
|
|
3054
|
+
super(message);
|
|
3055
|
+
// 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", {
|
|
3059
|
+
configurable: true,
|
|
3060
|
+
enumerable: false,
|
|
3061
|
+
value: DecodeError.name,
|
|
3062
|
+
});
|
|
3063
|
+
}
|
|
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
|
+
}
|
|
3086
|
+
|
|
3087
|
+
// 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 }) {
|
|
3092
|
+
if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
|
|
3093
|
+
// Here sec >= 0 && nsec >= 0
|
|
3094
|
+
if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
|
|
3095
|
+
// timestamp 32 = { sec32 (unsigned) }
|
|
3096
|
+
const rv = new Uint8Array(4);
|
|
3097
|
+
const view = new DataView(rv.buffer);
|
|
3098
|
+
view.setUint32(0, sec);
|
|
3099
|
+
return rv;
|
|
3100
|
+
}
|
|
3101
|
+
else {
|
|
3102
|
+
// 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);
|
|
3107
|
+
// nsec30 | secHigh2
|
|
3108
|
+
view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
|
|
3109
|
+
// secLow32
|
|
3110
|
+
view.setUint32(4, secLow);
|
|
3111
|
+
return rv;
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
else {
|
|
3115
|
+
// timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
|
|
3116
|
+
const rv = new Uint8Array(12);
|
|
3117
|
+
const view = new DataView(rv.buffer);
|
|
3118
|
+
view.setUint32(0, nsec);
|
|
3119
|
+
setInt64(view, 4, sec);
|
|
3120
|
+
return rv;
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
function encodeDateToTimeSpec(date) {
|
|
3124
|
+
const msec = date.getTime();
|
|
3125
|
+
const sec = Math.floor(msec / 1e3);
|
|
3126
|
+
const nsec = (msec - sec * 1e3) * 1e6;
|
|
3127
|
+
// Normalizes { sec, nsec } to ensure nsec is unsigned.
|
|
3128
|
+
const nsecInSec = Math.floor(nsec / 1e9);
|
|
3129
|
+
return {
|
|
3130
|
+
sec: sec + nsecInSec,
|
|
3131
|
+
nsec: nsec - nsecInSec * 1e9,
|
|
3132
|
+
};
|
|
3133
|
+
}
|
|
3134
|
+
function encodeTimestampExtension(object) {
|
|
3135
|
+
if (object instanceof Date) {
|
|
3136
|
+
const timeSpec = encodeDateToTimeSpec(object);
|
|
3137
|
+
return encodeTimeSpecToTimestamp(timeSpec);
|
|
3138
|
+
}
|
|
3139
|
+
else {
|
|
3140
|
+
return null;
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
function decodeTimestampToTimeSpec(data) {
|
|
3144
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
3145
|
+
// data may be 32, 64, or 96 bits
|
|
3146
|
+
switch (data.byteLength) {
|
|
3147
|
+
case 4: {
|
|
3148
|
+
// timestamp 32 = { sec32 }
|
|
3149
|
+
const sec = view.getUint32(0);
|
|
3150
|
+
const nsec = 0;
|
|
3151
|
+
return { sec, nsec };
|
|
3152
|
+
}
|
|
3153
|
+
case 8: {
|
|
3154
|
+
// 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 };
|
|
3160
|
+
}
|
|
3161
|
+
case 12: {
|
|
3162
|
+
// timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
|
|
3163
|
+
const sec = getInt64(view, 4);
|
|
3164
|
+
const nsec = view.getUint32(0);
|
|
3165
|
+
return { sec, nsec };
|
|
3166
|
+
}
|
|
3167
|
+
default:
|
|
3168
|
+
throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
function decodeTimestampExtension(data) {
|
|
3172
|
+
const timeSpec = decodeTimestampToTimeSpec(data);
|
|
3173
|
+
return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
|
|
3174
|
+
}
|
|
3175
|
+
const timestampExtension = {
|
|
3176
|
+
type: EXT_TIMESTAMP,
|
|
3177
|
+
encode: encodeTimestampExtension,
|
|
3178
|
+
decode: decodeTimestampExtension,
|
|
3179
|
+
};
|
|
3180
|
+
|
|
3181
|
+
// 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() {
|
|
3195
|
+
this.register(timestampExtension);
|
|
3196
|
+
}
|
|
3197
|
+
register({ type, encode, decode, }) {
|
|
3198
|
+
if (type >= 0) {
|
|
3199
|
+
// custom extensions
|
|
3200
|
+
this.encoders[type] = encode;
|
|
3201
|
+
this.decoders[type] = decode;
|
|
3202
|
+
}
|
|
3203
|
+
else {
|
|
3204
|
+
// built-in extensions
|
|
3205
|
+
const index = -1 - type;
|
|
3206
|
+
this.builtInEncoders[index] = encode;
|
|
3207
|
+
this.builtInDecoders[index] = decode;
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
tryToEncode(object, context) {
|
|
3211
|
+
// built-in extensions
|
|
3212
|
+
for (let i = 0; i < this.builtInEncoders.length; i++) {
|
|
3213
|
+
const encodeExt = this.builtInEncoders[i];
|
|
3214
|
+
if (encodeExt != null) {
|
|
3215
|
+
const data = encodeExt(object, context);
|
|
3216
|
+
if (data != null) {
|
|
3217
|
+
const type = -1 - i;
|
|
3218
|
+
return new ExtData(type, data);
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
// custom extensions
|
|
3223
|
+
for (let i = 0; i < this.encoders.length; i++) {
|
|
3224
|
+
const encodeExt = this.encoders[i];
|
|
3225
|
+
if (encodeExt != null) {
|
|
3226
|
+
const data = encodeExt(object, context);
|
|
3227
|
+
if (data != null) {
|
|
3228
|
+
const type = i;
|
|
3229
|
+
return new ExtData(type, data);
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
if (object instanceof ExtData) {
|
|
3234
|
+
// to keep ExtData as is
|
|
3235
|
+
return object;
|
|
3236
|
+
}
|
|
3237
|
+
return null;
|
|
3238
|
+
}
|
|
3239
|
+
decode(data, type, context) {
|
|
3240
|
+
const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
|
|
3241
|
+
if (decodeExt) {
|
|
3242
|
+
return decodeExt(data, type, context);
|
|
3243
|
+
}
|
|
3244
|
+
else {
|
|
3245
|
+
// decode() does not fail, returns ExtData instead.
|
|
3246
|
+
return new ExtData(type, data);
|
|
3247
|
+
}
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
|
|
3251
|
+
function isArrayBufferLike(buffer) {
|
|
3252
|
+
return (buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer));
|
|
3253
|
+
}
|
|
3254
|
+
function ensureUint8Array(buffer) {
|
|
3255
|
+
if (buffer instanceof Uint8Array) {
|
|
3256
|
+
return buffer;
|
|
3257
|
+
}
|
|
3258
|
+
else if (ArrayBuffer.isView(buffer)) {
|
|
3259
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
3260
|
+
}
|
|
3261
|
+
else if (isArrayBufferLike(buffer)) {
|
|
3262
|
+
return new Uint8Array(buffer);
|
|
3263
|
+
}
|
|
3264
|
+
else {
|
|
3265
|
+
// ArrayLike<number>
|
|
3266
|
+
return Uint8Array.from(buffer);
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
|
|
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;
|
|
3296
|
+
this.pos = 0;
|
|
3297
|
+
this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
|
|
3298
|
+
this.bytes = new Uint8Array(this.view.buffer);
|
|
3299
|
+
}
|
|
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() {
|
|
3317
|
+
this.pos = 0;
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* 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
|
+
*
|
|
3322
|
+
* @returns Encodes the object and returns a shared reference the encoder's internal buffer.
|
|
3323
|
+
*/
|
|
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
|
+
}
|
|
3339
|
+
/**
|
|
3340
|
+
* @returns Encodes the object and returns a copy of the encoder's internal buffer.
|
|
3341
|
+
*/
|
|
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) {
|
|
3358
|
+
if (depth > this.maxDepth) {
|
|
3359
|
+
throw new Error(`Too deep objects in depth ${depth}`);
|
|
3360
|
+
}
|
|
3361
|
+
if (object == null) {
|
|
3362
|
+
this.encodeNil();
|
|
3363
|
+
}
|
|
3364
|
+
else if (typeof object === "boolean") {
|
|
3365
|
+
this.encodeBoolean(object);
|
|
3366
|
+
}
|
|
3367
|
+
else if (typeof object === "number") {
|
|
3368
|
+
if (!this.forceIntegerToFloat) {
|
|
3369
|
+
this.encodeNumber(object);
|
|
3370
|
+
}
|
|
3371
|
+
else {
|
|
3372
|
+
this.encodeNumberAsFloat(object);
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
else if (typeof object === "string") {
|
|
3376
|
+
this.encodeString(object);
|
|
3377
|
+
}
|
|
3378
|
+
else if (this.useBigInt64 && typeof object === "bigint") {
|
|
3379
|
+
this.encodeBigInt64(object);
|
|
3380
|
+
}
|
|
3381
|
+
else {
|
|
3382
|
+
this.encodeObject(object, depth);
|
|
3383
|
+
}
|
|
3384
|
+
}
|
|
3385
|
+
ensureBufferSizeToWrite(sizeToWrite) {
|
|
3386
|
+
const requiredSize = this.pos + sizeToWrite;
|
|
3387
|
+
if (this.view.byteLength < requiredSize) {
|
|
3388
|
+
this.resizeBuffer(requiredSize * 2);
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
resizeBuffer(newSize) {
|
|
3392
|
+
const newBuffer = new ArrayBuffer(newSize);
|
|
3393
|
+
const newBytes = new Uint8Array(newBuffer);
|
|
3394
|
+
const newView = new DataView(newBuffer);
|
|
3395
|
+
newBytes.set(this.bytes);
|
|
3396
|
+
this.view = newView;
|
|
3397
|
+
this.bytes = newBytes;
|
|
3398
|
+
}
|
|
3399
|
+
encodeNil() {
|
|
3400
|
+
this.writeU8(0xc0);
|
|
3401
|
+
}
|
|
3402
|
+
encodeBoolean(object) {
|
|
3403
|
+
if (object === false) {
|
|
3404
|
+
this.writeU8(0xc2);
|
|
3405
|
+
}
|
|
3406
|
+
else {
|
|
3407
|
+
this.writeU8(0xc3);
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
encodeNumber(object) {
|
|
3411
|
+
if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
|
|
3412
|
+
if (object >= 0) {
|
|
3413
|
+
if (object < 0x80) {
|
|
3414
|
+
// positive fixint
|
|
3415
|
+
this.writeU8(object);
|
|
3416
|
+
}
|
|
3417
|
+
else if (object < 0x100) {
|
|
3418
|
+
// uint 8
|
|
3419
|
+
this.writeU8(0xcc);
|
|
3420
|
+
this.writeU8(object);
|
|
3421
|
+
}
|
|
3422
|
+
else if (object < 0x10000) {
|
|
3423
|
+
// uint 16
|
|
3424
|
+
this.writeU8(0xcd);
|
|
3425
|
+
this.writeU16(object);
|
|
3426
|
+
}
|
|
3427
|
+
else if (object < 0x100000000) {
|
|
3428
|
+
// uint 32
|
|
3429
|
+
this.writeU8(0xce);
|
|
3430
|
+
this.writeU32(object);
|
|
3431
|
+
}
|
|
3432
|
+
else if (!this.useBigInt64) {
|
|
3433
|
+
// uint 64
|
|
3434
|
+
this.writeU8(0xcf);
|
|
3435
|
+
this.writeU64(object);
|
|
3436
|
+
}
|
|
3437
|
+
else {
|
|
3438
|
+
this.encodeNumberAsFloat(object);
|
|
3439
|
+
}
|
|
3440
|
+
}
|
|
3441
|
+
else {
|
|
3442
|
+
if (object >= -32) {
|
|
3443
|
+
// negative fixint
|
|
3444
|
+
this.writeU8(0xe0 | (object + 0x20));
|
|
3445
|
+
}
|
|
3446
|
+
else if (object >= -128) {
|
|
3447
|
+
// int 8
|
|
3448
|
+
this.writeU8(0xd0);
|
|
3449
|
+
this.writeI8(object);
|
|
3450
|
+
}
|
|
3451
|
+
else if (object >= -32768) {
|
|
3452
|
+
// int 16
|
|
3453
|
+
this.writeU8(0xd1);
|
|
3454
|
+
this.writeI16(object);
|
|
3455
|
+
}
|
|
3456
|
+
else if (object >= -2147483648) {
|
|
3457
|
+
// int 32
|
|
3458
|
+
this.writeU8(0xd2);
|
|
3459
|
+
this.writeI32(object);
|
|
3460
|
+
}
|
|
3461
|
+
else if (!this.useBigInt64) {
|
|
3462
|
+
// int 64
|
|
3463
|
+
this.writeU8(0xd3);
|
|
3464
|
+
this.writeI64(object);
|
|
3465
|
+
}
|
|
3466
|
+
else {
|
|
3467
|
+
this.encodeNumberAsFloat(object);
|
|
3468
|
+
}
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
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);
|
|
3497
|
+
}
|
|
3498
|
+
}
|
|
3499
|
+
writeStringHeader(byteLength) {
|
|
3500
|
+
if (byteLength < 32) {
|
|
3501
|
+
// fixstr
|
|
3502
|
+
this.writeU8(0xa0 + byteLength);
|
|
3503
|
+
}
|
|
3504
|
+
else if (byteLength < 0x100) {
|
|
3505
|
+
// str 8
|
|
3506
|
+
this.writeU8(0xd9);
|
|
3507
|
+
this.writeU8(byteLength);
|
|
3508
|
+
}
|
|
3509
|
+
else if (byteLength < 0x10000) {
|
|
3510
|
+
// str 16
|
|
3511
|
+
this.writeU8(0xda);
|
|
3512
|
+
this.writeU16(byteLength);
|
|
3513
|
+
}
|
|
3514
|
+
else if (byteLength < 0x100000000) {
|
|
3515
|
+
// str 32
|
|
3516
|
+
this.writeU8(0xdb);
|
|
3517
|
+
this.writeU32(byteLength);
|
|
3518
|
+
}
|
|
3519
|
+
else {
|
|
3520
|
+
throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
|
|
3521
|
+
}
|
|
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) {
|
|
3532
|
+
// try to encode objects with custom codec first of non-primitives
|
|
3533
|
+
const ext = this.extensionCodec.tryToEncode(object, this.context);
|
|
3534
|
+
if (ext != null) {
|
|
3535
|
+
this.encodeExtension(ext);
|
|
3536
|
+
}
|
|
3537
|
+
else if (Array.isArray(object)) {
|
|
3538
|
+
this.encodeArray(object, depth);
|
|
3539
|
+
}
|
|
3540
|
+
else if (ArrayBuffer.isView(object)) {
|
|
3541
|
+
this.encodeBinary(object);
|
|
3542
|
+
}
|
|
3543
|
+
else if (typeof object === "object") {
|
|
3544
|
+
this.encodeMap(object, depth);
|
|
3545
|
+
}
|
|
3546
|
+
else {
|
|
3547
|
+
// symbol, function and other special object come here unless extensionCodec handles them.
|
|
3548
|
+
throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
encodeBinary(object) {
|
|
3552
|
+
const size = object.byteLength;
|
|
3553
|
+
if (size < 0x100) {
|
|
3554
|
+
// bin 8
|
|
3555
|
+
this.writeU8(0xc4);
|
|
3556
|
+
this.writeU8(size);
|
|
3557
|
+
}
|
|
3558
|
+
else if (size < 0x10000) {
|
|
3559
|
+
// bin 16
|
|
3560
|
+
this.writeU8(0xc5);
|
|
3561
|
+
this.writeU16(size);
|
|
3562
|
+
}
|
|
3563
|
+
else if (size < 0x100000000) {
|
|
3564
|
+
// bin 32
|
|
3565
|
+
this.writeU8(0xc6);
|
|
3566
|
+
this.writeU32(size);
|
|
3567
|
+
}
|
|
3568
|
+
else {
|
|
3569
|
+
throw new Error(`Too large binary: ${size}`);
|
|
3570
|
+
}
|
|
3571
|
+
const bytes = ensureUint8Array(object);
|
|
3572
|
+
this.writeU8a(bytes);
|
|
3573
|
+
}
|
|
3574
|
+
encodeArray(object, depth) {
|
|
3575
|
+
const size = object.length;
|
|
3576
|
+
if (size < 16) {
|
|
3577
|
+
// fixarray
|
|
3578
|
+
this.writeU8(0x90 + size);
|
|
3579
|
+
}
|
|
3580
|
+
else if (size < 0x10000) {
|
|
3581
|
+
// array 16
|
|
3582
|
+
this.writeU8(0xdc);
|
|
3583
|
+
this.writeU16(size);
|
|
3584
|
+
}
|
|
3585
|
+
else if (size < 0x100000000) {
|
|
3586
|
+
// array 32
|
|
3587
|
+
this.writeU8(0xdd);
|
|
3588
|
+
this.writeU32(size);
|
|
3589
|
+
}
|
|
3590
|
+
else {
|
|
3591
|
+
throw new Error(`Too large array: ${size}`);
|
|
3592
|
+
}
|
|
3593
|
+
for (const item of object) {
|
|
3594
|
+
this.doEncode(item, depth + 1);
|
|
3595
|
+
}
|
|
3596
|
+
}
|
|
3597
|
+
countWithoutUndefined(object, keys) {
|
|
3598
|
+
let count = 0;
|
|
3599
|
+
for (const key of keys) {
|
|
3600
|
+
if (object[key] !== undefined) {
|
|
3601
|
+
count++;
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
return count;
|
|
3605
|
+
}
|
|
3606
|
+
encodeMap(object, depth) {
|
|
3607
|
+
const keys = Object.keys(object);
|
|
3608
|
+
if (this.sortKeys) {
|
|
3609
|
+
keys.sort();
|
|
3610
|
+
}
|
|
3611
|
+
const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
|
|
3612
|
+
if (size < 16) {
|
|
3613
|
+
// fixmap
|
|
3614
|
+
this.writeU8(0x80 + size);
|
|
3615
|
+
}
|
|
3616
|
+
else if (size < 0x10000) {
|
|
3617
|
+
// map 16
|
|
3618
|
+
this.writeU8(0xde);
|
|
3619
|
+
this.writeU16(size);
|
|
3620
|
+
}
|
|
3621
|
+
else if (size < 0x100000000) {
|
|
3622
|
+
// map 32
|
|
3623
|
+
this.writeU8(0xdf);
|
|
3624
|
+
this.writeU32(size);
|
|
3625
|
+
}
|
|
3626
|
+
else {
|
|
3627
|
+
throw new Error(`Too large map object: ${size}`);
|
|
3628
|
+
}
|
|
3629
|
+
for (const key of keys) {
|
|
3630
|
+
const value = object[key];
|
|
3631
|
+
if (!(this.ignoreUndefined && value === undefined)) {
|
|
3632
|
+
this.encodeString(key);
|
|
3633
|
+
this.doEncode(value, depth + 1);
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
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;
|
|
3651
|
+
if (size === 1) {
|
|
3652
|
+
// fixext 1
|
|
3653
|
+
this.writeU8(0xd4);
|
|
3654
|
+
}
|
|
3655
|
+
else if (size === 2) {
|
|
3656
|
+
// fixext 2
|
|
3657
|
+
this.writeU8(0xd5);
|
|
3658
|
+
}
|
|
3659
|
+
else if (size === 4) {
|
|
3660
|
+
// fixext 4
|
|
3661
|
+
this.writeU8(0xd6);
|
|
3662
|
+
}
|
|
3663
|
+
else if (size === 8) {
|
|
3664
|
+
// fixext 8
|
|
3665
|
+
this.writeU8(0xd7);
|
|
3666
|
+
}
|
|
3667
|
+
else if (size === 16) {
|
|
3668
|
+
// fixext 16
|
|
3669
|
+
this.writeU8(0xd8);
|
|
3670
|
+
}
|
|
3671
|
+
else if (size < 0x100) {
|
|
3672
|
+
// ext 8
|
|
3673
|
+
this.writeU8(0xc7);
|
|
3674
|
+
this.writeU8(size);
|
|
3675
|
+
}
|
|
3676
|
+
else if (size < 0x10000) {
|
|
3677
|
+
// ext 16
|
|
3678
|
+
this.writeU8(0xc8);
|
|
3679
|
+
this.writeU16(size);
|
|
3680
|
+
}
|
|
3681
|
+
else if (size < 0x100000000) {
|
|
3682
|
+
// ext 32
|
|
3683
|
+
this.writeU8(0xc9);
|
|
3684
|
+
this.writeU32(size);
|
|
3685
|
+
}
|
|
3686
|
+
else {
|
|
3687
|
+
throw new Error(`Too large extension object: ${size}`);
|
|
3688
|
+
}
|
|
3689
|
+
this.writeI8(ext.type);
|
|
3690
|
+
this.writeU8a(ext.data);
|
|
3691
|
+
}
|
|
3692
|
+
writeU8(value) {
|
|
3693
|
+
this.ensureBufferSizeToWrite(1);
|
|
3694
|
+
this.view.setUint8(this.pos, value);
|
|
3695
|
+
this.pos++;
|
|
3696
|
+
}
|
|
3697
|
+
writeU8a(values) {
|
|
3698
|
+
const size = values.length;
|
|
3699
|
+
this.ensureBufferSizeToWrite(size);
|
|
3700
|
+
this.bytes.set(values, this.pos);
|
|
3701
|
+
this.pos += size;
|
|
3702
|
+
}
|
|
3703
|
+
writeI8(value) {
|
|
3704
|
+
this.ensureBufferSizeToWrite(1);
|
|
3705
|
+
this.view.setInt8(this.pos, value);
|
|
3706
|
+
this.pos++;
|
|
3707
|
+
}
|
|
3708
|
+
writeU16(value) {
|
|
3709
|
+
this.ensureBufferSizeToWrite(2);
|
|
3710
|
+
this.view.setUint16(this.pos, value);
|
|
3711
|
+
this.pos += 2;
|
|
3712
|
+
}
|
|
3713
|
+
writeI16(value) {
|
|
3714
|
+
this.ensureBufferSizeToWrite(2);
|
|
3715
|
+
this.view.setInt16(this.pos, value);
|
|
3716
|
+
this.pos += 2;
|
|
3717
|
+
}
|
|
3718
|
+
writeU32(value) {
|
|
3719
|
+
this.ensureBufferSizeToWrite(4);
|
|
3720
|
+
this.view.setUint32(this.pos, value);
|
|
3721
|
+
this.pos += 4;
|
|
3722
|
+
}
|
|
3723
|
+
writeI32(value) {
|
|
3724
|
+
this.ensureBufferSizeToWrite(4);
|
|
3725
|
+
this.view.setInt32(this.pos, value);
|
|
3726
|
+
this.pos += 4;
|
|
3727
|
+
}
|
|
3728
|
+
writeF32(value) {
|
|
3729
|
+
this.ensureBufferSizeToWrite(4);
|
|
3730
|
+
this.view.setFloat32(this.pos, value);
|
|
3731
|
+
this.pos += 4;
|
|
3732
|
+
}
|
|
3733
|
+
writeF64(value) {
|
|
3734
|
+
this.ensureBufferSizeToWrite(8);
|
|
3735
|
+
this.view.setFloat64(this.pos, value);
|
|
3736
|
+
this.pos += 8;
|
|
3737
|
+
}
|
|
3738
|
+
writeU64(value) {
|
|
3739
|
+
this.ensureBufferSizeToWrite(8);
|
|
3740
|
+
setUint64(this.view, this.pos, value);
|
|
3741
|
+
this.pos += 8;
|
|
3742
|
+
}
|
|
3743
|
+
writeI64(value) {
|
|
3744
|
+
this.ensureBufferSizeToWrite(8);
|
|
3745
|
+
setInt64(this.view, this.pos, value);
|
|
3746
|
+
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
|
+
}
|
|
3759
|
+
|
|
3760
|
+
/**
|
|
3761
|
+
* It encodes `value` in the MessagePack format and
|
|
3762
|
+
* returns a byte buffer.
|
|
3763
|
+
*
|
|
3764
|
+
* 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
|
+
*/
|
|
3766
|
+
function encode(value, options) {
|
|
3767
|
+
const encoder = new Encoder(options);
|
|
3768
|
+
return encoder.encodeSharedRef(value);
|
|
3769
|
+
}
|
|
3770
|
+
|
|
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) {
|
|
3780
|
+
this.maxKeyLength = maxKeyLength;
|
|
3781
|
+
this.maxLengthPerKey = maxLengthPerKey;
|
|
3782
|
+
// avoid `new Array(N)`, which makes a sparse array,
|
|
3783
|
+
// because a sparse array is typically slower than a non-sparse array.
|
|
3784
|
+
this.caches = [];
|
|
3785
|
+
for (let i = 0; i < this.maxKeyLength; i++) {
|
|
3786
|
+
this.caches.push([]);
|
|
3787
|
+
}
|
|
3788
|
+
}
|
|
3789
|
+
canBeCached(byteLength) {
|
|
3790
|
+
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++) {
|
|
3797
|
+
if (recordBytes[j] !== bytes[inputOffset + j]) {
|
|
3798
|
+
continue FIND_CHUNK;
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
return record.str;
|
|
3802
|
+
}
|
|
3803
|
+
return null;
|
|
3804
|
+
}
|
|
3805
|
+
store(bytes, value) {
|
|
3806
|
+
const records = this.caches[bytes.length - 1];
|
|
3807
|
+
const record = { bytes, str: value };
|
|
3808
|
+
if (records.length >= this.maxLengthPerKey) {
|
|
3809
|
+
// `records` are full!
|
|
3810
|
+
// Set `record` to an arbitrary position.
|
|
3811
|
+
records[(Math.random() * records.length) | 0] = record;
|
|
3812
|
+
}
|
|
3813
|
+
else {
|
|
3814
|
+
records.push(record);
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
decode(bytes, inputOffset, byteLength) {
|
|
3818
|
+
const cachedValue = this.find(bytes, inputOffset, byteLength);
|
|
3819
|
+
if (cachedValue != null) {
|
|
3820
|
+
this.hit++;
|
|
3821
|
+
return cachedValue;
|
|
3822
|
+
}
|
|
3823
|
+
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);
|
|
3827
|
+
this.store(slicedCopyOfBytes, str);
|
|
3828
|
+
return str;
|
|
3829
|
+
}
|
|
3830
|
+
}
|
|
3831
|
+
|
|
3832
|
+
const EMPTY_VIEW = new DataView(new ArrayBuffer(0));
|
|
3833
|
+
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");
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
new CachedKeyDecoder();
|
|
3845
|
+
|
|
3846
|
+
function encodeMiniProgramShareExtra(value) {
|
|
3847
|
+
assertExtraValue(value);
|
|
3848
|
+
const bytes = encode(value);
|
|
3849
|
+
if (bytes.byteLength > 128)
|
|
3850
|
+
throw new Error('share extra is too large');
|
|
3851
|
+
return btoa(String.fromCharCode(...bytes))
|
|
3852
|
+
.replaceAll('+', '-')
|
|
3853
|
+
.replaceAll('/', '_')
|
|
3854
|
+
.replaceAll('=', '');
|
|
3855
|
+
}
|
|
3856
|
+
function assertExtraValue(value, depth = 0, seen = new WeakSet()) {
|
|
3857
|
+
if (depth > 8)
|
|
3858
|
+
throw new Error('extra nesting depth exceeded');
|
|
3859
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
3860
|
+
return;
|
|
3861
|
+
if (typeof value === 'number') {
|
|
3862
|
+
if (Number.isFinite(value))
|
|
3863
|
+
return;
|
|
3864
|
+
throw new Error('extra number must be finite');
|
|
3865
|
+
}
|
|
3866
|
+
if (typeof value !== 'object')
|
|
3867
|
+
throw new Error('extra value must be JSON-compatible');
|
|
3868
|
+
if (seen.has(value))
|
|
3869
|
+
throw new Error('extra value must not contain cycles');
|
|
3870
|
+
seen.add(value);
|
|
3871
|
+
if (Array.isArray(value)) {
|
|
3872
|
+
if (value.length > 64)
|
|
3873
|
+
throw new Error('extra array is too large');
|
|
3874
|
+
for (const item of value)
|
|
3875
|
+
assertExtraValue(item, depth + 1, seen);
|
|
3876
|
+
seen.delete(value);
|
|
3877
|
+
return;
|
|
3878
|
+
}
|
|
3879
|
+
const prototype = Object.getPrototypeOf(value);
|
|
3880
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
3881
|
+
throw new Error('extra object must be a plain object');
|
|
3882
|
+
const values = Object.values(value);
|
|
3883
|
+
if (values.length > 64)
|
|
3884
|
+
throw new Error('extra object has too many fields');
|
|
3885
|
+
for (const item of values)
|
|
3886
|
+
assertExtraValue(item, depth + 1, seen);
|
|
3887
|
+
seen.delete(value);
|
|
3888
|
+
}
|
|
3889
|
+
|
|
2689
3890
|
function isRecord$3(value) {
|
|
2690
3891
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2691
3892
|
}
|
|
@@ -2809,11 +4010,11 @@ function readHttpUrl(value, message) {
|
|
|
2809
4010
|
function isShareChannel(value) {
|
|
2810
4011
|
return value === 'wechatSession' || value === 'wechatTimeline' || value === 'qqFriend' || value === 'qzone' || value === 'weibo';
|
|
2811
4012
|
}
|
|
2812
|
-
function createDefaultShareUrl(options) {
|
|
4013
|
+
function createDefaultShareUrl(options, method, extra) {
|
|
2813
4014
|
const identity = options.identity.get();
|
|
2814
4015
|
const miniProgramId = identity?.miniProgramId.trim();
|
|
2815
4016
|
if (!miniProgramId)
|
|
2816
|
-
return invalidParams$2(
|
|
4017
|
+
return invalidParams$2(`${method} 缺少有效的小程序分享地址`);
|
|
2817
4018
|
try {
|
|
2818
4019
|
const currentUrl = new URL(options.environment.getCurrentHref());
|
|
2819
4020
|
const shareUrl = new URL('/tools/common_share', currentUrl);
|
|
@@ -2824,10 +4025,12 @@ function createDefaultShareUrl(options) {
|
|
|
2824
4025
|
const hSrc = currentUrl.searchParams.get('h_src');
|
|
2825
4026
|
if (hSrc?.trim())
|
|
2826
4027
|
shareUrl.searchParams.set('h_src', hSrc);
|
|
4028
|
+
if (extra !== undefined)
|
|
4029
|
+
shareUrl.searchParams.set('extra', extra);
|
|
2827
4030
|
return shareUrl.href;
|
|
2828
4031
|
}
|
|
2829
4032
|
catch {
|
|
2830
|
-
return invalidParams$2(
|
|
4033
|
+
return invalidParams$2(`${method} 缺少有效的小程序分享地址`);
|
|
2831
4034
|
}
|
|
2832
4035
|
}
|
|
2833
4036
|
function readShareMenuInput(payload, options) {
|
|
@@ -2836,15 +4039,18 @@ function readShareMenuInput(payload, options) {
|
|
|
2836
4039
|
const channel = payload.channel;
|
|
2837
4040
|
if (channel !== undefined && !isShareChannel(channel))
|
|
2838
4041
|
return invalidParams$2('share.showShareMenu channel 不合法');
|
|
4042
|
+
const extra = readShareExtra(payload.extra, 'share.showShareMenu');
|
|
2839
4043
|
let url;
|
|
2840
4044
|
if (typeof payload.url === 'string' && payload.url.trim()) {
|
|
4045
|
+
if (extra !== undefined)
|
|
4046
|
+
return invalidParams$2('share.showShareMenu url 与 extra 不能同时使用');
|
|
2841
4047
|
url = readHttpUrl(payload.url, 'share.showShareMenu url 必须是 HTTP(S) URL');
|
|
2842
4048
|
}
|
|
2843
4049
|
else if (payload.url !== undefined && payload.url !== null && payload.url !== '') {
|
|
2844
4050
|
return invalidParams$2('share.showShareMenu url 必须是 HTTP(S) URL');
|
|
2845
4051
|
}
|
|
2846
4052
|
else {
|
|
2847
|
-
url = createDefaultShareUrl(options);
|
|
4053
|
+
url = createDefaultShareUrl(options, 'share.showShareMenu', extra);
|
|
2848
4054
|
}
|
|
2849
4055
|
return {
|
|
2850
4056
|
title: readRequiredString(payload.title, 'share.showShareMenu title 必须是非空字符串'),
|
|
@@ -2854,6 +4060,16 @@ function readShareMenuInput(payload, options) {
|
|
|
2854
4060
|
...(channel === undefined ? {} : { channel }),
|
|
2855
4061
|
};
|
|
2856
4062
|
}
|
|
4063
|
+
function readShareExtra(value, method) {
|
|
4064
|
+
if (value === undefined)
|
|
4065
|
+
return undefined;
|
|
4066
|
+
try {
|
|
4067
|
+
return encodeMiniProgramShareExtra(value);
|
|
4068
|
+
}
|
|
4069
|
+
catch {
|
|
4070
|
+
return invalidParams$2(`${method} extra 必须是符合限制的 JSON-compatible 数据`);
|
|
4071
|
+
}
|
|
4072
|
+
}
|
|
2857
4073
|
async function normalizePost(result, options) {
|
|
2858
4074
|
if (!result.invalidMessage)
|
|
2859
4075
|
return result.post;
|
|
@@ -2923,6 +4139,15 @@ async function showShareMenu(payload, options) {
|
|
|
2923
4139
|
const post = await normalizePost(postResult, options);
|
|
2924
4140
|
return waitForHostOperation(() => options.presentation.showShareMenu({ ...input, post }, options.operationContext), options.operationContext.signal);
|
|
2925
4141
|
}
|
|
4142
|
+
async function copyLink(payload, options) {
|
|
4143
|
+
throwIfAborted(options.operationContext.signal);
|
|
4144
|
+
if (payload !== undefined && !isRecord$2(payload))
|
|
4145
|
+
return invalidParams$2('share.copyLink 参数必须是对象');
|
|
4146
|
+
const extra = readShareExtra(payload?.extra, 'share.copyLink');
|
|
4147
|
+
const url = createDefaultShareUrl(options, 'share.copyLink', extra);
|
|
4148
|
+
await waitForHostOperation(() => options.presentation.setClipboard({ text: url }, options.operationContext), options.operationContext.signal);
|
|
4149
|
+
return url;
|
|
4150
|
+
}
|
|
2926
4151
|
async function screenshot(payload, options) {
|
|
2927
4152
|
throwIfAborted(options.operationContext.signal);
|
|
2928
4153
|
const input = readScreenshotOptions(payload, options.presentation);
|
|
@@ -2977,6 +4202,7 @@ async function restoreScreenshotChrome(presentation, cleanupContext, operationSi
|
|
|
2977
4202
|
}
|
|
2978
4203
|
function createShareCapabilityHandlers(options) {
|
|
2979
4204
|
return {
|
|
4205
|
+
[SHARE_COPY_LINK_METHOD]: (payload, _context) => copyLink(payload, options),
|
|
2980
4206
|
[SHARE_SHOW_SHARE_MENU_METHOD]: (payload, _context) => showShareMenu(payload, options),
|
|
2981
4207
|
[SHARE_SCREENSHOT_METHOD]: (payload, _context) => screenshot(payload, options),
|
|
2982
4208
|
};
|
|
@@ -3267,25 +4493,6 @@ function isBridgeError$1(error) {
|
|
|
3267
4493
|
return isCapabilityRecord(error) && typeof error.code === 'string' && typeof error.message === 'string';
|
|
3268
4494
|
}
|
|
3269
4495
|
|
|
3270
|
-
/**
|
|
3271
|
-
* @packageDocumentation
|
|
3272
|
-
* 定义 AccountUserBaseInfo 接口的 Runtime endpoint 契约。
|
|
3273
|
-
*/
|
|
3274
|
-
/**
|
|
3275
|
-
* AccountUserBaseInfo 原始信封 endpoint。
|
|
3276
|
-
*
|
|
3277
|
-
* @remarks
|
|
3278
|
-
* 供需要区分 `login`、`relogin` 等认证状态的领域服务使用;调用输入仍为 `void`,
|
|
3279
|
-
* wire path 只由本 API contract owner 维护。
|
|
3280
|
-
*/
|
|
3281
|
-
const accountUserBaseInfoEnvelopeEndpoint = {
|
|
3282
|
-
auth: 'optional',
|
|
3283
|
-
channel: 'api',
|
|
3284
|
-
id: 'heybox.account.user_base_info.envelope.get',
|
|
3285
|
-
method: 'GET',
|
|
3286
|
-
path: '/account/get_user_base_info',
|
|
3287
|
-
};
|
|
3288
|
-
|
|
3289
4496
|
/**
|
|
3290
4497
|
* @packageDocumentation
|
|
3291
4498
|
* 定义 GameSteamGetGameList 接口的 Runtime endpoint 契约。
|
|
@@ -3878,6 +5085,7 @@ function createRuntimeCapabilityModules(options) {
|
|
|
3878
5085
|
identity: options.identity,
|
|
3879
5086
|
operationContext,
|
|
3880
5087
|
authPresentation: options.authPresentation,
|
|
5088
|
+
miniProgramPresentation: options.miniProgramPresentation,
|
|
3881
5089
|
});
|
|
3882
5090
|
let user;
|
|
3883
5091
|
let cloud;
|
|
@@ -4564,6 +5772,7 @@ class MiniProgramRuntimeImpl {
|
|
|
4564
5772
|
if (this.isInactive())
|
|
4565
5773
|
return;
|
|
4566
5774
|
this.runtimePermissions = configuration.runtimePermissions;
|
|
5775
|
+
this.miniProgramPresentation = configuration.miniProgramPresentation;
|
|
4567
5776
|
this.locationBasePath = configuration.locationBasePath;
|
|
4568
5777
|
this.anonymousStorageScope = configuration.anonymousStorageScope ?? this.options.anonymousStorageScope;
|
|
4569
5778
|
this.allowedHttpOrigins = configuration.allowedHttpOrigins ?? this.options.allowedHttpOrigins;
|
|
@@ -4625,6 +5834,7 @@ class MiniProgramRuntimeImpl {
|
|
|
4625
5834
|
terminalSignal: this.terminalController.signal,
|
|
4626
5835
|
eventSink,
|
|
4627
5836
|
authPresentation: this.options.authPresentation,
|
|
5837
|
+
miniProgramPresentation: this.miniProgramPresentation,
|
|
4628
5838
|
anonymousStorageScope: this.anonymousStorageScope,
|
|
4629
5839
|
storageLimits: this.options.storageLimits,
|
|
4630
5840
|
allowedHttpOrigins: this.allowedHttpOrigins,
|