@hehanlin/open-agent-bridge 0.6.3 → 0.6.4

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 (70) hide show
  1. package/node_modules/@byted/frontier-web-sdk/README.md +11 -0
  2. package/node_modules/@byted/frontier-web-sdk/lib/fws.esm.js +2438 -0
  3. package/node_modules/@byted/frontier-web-sdk/lib/fws.js +2535 -0
  4. package/node_modules/@byted/frontier-web-sdk/lib/fws.umd.js +2699 -0
  5. package/node_modules/@byted/frontier-web-sdk/lib/fws.umd.min.js +1 -0
  6. package/node_modules/@byted/frontier-web-sdk/lib/types/db/index.d.ts +5 -0
  7. package/node_modules/@byted/frontier-web-sdk/lib/types/db/qos-idb.d.ts +22 -0
  8. package/node_modules/@byted/frontier-web-sdk/lib/types/db/qos-localstorage.d.ts +20 -0
  9. package/node_modules/@byted/frontier-web-sdk/lib/types/db/qos-ministorage.d.ts +20 -0
  10. package/node_modules/@byted/frontier-web-sdk/lib/types/fws.d.ts +225 -0
  11. package/node_modules/@byted/frontier-web-sdk/lib/types/idl/bppb2.d.ts +27 -0
  12. package/node_modules/@byted/frontier-web-sdk/lib/types/idl/protobuf.d.ts +8 -0
  13. package/node_modules/@byted/frontier-web-sdk/lib/types/manager/cursor-manager.d.ts +25 -0
  14. package/node_modules/@byted/frontier-web-sdk/lib/types/manager/endpoint-manager.d.ts +15 -0
  15. package/node_modules/@byted/frontier-web-sdk/lib/types/manager/qos-manager.d.ts +17 -0
  16. package/node_modules/@byted/frontier-web-sdk/lib/types/manager/tnc-manager.d.ts +0 -0
  17. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/ack-process.d.ts +3 -0
  18. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/cursor-helper.d.ts +3 -0
  19. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/cursor-process.d.ts +3 -0
  20. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/decode-process.d.ts +2 -0
  21. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/dispatch-message-process.d.ts +3 -0
  22. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/finish-message-process.d.ts +3 -0
  23. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/index.d.ts +7 -0
  24. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/qos-helper.d.ts +12 -0
  25. package/node_modules/@byted/frontier-web-sdk/lib/types/process/message/qos-process.d.ts +3 -0
  26. package/node_modules/@byted/frontier-web-sdk/lib/types/process/open/finish-open-process.d.ts +2 -0
  27. package/node_modules/@byted/frontier-web-sdk/lib/types/process/open/index.d.ts +3 -0
  28. package/node_modules/@byted/frontier-web-sdk/lib/types/process/open/open-process.d.ts +2 -0
  29. package/node_modules/@byted/frontier-web-sdk/lib/types/process/open/open-success-process.d.ts +2 -0
  30. package/node_modules/@byted/frontier-web-sdk/lib/types/process/process-trigger.d.ts +3 -0
  31. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/arraybuffer-trans.d.ts +2 -0
  32. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/buffer.d.ts +115 -0
  33. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/check-payload-type.d.ts +1 -0
  34. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/cursor-serialize.d.ts +14 -0
  35. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/env-params-gen.d.ts +5 -0
  36. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/env.d.ts +5 -0
  37. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/event-emitter.d.ts +39 -0
  38. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/event.d.ts +88 -0
  39. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/get-socket-error.d.ts +1 -0
  40. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/header-key.d.ts +2 -0
  41. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/log-id.d.ts +6 -0
  42. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/long.d.ts +25 -0
  43. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/pkg-loss-counter.d.ts +8 -0
  44. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/pool.d.ts +29 -0
  45. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/utf8.d.ts +24 -0
  46. package/node_modules/@byted/frontier-web-sdk/lib/types/utils/websocket.d.ts +2 -0
  47. package/node_modules/@byted/frontier-web-sdk/lib/types/websocket/mini-websocket.d.ts +20 -0
  48. package/node_modules/@byted/frontier-web-sdk/package.json +52 -0
  49. package/node_modules/idb/CHANGELOG.md +87 -0
  50. package/node_modules/idb/LICENSE +6 -0
  51. package/node_modules/idb/README.md +497 -0
  52. package/node_modules/idb/build/async-iterators.cjs +57 -0
  53. package/node_modules/idb/build/async-iterators.d.ts +1 -0
  54. package/node_modules/idb/build/async-iterators.js +55 -0
  55. package/node_modules/idb/build/database-extras.d.ts +1 -0
  56. package/node_modules/idb/build/entry.d.ts +615 -0
  57. package/node_modules/idb/build/index.cjs +94 -0
  58. package/node_modules/idb/build/index.d.ts +2 -0
  59. package/node_modules/idb/build/index.js +88 -0
  60. package/node_modules/idb/build/umd-with-async-ittr.js +1 -0
  61. package/node_modules/idb/build/umd.js +1 -0
  62. package/node_modules/idb/build/util.d.ts +3 -0
  63. package/node_modules/idb/build/wrap-idb-value.cjs +191 -0
  64. package/node_modules/idb/build/wrap-idb-value.d.ts +34 -0
  65. package/node_modules/idb/build/wrap-idb-value.js +185 -0
  66. package/node_modules/idb/package.json +59 -0
  67. package/node_modules/idb/with-async-ittr.cjs +2 -0
  68. package/node_modules/idb/with-async-ittr.d.ts +1 -0
  69. package/node_modules/idb/with-async-ittr.js +2 -0
  70. package/package.json +4 -1
@@ -0,0 +1,2699 @@
1
+ (function(root, factory) {
2
+ if ('object' == typeof exports && 'object' == typeof module) module.exports = factory();
3
+ else if ('function' == typeof define && define.amd) define([], factory);
4
+ else if ('object' == typeof exports) exports["fws"] = factory();
5
+ else root["fws"] = factory();
6
+ })(globalThis, ()=>(()=>{
7
+ "use strict";
8
+ var __webpack_modules__ = {
9
+ "../../node_modules/.pnpm/idb@7.0.2/node_modules/idb/build/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
10
+ __webpack_require__.r(__webpack_exports__);
11
+ __webpack_require__.d(__webpack_exports__, {
12
+ deleteDB: ()=>deleteDB,
13
+ wrap: ()=>wrap,
14
+ openDB: ()=>openDB,
15
+ unwrap: ()=>unwrap
16
+ });
17
+ const instanceOfAny = (object, constructors)=>constructors.some((c)=>object instanceof c);
18
+ let idbProxyableTypes;
19
+ let cursorAdvanceMethods;
20
+ function getIdbProxyableTypes() {
21
+ return idbProxyableTypes || (idbProxyableTypes = [
22
+ IDBDatabase,
23
+ IDBObjectStore,
24
+ IDBIndex,
25
+ IDBCursor,
26
+ IDBTransaction
27
+ ]);
28
+ }
29
+ function getCursorAdvanceMethods() {
30
+ return cursorAdvanceMethods || (cursorAdvanceMethods = [
31
+ IDBCursor.prototype.advance,
32
+ IDBCursor.prototype.continue,
33
+ IDBCursor.prototype.continuePrimaryKey
34
+ ]);
35
+ }
36
+ const cursorRequestMap = new WeakMap();
37
+ const transactionDoneMap = new WeakMap();
38
+ const transactionStoreNamesMap = new WeakMap();
39
+ const transformCache = new WeakMap();
40
+ const reverseTransformCache = new WeakMap();
41
+ function promisifyRequest(request) {
42
+ const promise = new Promise((resolve, reject)=>{
43
+ const unlisten = ()=>{
44
+ request.removeEventListener('success', success);
45
+ request.removeEventListener('error', error);
46
+ };
47
+ const success = ()=>{
48
+ resolve(wrap(request.result));
49
+ unlisten();
50
+ };
51
+ const error = ()=>{
52
+ reject(request.error);
53
+ unlisten();
54
+ };
55
+ request.addEventListener('success', success);
56
+ request.addEventListener('error', error);
57
+ });
58
+ promise.then((value)=>{
59
+ if (value instanceof IDBCursor) cursorRequestMap.set(value, request);
60
+ }).catch(()=>{});
61
+ reverseTransformCache.set(promise, request);
62
+ return promise;
63
+ }
64
+ function cacheDonePromiseForTransaction(tx) {
65
+ if (transactionDoneMap.has(tx)) return;
66
+ const done = new Promise((resolve, reject)=>{
67
+ const unlisten = ()=>{
68
+ tx.removeEventListener('complete', complete);
69
+ tx.removeEventListener('error', error);
70
+ tx.removeEventListener('abort', error);
71
+ };
72
+ const complete = ()=>{
73
+ resolve();
74
+ unlisten();
75
+ };
76
+ const error = ()=>{
77
+ reject(tx.error || new DOMException('AbortError', 'AbortError'));
78
+ unlisten();
79
+ };
80
+ tx.addEventListener('complete', complete);
81
+ tx.addEventListener('error', error);
82
+ tx.addEventListener('abort', error);
83
+ });
84
+ transactionDoneMap.set(tx, done);
85
+ }
86
+ let idbProxyTraps = {
87
+ get (target, prop, receiver) {
88
+ if (target instanceof IDBTransaction) {
89
+ if ('done' === prop) return transactionDoneMap.get(target);
90
+ if ('objectStoreNames' === prop) return target.objectStoreNames || transactionStoreNamesMap.get(target);
91
+ if ('store' === prop) return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
92
+ }
93
+ return wrap(target[prop]);
94
+ },
95
+ set (target, prop, value) {
96
+ target[prop] = value;
97
+ return true;
98
+ },
99
+ has (target, prop) {
100
+ if (target instanceof IDBTransaction && ('done' === prop || 'store' === prop)) return true;
101
+ return prop in target;
102
+ }
103
+ };
104
+ function replaceTraps(callback) {
105
+ idbProxyTraps = callback(idbProxyTraps);
106
+ }
107
+ function wrapFunction(func) {
108
+ if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) return function(storeNames, ...args) {
109
+ const tx = func.call(unwrap(this), storeNames, ...args);
110
+ transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [
111
+ storeNames
112
+ ]);
113
+ return wrap(tx);
114
+ };
115
+ if (getCursorAdvanceMethods().includes(func)) return function(...args) {
116
+ func.apply(unwrap(this), args);
117
+ return wrap(cursorRequestMap.get(this));
118
+ };
119
+ return function(...args) {
120
+ return wrap(func.apply(unwrap(this), args));
121
+ };
122
+ }
123
+ function transformCachableValue(value) {
124
+ if ('function' == typeof value) return wrapFunction(value);
125
+ if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
126
+ if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
127
+ return value;
128
+ }
129
+ function wrap(value) {
130
+ if (value instanceof IDBRequest) return promisifyRequest(value);
131
+ if (transformCache.has(value)) return transformCache.get(value);
132
+ const newValue = transformCachableValue(value);
133
+ if (newValue !== value) {
134
+ transformCache.set(value, newValue);
135
+ reverseTransformCache.set(newValue, value);
136
+ }
137
+ return newValue;
138
+ }
139
+ const unwrap = (value)=>reverseTransformCache.get(value);
140
+ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
141
+ const request = indexedDB.open(name, version);
142
+ const openPromise = wrap(request);
143
+ if (upgrade) request.addEventListener('upgradeneeded', (event)=>{
144
+ upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));
145
+ });
146
+ if (blocked) request.addEventListener('blocked', ()=>blocked());
147
+ openPromise.then((db)=>{
148
+ if (terminated) db.addEventListener('close', ()=>terminated());
149
+ if (blocking) db.addEventListener('versionchange', ()=>blocking());
150
+ }).catch(()=>{});
151
+ return openPromise;
152
+ }
153
+ function deleteDB(name, { blocked } = {}) {
154
+ const request = indexedDB.deleteDatabase(name);
155
+ if (blocked) request.addEventListener('blocked', ()=>blocked());
156
+ return wrap(request).then(()=>void 0);
157
+ }
158
+ const readMethods = [
159
+ 'get',
160
+ 'getKey',
161
+ 'getAll',
162
+ 'getAllKeys',
163
+ 'count'
164
+ ];
165
+ const writeMethods = [
166
+ 'put',
167
+ 'add',
168
+ 'delete',
169
+ 'clear'
170
+ ];
171
+ const cachedMethods = new Map();
172
+ function getMethod(target, prop) {
173
+ if (!(target instanceof IDBDatabase && !(prop in target) && 'string' == typeof prop)) return;
174
+ if (cachedMethods.get(prop)) return cachedMethods.get(prop);
175
+ const targetFuncName = prop.replace(/FromIndex$/, '');
176
+ const useIndex = prop !== targetFuncName;
177
+ const isWrite = writeMethods.includes(targetFuncName);
178
+ if (!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) return;
179
+ const method = async function(storeName, ...args) {
180
+ const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
181
+ let target = tx.store;
182
+ if (useIndex) target = target.index(args.shift());
183
+ return (await Promise.all([
184
+ target[targetFuncName](...args),
185
+ isWrite && tx.done
186
+ ]))[0];
187
+ };
188
+ cachedMethods.set(prop, method);
189
+ return method;
190
+ }
191
+ replaceTraps((oldTraps)=>({
192
+ ...oldTraps,
193
+ get: (target, prop, receiver)=>getMethod(target, prop) || oldTraps.get(target, prop, receiver),
194
+ has: (target, prop)=>!!getMethod(target, prop) || oldTraps.has(target, prop)
195
+ }));
196
+ }
197
+ };
198
+ var __webpack_module_cache__ = {};
199
+ function __webpack_require__(moduleId) {
200
+ var cachedModule = __webpack_module_cache__[moduleId];
201
+ if (void 0 !== cachedModule) return cachedModule.exports;
202
+ var module1 = __webpack_module_cache__[moduleId] = {
203
+ exports: {}
204
+ };
205
+ __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__);
206
+ return module1.exports;
207
+ }
208
+ (()=>{
209
+ __webpack_require__.d = (exports1, definition)=>{
210
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
211
+ enumerable: true,
212
+ get: definition[key]
213
+ });
214
+ };
215
+ })();
216
+ (()=>{
217
+ __webpack_require__.g = (()=>{
218
+ if ('object' == typeof globalThis) return globalThis;
219
+ try {
220
+ return this || new Function('return this')();
221
+ } catch (e) {
222
+ if ('object' == typeof window) return window;
223
+ }
224
+ })();
225
+ })();
226
+ (()=>{
227
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
228
+ })();
229
+ (()=>{
230
+ __webpack_require__.r = (exports1)=>{
231
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
232
+ value: 'Module'
233
+ });
234
+ Object.defineProperty(exports1, '__esModule', {
235
+ value: true
236
+ });
237
+ };
238
+ })();
239
+ var __webpack_exports__ = {};
240
+ (()=>{
241
+ __webpack_require__.r(__webpack_exports__);
242
+ __webpack_require__.d(__webpack_exports__, {
243
+ FWS: ()=>FWS,
244
+ CustomErrorEvent: ()=>CustomErrorEvent,
245
+ createCloseEvent: ()=>createCloseEvent,
246
+ ReconnectEvent: ()=>ReconnectEvent,
247
+ createErrorEvent: ()=>createErrorEvent,
248
+ decodedFrame: ()=>decodedFrame,
249
+ createOpenEvent: ()=>createOpenEvent,
250
+ CustomCloseEvent: ()=>CustomCloseEvent,
251
+ createReconnectEvent: ()=>createReconnectEvent,
252
+ FrontierMessageEvent: ()=>FrontierMessageEvent,
253
+ encodeFrame: ()=>protobuf_encodeFrame,
254
+ createMessageEvent: ()=>createMessageEvent,
255
+ OpenEvent: ()=>OpenEvent,
256
+ ErrorCode: ()=>event_ErrorCode,
257
+ Event: ()=>Event,
258
+ MessageEvent: ()=>MessageEvent
259
+ });
260
+ let cachedIP = '';
261
+ function genLogIDNew(ip = '') {
262
+ const version = '02';
263
+ const timeStamp = `${Date.now()}`;
264
+ const v6Addr = cachedIP || (cachedIP = IPToIPv6(ip));
265
+ const rand = Math.random().toString(16).slice(-6);
266
+ return version + timeStamp + v6Addr + rand;
267
+ }
268
+ function genLogID() {
269
+ return 10000 * Date.now() + Math.floor(10000 * Math.random());
270
+ }
271
+ function ocetToBinary(ocetStr) {
272
+ return (Array(8).join('0') + parseInt(ocetStr, 10).toString(2)).slice(-8);
273
+ }
274
+ function binaryToHex(binaryStr) {
275
+ return (Array(4).join('0') + parseInt(binaryStr, 2).toString(16)).slice(-4);
276
+ }
277
+ function IPv4ToIPv6(v4Addr) {
278
+ const v4AddrBytes = v4Addr.split(/\./).map((ocetPart)=>ocetToBinary(ocetPart));
279
+ const v6AddrBytes = [];
280
+ v6AddrBytes[0] = binaryToHex(v4AddrBytes[0] + v4AddrBytes[1]);
281
+ v6AddrBytes[1] = binaryToHex(v4AddrBytes[2] + v4AddrBytes[3]);
282
+ const v6Addr = [
283
+ '0000',
284
+ '0000',
285
+ '0000',
286
+ '0000',
287
+ '0000',
288
+ 'ffff',
289
+ v6AddrBytes[0],
290
+ v6AddrBytes[1]
291
+ ];
292
+ return v6Addr.join('');
293
+ }
294
+ function IPToIPv6(ip) {
295
+ const isIPv4 = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(ip);
296
+ const isIPv6 = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(ip);
297
+ return isIPv4 ? IPv4ToIPv6(ip) : isIPv6 ? formatIpv6Address(ip) : '00000000000000000000000000000000';
298
+ }
299
+ function formatIpv6Address(address) {
300
+ let result = '';
301
+ const resultParts = [];
302
+ let zerosPos = 0;
303
+ let partNums = 0;
304
+ let zerosPosFlag = true;
305
+ const ZERO_PART = '0000';
306
+ if (address.indexOf('::') > -1) {
307
+ const parts = address.split('::');
308
+ for(let i = 0; i < parts.length; i++){
309
+ const part = parts[i];
310
+ if (part.indexOf(':') > 0) {
311
+ const subPart = part.split(':');
312
+ if (zerosPosFlag) zerosPos = subPart.length;
313
+ partNums += subPart.length;
314
+ for(let j = 0; j < subPart.length; j++)if (4 !== subPart[j].length) {
315
+ const zeroPad = ZERO_PART.substring(0, 4 - subPart[j].length);
316
+ const partWithPad = zeroPad.concat(subPart[j]);
317
+ resultParts.push(partWithPad);
318
+ } else resultParts.push(subPart[j]);
319
+ zerosPosFlag = false;
320
+ } else {
321
+ if (4 !== part.length) {
322
+ const zeroPad = ZERO_PART.substring(0, 4 - part.length);
323
+ const partWithPad = zeroPad.concat(part);
324
+ resultParts.push(partWithPad);
325
+ } else resultParts.push(part);
326
+ if (zerosPosFlag) zerosPos += 1;
327
+ partNums += 1;
328
+ zerosPosFlag = false;
329
+ }
330
+ }
331
+ let zeros = '';
332
+ for(let h = 0; h < 8 - partNums; h++)zeros = zeros.concat(ZERO_PART);
333
+ for(let y = 0; y < resultParts.length; y++)if (y === zerosPos) {
334
+ result = result.concat(zeros);
335
+ result = result.concat(resultParts[y]);
336
+ } else result = result.concat(resultParts[y]);
337
+ return result;
338
+ }
339
+ {
340
+ const parts = address.split(':');
341
+ for(let i = 0; i < parts.length; i++){
342
+ const part = parts[i];
343
+ if (4 !== parts[i].length) {
344
+ const zeroPad = ZERO_PART.substring(0, 4 - parts[i].length);
345
+ const partWithPad = zeroPad.concat(part);
346
+ result = result.concat(partWithPad);
347
+ } else result = result.concat(part);
348
+ }
349
+ return result;
350
+ }
351
+ }
352
+ function _encodeHeader(message, bb) {
353
+ const $key = message.key;
354
+ if (void 0 !== $key) {
355
+ writeVarint32(bb, 10);
356
+ writeString(bb, $key);
357
+ }
358
+ const $value = message.value;
359
+ if (void 0 !== $value) {
360
+ writeVarint32(bb, 18);
361
+ writeString(bb, $value);
362
+ }
363
+ }
364
+ function _decodeHeader(bb) {
365
+ const message = {};
366
+ end_of_message: while(!isAtEnd(bb)){
367
+ const tag = readVarint32(bb);
368
+ switch(tag >>> 3){
369
+ case 0:
370
+ break end_of_message;
371
+ case 1:
372
+ message.key = readString(bb, readVarint32(bb));
373
+ break;
374
+ case 2:
375
+ message.value = readString(bb, readVarint32(bb));
376
+ break;
377
+ default:
378
+ skipUnknownField(bb, 7 & tag);
379
+ }
380
+ }
381
+ if (void 0 === message.key) throw new Error('Missing required field: key');
382
+ if (void 0 === message.value) throw new Error('Missing required field: value');
383
+ return message;
384
+ }
385
+ function encodeFrame(message) {
386
+ const bb = popByteBuffer();
387
+ _encodeFrame(message, bb);
388
+ return toUint8Array(bb);
389
+ }
390
+ function _encodeFrame(message, bb) {
391
+ const $SeqID = message.SeqID;
392
+ if (void 0 !== $SeqID) {
393
+ writeVarint32(bb, 8);
394
+ writeVarint64(bb, $SeqID);
395
+ }
396
+ const $LogID = message.LogID;
397
+ if (void 0 !== $LogID) {
398
+ writeVarint32(bb, 16);
399
+ writeVarint64(bb, $LogID);
400
+ }
401
+ const $service = message.service;
402
+ if (void 0 !== $service) {
403
+ writeVarint32(bb, 24);
404
+ writeVarint64(bb, intToLong($service));
405
+ }
406
+ const $method = message.method;
407
+ if (void 0 !== $method) {
408
+ writeVarint32(bb, 32);
409
+ writeVarint64(bb, intToLong($method));
410
+ }
411
+ const array$headers = message.headers;
412
+ if (void 0 !== array$headers) for (const value of array$headers){
413
+ writeVarint32(bb, 42);
414
+ const nested = popByteBuffer();
415
+ _encodeHeader(value, nested);
416
+ writeVarint32(bb, nested.limit);
417
+ writeByteBuffer(bb, nested);
418
+ pushByteBuffer(nested);
419
+ }
420
+ const $payload_encoding = message.payloadEncoding;
421
+ if (void 0 !== $payload_encoding) {
422
+ writeVarint32(bb, 50);
423
+ writeString(bb, $payload_encoding);
424
+ }
425
+ const $payload_type = message.payloadType;
426
+ if (void 0 !== $payload_type) {
427
+ writeVarint32(bb, 58);
428
+ writeString(bb, $payload_type);
429
+ }
430
+ const $payload = message.payload;
431
+ if (void 0 !== $payload) {
432
+ writeVarint32(bb, 66);
433
+ writeVarint32(bb, $payload.length), writeBytes(bb, $payload);
434
+ }
435
+ const $LogIDNew = message.LogIDNew;
436
+ if (void 0 !== $LogIDNew) {
437
+ writeVarint32(bb, 74);
438
+ writeString(bb, $LogIDNew);
439
+ }
440
+ const $server_timing = message.serverTiming;
441
+ if (void 0 !== $server_timing) {
442
+ writeVarint32(bb, 82);
443
+ writeString(bb, $server_timing);
444
+ }
445
+ const $msg_id = message.msgID;
446
+ if (void 0 !== $msg_id) {
447
+ writeVarint32(bb, 90);
448
+ writeString(bb, $msg_id);
449
+ }
450
+ const $frame_type = message.frameType;
451
+ if (void 0 !== $frame_type) {
452
+ writeVarint32(bb, 96);
453
+ writeVarint64(bb, intToLong($frame_type));
454
+ }
455
+ }
456
+ function decodeFrame(binary) {
457
+ return _decodeFrame(wrapByteBuffer(binary));
458
+ }
459
+ function _decodeFrame(bb) {
460
+ const message = {};
461
+ end_of_message: while(!isAtEnd(bb)){
462
+ const tag = readVarint32(bb);
463
+ switch(tag >>> 3){
464
+ case 0:
465
+ break end_of_message;
466
+ case 1:
467
+ message.SeqID = readVarint64(bb, true);
468
+ break;
469
+ case 2:
470
+ message.LogID = readVarint64(bb, true);
471
+ break;
472
+ case 3:
473
+ message.service = readVarint32(bb);
474
+ break;
475
+ case 4:
476
+ message.method = readVarint32(bb);
477
+ break;
478
+ case 5:
479
+ {
480
+ const limit = pushTemporaryLength(bb);
481
+ const values = message.headers || (message.headers = []);
482
+ values.push(_decodeHeader(bb));
483
+ bb.limit = limit;
484
+ break;
485
+ }
486
+ case 6:
487
+ message.payloadEncoding = readString(bb, readVarint32(bb));
488
+ break;
489
+ case 7:
490
+ message.payloadType = readString(bb, readVarint32(bb));
491
+ break;
492
+ case 8:
493
+ message.payload = readBytes(bb, readVarint32(bb));
494
+ break;
495
+ case 9:
496
+ message.LogIDNew = readString(bb, readVarint32(bb));
497
+ break;
498
+ case 10:
499
+ message.serverTiming = readString(bb, readVarint32(bb));
500
+ break;
501
+ case 11:
502
+ message.msgID = readString(bb, readVarint32(bb));
503
+ break;
504
+ case 12:
505
+ message.frameType = readVarint32(bb);
506
+ break;
507
+ default:
508
+ skipUnknownField(bb, 7 & tag);
509
+ }
510
+ }
511
+ if (void 0 === message.SeqID) throw new Error('Missing required field: SeqID');
512
+ if (void 0 === message.LogID) throw new Error('Missing required field: LogID');
513
+ if (void 0 === message.service) throw new Error('Missing required field: service');
514
+ if (void 0 === message.method) throw new Error('Missing required field: method');
515
+ return message;
516
+ }
517
+ function pushTemporaryLength(bb) {
518
+ const length = readVarint32(bb);
519
+ const limit = bb.limit;
520
+ bb.limit = bb.offset + length;
521
+ return limit;
522
+ }
523
+ function skipUnknownField(bb, type) {
524
+ switch(type){
525
+ case 0:
526
+ while(0x80 & readByte(bb));
527
+ break;
528
+ case 2:
529
+ skip(bb, readVarint32(bb));
530
+ break;
531
+ case 5:
532
+ skip(bb, 4);
533
+ break;
534
+ case 1:
535
+ skip(bb, 8);
536
+ break;
537
+ default:
538
+ throw new Error('Unimplemented type: ' + type);
539
+ }
540
+ }
541
+ function intToLong(value) {
542
+ value |= 0;
543
+ return {
544
+ low: value,
545
+ high: value >> 31,
546
+ unsigned: value >= 0
547
+ };
548
+ }
549
+ const bbStack = [];
550
+ function popByteBuffer() {
551
+ const bb = bbStack.pop();
552
+ if (!bb) return {
553
+ bytes: new Uint8Array(64),
554
+ offset: 0,
555
+ limit: 0
556
+ };
557
+ bb.offset = bb.limit = 0;
558
+ return bb;
559
+ }
560
+ function pushByteBuffer(bb) {
561
+ bbStack.push(bb);
562
+ }
563
+ function wrapByteBuffer(bytes) {
564
+ return {
565
+ bytes,
566
+ offset: 0,
567
+ limit: bytes.length
568
+ };
569
+ }
570
+ function toUint8Array(bb) {
571
+ const bytes = bb.bytes;
572
+ const limit = bb.limit;
573
+ return bytes.length === limit ? bytes : bytes.subarray(0, limit);
574
+ }
575
+ function skip(bb, offset) {
576
+ if (bb.offset + offset > bb.limit) throw new Error('Skip past limit');
577
+ bb.offset += offset;
578
+ }
579
+ function isAtEnd(bb) {
580
+ return bb.offset >= bb.limit;
581
+ }
582
+ function grow(bb, count) {
583
+ const bytes = bb.bytes;
584
+ const offset = bb.offset;
585
+ const limit = bb.limit;
586
+ const finalOffset = offset + count;
587
+ if (finalOffset > bytes.length) {
588
+ const newBytes = new Uint8Array(2 * finalOffset);
589
+ newBytes.set(bytes);
590
+ bb.bytes = newBytes;
591
+ }
592
+ bb.offset = finalOffset;
593
+ if (finalOffset > limit) bb.limit = finalOffset;
594
+ return offset;
595
+ }
596
+ function advance(bb, count) {
597
+ const offset = bb.offset;
598
+ if (offset + count > bb.limit) throw new Error('Read past limit');
599
+ bb.offset += count;
600
+ return offset;
601
+ }
602
+ function readBytes(bb, count) {
603
+ const offset = advance(bb, count);
604
+ return bb.bytes.subarray(offset, offset + count);
605
+ }
606
+ function writeBytes(bb, buffer) {
607
+ const offset = grow(bb, buffer.length);
608
+ bb.bytes.set(buffer, offset);
609
+ }
610
+ function readString(bb, count) {
611
+ const offset = advance(bb, count);
612
+ const fromCharCode = String.fromCharCode;
613
+ const bytes = bb.bytes;
614
+ const invalid = '\uFFFD';
615
+ let text = '';
616
+ for(let i = 0; i < count; i++){
617
+ const c1 = bytes[i + offset];
618
+ let c2, c3, c4, c;
619
+ if ((0x80 & c1) === 0) text += fromCharCode(c1);
620
+ else if ((0xe0 & c1) === 0xc0) if (i + 1 >= count) text += invalid;
621
+ else {
622
+ c2 = bytes[i + offset + 1];
623
+ if ((0xc0 & c2) !== 0x80) text += invalid;
624
+ else {
625
+ c = (0x1f & c1) << 6 | 0x3f & c2;
626
+ if (c < 0x80) text += invalid;
627
+ else {
628
+ text += fromCharCode(c);
629
+ i++;
630
+ }
631
+ }
632
+ }
633
+ else if ((0xf0 & c1) == 0xe0) if (i + 2 >= count) text += invalid;
634
+ else {
635
+ c2 = bytes[i + offset + 1];
636
+ c3 = bytes[i + offset + 2];
637
+ if (((c2 | c3 << 8) & 0xc0c0) !== 0x8080) text += invalid;
638
+ else {
639
+ c = (0x0f & c1) << 12 | (0x3f & c2) << 6 | 0x3f & c3;
640
+ if (c < 0x0800 || c >= 0xd800 && c <= 0xdfff) text += invalid;
641
+ else {
642
+ text += fromCharCode(c);
643
+ i += 2;
644
+ }
645
+ }
646
+ }
647
+ else if ((0xf8 & c1) == 0xf0) if (i + 3 >= count) text += invalid;
648
+ else {
649
+ c2 = bytes[i + offset + 1];
650
+ c3 = bytes[i + offset + 2];
651
+ c4 = bytes[i + offset + 3];
652
+ if (((c2 | c3 << 8 | c4 << 16) & 0xc0c0c0) !== 0x808080) text += invalid;
653
+ else {
654
+ c = (0x07 & c1) << 0x12 | (0x3f & c2) << 0x0c | (0x3f & c3) << 0x06 | 0x3f & c4;
655
+ if (c < 0x10000 || c > 0x10ffff) text += invalid;
656
+ else {
657
+ c -= 0x10000;
658
+ text += fromCharCode((c >> 10) + 0xd800, (0x3ff & c) + 0xdc00);
659
+ i += 3;
660
+ }
661
+ }
662
+ }
663
+ else text += invalid;
664
+ }
665
+ return text;
666
+ }
667
+ function writeString(bb, text) {
668
+ const n = text.length;
669
+ let byteCount = 0;
670
+ for(let i = 0; i < n; i++){
671
+ let c = text.charCodeAt(i);
672
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < n) c = (c << 10) + text.charCodeAt(++i) - 0x35fdc00;
673
+ byteCount += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
674
+ }
675
+ writeVarint32(bb, byteCount);
676
+ let offset = grow(bb, byteCount);
677
+ const bytes = bb.bytes;
678
+ for(let i = 0; i < n; i++){
679
+ let c = text.charCodeAt(i);
680
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < n) c = (c << 10) + text.charCodeAt(++i) - 0x35fdc00;
681
+ if (c < 0x80) bytes[offset++] = c;
682
+ else {
683
+ if (c < 0x800) bytes[offset++] = c >> 6 & 0x1f | 0xc0;
684
+ else {
685
+ if (c < 0x10000) bytes[offset++] = c >> 12 & 0x0f | 0xe0;
686
+ else {
687
+ bytes[offset++] = c >> 18 & 0x07 | 0xf0;
688
+ bytes[offset++] = c >> 12 & 0x3f | 0x80;
689
+ }
690
+ bytes[offset++] = c >> 6 & 0x3f | 0x80;
691
+ }
692
+ bytes[offset++] = 0x3f & c | 0x80;
693
+ }
694
+ }
695
+ }
696
+ function writeByteBuffer(bb, buffer) {
697
+ const offset = grow(bb, buffer.limit);
698
+ const from = bb.bytes;
699
+ const to = buffer.bytes;
700
+ for(let i = 0, n = buffer.limit; i < n; i++)from[i + offset] = to[i];
701
+ }
702
+ function readByte(bb) {
703
+ return bb.bytes[advance(bb, 1)];
704
+ }
705
+ function writeByte(bb, value) {
706
+ const offset = grow(bb, 1);
707
+ bb.bytes[offset] = value;
708
+ }
709
+ function readVarint32(bb) {
710
+ let c = 0;
711
+ let value = 0;
712
+ let b;
713
+ do {
714
+ b = readByte(bb);
715
+ if (c < 32) value |= (0x7f & b) << c;
716
+ c += 7;
717
+ }while (0x80 & b);
718
+ return value;
719
+ }
720
+ function writeVarint32(bb, value) {
721
+ value >>>= 0;
722
+ while(value >= 0x80){
723
+ writeByte(bb, 0x7f & value | 0x80);
724
+ value >>>= 7;
725
+ }
726
+ writeByte(bb, value);
727
+ }
728
+ function readVarint64(bb, unsigned) {
729
+ let part0 = 0;
730
+ let part1 = 0;
731
+ let part2 = 0;
732
+ let b;
733
+ b = readByte(bb);
734
+ part0 = 0x7f & b;
735
+ if (0x80 & b) {
736
+ b = readByte(bb);
737
+ part0 |= (0x7f & b) << 7;
738
+ if (0x80 & b) {
739
+ b = readByte(bb);
740
+ part0 |= (0x7f & b) << 14;
741
+ if (0x80 & b) {
742
+ b = readByte(bb);
743
+ part0 |= (0x7f & b) << 21;
744
+ if (0x80 & b) {
745
+ b = readByte(bb);
746
+ part1 = 0x7f & b;
747
+ if (0x80 & b) {
748
+ b = readByte(bb);
749
+ part1 |= (0x7f & b) << 7;
750
+ if (0x80 & b) {
751
+ b = readByte(bb);
752
+ part1 |= (0x7f & b) << 14;
753
+ if (0x80 & b) {
754
+ b = readByte(bb);
755
+ part1 |= (0x7f & b) << 21;
756
+ if (0x80 & b) {
757
+ b = readByte(bb);
758
+ part2 = 0x7f & b;
759
+ if (0x80 & b) {
760
+ b = readByte(bb);
761
+ part2 |= (0x7f & b) << 7;
762
+ }
763
+ }
764
+ }
765
+ }
766
+ }
767
+ }
768
+ }
769
+ }
770
+ }
771
+ return {
772
+ low: part0 | part1 << 28,
773
+ high: part1 >>> 4 | part2 << 24,
774
+ unsigned
775
+ };
776
+ }
777
+ function writeVarint64(bb, value) {
778
+ const part0 = value.low >>> 0;
779
+ const part1 = (value.low >>> 28 | value.high << 4) >>> 0;
780
+ const part2 = value.high >>> 24;
781
+ const size = 0 === part2 ? 0 === part1 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10;
782
+ const offset = grow(bb, size);
783
+ const bytes = bb.bytes;
784
+ switch(size){
785
+ case 10:
786
+ bytes[offset + 9] = part2 >>> 7 & 0x01;
787
+ case 9:
788
+ bytes[offset + 8] = 9 !== size ? 0x80 | part2 : 0x7f & part2;
789
+ case 8:
790
+ bytes[offset + 7] = 8 !== size ? part1 >>> 21 | 0x80 : part1 >>> 21 & 0x7f;
791
+ case 7:
792
+ bytes[offset + 6] = 7 !== size ? part1 >>> 14 | 0x80 : part1 >>> 14 & 0x7f;
793
+ case 6:
794
+ bytes[offset + 5] = 6 !== size ? part1 >>> 7 | 0x80 : part1 >>> 7 & 0x7f;
795
+ case 5:
796
+ bytes[offset + 4] = 5 !== size ? 0x80 | part1 : 0x7f & part1;
797
+ case 4:
798
+ bytes[offset + 3] = 4 !== size ? part0 >>> 21 | 0x80 : part0 >>> 21 & 0x7f;
799
+ case 3:
800
+ bytes[offset + 2] = 3 !== size ? part0 >>> 14 | 0x80 : part0 >>> 14 & 0x7f;
801
+ case 2:
802
+ bytes[offset + 1] = 2 !== size ? part0 >>> 7 | 0x80 : part0 >>> 7 & 0x7f;
803
+ case 1:
804
+ bytes[offset] = 1 !== size ? 0x80 | part0 : 0x7f & part0;
805
+ }
806
+ }
807
+ function decodedFrame(buffer) {
808
+ return decodeFrame(buffer);
809
+ }
810
+ function protobuf_encodeFrame(message) {
811
+ return encodeFrame(message);
812
+ }
813
+ const TWO_PWR_16_DBL = 65536;
814
+ const ZERO_HASH = '\0\0\0\0\0\0\0\0';
815
+ const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
816
+ const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
817
+ const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
818
+ const charCodeAt = String.prototype.charCodeAt;
819
+ class long_Long {
820
+ constructor(low, high, unsigned){
821
+ this.isLong = true;
822
+ this.low = 0 | low;
823
+ this.high = 0 | high;
824
+ this.unsigned = !!unsigned;
825
+ }
826
+ static isLong(obj) {
827
+ return obj && true === obj.isLong;
828
+ }
829
+ static fromBits(lowBits, highBits, unsigned) {
830
+ return new long_Long(lowBits, highBits, unsigned);
831
+ }
832
+ static fromBytes(bytes, unsigned, le) {
833
+ return le ? long_Long.fromBytesLE(bytes, unsigned) : long_Long.fromBytesBE(bytes, unsigned);
834
+ }
835
+ static fromBytesLE(bytes, unsigned) {
836
+ return new long_Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
837
+ }
838
+ static fromBytesBE(bytes, unsigned) {
839
+ return new long_Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
840
+ }
841
+ static fromHash(hash) {
842
+ if (hash === ZERO_HASH) return ZERO;
843
+ return new long_Long((charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0, true);
844
+ }
845
+ toHash() {
846
+ return String.fromCharCode(255 & this.low, this.low >>> 8 & 255, this.low >>> 16 & 255, this.low >>> 24, 255 & this.high, this.high >>> 8 & 255, this.high >>> 16 & 255, this.high >>> 24);
847
+ }
848
+ static fromNumber(value, unsigned = true) {
849
+ if (isNaN(value)) return unsigned ? UNSIGNED_ZERO : ZERO;
850
+ if (unsigned) {
851
+ if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
852
+ } else {
853
+ if (value <= -TWO_PWR_63_DBL) return MIN_VALUE;
854
+ if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
855
+ }
856
+ return long_Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
857
+ }
858
+ toNumber() {
859
+ if (this.unsigned) return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
860
+ return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
861
+ }
862
+ isZero() {
863
+ return 0 === this.high && 0 === this.low;
864
+ }
865
+ add(addend) {
866
+ if (!long_Long.isLong(addend)) addend = long_Long.fromNumber(addend);
867
+ const a48 = this.high >>> 16;
868
+ const a32 = 0xffff & this.high;
869
+ const a16 = this.low >>> 16;
870
+ const a00 = 0xffff & this.low;
871
+ const b48 = addend.high >>> 16;
872
+ const b32 = 0xffff & addend.high;
873
+ const b16 = addend.low >>> 16;
874
+ const b00 = 0xffff & addend.low;
875
+ let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
876
+ c00 += a00 + b00;
877
+ c16 += c00 >>> 16;
878
+ c00 &= 0xffff;
879
+ c16 += a16 + b16;
880
+ c32 += c16 >>> 16;
881
+ c16 &= 0xffff;
882
+ c32 += a32 + b32;
883
+ c48 += c32 >>> 16;
884
+ c32 &= 0xffff;
885
+ c48 += a48 + b48;
886
+ c48 &= 0xffff;
887
+ return long_Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
888
+ }
889
+ equals(other) {
890
+ if (!long_Long.isLong(other)) other = long_Long.fromNumber(other);
891
+ if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;
892
+ return this.high === other.high && this.low === other.low;
893
+ }
894
+ addOne() {
895
+ if (-1 === this.low && -1 === this.high) return long_Long.fromBits(0, 0, this.unsigned);
896
+ if (-1 === this.low) return long_Long.fromBits(0, this.high + 1, this.unsigned);
897
+ return long_Long.fromBits(this.low + 1, this.high, this.unsigned);
898
+ }
899
+ toBytes(le) {
900
+ return le ? this.toBytesLE() : this.toBytesBE();
901
+ }
902
+ toBytesLE() {
903
+ const hi = this.high, lo = this.low;
904
+ return [
905
+ 0xff & lo,
906
+ lo >>> 8 & 0xff,
907
+ lo >>> 16 & 0xff,
908
+ lo >>> 24,
909
+ 0xff & hi,
910
+ hi >>> 8 & 0xff,
911
+ hi >>> 16 & 0xff,
912
+ hi >>> 24
913
+ ];
914
+ }
915
+ toBytesBE() {
916
+ const hi = this.high, lo = this.low;
917
+ return [
918
+ hi >>> 24,
919
+ hi >>> 16 & 0xff,
920
+ hi >>> 8 & 0xff,
921
+ 0xff & hi,
922
+ lo >>> 24,
923
+ lo >>> 16 & 0xff,
924
+ lo >>> 8 & 0xff,
925
+ 0xff & lo
926
+ ];
927
+ }
928
+ }
929
+ const ZERO = new long_Long(0, 0, false);
930
+ const UNSIGNED_ZERO = new long_Long(0, 0, true);
931
+ const MAX_VALUE = long_Long.fromBits(-1, 2147483647, false);
932
+ const MAX_UNSIGNED_VALUE = long_Long.fromBits(-1, -1, true);
933
+ const MIN_VALUE = long_Long.fromBits(0, -2147483648, false);
934
+ var event_ErrorCode = /*#__PURE__*/ function(ErrorCode) {
935
+ ErrorCode[ErrorCode["NATIVE_ERROR"] = 5001] = "NATIVE_ERROR";
936
+ ErrorCode[ErrorCode["CONNECTING_ERROR"] = 5002] = "CONNECTING_ERROR";
937
+ ErrorCode[ErrorCode["MAX_RETRIES_ERROR"] = 5003] = "MAX_RETRIES_ERROR";
938
+ ErrorCode[ErrorCode["MESSAGE_ERROR"] = 5004] = "MESSAGE_ERROR";
939
+ ErrorCode[ErrorCode["OPEN_ERROR"] = 5005] = "OPEN_ERROR";
940
+ return ErrorCode;
941
+ }({});
942
+ class Event {
943
+ constructor(type){
944
+ this.type = type;
945
+ this.target = null;
946
+ }
947
+ }
948
+ class ReconnectEvent extends Event {
949
+ constructor(type, eventInitDict){
950
+ super(type);
951
+ this.message = eventInitDict && eventInitDict.message || null;
952
+ }
953
+ }
954
+ class CustomErrorEvent extends Event {
955
+ constructor(type, eventInitDict){
956
+ super(type);
957
+ this.error = eventInitDict && eventInitDict.error || null;
958
+ this.colno = eventInitDict && eventInitDict.colno || 0;
959
+ this.filename = eventInitDict && eventInitDict.filename || '';
960
+ this.lineno = eventInitDict && eventInitDict.lineno || 0;
961
+ this.message = eventInitDict && eventInitDict.message || '';
962
+ this.code = eventInitDict && eventInitDict.code || 5001;
963
+ }
964
+ }
965
+ class CustomCloseEvent extends Event {
966
+ constructor(type, eventInitDict){
967
+ super(type);
968
+ this.code = eventInitDict && eventInitDict.code || 0;
969
+ this.reason = eventInitDict && eventInitDict.reason || '';
970
+ this.wasClean = eventInitDict && eventInitDict.wasClean || false;
971
+ this.willReconnect = eventInitDict && eventInitDict.willReconnect || false;
972
+ }
973
+ }
974
+ class MessageEvent extends Event {
975
+ constructor(type, eventInitDict){
976
+ super(type);
977
+ this.data = eventInitDict && eventInitDict.data || null;
978
+ }
979
+ }
980
+ class FrontierMessageEvent extends MessageEvent {
981
+ constructor(type, eventInitDict){
982
+ super(type);
983
+ this.data = eventInitDict && eventInitDict.data || null;
984
+ this.message = eventInitDict && eventInitDict.message || null;
985
+ }
986
+ }
987
+ class OpenEvent extends Event {
988
+ constructor(type, eventInitDict){
989
+ super(type);
990
+ this.data = eventInitDict && eventInitDict.data || null;
991
+ }
992
+ }
993
+ function createErrorEvent(type, { message, code, error }) {
994
+ return new CustomErrorEvent(type, {
995
+ message,
996
+ code,
997
+ error
998
+ });
999
+ }
1000
+ function createCloseEvent(type, { code, reason, wasClean, willReconnect }) {
1001
+ return new CustomCloseEvent(type, {
1002
+ code,
1003
+ reason,
1004
+ wasClean,
1005
+ willReconnect
1006
+ });
1007
+ }
1008
+ function createMessageEvent(type, { data, message }) {
1009
+ return new FrontierMessageEvent(type, {
1010
+ data,
1011
+ message
1012
+ });
1013
+ }
1014
+ function createOpenEvent(type, { data }) {
1015
+ return new OpenEvent(type, {
1016
+ data
1017
+ });
1018
+ }
1019
+ function createReconnectEvent(type, { message }) {
1020
+ return new ReconnectEvent(type, {
1021
+ message
1022
+ });
1023
+ }
1024
+ class EndpointManager {
1025
+ constructor(endpoints, maxRetries){
1026
+ this.endpoints = endpoints;
1027
+ this.maxRetries = maxRetries;
1028
+ this.currentIndex = 0;
1029
+ this.currentEndpointTriesCount = 0;
1030
+ }
1031
+ resetEndpointConfig() {
1032
+ this.currentIndex = 0;
1033
+ this.currentEndpointTriesCount = 0;
1034
+ }
1035
+ resetTries() {
1036
+ this.currentEndpointTriesCount = 0;
1037
+ }
1038
+ getCurrentEndpoint() {
1039
+ return this.endpoints[this.currentIndex];
1040
+ }
1041
+ getCurrentEndpointTriesCount() {
1042
+ return this.currentEndpointTriesCount;
1043
+ }
1044
+ checkReachMaxTries() {
1045
+ if (this.currentIndex >= this.endpoints.length) return true;
1046
+ if (this.currentIndex === this.endpoints.length - 1 && this.currentEndpointTriesCount === this.maxRetries) return true;
1047
+ return false;
1048
+ }
1049
+ checkCurrentEndpointReachedMaxRetries() {
1050
+ if (this.currentIndex == this.endpoints.length) return true;
1051
+ return this.currentEndpointTriesCount > this.maxRetries;
1052
+ }
1053
+ replaceBackupEndpointAndUpdateCount() {
1054
+ this.currentEndpointTriesCount = 1;
1055
+ this.currentIndex++;
1056
+ return this.endpoints[this.currentIndex];
1057
+ }
1058
+ getCurrentEndpointAndUpdateCount() {
1059
+ this.currentEndpointTriesCount++;
1060
+ return this.getCurrentEndpoint();
1061
+ }
1062
+ }
1063
+ const IS_BROWSER = ('undefined' != typeof globalThis && 'Window' === globalThis.constructor.name || 'undefined' != typeof window && 'Window' === window.constructor.name) && 'undefined' != typeof document;
1064
+ const IS_MINI_TT = 'undefined' != typeof globalThis && ('Object' === globalThis.constructor.name || 'DedicatedWorkerGlobalScope' === globalThis.constructor.name) && 'undefined' != typeof tt;
1065
+ const IS_MINI_WX = ('undefined' != typeof globalThis && 'Object' === globalThis.constructor.name || 'undefined' == typeof globalThis || 'undefined' != typeof globalThis && !!globalThis.WeixinJSBridge) && 'undefined' != typeof wx;
1066
+ const IS_WORKER = 'undefined' != typeof globalThis && ('DedicatedWorkerGlobalScope' === globalThis.constructor.name || 'SharedWorkerGlobalScope' === globalThis.constructor.name || 'ServiceWorkerGlobalScope' === globalThis.constructor.name) && 'undefined' != typeof self;
1067
+ const IS_NODE = 'undefined' != typeof globalThis && 'Object' === globalThis.constructor.name && void 0 !== __webpack_require__.g && 'Object' === __webpack_require__.g.constructor.name && 'undefined' != typeof process && !!process.version;
1068
+ class EventEmitter {
1069
+ constructor(){
1070
+ this._listeners = {};
1071
+ }
1072
+ emit(evt, ...args) {
1073
+ const listeners = this._listeners[evt];
1074
+ if (listeners) listeners.slice().forEach((listener)=>listener.fn.apply(listener.ctx, args));
1075
+ else if ('error' === evt && !this.onerror) {
1076
+ const err = args.length && args[0];
1077
+ if (err instanceof Error) throw err;
1078
+ const error = new Error('Unhandled error.' + (err ? ' (' + err.message + ')' : ''));
1079
+ error.context = err;
1080
+ throw err;
1081
+ }
1082
+ return this;
1083
+ }
1084
+ off(evt, fn) {
1085
+ if (void 0 === evt) this._listeners = {};
1086
+ else if (void 0 === fn) this._listeners[evt] = null;
1087
+ else {
1088
+ const listeners = this._listeners[evt];
1089
+ if (listeners) for(let i = 0; i < listeners.length;)if (listeners[i].fn === fn) listeners.splice(i, 1);
1090
+ else ++i;
1091
+ }
1092
+ return this;
1093
+ }
1094
+ on(evt, fn, ctx) {
1095
+ (this._listeners[evt] || (this._listeners[evt] = [])).push({
1096
+ fn: fn,
1097
+ ctx: ctx || this
1098
+ });
1099
+ return this;
1100
+ }
1101
+ }
1102
+ class MiniWebSocket extends EventEmitter {
1103
+ _formatErrorMessage(error) {
1104
+ if (error.errMsg || error.errNo) return `message: ${error.errMsg || ''} code: ${error.errNo || ''}`.trim();
1105
+ return JSON.stringify(error);
1106
+ }
1107
+ constructor(url, protocols, headers){
1108
+ super(), this._socket = null;
1109
+ if (IS_MINI_WX && wx.connectSocket) this._socket = wx.connectSocket({
1110
+ url: url,
1111
+ protocols: protocols,
1112
+ header: headers,
1113
+ fail: this._createSocketFailHandler.bind(this),
1114
+ success: this._createSocketSuccessHandler.bind(this)
1115
+ });
1116
+ if (IS_MINI_TT && tt.connectSocket) this._socket = tt.connectSocket({
1117
+ url: url,
1118
+ protocols: protocols,
1119
+ header: headers,
1120
+ fail: this._createSocketFailHandler.bind(this),
1121
+ success: this._createSocketSuccessHandler.bind(this)
1122
+ });
1123
+ }
1124
+ _createSocketSuccessHandler() {
1125
+ Promise.resolve().then(()=>{
1126
+ this._addWsListeners();
1127
+ });
1128
+ }
1129
+ _createSocketFailHandler(error) {
1130
+ Promise.resolve().then(()=>{
1131
+ const errorEvent = createErrorEvent('error', {
1132
+ message: this._formatErrorMessage(error)
1133
+ });
1134
+ this.emit('error', errorEvent);
1135
+ const closeEvent = createCloseEvent('close', {
1136
+ reason: this._formatErrorMessage(error)
1137
+ });
1138
+ this.emit('close', closeEvent);
1139
+ });
1140
+ }
1141
+ _addWsListeners() {
1142
+ this._socket.onOpen((event)=>{
1143
+ this.emit('open', createOpenEvent('open', {
1144
+ ...event,
1145
+ data: event.errMsg || ''
1146
+ }));
1147
+ });
1148
+ this._socket.onClose((event)=>{
1149
+ this.emit('close', createCloseEvent('close', {
1150
+ ...event
1151
+ }));
1152
+ });
1153
+ this._socket.onMessage((event)=>{
1154
+ this.emit('message', createMessageEvent('message', {
1155
+ ...event
1156
+ }));
1157
+ });
1158
+ this._socket.onError((event)=>{
1159
+ this.emit('error', createErrorEvent('error', {
1160
+ ...event,
1161
+ message: event.errMsg || ''
1162
+ }));
1163
+ });
1164
+ }
1165
+ send(data) {
1166
+ if (data instanceof Uint8Array) {
1167
+ const buffer = data.buffer.slice(data.byteOffset, data.byteLength + data.byteOffset);
1168
+ this._socket && this._socket.send({
1169
+ data: buffer,
1170
+ fail: (err)=>{
1171
+ this.emit('error', createErrorEvent('error', {
1172
+ message: this._formatErrorMessage(err)
1173
+ }));
1174
+ }
1175
+ });
1176
+ } else this._socket && this._socket.send({
1177
+ data,
1178
+ fail: (err)=>{
1179
+ this.emit('error', createErrorEvent('error', {
1180
+ message: this._formatErrorMessage(err)
1181
+ }));
1182
+ }
1183
+ });
1184
+ }
1185
+ close(code, reason) {
1186
+ this._socket && this._socket.close({
1187
+ code,
1188
+ reason
1189
+ });
1190
+ }
1191
+ addEventListener(type, listener) {
1192
+ this.on(type, listener);
1193
+ }
1194
+ removeEventListener(type, listener) {
1195
+ this.off(type, listener);
1196
+ }
1197
+ get readyState() {
1198
+ return this._socket.readyState;
1199
+ }
1200
+ get binaryType() {
1201
+ return this._socket.binaryType;
1202
+ }
1203
+ set binaryType(_val) {}
1204
+ get url() {
1205
+ return this._socket.url;
1206
+ }
1207
+ get protocol() {
1208
+ return this._socket.protocol;
1209
+ }
1210
+ get extensions() {
1211
+ return this._socket.extensions;
1212
+ }
1213
+ get bufferedAmount() {
1214
+ return 0;
1215
+ }
1216
+ }
1217
+ function globalWebSocketInit(params, ws) {
1218
+ if (ws) return new ws(params.url, params.protocol);
1219
+ if (IS_MINI_WX || IS_MINI_TT) return new MiniWebSocket(params.url, params.protocol, params.headers);
1220
+ if ((IS_BROWSER || IS_WORKER) && 'undefined' != typeof WebSocket && !!WebSocket) return new WebSocket(params.url, params.protocols);
1221
+ }
1222
+ function checkWebSocketConstructorValid(ws) {
1223
+ if (ws) return true;
1224
+ if (IS_MINI_WX && wx.connectSocket) return true;
1225
+ if (IS_MINI_TT && tt.connectSocket) return true;
1226
+ if ((IS_BROWSER || IS_WORKER) && 'undefined' != typeof WebSocket && !!WebSocket) return true;
1227
+ return false;
1228
+ }
1229
+ function processTrigger(self1, ctx, process1) {
1230
+ let index = -1;
1231
+ async function dispatch(i) {
1232
+ if (i <= index) return Promise.reject(new Error('next() called multiple times in process'));
1233
+ index = i;
1234
+ if (i === process1.length) return Promise.resolve();
1235
+ const fn = process1[i];
1236
+ return fn.bind(self1)(ctx, dispatch.bind(null, i + 1));
1237
+ }
1238
+ dispatch(0);
1239
+ }
1240
+ function utf8Length(string) {
1241
+ let len = 0, c = 0;
1242
+ for(let i = 0; i < string.length; ++i){
1243
+ c = string.charCodeAt(i);
1244
+ if (c < 128) len += 1;
1245
+ else if (c < 2048) len += 2;
1246
+ else if ((0xfc00 & c) === 0xd800 && (0xfc00 & string.charCodeAt(i + 1)) === 0xdc00) {
1247
+ ++i;
1248
+ len += 4;
1249
+ } else len += 3;
1250
+ }
1251
+ return len;
1252
+ }
1253
+ function utf8_utf8Read(buffer, start, end) {
1254
+ if (end - start < 1) return '';
1255
+ let str = '';
1256
+ for(let i = start; i < end;){
1257
+ const t = buffer[i++];
1258
+ if (t <= 0x7f) str += String.fromCharCode(t);
1259
+ else if (t >= 0xc0 && t < 0xe0) str += String.fromCharCode((0x1f & t) << 6 | 0x3f & buffer[i++]);
1260
+ else if (t >= 0xe0 && t < 0xf0) str += String.fromCharCode((0xf & t) << 12 | (0x3f & buffer[i++]) << 6 | 0x3f & buffer[i++]);
1261
+ else if (t >= 0xf0) {
1262
+ const t2 = ((7 & t) << 18 | (0x3f & buffer[i++]) << 12 | (0x3f & buffer[i++]) << 6 | 0x3f & buffer[i++]) - 0x10000;
1263
+ str += String.fromCharCode(0xd800 + (t2 >> 10));
1264
+ str += String.fromCharCode(0xdc00 + (0x3ff & t2));
1265
+ }
1266
+ }
1267
+ return str;
1268
+ }
1269
+ function utf8Write(string, buffer, offset) {
1270
+ const start = offset;
1271
+ let c1, c2;
1272
+ for(let i = 0; i < string.length; ++i){
1273
+ c1 = string.charCodeAt(i);
1274
+ if (c1 < 128) buffer[offset++] = c1;
1275
+ else if (c1 < 2048) {
1276
+ buffer[offset++] = c1 >> 6 | 192;
1277
+ buffer[offset++] = 63 & c1 | 128;
1278
+ } else if ((0xfc00 & c1) === 0xd800 && (0xfc00 & (c2 = string.charCodeAt(i + 1))) === 0xdc00) {
1279
+ c1 = 0x10000 + ((0x03ff & c1) << 10) + (0x03ff & c2);
1280
+ ++i;
1281
+ buffer[offset++] = c1 >> 18 | 240;
1282
+ buffer[offset++] = c1 >> 12 & 63 | 128;
1283
+ buffer[offset++] = c1 >> 6 & 63 | 128;
1284
+ buffer[offset++] = 63 & c1 | 128;
1285
+ } else {
1286
+ buffer[offset++] = c1 >> 12 | 224;
1287
+ buffer[offset++] = c1 >> 6 & 63 | 128;
1288
+ buffer[offset++] = 63 & c1 | 128;
1289
+ }
1290
+ }
1291
+ return offset - start;
1292
+ }
1293
+ async function dataToUnit8Array(data) {
1294
+ if ('string' == typeof data) {
1295
+ const buffer = new Uint8Array(utf8Length(data));
1296
+ utf8Write(data, buffer, 0);
1297
+ return buffer;
1298
+ }
1299
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1300
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1301
+ }
1302
+ function checkPayloadType(payload) {
1303
+ try {
1304
+ if ('string' != typeof payload && (payload instanceof ArrayBuffer || payload.buffer && payload.buffer instanceof ArrayBuffer)) return '';
1305
+ if ('string' != typeof payload) return '';
1306
+ JSON.parse(payload);
1307
+ return 'application/json';
1308
+ } catch {
1309
+ if ('string' == typeof payload) return 'text/plain;charset=utf-8';
1310
+ return '';
1311
+ }
1312
+ }
1313
+ const envParamsGen = (xUseEnv, xTTEnv)=>{
1314
+ switch(xUseEnv){
1315
+ case 'boe':
1316
+ case 'ppe':
1317
+ return {
1318
+ [`x-use-${xUseEnv}`]: 1,
1319
+ 'x-tt-env': xTTEnv
1320
+ };
1321
+ default:
1322
+ return {};
1323
+ }
1324
+ };
1325
+ class PkgLossCounter {
1326
+ constructor(maxLossCount){
1327
+ this.maxLossCount = maxLossCount;
1328
+ this.count = 0;
1329
+ }
1330
+ addCount() {
1331
+ this.count++;
1332
+ }
1333
+ checkReachMaxCount() {
1334
+ return this.count >= this.maxLossCount;
1335
+ }
1336
+ resetCounter(maxCount = 0) {
1337
+ this.maxLossCount = maxCount;
1338
+ this.count = 0;
1339
+ }
1340
+ }
1341
+ async function getSocketError(url) {
1342
+ return new Promise((resolve)=>{
1343
+ if (!IS_BROWSER) return resolve('unknown reason');
1344
+ try {
1345
+ const script = document.createElement("script");
1346
+ window.frontierJSONP = (reason)=>{
1347
+ document.body.removeChild(script);
1348
+ window.frontierJSONP = void 0;
1349
+ resolve(reason && reason.msg || 'unknown reason');
1350
+ };
1351
+ script.type = "text/javascript";
1352
+ script.src = url.replace(/^ws/, 'http') + '&jscallback=frontierJSONP';
1353
+ try {
1354
+ document.body.appendChild(script);
1355
+ } catch {
1356
+ document.body.removeChild(script);
1357
+ }
1358
+ } catch {
1359
+ window.frontierJSONP = void 0;
1360
+ resolve('unknown reason');
1361
+ }
1362
+ });
1363
+ }
1364
+ function getKeyBoolean(headers, key, value) {
1365
+ return !!headers?.find((header)=>header.key === key && header.value === value);
1366
+ }
1367
+ function getKeyValue(headers, key) {
1368
+ return headers?.find((header)=>header.key === key)?.value;
1369
+ }
1370
+ let openDBLoader = null;
1371
+ async function loadOpenDB() {
1372
+ if (!openDBLoader) openDBLoader = Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/idb@7.0.2/node_modules/idb/build/index.js"));
1373
+ return openDBLoader;
1374
+ }
1375
+ class QoSDB extends EventEmitter {
1376
+ constructor(_dbName, _keyPath){
1377
+ super(), this._dbName = _dbName, this._keyPath = _keyPath, this._qosDB = void 0, this._initPromise = null;
1378
+ }
1379
+ async openDB() {
1380
+ await this._init();
1381
+ }
1382
+ async _init() {
1383
+ if (this._qosDB) return;
1384
+ if (this._initPromise) return this._initPromise;
1385
+ try {
1386
+ const dbName = this._dbName;
1387
+ const keyPath = this._keyPath;
1388
+ this._initPromise = (async ()=>{
1389
+ const { openDB } = await loadOpenDB();
1390
+ this._qosDB = await openDB(`frontier_${dbName}`, 1, {
1391
+ upgrade (db) {
1392
+ db.createObjectStore(dbName, {
1393
+ keyPath: keyPath
1394
+ });
1395
+ }
1396
+ });
1397
+ })();
1398
+ await this._initPromise;
1399
+ } catch (e) {
1400
+ console.log(e);
1401
+ } finally{
1402
+ this._initPromise = null;
1403
+ }
1404
+ }
1405
+ async get(key) {
1406
+ try {
1407
+ await this._init();
1408
+ return this._qosDB?.get(this._dbName, key);
1409
+ } catch (e) {
1410
+ console.log(e);
1411
+ }
1412
+ }
1413
+ async set(val, _key) {
1414
+ await this._init();
1415
+ return this._qosDB?.put(this._dbName, val);
1416
+ }
1417
+ async del(key) {
1418
+ try {
1419
+ await this._init();
1420
+ return this._qosDB?.delete(this._dbName, key);
1421
+ } catch (e) {
1422
+ console.log(e);
1423
+ }
1424
+ }
1425
+ async clear() {
1426
+ try {
1427
+ await this._init();
1428
+ return this._qosDB?.clear(this._dbName);
1429
+ } catch (e) {
1430
+ console.log(e);
1431
+ }
1432
+ }
1433
+ async keys() {
1434
+ await this._init();
1435
+ return this._qosDB?.getAllKeys(this._dbName);
1436
+ }
1437
+ async getAll() {
1438
+ await this._init();
1439
+ return this._qosDB?.getAll(this._dbName);
1440
+ }
1441
+ async closeDB() {
1442
+ try {
1443
+ this._qosDB?.close();
1444
+ this._qosDB = void 0;
1445
+ } catch (e) {
1446
+ console.log(e);
1447
+ }
1448
+ }
1449
+ get isReady() {
1450
+ try {
1451
+ return !!this._qosDB;
1452
+ } catch (e) {
1453
+ console.log(e);
1454
+ return false;
1455
+ }
1456
+ }
1457
+ }
1458
+ class QoSLocalStorage {
1459
+ constructor(_DBName, _pathKey){
1460
+ this._DBName = _DBName;
1461
+ this._pathKey = _pathKey;
1462
+ this._qosDB = localStorage;
1463
+ }
1464
+ async openDB() {}
1465
+ get _prefix() {
1466
+ return `frontier_${this._DBName}`;
1467
+ }
1468
+ async get(key) {
1469
+ const jsonString = this._qosDB.getItem(this._prefix);
1470
+ const jsonData = JSON.parse(jsonString || '{}');
1471
+ return jsonData[key];
1472
+ }
1473
+ async set(val, key) {
1474
+ const jsonString = this._qosDB.getItem(this._prefix);
1475
+ const jsonData = JSON.parse(jsonString || '{}');
1476
+ jsonData[key || val[this._pathKey]] = val;
1477
+ this._qosDB.setItem(this._prefix, JSON.stringify(jsonData));
1478
+ return key || val[this._pathKey];
1479
+ }
1480
+ async del(key) {
1481
+ const jsonString = this._qosDB.getItem(this._prefix);
1482
+ const jsonData = JSON.parse(jsonString || '{}');
1483
+ jsonData[key] = void 0;
1484
+ return this._qosDB.setItem(this._prefix, JSON.stringify(jsonData));
1485
+ }
1486
+ async clear() {
1487
+ return this._qosDB.clear();
1488
+ }
1489
+ async keys() {
1490
+ const jsonString = this._qosDB.getItem(this._prefix);
1491
+ const jsonData = JSON.parse(jsonString || '{}');
1492
+ return Object.keys(jsonData);
1493
+ }
1494
+ async getAll() {
1495
+ const jsonString = this._qosDB.getItem(this._prefix);
1496
+ const jsonData = JSON.parse(jsonString || '{}');
1497
+ return Object.values(jsonData);
1498
+ }
1499
+ closeDB() {
1500
+ return Promise.resolve();
1501
+ }
1502
+ get isReady() {
1503
+ return !!this._qosDB;
1504
+ }
1505
+ }
1506
+ class QoSMiniStorage {
1507
+ constructor(_DBName, _pathKey){
1508
+ this._DBName = _DBName;
1509
+ this._pathKey = _pathKey;
1510
+ this._qosDB = IS_MINI_TT ? tt : IS_MINI_WX ? wx : null;
1511
+ }
1512
+ async openDB() {}
1513
+ get _prefix() {
1514
+ return `frontier_${this._DBName}`;
1515
+ }
1516
+ async get(key) {
1517
+ const jsonString = this._qosDB.getStorageSync(this._prefix);
1518
+ const jsonData = JSON.parse(jsonString || '{}');
1519
+ return jsonData[key];
1520
+ }
1521
+ async set(val, key) {
1522
+ const jsonString = this._qosDB.getStorageSync(this._prefix);
1523
+ const jsonData = JSON.parse(jsonString || '{}');
1524
+ jsonData[key || val[this._pathKey]] = val;
1525
+ this._qosDB.setStorageSync(this._prefix, JSON.stringify(jsonData));
1526
+ return key || val[this._pathKey];
1527
+ }
1528
+ async del(key) {
1529
+ const jsonString = this._qosDB.getStorageSync(this._prefix);
1530
+ const jsonData = JSON.parse(jsonString || '{}');
1531
+ jsonData[key] = void 0;
1532
+ return this._qosDB.setStorageSync(this._prefix, JSON.stringify(jsonData));
1533
+ }
1534
+ async clear() {
1535
+ return this._qosDB.clearStorageSync();
1536
+ }
1537
+ async keys() {
1538
+ const jsonString = this._qosDB.getStorageInfoSync(this._prefix);
1539
+ const jsonData = JSON.parse(jsonString || '{}');
1540
+ return Object.keys(jsonData);
1541
+ }
1542
+ async getAll() {
1543
+ const jsonString = this._qosDB.getStorageInfoSync(this._prefix);
1544
+ const jsonData = JSON.parse(jsonString || '{}');
1545
+ return Object.values(jsonData);
1546
+ }
1547
+ closeDB() {
1548
+ return Promise.resolve();
1549
+ }
1550
+ get isReady() {
1551
+ return !!this._qosDB;
1552
+ }
1553
+ }
1554
+ function getQoSDB(dbName, keyPath) {
1555
+ if (IS_MINI_TT || IS_MINI_TT) return new QoSMiniStorage(dbName, keyPath);
1556
+ if ((IS_BROWSER || IS_WORKER) && 'undefined' != typeof indexedDB) return new QoSDB(dbName, keyPath);
1557
+ if ((IS_BROWSER || IS_WORKER) && 'undefined' != typeof localStorage) return new QoSLocalStorage(dbName, keyPath);
1558
+ throw new Error('init QoSDB failed');
1559
+ }
1560
+ class QoSManager {
1561
+ constructor(){
1562
+ this._intervalTimeoutId = null;
1563
+ this._interval = 3600000;
1564
+ this._qosDB = getQoSDB('qos', 'message_id');
1565
+ }
1566
+ async _intervalFlush() {
1567
+ clearInterval(this._intervalTimeoutId);
1568
+ this._intervalTimeoutId = setInterval(()=>{
1569
+ this.flushExpired();
1570
+ }, this._interval);
1571
+ }
1572
+ async openDB() {
1573
+ await this._qosDB.openDB().then(()=>{
1574
+ this._intervalFlush();
1575
+ });
1576
+ }
1577
+ async flushExpired() {
1578
+ const allMsgs = await this._qosDB?.getAll() || [];
1579
+ const expiredMsgs = allMsgs.filter(({ timestamp })=>timestamp < Date.now());
1580
+ expiredMsgs.forEach((msg)=>{
1581
+ this._qosDB?.del(msg.message_id);
1582
+ });
1583
+ }
1584
+ async del(msgID) {
1585
+ return this._qosDB?.del(msgID);
1586
+ }
1587
+ async set(msgID, timestamp) {
1588
+ return this._qosDB?.set({
1589
+ message_id: msgID,
1590
+ timestamp
1591
+ });
1592
+ }
1593
+ async get(msgID) {
1594
+ return this._qosDB?.get(msgID);
1595
+ }
1596
+ async closeDB() {
1597
+ clearInterval(this._intervalTimeoutId);
1598
+ await this._qosDB?.closeDB();
1599
+ }
1600
+ get isReady() {
1601
+ return this._qosDB?.isReady;
1602
+ }
1603
+ }
1604
+ function getFrontierQoSState(ctx) {
1605
+ const enabled = !!this._options.enableQoS;
1606
+ if (!enabled) return {
1607
+ enabled,
1608
+ isQoSMessage: false,
1609
+ isQoSAck: false,
1610
+ isAckCleanupMessage: false,
1611
+ ackMsgIds: []
1612
+ };
1613
+ const isQoSMessage = getKeyBoolean(ctx.message.headers, 'x_frontier_qos', '2');
1614
+ const isQoSAck = isQoSMessage && getKeyBoolean(ctx.message.headers, 'x_frontier_qos_ack', '1');
1615
+ const isAckCleanupMessage = isQoSMessage && getKeyBoolean(ctx.message.headers, 'x_frontier_is_ack', '1');
1616
+ const ackMsgIds = isAckCleanupMessage ? getKeyValue(ctx.message.headers, 'x_frontier_ack_msgid')?.split(',').filter(Boolean) || [] : [];
1617
+ return {
1618
+ enabled,
1619
+ isQoSMessage,
1620
+ isQoSAck,
1621
+ isAckCleanupMessage,
1622
+ ackMsgIds
1623
+ };
1624
+ }
1625
+ async function ensureQoSManager() {
1626
+ if (!this._QoSManager) this._QoSManager = new QoSManager();
1627
+ if (!this._QoSManager.isReady) await this._QoSManager.openDB();
1628
+ return this._QoSManager;
1629
+ }
1630
+ async function ackProcess(ctx, next) {
1631
+ const { enableAutoAck } = this._options;
1632
+ const needAck = getKeyBoolean(ctx.message.headers, 'need_ack', '1');
1633
+ const isAck = getKeyBoolean(ctx.message.headers, 'is_ack', '1');
1634
+ const qosState = getFrontierQoSState.call(this, ctx);
1635
+ if (enableAutoAck && needAck) {
1636
+ const { SeqID, LogID, service, LogIDNew, method } = ctx.message;
1637
+ this._sendAck({
1638
+ SeqID,
1639
+ LogID,
1640
+ LogIDNew,
1641
+ service,
1642
+ method,
1643
+ headers: [
1644
+ {
1645
+ key: 'is_ack',
1646
+ value: '1'
1647
+ },
1648
+ {
1649
+ key: 'ack_id',
1650
+ value: LogIDNew || ''
1651
+ },
1652
+ {
1653
+ key: 'ack_code',
1654
+ value: '0'
1655
+ }
1656
+ ]
1657
+ });
1658
+ }
1659
+ if (isAck && !qosState.isQoSAck) this._dispatchAckMessageEvent(ctx);
1660
+ next();
1661
+ }
1662
+ async function finishMessageProcess(ctx, next) {
1663
+ this._debug('received', ctx.message);
1664
+ next();
1665
+ }
1666
+ async function decodeMessageProcess(ctx, next) {
1667
+ const data = decodedFrame(await dataToUnit8Array(ctx.data));
1668
+ try {
1669
+ if (data.payload instanceof Uint8Array) {
1670
+ const localPayloadEncoding = this._options.payloadEncoding instanceof Object ? {
1671
+ force: !!this._options.payloadEncoding.force,
1672
+ encoding: this._options.payloadEncoding.encoding ? this._options.payloadEncoding.encoding.replace(/\s/g, '').toLowerCase() : ''
1673
+ } : {
1674
+ force: false,
1675
+ encoding: this._options.payloadEncoding ? this._options.payloadEncoding.replace(/\s/g, '').toLowerCase() : ''
1676
+ };
1677
+ const remotePayloadEncoding = data.payloadEncoding ? data.payloadEncoding.replace(/\s/g, '').toLowerCase() : '';
1678
+ const localPayloadType = this._options.payloadType instanceof Object ? {
1679
+ force: !!this._options.payloadType.force,
1680
+ type: this._options.payloadType.type ? this._options.payloadType.type.replace(/\s/g, '').toLowerCase() : ''
1681
+ } : {
1682
+ force: false,
1683
+ type: this._options.payloadType ? this._options.payloadType.replace(/\s/g, '').toLowerCase() : ''
1684
+ };
1685
+ const remotePayloadType = data.payloadType ? data.payloadType.replace(/\s/g, '').toLowerCase() : '';
1686
+ const payloadType = localPayloadType.force ? localPayloadType.type : remotePayloadType ? remotePayloadType : localPayloadType.type;
1687
+ const payloadEncoding = localPayloadEncoding.force ? localPayloadEncoding.encoding : remotePayloadEncoding ? remotePayloadEncoding : localPayloadEncoding.encoding;
1688
+ const encodingAllowList = [
1689
+ 'text/plain;charset=utf-8',
1690
+ 'application/json',
1691
+ 'application/json;charset=utf-8',
1692
+ 'string'
1693
+ ];
1694
+ const typeAllowList = [
1695
+ 'none_none',
1696
+ 'binary'
1697
+ ];
1698
+ if (this._options.enableTransformTextPayload && encodingAllowList.includes(payloadType) && (!payloadEncoding || typeAllowList.includes(payloadEncoding))) data.textPayload = utf8_utf8Read(data.payload, 0, data.payload.byteLength);
1699
+ else data.textPayload = '';
1700
+ } else data.textPayload = '';
1701
+ } catch (err) {
1702
+ data.textPayload = '';
1703
+ console.log(err);
1704
+ }
1705
+ ctx.message = data;
1706
+ next();
1707
+ }
1708
+ function pool(alloc, slice, size) {
1709
+ const SIZE = size || 8192;
1710
+ const MAX = SIZE >>> 1;
1711
+ let slab = null;
1712
+ let offset = SIZE;
1713
+ return function(size) {
1714
+ if (size < 1 || size > MAX) return alloc(size);
1715
+ if (offset + size > SIZE) {
1716
+ slab = alloc(SIZE);
1717
+ offset = 0;
1718
+ }
1719
+ const buf = slice.call(slab, offset, offset += size);
1720
+ if (7 & offset) offset = (7 | offset) + 1;
1721
+ return buf;
1722
+ };
1723
+ }
1724
+ const MAX_UINT32 = 0xffffffff;
1725
+ function IndexOutOfRangeError(pos, span, length) {
1726
+ return RangeError('index out of range: ' + pos + ' + ' + (span || 1) + ' > ' + length);
1727
+ }
1728
+ function writeUInt32(buf, pos, num) {
1729
+ if (num > MAX_UINT32) throw new Error('integer too large');
1730
+ let index = 3;
1731
+ while(index >= 0){
1732
+ const value = 0xff & num;
1733
+ buffer_writeByte(value, buf, pos + index);
1734
+ num >>>= 8;
1735
+ index--;
1736
+ }
1737
+ return pos + 4;
1738
+ }
1739
+ function readUInt32(buffer, pos) {
1740
+ let result = 0;
1741
+ let bufferOffset = pos;
1742
+ const end = pos + 4;
1743
+ while(bufferOffset < end){
1744
+ const { value, offset } = buffer_readByte(buffer, bufferOffset);
1745
+ bufferOffset = offset;
1746
+ result = result << 8 >>> 0;
1747
+ result += value;
1748
+ }
1749
+ return {
1750
+ value: result,
1751
+ offset: end
1752
+ };
1753
+ }
1754
+ function buffer_writeString(val, buf, pos) {
1755
+ if (!val) return pos;
1756
+ if (val.length < 40) return utf8Write(val, buf, pos) + pos;
1757
+ if (buf.utf8Write) return buf.utf8Write(val, pos) + pos;
1758
+ if (buf.write) return buf.write(val, pos) + pos;
1759
+ return utf8Write(val, buf, pos) + pos;
1760
+ }
1761
+ function readInt64FromBE(buf, pos) {
1762
+ const value = new long_Long(buf[pos + 4] << 24 | buf[pos + 5] << 16 | buf[pos + 6] << 8 | buf[pos + 7], buf[pos + 0] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3], true);
1763
+ pos += 8;
1764
+ return {
1765
+ value,
1766
+ offset: pos + 8
1767
+ };
1768
+ }
1769
+ function writeInt64ToBE(val, buf, pos) {
1770
+ const low = val.low;
1771
+ const high = val.high;
1772
+ buf[pos] = high >>> 24;
1773
+ buf[pos + 1] = high >>> 16 & 255;
1774
+ buf[pos + 2] = high >>> 8 & 255;
1775
+ buf[pos + 3] = 255 & high;
1776
+ buf[pos + 4] = low >>> 24;
1777
+ buf[pos + 5] = low >>> 16 & 255;
1778
+ buf[pos + 6] = low >>> 8 & 255;
1779
+ buf[pos + 7] = 255 & low;
1780
+ pos += 8;
1781
+ return pos;
1782
+ }
1783
+ function buffer_readByte(buf, pos) {
1784
+ if (buf.readUInt8) return {
1785
+ value: buf.readUInt8(pos),
1786
+ offset: pos + 1
1787
+ };
1788
+ return {
1789
+ value: 255 & buf[pos],
1790
+ offset: pos + 1
1791
+ };
1792
+ }
1793
+ function buffer_writeByte(val, buf, pos) {
1794
+ if (buf.writeUint8) buf.writeUint8(val, pos);
1795
+ else buf[pos] = 255 & val;
1796
+ return pos + 1;
1797
+ }
1798
+ const uint8ArrayAlloc = function(size) {
1799
+ return new Uint8Array(size);
1800
+ };
1801
+ const buffer_alloc = 'undefined' != typeof Buffer ? Buffer.allocUnsafe : pool(uint8ArrayAlloc, Uint8Array.prototype.subarray);
1802
+ (()=>{
1803
+ let value = 4294967295;
1804
+ return function(buf, pos, unsigned = true) {
1805
+ value = (127 & buf[pos]) >>> 0;
1806
+ if (buf[pos++] < 128) return {
1807
+ value: unsigned ? value : 0 | value,
1808
+ offset: pos
1809
+ };
1810
+ value = (value | (127 & buf[pos]) << 7) >>> 0;
1811
+ if (buf[pos++] < 128) return {
1812
+ value: unsigned ? value : 0 | value,
1813
+ offset: pos
1814
+ };
1815
+ value = (value | (127 & buf[pos]) << 14) >>> 0;
1816
+ if (buf[pos++] < 128) return {
1817
+ value: unsigned ? value : 0 | value,
1818
+ offset: pos
1819
+ };
1820
+ value = (value | (127 & buf[pos]) << 21) >>> 0;
1821
+ if (buf[pos++] < 128) return {
1822
+ value: unsigned ? value : 0 | value,
1823
+ offset: pos
1824
+ };
1825
+ value = (value | (15 & buf[pos]) << 28) >>> 0;
1826
+ if (buf[pos++] < 128) return {
1827
+ value: unsigned ? value : 0 | value,
1828
+ offset: pos
1829
+ };
1830
+ if ((pos += 5) > buf.length) {
1831
+ pos = buf.length;
1832
+ throw IndexOutOfRangeError(pos, 10, buf.length);
1833
+ }
1834
+ return {
1835
+ value: unsigned ? value : 0 | value,
1836
+ offset: pos
1837
+ };
1838
+ };
1839
+ })();
1840
+ const CURSOR_FILE_NAME_FRAME = 16;
1841
+ const CURSOR_DATA_FRAME = 32;
1842
+ function calculateTotalBufferLength(cursors) {
1843
+ let totalLength = 0;
1844
+ const cursorLengthMap = {};
1845
+ for(let i = 0; i < cursors.length; i++){
1846
+ cursorLengthMap[cursors[i].cursor_name] = utf8Length(cursors[i].cursor_name);
1847
+ totalLength += 14 + cursorLengthMap[cursors[i].cursor_name];
1848
+ }
1849
+ return [
1850
+ totalLength,
1851
+ cursorLengthMap
1852
+ ];
1853
+ }
1854
+ function serializeCursorData(cursors, defaultCursor, cursorFileName) {
1855
+ const [totalBufferLength, cursorLengthMap] = calculateTotalBufferLength(cursors);
1856
+ const dataBuffer = buffer_alloc(totalBufferLength);
1857
+ let pos = 0;
1858
+ cursors.forEach((cursor)=>{
1859
+ console.log('cursor.service', cursor, cursor.service);
1860
+ pos = buffer_writeByte(0, dataBuffer, pos);
1861
+ console.log('header', pos);
1862
+ pos = writeUInt32(dataBuffer, pos, cursor.service || 0);
1863
+ console.log('service', pos);
1864
+ pos = buffer_writeByte(cursorLengthMap[cursor.cursor_name], dataBuffer, pos);
1865
+ console.log('service-name', pos);
1866
+ pos = buffer_writeString(cursor.cursor_name, dataBuffer, pos);
1867
+ console.log('name', pos);
1868
+ pos = writeInt64ToBE(long_Long.fromNumber(cursor.cursor || defaultCursor), dataBuffer, pos);
1869
+ console.log('curvalue', pos);
1870
+ });
1871
+ return {
1872
+ frameType: CURSOR_DATA_FRAME,
1873
+ headers: [
1874
+ {
1875
+ key: 'cursor_file_name',
1876
+ value: cursorFileName
1877
+ }
1878
+ ],
1879
+ payload: dataBuffer
1880
+ };
1881
+ }
1882
+ function deserializeCursorData(cursorData) {
1883
+ let pos = 0;
1884
+ const cursors = [];
1885
+ while(pos < cursorData.byteLength){
1886
+ const { offset: versionOffset } = buffer_readByte(cursorData, pos);
1887
+ pos = versionOffset;
1888
+ const cursor = {
1889
+ cursor_name: '',
1890
+ cursor: 0,
1891
+ service: 0
1892
+ };
1893
+ const { value: serviceValue, offset: serviceOffset } = readUInt32(cursorData, pos);
1894
+ cursor.service = serviceValue;
1895
+ pos = serviceOffset;
1896
+ const { value: length, offset: lenOffset } = buffer_readByte(cursorData, pos);
1897
+ pos = lenOffset;
1898
+ cursor.cursor_name = utf8_utf8Read(cursorData, pos, pos + length);
1899
+ pos += length;
1900
+ const { value: cursorValue, offset: valueOffset } = readInt64FromBE(cursorData, pos);
1901
+ cursor.cursor = cursorValue.toNumber();
1902
+ pos = valueOffset;
1903
+ cursors.push(cursor);
1904
+ }
1905
+ return cursors;
1906
+ }
1907
+ function serializeCursorFileName() {
1908
+ return {
1909
+ frameType: CURSOR_DATA_FRAME,
1910
+ headers: [
1911
+ {
1912
+ key: 'cursor_file_name',
1913
+ value: 'FILE_NOT_EXIST'
1914
+ }
1915
+ ],
1916
+ payload: void 0
1917
+ };
1918
+ }
1919
+ class CursorManager {
1920
+ constructor(_cursorNameSpace, _cursorFileName, _messageStrategy){
1921
+ this._cursorNameSpace = _cursorNameSpace;
1922
+ this._cursorFileName = _cursorFileName;
1923
+ this._messageStrategy = _messageStrategy;
1924
+ this._qosDB = getQoSDB(this._cursorNameSpace, 'cursor_name');
1925
+ }
1926
+ async openDB() {
1927
+ await this._qosDB.openDB();
1928
+ }
1929
+ async getCursors() {
1930
+ if (!this._qosDB.isReady) return;
1931
+ const strategy = this._messageStrategy;
1932
+ const allCursorValues = await this._qosDB.getAll();
1933
+ console.log('allCursorValues', allCursorValues);
1934
+ switch(strategy){
1935
+ case 'ALL':
1936
+ return allCursorValues && allCursorValues.length ? serializeCursorData(allCursorValues, 0, this._cursorFileName) : void 0;
1937
+ case 'INSTANT':
1938
+ return;
1939
+ case 'CONTINUE':
1940
+ return allCursorValues && allCursorValues.length ? serializeCursorData(allCursorValues, 0, this._cursorFileName) : serializeCursorFileName();
1941
+ }
1942
+ }
1943
+ async set(cursorName, cursor, service) {
1944
+ console.log('setdb', cursorName, cursor, service);
1945
+ return this._qosDB.set({
1946
+ cursor_name: cursorName,
1947
+ cursor: cursor,
1948
+ service: service
1949
+ });
1950
+ }
1951
+ async setCursors(cursorData) {
1952
+ const cursors = deserializeCursorData(cursorData);
1953
+ for (const cursor of cursors){
1954
+ console.log('setcursor', cursors);
1955
+ await this._qosDB.set(cursor);
1956
+ }
1957
+ }
1958
+ async get(cursorName) {
1959
+ return (await this._qosDB.get(cursorName))?.cursor;
1960
+ }
1961
+ async closeDB() {
1962
+ await this._qosDB.closeDB();
1963
+ }
1964
+ updateCursorFileName(cursorFileName) {
1965
+ this._cursorFileName = cursorFileName;
1966
+ }
1967
+ get isReady() {
1968
+ return this._qosDB.isReady;
1969
+ }
1970
+ }
1971
+ const DEFAULT_X_MSG_CURSOR_FILE_NAME = '__x_msg_qos__';
1972
+ async function ensureCursorManager(cursorFileName) {
1973
+ if (!this._options.enableQoS) return null;
1974
+ const { aID, fpID, messageStrategy } = this._options;
1975
+ const resolvedCursorFileName = cursorFileName || DEFAULT_X_MSG_CURSOR_FILE_NAME;
1976
+ try {
1977
+ if (this._cursorManager) {
1978
+ if (cursorFileName) this._cursorManager.updateCursorFileName(cursorFileName);
1979
+ } else this._cursorManager = new CursorManager(`${fpID}_${aID}_${resolvedCursorFileName}`, resolvedCursorFileName, messageStrategy);
1980
+ if (!this._cursorManager.isReady) await this._cursorManager.openDB();
1981
+ return this._cursorManager;
1982
+ } catch {
1983
+ return null;
1984
+ }
1985
+ }
1986
+ async function dispatchMessageProcess(ctx, next) {
1987
+ const isAbnormalCode = getKeyBoolean(ctx.message.headers, 'code', '-1');
1988
+ const isAck = getKeyBoolean(ctx.message.headers, 'is_ack', '1');
1989
+ const xFrontierMsgId = getKeyValue(ctx.message.headers, 'x_frontier_msgid');
1990
+ const xFrontierTTL = Number(getKeyValue(ctx.message.headers, 'x_frontier_ttl')) || 0;
1991
+ const qosState = getFrontierQoSState.call(this, ctx);
1992
+ const isXMsgQoS = getKeyBoolean(ctx.message.headers, 'x-msg-qos', '2');
1993
+ const xMsgCursorName = getKeyValue(ctx.message.headers, 'x-msg-cursor_name');
1994
+ const xMsgCursorValue = Number(getKeyValue(ctx.message.headers, 'x-msg-cursor_value'));
1995
+ if (qosState.isQoSAck) return next();
1996
+ const qosManager = qosState.isQoSMessage ? await ensureQoSManager.call(this) : null;
1997
+ if (ctx.message.service > 0 && isAck && !isAbnormalCode || ctx.message.service > 0) {
1998
+ if (xFrontierMsgId && qosState.isQoSMessage && qosManager) {
1999
+ const isDuplicatedMsg = !!await qosManager.get(xFrontierMsgId);
2000
+ if (!isDuplicatedMsg) {
2001
+ this._dispatchMessageEvent(ctx);
2002
+ await qosManager.set(xFrontierMsgId, Date.now() + xFrontierTTL);
2003
+ }
2004
+ return next();
2005
+ }
2006
+ if (isXMsgQoS) {
2007
+ const cursorManager = await ensureCursorManager.call(this);
2008
+ if (!cursorManager) {
2009
+ this._dispatchMessageEvent(ctx);
2010
+ return next();
2011
+ }
2012
+ const localCursorValue = await cursorManager.get(xMsgCursorName) ?? -1;
2013
+ if (localCursorValue < xMsgCursorValue) {
2014
+ this._dispatchMessageEvent(ctx);
2015
+ cursorManager.set(xMsgCursorName, xMsgCursorValue, ctx.message.service);
2016
+ } else throw new Error(`recevied message cursor ${xMsgCursorValue} larger than local cursor ${localCursorValue}`);
2017
+ return next();
2018
+ }
2019
+ this._dispatchMessageEvent(ctx);
2020
+ return next();
2021
+ }
2022
+ }
2023
+ async function qosProcess(ctx, next) {
2024
+ const qosState = getFrontierQoSState.call(this, ctx);
2025
+ if (!qosState.isQoSMessage) return next();
2026
+ const qosManager = await ensureQoSManager.call(this);
2027
+ if (qosState.isAckCleanupMessage && qosState.ackMsgIds.length) for (const msgId of qosState.ackMsgIds)await qosManager.del(msgId);
2028
+ next();
2029
+ }
2030
+ async function cursorProcess(ctx, next) {
2031
+ const isCursorFileNameFrame = ctx.message.frameType === CURSOR_FILE_NAME_FRAME;
2032
+ const isCursorDataFrame = ctx.message.frameType === CURSOR_DATA_FRAME;
2033
+ if (!isCursorFileNameFrame && !isCursorDataFrame) return next();
2034
+ const cursorFileName = getKeyValue(ctx.message.headers, 'cursor_file_name');
2035
+ if (!cursorFileName) return next();
2036
+ const cursorManager = await ensureCursorManager.call(this, cursorFileName);
2037
+ if (!cursorManager) return next();
2038
+ if (isCursorFileNameFrame) {
2039
+ const cursorInfo = await cursorManager.getCursors();
2040
+ const frameData = {
2041
+ frameType: cursorInfo?.frameType,
2042
+ SeqID: long_Long.fromNumber(this._seqId++),
2043
+ LogID: long_Long.fromNumber(this._options.logIDGenerator()),
2044
+ service: 9000,
2045
+ method: 5,
2046
+ headers: cursorInfo?.headers,
2047
+ payload: cursorInfo?.payload
2048
+ };
2049
+ const encodedData = encodeFrame(frameData);
2050
+ this._ws && this._ws.readyState && this._ws.send(encodedData);
2051
+ }
2052
+ if (isCursorDataFrame) {
2053
+ const cursorData = ctx.message.payload;
2054
+ cursorData && cursorManager.setCursors(cursorData);
2055
+ }
2056
+ }
2057
+ const openProcess = async function(_, next) {
2058
+ this._isInit = false;
2059
+ clearTimeout(this._connectionTimeoutId);
2060
+ next();
2061
+ };
2062
+ const openSucceedProcess = async function(ctx, next) {
2063
+ if (!this._ws || this._ws.readyState !== this.OPEN) return next();
2064
+ const { pingInterval } = this._options;
2065
+ this._endpointManager?.resetEndpointConfig();
2066
+ for(let i = 0; i < this._messageQueue.length; i++){
2067
+ const message = this._messageQueue[i];
2068
+ if (this._ws.readyState === this.OPEN && null !== message) {
2069
+ this._ws && this._ws.send(message);
2070
+ this._messageQueue[i] = null;
2071
+ } else break;
2072
+ }
2073
+ this._messageQueue = this._messageQueue.filter((item)=>Boolean(item));
2074
+ this._pingPongTimeoutId = setTimeout(()=>this._ping(), pingInterval);
2075
+ this._dispatchOpenEvent(ctx);
2076
+ if (this._isBrowser) this._ws && (this._ws.binaryType = this._binaryType);
2077
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2078
+ this._debug(`open ${currentEndpoint} success`);
2079
+ next();
2080
+ };
2081
+ const finishOpenProcess = async function(_, next) {
2082
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2083
+ this._debug(`open ${currentEndpoint}`);
2084
+ next();
2085
+ };
2086
+ class FWS extends EventEmitter {
2087
+ constructor(options){
2088
+ super(), this._miniNavigatorOnline = true, this._isBrowser = IS_BROWSER, this._isNode = IS_NODE, this._isMiniTT = IS_MINI_TT, this._isMiniWX = IS_MINI_WX, this._isWorker = IS_WORKER, this._messageQueue = [], this._endpointManager = null, this._readyClosed = false, this._binaryType = 'arraybuffer', this._connectLock = false, this._connectionTimeoutId = null, this._reconnectTimeoutId = null, this._pingPongTimeoutId = null, this._seqId = 0, this._isInit = false, this._url = '', this._QoSManager = null, this._cursorManager = null, this._pingLossCounter = null, this._protocols = 'pbbp2', this.CLOSED = 3, this.CONNECTING = 0, this.OPEN = 1, this.CLOSING = 2, this._onOpen = (openEvent)=>{
2089
+ try {
2090
+ processTrigger(this, openEvent, [
2091
+ openProcess,
2092
+ openSucceedProcess,
2093
+ finishOpenProcess
2094
+ ]);
2095
+ } catch (error) {
2096
+ const errorEvent = createErrorEvent('error', {
2097
+ message: error.message,
2098
+ code: event_ErrorCode.OPEN_ERROR,
2099
+ error
2100
+ });
2101
+ this._dispatchErrorEvent(errorEvent);
2102
+ }
2103
+ }, this._onMessage = async (messageEvent)=>{
2104
+ const { pingInterval, pingFrequency } = this._options;
2105
+ if ('hi' === messageEvent.data && 'always' === pingFrequency || 'auto' === pingFrequency) {
2106
+ this._clearPingTimer();
2107
+ this.emit('ping_once_success', 'success');
2108
+ this._pingPongTimeoutId = setTimeout(this._ping.bind(this), pingInterval);
2109
+ }
2110
+ if ('hi' === messageEvent.data) return;
2111
+ try {
2112
+ processTrigger(this, messageEvent, [
2113
+ decodeMessageProcess,
2114
+ ackProcess,
2115
+ qosProcess,
2116
+ cursorProcess,
2117
+ dispatchMessageProcess,
2118
+ finishMessageProcess
2119
+ ]);
2120
+ } catch (error) {
2121
+ const errorEvent = createErrorEvent('error', {
2122
+ message: error.message,
2123
+ code: event_ErrorCode.MESSAGE_ERROR,
2124
+ error
2125
+ });
2126
+ this._dispatchErrorEvent(errorEvent);
2127
+ }
2128
+ }, this._onError = (errorEvent)=>{
2129
+ const isReachMaxTries = this._endpointManager?.checkReachMaxTries();
2130
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2131
+ if (isReachMaxTries && !errorEvent.message) {
2132
+ const message = `connect ${currentEndpoint} fail, max retries reached`;
2133
+ this._dispatchErrorEvent(createErrorEvent('error', {
2134
+ message,
2135
+ code: event_ErrorCode.MAX_RETRIES_ERROR,
2136
+ error: errorEvent
2137
+ }));
2138
+ return;
2139
+ }
2140
+ this._ws && this._ws.readyState === this.OPEN && this._disconnect();
2141
+ this._dispatchErrorEvent(createErrorEvent('error', {
2142
+ message: errorEvent.message,
2143
+ code: event_ErrorCode.NATIVE_ERROR,
2144
+ error: errorEvent
2145
+ }));
2146
+ }, this._onClose = async (event)=>{
2147
+ this._clearTimer();
2148
+ this._clearPingTimer();
2149
+ this._removeWsListeners();
2150
+ this._ws = null;
2151
+ this._connectLock = false;
2152
+ const isReachMaxTries = this._endpointManager?.checkReachMaxTries();
2153
+ if (!isReachMaxTries && this._navigatorOnline() && !this._readyClosed) {
2154
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2155
+ const interceptorRes = this._options.reconnectInterceptor(event.code, event.reason);
2156
+ this._dispatchCloseEvent(createCloseEvent('close', {
2157
+ code: 1006,
2158
+ reason: event.reason || `connecting failed, unknown reason, hostname: ${currentEndpoint}`,
2159
+ willReconnect: interceptorRes
2160
+ }));
2161
+ interceptorRes && this._connect();
2162
+ return;
2163
+ }
2164
+ if (1000 !== event.code && this._readyClosed) {
2165
+ this._dispatchCloseEvent(createCloseEvent('close', {
2166
+ code: 1000,
2167
+ reason: 'bye'
2168
+ }));
2169
+ this._endpointManager?.resetEndpointConfig();
2170
+ this._pingLossCounter?.resetCounter();
2171
+ return;
2172
+ }
2173
+ if (1000 !== event.code && isReachMaxTries) {
2174
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2175
+ let _reason = event.reason;
2176
+ if (!_reason) _reason = await getSocketError(this._url);
2177
+ _reason = `connecting failed, ${_reason}, hostname: ${currentEndpoint}, max retries reached`;
2178
+ this._dispatchCloseEvent(createCloseEvent('close', {
2179
+ code: event.code,
2180
+ reason: _reason
2181
+ }));
2182
+ const message = `connect ${currentEndpoint} fail, max retries reached`;
2183
+ this._dispatchErrorEvent(createErrorEvent('error', {
2184
+ message,
2185
+ code: event_ErrorCode.MAX_RETRIES_ERROR
2186
+ }));
2187
+ this._endpointManager?.resetEndpointConfig();
2188
+ this._pingLossCounter?.resetCounter();
2189
+ return;
2190
+ }
2191
+ if (1000 !== event.code && !event.reason) {
2192
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2193
+ this._dispatchCloseEvent(createCloseEvent('close', {
2194
+ code: event.code,
2195
+ reason: `connecting failed, unknown reason, hostname: ${currentEndpoint}`
2196
+ }));
2197
+ this._endpointManager?.resetEndpointConfig();
2198
+ this._pingLossCounter?.resetCounter();
2199
+ return;
2200
+ }
2201
+ this._dispatchCloseEvent(event);
2202
+ this._endpointManager?.resetEndpointConfig();
2203
+ this._pingLossCounter?.resetCounter();
2204
+ }, this.onclose = null, this.onerror = null, this.onmessage = null, this.onopen = null, this.onStartReconnect = null, this.onReceiveAck = null, this.onStopImmediatelyReconnect = null;
2205
+ this._handleOnLine = this._handleOnLine.bind(this);
2206
+ this._handleOffLine = this._handleOffLine.bind(this);
2207
+ this._handlePageHide = this._handlePageHide.bind(this);
2208
+ this._handlePageShow = this._handlePageShow.bind(this);
2209
+ this._options = {
2210
+ url: '',
2211
+ automaticOpen: true,
2212
+ initReconnectInterval: 1000,
2213
+ maxReconnectInterval: 10000,
2214
+ reconnectIntervalGrowFactor: 2,
2215
+ timeoutInterval: 5000,
2216
+ maxRetries: 5,
2217
+ debug: false,
2218
+ maxMessageQueueLength: 1 / 0,
2219
+ service: 0,
2220
+ logIDGenerator: genLogID,
2221
+ headers: void 0,
2222
+ payloadEncoding: '',
2223
+ payloadType: '',
2224
+ fpID: '',
2225
+ deviceID: '',
2226
+ accessKey: '',
2227
+ ttwID: '',
2228
+ bddID: '',
2229
+ aID: '',
2230
+ disableAutoReconnect: false,
2231
+ customParams: {},
2232
+ pingInterval: 15000,
2233
+ pingTimeoutInterval: 4000,
2234
+ pingFrequency: 'auto',
2235
+ pingLossCount: 2,
2236
+ enableTransformTextPayload: false,
2237
+ logIDNewConfig: {
2238
+ enableAutoGenerateLogIDNew: false,
2239
+ userIp: ''
2240
+ },
2241
+ miniProgramParams: {
2242
+ customHttpHeader: {}
2243
+ },
2244
+ enableAutoAck: false,
2245
+ reconnectInterceptor: ()=>true,
2246
+ enableQoS: false,
2247
+ QoSLevel: 2,
2248
+ messageStrategy: 'CONTINUE',
2249
+ env: {
2250
+ xTTEnv: '',
2251
+ xUseEnv: ''
2252
+ },
2253
+ listenNetworkChanged: true
2254
+ };
2255
+ const { url, ws } = options;
2256
+ const endpoints = Array.isArray(url) ? url : 'string' == typeof url ? [
2257
+ url
2258
+ ] : [];
2259
+ if (!endpoints || 0 === endpoints.length) throw new Error('please provide valid url');
2260
+ if (!checkWebSocketConstructorValid(ws)) throw new Error('please provide ws params, WebSocket constructor is undefined');
2261
+ Object.assign(this._options, options);
2262
+ this._endpointManager = new EndpointManager(endpoints, this._options.maxRetries);
2263
+ this._pingLossCounter = new PkgLossCounter(this._options.pingLossCount);
2264
+ if (this._options.automaticOpen) {
2265
+ this._isInit = true;
2266
+ this._connect();
2267
+ }
2268
+ if (this._options.listenNetworkChanged) {
2269
+ if (this._isMiniTT || this._isMiniWX) this._onPageNetWorkChange();
2270
+ else if (this._isBrowser) this._initGlobalEventListener();
2271
+ }
2272
+ }
2273
+ _handleOnLine() {
2274
+ if (this._options.disableAutoReconnect || this._readyClosed) return;
2275
+ this._handleReconnect();
2276
+ }
2277
+ _handleOffLine() {
2278
+ this._destroyWebSocket();
2279
+ const reconnectEvent = createReconnectEvent('reconnect', {
2280
+ message: 'stop immediately reconnect'
2281
+ });
2282
+ this.onStopImmediatelyReconnect && this.onStopImmediatelyReconnect(reconnectEvent);
2283
+ }
2284
+ _initGlobalEventListener() {
2285
+ this._isBrowser && window.addEventListener('online', this._handleOnLine);
2286
+ this._isBrowser && window.addEventListener('offline', this._handleOffLine);
2287
+ this._isBrowser && window.addEventListener('pagehide', this._handlePageHide);
2288
+ this._isBrowser && window.addEventListener('pageshow', this._handlePageShow);
2289
+ }
2290
+ _dropGlobalEventListener() {
2291
+ this._isBrowser && window.removeEventListener('online', this._handleOnLine);
2292
+ this._isBrowser && window.removeEventListener('offline', this._handleOffLine);
2293
+ this._isBrowser && window.removeEventListener('pagehide', this._handlePageHide);
2294
+ this._isBrowser && window.removeEventListener('pageshow', this._handlePageShow);
2295
+ }
2296
+ _handlePageHide(event) {
2297
+ if (!event.persisted) {
2298
+ this._isBrowser && window.removeEventListener('pagehide', this._handlePageHide);
2299
+ this._isBrowser && window.removeEventListener('pageshow', this._handlePageShow);
2300
+ this.close();
2301
+ }
2302
+ this._isBrowser && window.removeEventListener('online', this._handleOnLine);
2303
+ this._isBrowser && window.removeEventListener('offline', this._handleOffLine);
2304
+ }
2305
+ _handlePageShow(event) {
2306
+ if (event.persisted) {
2307
+ if (this._navigatorOnline() && (!this._ws || this._ws.readyState !== this.OPEN || this._ws.readyState !== this.CONNECTING)) this._handleOnLine();
2308
+ this._isBrowser && window.addEventListener('online', this._handleOnLine);
2309
+ this._isBrowser && window.addEventListener('offline', this._handleOffLine);
2310
+ }
2311
+ }
2312
+ async _generateUrl(endpoint) {
2313
+ const { fpID, deviceID, bddID, ttwID, accessKey, aID, customParams = {}, enableAutoAck, enableQoS, QoSLevel, env } = this._options;
2314
+ let wsProtocol, wsEndpoint, currentEndpoint;
2315
+ if (this._isBrowser || this._isMiniWX || this._isMiniTT) {
2316
+ wsProtocol = location && 'https:' == location.protocol ? 'wss://' : 'ws://';
2317
+ wsEndpoint = endpoint.replace(/((^ws)|(^http))((?:[s]*:\/\/))/, '');
2318
+ currentEndpoint = /^wss(.*:\/\/)/.test(endpoint) ? endpoint : `${wsProtocol}${wsEndpoint}`;
2319
+ } else {
2320
+ wsProtocol = 'wss://';
2321
+ wsEndpoint = endpoint.replace(/(^http)((?:[s]*:\/\/))/, '');
2322
+ currentEndpoint = /(^ws)((?:[s]*:\/\/))/.test(wsEndpoint) ? wsEndpoint : `${wsProtocol}${wsEndpoint}`;
2323
+ }
2324
+ const dIDKey = bddID ? 'bd_did' : ttwID ? 'ttwid' : 'device_id';
2325
+ const dIDArg = bddID ? bddID : ttwID ? ttwID : deviceID;
2326
+ if (!dIDArg || !dIDKey) throw new Error('please provide bddID, deviceID or ttwID');
2327
+ const customParamsMap = 'function' == typeof customParams ? await customParams() : customParams;
2328
+ const envParams = env ? envParamsGen(env.xUseEnv, env.xTTEnv) : {};
2329
+ const params = Object.assign({
2330
+ device_platform: 'web',
2331
+ version_code: 'fws_1.0.0',
2332
+ access_key: accessKey,
2333
+ fpid: fpID,
2334
+ aid: aID,
2335
+ [dIDKey]: dIDArg,
2336
+ xsack: enableAutoAck ? 1 : 0,
2337
+ xaack: enableAutoAck ? 1 : 0,
2338
+ xsqos: enableQoS ? 1 : 0,
2339
+ qos_level: enableQoS ? QoSLevel : void 0,
2340
+ qos_sdk_version: 2,
2341
+ ...envParams
2342
+ }, customParamsMap);
2343
+ const queryParams = Object.keys(params).reduce((pre, key)=>void 0 !== params[key] ? `${pre}${pre ? '&' : '?'}${key}=${params[key]}` : pre, '');
2344
+ return `${currentEndpoint}/ws/v2${queryParams}`;
2345
+ }
2346
+ async _connect() {
2347
+ if (this._connectLock || this._readyClosed) return;
2348
+ this._connectLock = true;
2349
+ try {
2350
+ const isReachedMaxRetries = this._endpointManager?.checkCurrentEndpointReachedMaxRetries();
2351
+ const { timeoutInterval } = this._options;
2352
+ if (isReachedMaxRetries) {
2353
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2354
+ const backUpEndpoint = this._endpointManager?.replaceBackupEndpointAndUpdateCount();
2355
+ const backUpEndpointTriesCount = this._endpointManager?.getCurrentEndpointTriesCount();
2356
+ if (backUpEndpoint) {
2357
+ const message = `connect ${currentEndpoint} timeout, max retries reached, will use backup endpoint ${backUpEndpoint} to retry`;
2358
+ const errorEvent = createErrorEvent('error', {
2359
+ message,
2360
+ code: event_ErrorCode.MAX_RETRIES_ERROR
2361
+ });
2362
+ this._debug(message);
2363
+ this._dispatchErrorEvent(errorEvent);
2364
+ this._url = await this._generateUrl(backUpEndpoint);
2365
+ this._debug(`connect ${backUpEndpoint} ${backUpEndpointTriesCount} times`);
2366
+ this._removeWsListeners();
2367
+ } else {
2368
+ const message = `connect ${currentEndpoint} timeout, max retries reached`;
2369
+ this._debug(message);
2370
+ this._dispatchErrorEvent(createErrorEvent('error', {
2371
+ message,
2372
+ code: event_ErrorCode.MAX_RETRIES_ERROR
2373
+ }));
2374
+ return;
2375
+ }
2376
+ } else {
2377
+ const currentEndpoint = this._endpointManager?.getCurrentEndpointAndUpdateCount();
2378
+ const currentEndpointTriesCount = this._endpointManager?.getCurrentEndpointTriesCount();
2379
+ this._url = await this._generateUrl(currentEndpoint || '');
2380
+ this._debug(`connect ${currentEndpoint} ${currentEndpointTriesCount} times`);
2381
+ this._removeWsListeners();
2382
+ }
2383
+ if (this._isInit) this._isInit = false;
2384
+ else {
2385
+ const reconnectEvent = createReconnectEvent('reconnect', {
2386
+ message: 'start'
2387
+ });
2388
+ this.onStartReconnect && this.onStartReconnect(reconnectEvent);
2389
+ }
2390
+ const currentEndpointTriesCount = this._endpointManager?.getCurrentEndpointTriesCount() || 0;
2391
+ if (currentEndpointTriesCount > 1) await this._wait(currentEndpointTriesCount - 1);
2392
+ this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`);
2393
+ this._ws = globalWebSocketInit({
2394
+ url: this._url,
2395
+ protocols: [
2396
+ this._protocols
2397
+ ],
2398
+ headers: this._options.miniProgramParams.customHttpHeader
2399
+ }, this._options.ws);
2400
+ if (this._isBrowser || this._isWorker) this._ws && (this._ws.binaryType = this._binaryType);
2401
+ this._addWsListeners();
2402
+ this._connectionTimeoutId = setTimeout(this._onTimeout.bind(this), timeoutInterval);
2403
+ } catch (err) {
2404
+ this._connectLock = false;
2405
+ throw err;
2406
+ }
2407
+ }
2408
+ _clearTimer() {
2409
+ clearTimeout(this._connectionTimeoutId);
2410
+ this._connectionTimeoutId = null;
2411
+ }
2412
+ _clearPingTimer() {
2413
+ clearTimeout(this._pingPongTimeoutId);
2414
+ clearTimeout(this._reconnectTimeoutId);
2415
+ this._pingPongTimeoutId = null;
2416
+ this._reconnectTimeoutId = null;
2417
+ }
2418
+ _debug(...args) {
2419
+ if (this._options.debug) console.log.apply(console, [
2420
+ 'FRONTIER>',
2421
+ ...args
2422
+ ]);
2423
+ }
2424
+ _getIntervalValue(times) {
2425
+ const { initReconnectInterval, maxReconnectInterval, reconnectIntervalGrowFactor } = this._options;
2426
+ const nextInterval = initReconnectInterval * Math.pow(reconnectIntervalGrowFactor, times - 1);
2427
+ return nextInterval > maxReconnectInterval ? maxReconnectInterval : nextInterval;
2428
+ }
2429
+ _ping() {
2430
+ if (this._ws && this._ws.readyState === this.CONNECTING) {
2431
+ this._clearPingTimer();
2432
+ this._pingPongTimeoutId = setTimeout(this._ping.bind(this), this._options.pingInterval);
2433
+ return;
2434
+ }
2435
+ if (!this._ws || this._ws.readyState !== this.OPEN) return void this._handleReconnect();
2436
+ this._ws && this._ws.send('hi');
2437
+ this._reconnectTimeoutId = setTimeout(this._handleReconnectTimeout.bind(this), this._options.pingTimeoutInterval);
2438
+ }
2439
+ _handleReconnectTimeout() {
2440
+ this._pingLossCounter?.addCount();
2441
+ this.emit('ping_once_timeout', 'timeout');
2442
+ if (this._pingLossCounter?.checkReachMaxCount()) this._handleReconnect();
2443
+ else this._ping();
2444
+ }
2445
+ _navigatorOnline() {
2446
+ if (this._isMiniTT || this._isMiniWX) return this._miniNavigatorOnline;
2447
+ if ((this._isBrowser || this._isWorker) && this._options.listenNetworkChanged) return navigator.onLine;
2448
+ return true;
2449
+ }
2450
+ _handleReconnect() {
2451
+ if (!this._navigatorOnline() || this._readyClosed) return;
2452
+ this._endpointManager?.resetEndpointConfig();
2453
+ this._pingLossCounter?.resetCounter();
2454
+ this._ws ? this._disconnect(1001, 'going away, try reconnecting server', true) : this._connect();
2455
+ }
2456
+ _onPageNetWorkChange() {
2457
+ if (this._isMiniTT) tt.onNetworkStatusChange(({ isConnected })=>{
2458
+ this._miniNavigatorOnline = isConnected;
2459
+ isConnected ? this._handleOnLine() : this._handleOffLine();
2460
+ });
2461
+ else if (this._isMiniWX) wx.onNetworkStatusChange(({ isConnected })=>{
2462
+ this._miniNavigatorOnline = isConnected;
2463
+ isConnected ? this._handleOnLine() : this._handleOffLine();
2464
+ });
2465
+ }
2466
+ _wait(times) {
2467
+ return new Promise((resolve)=>{
2468
+ setTimeout(resolve, this._getIntervalValue(times));
2469
+ });
2470
+ }
2471
+ _disconnect(code = 1000, reason = '', needReconnect = false) {
2472
+ if (!this._ws) return;
2473
+ this._destroyWebSocket(code, reason, needReconnect);
2474
+ }
2475
+ _onTimeout() {
2476
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2477
+ this._debug(`connect ${currentEndpoint} timeout`);
2478
+ this._disconnect(1001, 'timeout, try reconnecting', true);
2479
+ }
2480
+ _sendAck(frameData) {
2481
+ const encodedData = protobuf_encodeFrame(frameData);
2482
+ if (this._ws && this._ws.readyState === this.OPEN) {
2483
+ this._ws && this._ws.send(encodedData);
2484
+ this._debug('send_ack', frameData);
2485
+ }
2486
+ }
2487
+ _removeWsListeners() {
2488
+ if (!this._ws) return;
2489
+ this._ws.removeEventListener('open', this._onOpen);
2490
+ this._ws.removeEventListener('close', this._onClose);
2491
+ this._ws.removeEventListener('message', this._onMessage);
2492
+ this._ws.removeEventListener('error', this._onError);
2493
+ }
2494
+ _addWsListeners() {
2495
+ if (!this._ws) return;
2496
+ this._ws.addEventListener('open', this._onOpen);
2497
+ this._ws.addEventListener('close', this._onClose);
2498
+ this._ws.addEventListener('message', this._onMessage);
2499
+ this._ws.addEventListener('error', this._onError);
2500
+ }
2501
+ _wsInstanceClose(code = 1000, reason = '') {
2502
+ try {
2503
+ this._ws && this._ws.close(code, reason);
2504
+ } catch {}
2505
+ }
2506
+ _destroyWebSocket(code = 1000, reason = '', needReconnect = false) {
2507
+ this._clearPingTimer();
2508
+ this._clearTimer();
2509
+ this._removeWsListeners();
2510
+ this._wsInstanceClose(1000, reason);
2511
+ this._connectLock = false;
2512
+ if (needReconnect && this._navigatorOnline() && !this._readyClosed) {
2513
+ const isReachedMaxRetries = this._endpointManager?.checkReachMaxTries();
2514
+ if (isReachedMaxRetries) {
2515
+ const currentEndpoint = this._endpointManager?.getCurrentEndpoint();
2516
+ this._dispatchCloseEvent(createCloseEvent('close', {
2517
+ code: 1006,
2518
+ reason: `connect ${currentEndpoint} timeout, max retries reached`,
2519
+ wasClean: true
2520
+ }));
2521
+ } else {
2522
+ const interceptorRes = this._options.reconnectInterceptor(code, reason);
2523
+ this._dispatchCloseEvent(createCloseEvent('close', {
2524
+ code,
2525
+ reason,
2526
+ wasClean: true,
2527
+ willReconnect: interceptorRes
2528
+ }));
2529
+ interceptorRes && this._connect();
2530
+ }
2531
+ return;
2532
+ }
2533
+ if (this._navigatorOnline() || this._readyClosed) this._dispatchCloseEvent(createCloseEvent('close', {
2534
+ code,
2535
+ reason: 'bye'
2536
+ }));
2537
+ else this._dispatchCloseEvent(createCloseEvent('close', {
2538
+ code: 1006,
2539
+ reason: 'going away, network offline'
2540
+ }));
2541
+ this._ws = null;
2542
+ this._endpointManager?.resetEndpointConfig();
2543
+ this._pingLossCounter?.resetCounter();
2544
+ }
2545
+ _dispatchOpenEvent(event) {
2546
+ this.emit('open', event);
2547
+ this.onopen && this.onopen(event);
2548
+ }
2549
+ _dispatchMessageEvent(event) {
2550
+ this.emit('message', event);
2551
+ this.onmessage && this.onmessage(event);
2552
+ }
2553
+ _dispatchAckMessageEvent(event) {
2554
+ this.emit('ack', event);
2555
+ this.onReceiveAck && this.onReceiveAck(event);
2556
+ }
2557
+ _dispatchErrorEvent(event) {
2558
+ this.emit('error', event);
2559
+ this.onerror && this.onerror(event);
2560
+ }
2561
+ _dispatchCloseEvent(event) {
2562
+ this.emit('close', event);
2563
+ this.onclose && this.onclose(event);
2564
+ }
2565
+ get binaryType() {
2566
+ return this._ws ? this._ws.binaryType : this._binaryType;
2567
+ }
2568
+ set binaryType(value) {
2569
+ this._binaryType = value;
2570
+ this._ws && (this._ws.binaryType = value);
2571
+ }
2572
+ get retryCount() {
2573
+ return this._endpointManager?.getCurrentEndpointTriesCount() || 0;
2574
+ }
2575
+ get bufferedAmount() {
2576
+ const bytes = this._messageQueue.reduce((amo, message)=>{
2577
+ amo += message && message.byteLength || 0;
2578
+ return amo;
2579
+ }, 0);
2580
+ return bytes + (this._ws ? this._ws.bufferedAmount : 0);
2581
+ }
2582
+ get extensions() {
2583
+ return this._ws ? this._ws.extensions : '';
2584
+ }
2585
+ get protocol() {
2586
+ return this._ws ? this._ws.protocol : '';
2587
+ }
2588
+ get readyState() {
2589
+ if (this._ws) return this._ws.readyState;
2590
+ if (this._options.automaticOpen) return this.CONNECTING;
2591
+ return this.CLOSED;
2592
+ }
2593
+ get url() {
2594
+ return this._ws ? this._ws.url : this._url;
2595
+ }
2596
+ close(code = 1000, reason) {
2597
+ this._readyClosed = true;
2598
+ this._clearTimer();
2599
+ this._clearPingTimer();
2600
+ this._dropGlobalEventListener();
2601
+ this._QoSManager?.closeDB();
2602
+ if (!this._ws) return void this._debug('close, ws instance not initialized');
2603
+ if (this._ws.readyState === this.CLOSED || this._ws.readyState === this.CLOSING) return void this._debug('close, ws already closed');
2604
+ this._destroyWebSocket(code, reason);
2605
+ }
2606
+ async send(data, options) {
2607
+ if (null == data) throw new Error('please provide a valid data, data must be a string or an arraybuffer');
2608
+ if ('number' == typeof data) data = JSON.stringify(data);
2609
+ if ('string' != typeof data && !(data instanceof ArrayBuffer) && !(data.buffer && data.buffer instanceof ArrayBuffer)) data = JSON.stringify(data);
2610
+ const payload = await dataToUnit8Array(data);
2611
+ const identifiedPayloadType = checkPayloadType(data);
2612
+ const { method = 0, service = this._options.service, logID = this._options.logIDGenerator(), headers = this._options.headers, payloadEncoding = this._options.payloadEncoding, payloadType = this._options.payloadType, logIDNew = this._options.logIDNewConfig.enableAutoGenerateLogIDNew ? genLogIDNew(this._options.logIDNewConfig.userIp) : '' } = options || {};
2613
+ if (!service) throw new Error('please provide a valid service');
2614
+ const frameData = {
2615
+ SeqID: long_Long.fromNumber(this._seqId++),
2616
+ LogID: long_Long.fromNumber(logID),
2617
+ service,
2618
+ method,
2619
+ headers,
2620
+ payloadEncoding: payloadEncoding instanceof Object ? payloadEncoding.encoding ? payloadEncoding.encoding : '' : payloadEncoding,
2621
+ payloadType: payloadType instanceof Object ? payloadType.type ? payloadType.type : identifiedPayloadType : payloadType ? payloadType : identifiedPayloadType,
2622
+ payload,
2623
+ LogIDNew: logIDNew
2624
+ };
2625
+ const encodedData = protobuf_encodeFrame(frameData);
2626
+ if (this._ws && this._ws.readyState === this.OPEN) {
2627
+ this._ws && this._ws.send(encodedData);
2628
+ this._debug('sent', frameData);
2629
+ } else if (this._messageQueue.length < this._options.maxMessageQueueLength) {
2630
+ this._messageQueue.push(encodedData);
2631
+ this._debug('enqueue', frameData);
2632
+ } else {
2633
+ this._messageQueue.shift();
2634
+ this._messageQueue.push(encodedData);
2635
+ }
2636
+ return {
2637
+ seqID: this._seqId,
2638
+ logID: logID,
2639
+ logIDNew: logIDNew
2640
+ };
2641
+ }
2642
+ async reconnect(options) {
2643
+ const { url } = options || {};
2644
+ const endpoints = Array.isArray(url) ? url : 'string' == typeof url ? [
2645
+ url
2646
+ ] : [];
2647
+ if (options) Object.assign(this._options, options);
2648
+ if (endpoints && endpoints.length) this._endpointManager = new EndpointManager(endpoints, this._options.maxRetries);
2649
+ else this._endpointManager?.resetEndpointConfig();
2650
+ this._pingLossCounter?.resetCounter(this._options.pingLossCount);
2651
+ this._readyClosed = false;
2652
+ if (this._ws && this._ws.readyState !== this.CLOSED) this._disconnect(1000, 'manual reconnecting', true);
2653
+ else {
2654
+ this._isInit = true;
2655
+ this._connect();
2656
+ }
2657
+ }
2658
+ async connect() {
2659
+ if (!this._connectLock) {
2660
+ this._endpointManager?.resetEndpointConfig();
2661
+ this._pingLossCounter?.resetCounter();
2662
+ this._readyClosed = false;
2663
+ this._isInit = true;
2664
+ this._connect();
2665
+ }
2666
+ }
2667
+ addEventListener(type, listener) {
2668
+ this.on(type, listener);
2669
+ }
2670
+ dispatchEvent(event) {
2671
+ const { type } = event;
2672
+ this.emit(type, event);
2673
+ }
2674
+ removeEventListener(type, listener) {
2675
+ this.off(type, listener);
2676
+ }
2677
+ pingOnce() {
2678
+ return new Promise((resolve, reject)=>{
2679
+ this._clearPingTimer();
2680
+ this._pingPongTimeoutId = setTimeout(this._ping.bind(this), this._options.pingInterval);
2681
+ const resolveFn = ()=>{
2682
+ resolve('success');
2683
+ this.off('ping_once_success', resolveFn);
2684
+ this.off('ping_once_timeout', rejectFn);
2685
+ };
2686
+ const rejectFn = ()=>{
2687
+ reject('timeout');
2688
+ this.off('ping_once_success', resolveFn);
2689
+ this.off('ping_once_timeout', rejectFn);
2690
+ };
2691
+ this.on('ping_once_success', resolveFn);
2692
+ this.on('ping_once_timeout', rejectFn);
2693
+ this._ping();
2694
+ });
2695
+ }
2696
+ }
2697
+ })();
2698
+ return __webpack_exports__;
2699
+ })());