@jolibox/implement 1.1.4-beta.9 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.rush/temp/package-deps_build.json +33 -33
  2. package/dist/{h5 → common}/ads/ads-action-detection.d.ts +3 -1
  3. package/dist/{h5 → common}/ads/anti-cheating.d.ts +2 -2
  4. package/dist/common/ads/channel-policy.d.ts +26 -0
  5. package/dist/{h5 → common}/ads/index.d.ts +12 -3
  6. package/dist/common/context/index.d.ts +2 -0
  7. package/dist/common/http/uuid.d.ts +2 -2
  8. package/dist/common/http/xua.d.ts +0 -15
  9. package/dist/common/report/base-tracker.d.ts +10 -1
  10. package/dist/common/report/errors/index.d.ts +2 -2
  11. package/dist/common/report/task-track/index.d.ts +3 -0
  12. package/dist/common/report/types.d.ts +2 -55
  13. package/dist/h5/api/index.d.ts +1 -0
  14. package/dist/h5/http/index.d.ts +3 -3
  15. package/dist/h5/report/index.d.ts +1 -1
  16. package/dist/index.d.ts +0 -1
  17. package/dist/index.js +3 -5033
  18. package/dist/index.native.js +3 -3750
  19. package/dist/native/api/keyboard.d.ts +9 -3
  20. package/dist/native/network/index.d.ts +0 -3
  21. package/esbuild.config.js +1 -1
  22. package/implement.build.log +2 -2
  23. package/package.json +3 -3
  24. package/src/{h5 → common}/ads/ads-action-detection.ts +4 -4
  25. package/src/{h5 → common}/ads/anti-cheating.ts +2 -4
  26. package/src/common/ads/channel-policy.ts +52 -0
  27. package/src/{h5 → common}/ads/index.ts +39 -45
  28. package/src/common/api-factory/index.ts +3 -3
  29. package/src/common/context/index.ts +20 -11
  30. package/src/common/http/uuid.ts +2 -10
  31. package/src/common/http/xua.ts +2 -69
  32. package/src/common/report/base-tracker.ts +40 -44
  33. package/src/common/report/errors/index.ts +3 -3
  34. package/src/common/report/errors/report/listeners.ts +0 -2
  35. package/src/common/report/task-track/index.ts +63 -14
  36. package/src/common/report/track.ts +2 -2
  37. package/src/common/report/types.ts +2 -64
  38. package/src/h5/api/ads.ts +24 -0
  39. package/src/h5/api/get-system-info.ts +5 -1
  40. package/src/h5/api/index.ts +1 -0
  41. package/src/h5/http/index.ts +24 -28
  42. package/src/h5/http/utils/__tests__/xua.test.ts +1 -1
  43. package/src/h5/http/utils/session.ts +1 -1
  44. package/src/h5/report/errors/index.ts +1 -1
  45. package/src/h5/report/event-tracker.ts +1 -1
  46. package/src/h5/report/index.ts +5 -4
  47. package/src/index.ts +0 -1
  48. package/src/native/api/ads.ts +32 -8
  49. package/src/native/api/get-system-info.ts +5 -2
  50. package/src/native/api/keyboard.ts +13 -13
  51. package/src/native/bootstrap/index.ts +0 -1
  52. package/src/native/network/index.ts +11 -4
  53. package/src/native/report/index.ts +4 -4
  54. package/src/native/types/native-method-map.d.ts +11 -0
  55. package/dist/common/report/errors/error-types.d.ts +0 -122
  56. package/src/common/report/errors/error-types.ts +0 -206
  57. package/src/h5/http/utils/__tests__/uuid.test.ts +0 -16
  58. /package/dist/h5/{http/utils/__tests__/uuid.test.d.ts → api/ads.d.ts} +0 -0
@@ -1,3750 +1,3 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esm = (fn, res) => function __init() {
8
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
- };
10
- var __commonJS = (cb, mod) => function __require() {
11
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
-
30
- // src/native/js-bridge/utils.ts
31
- function isNativeBuffers(x2) {
32
- return Boolean(x2?.__nativeBuffers__);
33
- }
34
- function unpack(data) {
35
- if (typeof data === "string") {
36
- try {
37
- data = JSON.parse(data);
38
- } catch {
39
- return {};
40
- }
41
- }
42
- if (typeof data !== "object" || data === null) {
43
- return {};
44
- }
45
- if (!isNativeBuffers(data)) return data;
46
- const nativeBuffers = data.__nativeBuffers__;
47
- delete data.__nativeBuffers__;
48
- if (nativeBuffers) {
49
- for (let i = 0; i < nativeBuffers.length; i++) {
50
- const item = nativeBuffers[i];
51
- if (item) {
52
- let tmp;
53
- if (item.value) {
54
- tmp = item.value;
55
- } else if (item.base64) {
56
- tmp = decodeFromUi8Base64(item.base64);
57
- }
58
- if (typeof tmp !== "undefined" && tmp instanceof ArrayBuffer) {
59
- data[item.key] = tmp;
60
- }
61
- }
62
- }
63
- }
64
- return data;
65
- }
66
- function pack(_data = {}, useArrayBuffer = false) {
67
- const data = _data;
68
- const needTransAttrs = [];
69
- for (const [key, item] of Object.entries(data)) {
70
- if (item !== void 0 && item instanceof ArrayBuffer && item.byteLength !== void 0) {
71
- const obj = useArrayBuffer ? { value: item, key } : {
72
- base64: encodeToUi8Base64(item),
73
- key
74
- };
75
- needTransAttrs.push(obj);
76
- delete data[key];
77
- }
78
- }
79
- if (needTransAttrs.length > 0) {
80
- data.__nativeBuffers__ = needTransAttrs;
81
- }
82
- return data;
83
- }
84
- var decodeFromUi8Base64, encodeToUi8Base64;
85
- var init_utils = __esm({
86
- "src/native/js-bridge/utils.ts"() {
87
- "use strict";
88
- decodeFromUi8Base64 = (string) => {
89
- const base64String = atob(string);
90
- const len = base64String.length;
91
- const ui8aReader = new Uint8Array(len);
92
- for (let i = 0; i < len; i++) {
93
- ui8aReader[i] = base64String.charCodeAt(i);
94
- }
95
- return ui8aReader.buffer;
96
- };
97
- encodeToUi8Base64 = (arrayBuffer) => {
98
- let string = "";
99
- const ui8aReader = new Uint8Array(arrayBuffer);
100
- const len = ui8aReader.byteLength;
101
- for (let i = 0; i < len; i++) {
102
- string += String.fromCharCode(ui8aReader[i]);
103
- }
104
- return btoa(string);
105
- };
106
- }
107
- });
108
-
109
- // ../common/dist/index.es.js
110
- function M(n2) {
111
- return new Promise((e) => {
112
- setTimeout(() => {
113
- e();
114
- }, n2);
115
- });
116
- }
117
- function b(n2) {
118
- return typeof n2 == "string";
119
- }
120
- function ie(n2) {
121
- return typeof n2 == "object" && n2 !== null && !Array.isArray(n2) && !(n2 instanceof RegExp) && !(n2 instanceof Date);
122
- }
123
- function Ce(n2) {
124
- return typeof n2 == "object" && Array.isArray(n2);
125
- }
126
- function se(n2) {
127
- return typeof n2 > "u";
128
- }
129
- function N(n2) {
130
- return se(n2) || n2 === null;
131
- }
132
- function A(n2) {
133
- return typeof n2 == "function";
134
- }
135
- function Oe(n2) {
136
- return ie(n2) && A(n2.then);
137
- }
138
- function x(n2) {
139
- let e = n2, r = null, t3 = function(...o) {
140
- return r || (r = new e(...o)), r;
141
- };
142
- return t3.prototype = e.prototype, t3;
143
- }
144
- function ke(n2, e, r) {
145
- if (typeof r != "function") throw new Error("[Jolibox SDK]Customizer must be a function");
146
- function t3(o, i) {
147
- for (let s in i) if (Object.prototype.hasOwnProperty.call(i, s)) {
148
- let l = o[s], a = i[s], c = r(l, a, s, o, i);
149
- c !== void 0 ? o[s] = c : U(a) && U(l) ? o[s] = t3({ ...l }, a) : Array.isArray(a) && Array.isArray(l) ? o[s] = [...l, ...a] : o[s] = a;
150
- }
151
- return o;
152
- }
153
- return t3(n2, e);
154
- }
155
- function U(n2) {
156
- return n2 && typeof n2 == "object" && n2.constructor === Object;
157
- }
158
- function Le(n2, e) {
159
- if (Array.isArray(n2)) return n2.concat(e);
160
- }
161
- function Ue(n2, e, r = {}) {
162
- let t3 = null, o, i, s, { leading: l = false, trailing: a = true } = r, c = () => (s = n2.apply(i, o), o = void 0, i = void 0, s), I = function(...te) {
163
- o = te, i = this;
164
- let w = l && !t3;
165
- if (t3 && clearTimeout(t3), t3 = setTimeout(() => {
166
- t3 = null, a && !w && c();
167
- }, e), w) return c();
168
- };
169
- return I.cancel = () => {
170
- t3 && clearTimeout(t3), t3 = null, o = i = void 0;
171
- }, I.flush = () => {
172
- if (t3) return clearTimeout(t3), t3 = null, c();
173
- }, I;
174
- }
175
- function de(n2, e) {
176
- return (...r) => e(n2, ...r);
177
- }
178
- function He(n2) {
179
- return (e) => de(e, function(r, ...t3) {
180
- if (typeof r == "function") try {
181
- return r.apply(this, t3);
182
- } catch (o) {
183
- n2(new v(`${o}`));
184
- }
185
- });
186
- }
187
- function R(n2) {
188
- return (...e) => {
189
- (globalThis.VConsole?.[n2] ?? globalThis.console[n2])(...e);
190
- };
191
- }
192
- function ce(n2) {
193
- return new Promise((e) => ee(n2)(e));
194
- }
195
- function ee(n2) {
196
- return (e, r = null) => {
197
- let t3 = false;
198
- return n2((i) => {
199
- if (!t3) return t3 = true, e.call(r, i);
200
- }, null);
201
- };
202
- }
203
- function pe(n2, e) {
204
- return ((t3) => {
205
- let o, i = { onWillAddFirstListener() {
206
- o = t3(s.fire, s);
207
- } }, s = new u(i);
208
- return s.event;
209
- })((t3, o = null) => n2((i) => e(i) && t3.call(o, i), null));
210
- }
211
- function ne(n2, e) {
212
- let r = Math.min(n2.length, e.length);
213
- for (let t3 = 0; t3 < r; t3++) Ee(n2[t3], e[t3]);
214
- }
215
- function Ee(n2, e) {
216
- if (b(e)) {
217
- if (typeof n2 !== e) throw new Error(`argument does not match constraint: typeof ${e}`);
218
- } else if (A(e)) {
219
- try {
220
- if (n2 instanceof e) return;
221
- } catch {
222
- }
223
- if (!N(n2) && n2.constructor === e || e.length === 1 && e.call(void 0, n2) === true) return;
224
- throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true");
225
- }
226
- }
227
- function Vn() {
228
- if (globalThis[P]) return globalThis[P];
229
- let n2 = new p(), e = new y(), r = { registerCommand(t3, o, i) {
230
- n2.registerCommand({ id: t3, handler: o, metadata: i });
231
- }, executeCommand(t3, ...o) {
232
- return e.executeCommand(t3, ...o);
233
- }, excuteCommandSync(t3, ...o) {
234
- return e.executeCommandThowErr(t3, ...o);
235
- } };
236
- return globalThis[P] = r, r;
237
- }
238
- var k, re, oe, g, L, ae, T, m, f, v, H, J, z, B, $, Q, X, Y, q, Z, me, Be, d, C, le, E, u, _, h, ue, O, fe, En, p, y, P;
239
- var init_index_es = __esm({
240
- "../common/dist/index.es.js"() {
241
- "use strict";
242
- k = Object.defineProperty;
243
- re = Object.getOwnPropertyDescriptor;
244
- oe = (n2, e) => {
245
- for (var r in e) k(n2, r, { get: e[r], enumerable: true });
246
- };
247
- g = (n2, e, r, t3) => {
248
- for (var o = t3 > 1 ? void 0 : t3 ? re(e, r) : e, i = n2.length - 1, s; i >= 0; i--) (s = n2[i]) && (o = (t3 ? s(e, r, o) : s(o)) || o);
249
- return t3 && o && k(e, r, o), o;
250
- };
251
- L = class {
252
- constructor() {
253
- this.state = "pending";
254
- this.promise = new Promise((e, r) => {
255
- this.resolve = (t3) => {
256
- this.state === "pending" && (this.state = "fulfilled", e(t3));
257
- }, this.reject = (t3) => {
258
- this.state === "pending" && (this.state = "rejected", r(t3));
259
- };
260
- });
261
- }
262
- };
263
- ae = ((a) => (a[a.DEVELOPER_FILE_NOT_FOUND = 0] = "DEVELOPER_FILE_NOT_FOUND", a[a.INTERNAL_IOS_CAN_NOT_FOUND_PKG = 1] = "INTERNAL_IOS_CAN_NOT_FOUND_PKG", a[a.USER_IOS_LOAD_TIMEOUT = 2] = "USER_IOS_LOAD_TIMEOUT", a[a.INTERNAL_IOS_PKG_LOAD_ERROR = 3] = "INTERNAL_IOS_PKG_LOAD_ERROR", a[a.INTERNAL_IOS_PKG_PARSE_FAIL = 4] = "INTERNAL_IOS_PKG_PARSE_FAIL", a[a.USER_IOS_GET_EMPTY_DATA = 5] = "USER_IOS_GET_EMPTY_DATA", a[a.USER_ANDROID_GET_PKG_FAIL = 6] = "USER_ANDROID_GET_PKG_FAIL", a[a.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE = 7] = "DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE", a))(ae || {});
264
- T = class extends Error {
265
- constructor(e) {
266
- if (typeof e == "string") {
267
- super(e), this.priority = "P1";
268
- return;
269
- }
270
- super(e.message), this.priority = "P1", this.stack = e.stack, this.raw = e;
271
- }
272
- };
273
- m = class extends T {
274
- constructor() {
275
- super(...arguments);
276
- this.kind = "INTERNAL_ERROR";
277
- }
278
- };
279
- f = class extends T {
280
- constructor() {
281
- super(...arguments);
282
- this.kind = "USER_ERROR";
283
- }
284
- };
285
- v = class extends f {
286
- constructor(r, t3, o) {
287
- super(r);
288
- this.message = r;
289
- this.errNo = t3;
290
- this.name = "USER_CUSTOM_ERROR";
291
- this.errMsg = r, o && (this.extra = Object.assign({}, this.extra, o));
292
- }
293
- };
294
- H = class extends m {
295
- constructor() {
296
- super(...arguments);
297
- this.name = "INTERNAL_SCHEMA_PARSE_ERROR";
298
- this.priority = "P0";
299
- }
300
- };
301
- J = class extends m {
302
- constructor() {
303
- super(...arguments);
304
- this.name = "INTERNAL_INVOKE_NATIVE_ERROR";
305
- }
306
- };
307
- z = class extends m {
308
- constructor(r, t3, o, i) {
309
- super(r);
310
- this.errNo = t3;
311
- this.name = "INTERNAL_APPLY_NATIVE_ERROR";
312
- this.errorType = o, this.errorCode = i;
313
- }
314
- };
315
- B = class extends m {
316
- constructor() {
317
- super(...arguments);
318
- this.name = "INTERNAL_JSCORE_ERROR";
319
- this.priority = "P0";
320
- }
321
- };
322
- $ = class extends m {
323
- constructor(r, t3) {
324
- super(r);
325
- this.message = r;
326
- this.name = "INTERNAL_CONTEXT_ERROR";
327
- this.property = t3;
328
- }
329
- };
330
- Q = class extends T {
331
- constructor(r, t3, o, i, s) {
332
- super(r);
333
- this.message = r;
334
- this.code = t3;
335
- this.kind = "API_ERROR";
336
- this.name = "API_ERROR";
337
- o && (this.errorType = o), i !== void 0 && (this.stack = i), s && (this.priority = s);
338
- }
339
- toJSON() {
340
- return { message: this.message, stack: this.stack, name: this.name, code: this.code, errorType: this.errorType };
341
- }
342
- };
343
- X = class extends m {
344
- constructor() {
345
- super(...arguments);
346
- this.name = "INTERNAL_METRIC_REPORT_ERROR";
347
- }
348
- };
349
- Y = class extends m {
350
- constructor() {
351
- super(...arguments);
352
- this.name = "INTERNAL_REPORTER_ERROR";
353
- }
354
- };
355
- q = { log: R("log"), warn: R("warn"), info: R("info"), error: R("error"), debug: R("debug") };
356
- Object.assign(globalThis, { logger: q });
357
- Z = Symbol.for("Jolibox.canIUseMap");
358
- me = {};
359
- globalThis[Z] = me;
360
- Be = { get config() {
361
- return globalThis[Z];
362
- } };
363
- d = class n {
364
- static {
365
- this.Undefined = new n(void 0);
366
- }
367
- constructor(e) {
368
- this.element = e, this.next = n.Undefined, this.prev = n.Undefined;
369
- }
370
- };
371
- C = class {
372
- constructor() {
373
- this._first = d.Undefined;
374
- this._last = d.Undefined;
375
- this._size = 0;
376
- }
377
- get size() {
378
- return this._size;
379
- }
380
- isEmpty() {
381
- return this._first === d.Undefined;
382
- }
383
- clear() {
384
- let e = this._first;
385
- for (; e !== d.Undefined; ) {
386
- let r = e.next;
387
- e.prev = d.Undefined, e.next = d.Undefined, e = r;
388
- }
389
- this._first = d.Undefined, this._last = d.Undefined, this._size = 0;
390
- }
391
- unshift(e) {
392
- return this._insert(e, false);
393
- }
394
- push(e) {
395
- return this._insert(e, true);
396
- }
397
- _insert(e, r) {
398
- let t3 = new d(e);
399
- if (this._first === d.Undefined) this._first = t3, this._last = t3;
400
- else if (r) {
401
- let i = this._last;
402
- this._last = t3, t3.prev = i, i.next = t3;
403
- } else {
404
- let i = this._first;
405
- this._first = t3, t3.next = i, i.prev = t3;
406
- }
407
- this._size += 1;
408
- let o = false;
409
- return () => {
410
- o || (o = true, this._remove(t3));
411
- };
412
- }
413
- shift() {
414
- if (this._first !== d.Undefined) {
415
- let e = this._first.element;
416
- return this._remove(this._first), e;
417
- }
418
- }
419
- pop() {
420
- if (this._last !== d.Undefined) {
421
- let e = this._last.element;
422
- return this._remove(this._last), e;
423
- }
424
- }
425
- _remove(e) {
426
- if (e.prev !== d.Undefined && e.next !== d.Undefined) {
427
- let r = e.prev;
428
- r.next = e.next, e.next.prev = r;
429
- } else e.prev === d.Undefined && e.next === d.Undefined ? (this._first = d.Undefined, this._last = d.Undefined) : e.next === d.Undefined ? (this._last = this._last.prev, this._last.next = d.Undefined) : e.prev === d.Undefined && (this._first = this._first.next, this._first.prev = d.Undefined);
430
- this._size -= 1;
431
- }
432
- *[Symbol.iterator]() {
433
- let e = this._first;
434
- for (; e !== d.Undefined; ) yield e.element, e = e.next;
435
- }
436
- };
437
- le = 0;
438
- E = class {
439
- constructor(e) {
440
- this.value = e;
441
- this.id = le++;
442
- }
443
- };
444
- u = class {
445
- constructor(e) {
446
- this.options = e;
447
- this._size = 0;
448
- }
449
- dispose(e) {
450
- this._disposed || (this._disposed = true, this._listeners && (e ? (this._listeners instanceof E && (this._listeners = [this._listeners]), this._listeners = this._listeners.filter((r) => r?.value === e)) : (this._listeners = void 0, this._size = 0)), this.options?.onDidRemoveLastListener?.());
451
- }
452
- get event() {
453
- return this._event ??= (e, r) => {
454
- if (this._disposed) return () => {
455
- console.info("[Jolibox SDK] Emitter is _disposed");
456
- };
457
- r && (e = e.bind(r));
458
- let t3 = new E(e);
459
- this._listeners ? this._listeners instanceof E ? this._listeners = [this._listeners, t3] : this._listeners.push(t3) : (this.options?.onWillAddFirstListener?.(this), this._listeners = t3, this.options?.onDidFirstListener?.(this)), this.options?.onDidAddListener?.(this), this._size++;
460
- }, this._event;
461
- }
462
- _deliver(e, r) {
463
- if (!e) return;
464
- let t3 = this.options?.onListenerError || Error.constructor;
465
- if (!t3) {
466
- e.value(r);
467
- return;
468
- }
469
- try {
470
- e.value(r);
471
- } catch (o) {
472
- t3(o);
473
- }
474
- }
475
- fire(e) {
476
- this._listeners && (this._listeners instanceof E ? this._deliver(this._listeners, e) : this._listeners.forEach((r) => this._deliver(r, e)));
477
- }
478
- hasListeners() {
479
- return this._size > 0;
480
- }
481
- };
482
- _ = class {
483
- constructor() {
484
- this.listeners = /* @__PURE__ */ new Map();
485
- this.listerHandlerMap = /* @__PURE__ */ new WeakMap();
486
- this.cachedEventQueue = /* @__PURE__ */ new Map();
487
- }
488
- on(e, r) {
489
- let t3 = this.listeners.get(e) ?? new u(), o = (s) => r(...s.args);
490
- this.listerHandlerMap.set(r, o), t3.event(o), this.listeners.set(e, t3);
491
- let i = this.cachedEventQueue.get(e);
492
- if (i) for (; i.size > 0; ) t3.fire({ event: e, ...i.shift() });
493
- }
494
- off(e, r) {
495
- let t3 = this.listeners.get(e);
496
- if (t3) {
497
- let o = this.listerHandlerMap.get(r);
498
- t3.dispose(o);
499
- }
500
- }
501
- emit(e, ...r) {
502
- let t3 = this.listeners.get(e);
503
- if (t3) t3.fire({ event: e, args: r });
504
- else {
505
- let o = this.cachedEventQueue.get(e);
506
- o || (o = new C(), this.cachedEventQueue.set(e, o)), o.push({ args: r });
507
- }
508
- }
509
- };
510
- h = {};
511
- oe(h, { None: () => ue, filter: () => pe, once: () => ee, toPromise: () => ce });
512
- ue = () => {
513
- console.log("[Jolibox SDK] None Event");
514
- };
515
- O = Symbol.for("Jolibox.hostEmitter");
516
- fe = () => {
517
- let n2 = new _();
518
- return globalThis[O] || (globalThis[O] = { on: n2.on.bind(n2), off: n2.off.bind(n2), emit: n2.emit.bind(n2) }), globalThis[O];
519
- };
520
- En = fe();
521
- p = class {
522
- constructor() {
523
- this._commands = /* @__PURE__ */ new Map();
524
- this._onDidRegisterCommand = new u();
525
- this.onDidRegisterCommand = this._onDidRegisterCommand.event;
526
- console.log("[Jolibox SDK] command registry");
527
- }
528
- registerCommand(e) {
529
- if (!e) throw new Error("invalid command");
530
- if (e.metadata && Array.isArray(e.metadata.args)) {
531
- let o = [];
532
- for (let s of e.metadata.args) o.push(s.constraint);
533
- let i = e.handler;
534
- e.handler = function(...s) {
535
- return ne(s, o), i(...s);
536
- };
537
- }
538
- let { id: r } = e;
539
- this._commands.get(r) && console.info(`[Jolibox SDK] duplicated command is registered ${r}`), this._commands.set(r, e), this._onDidRegisterCommand.fire(r);
540
- }
541
- getCommand(e) {
542
- return this._commands.get(e);
543
- }
544
- getCommands() {
545
- let e = /* @__PURE__ */ new Map();
546
- for (let r of this._commands.keys()) {
547
- let t3 = this.getCommand(r);
548
- t3 && e.set(r, t3);
549
- }
550
- return e;
551
- }
552
- };
553
- p = g([x], p);
554
- y = class {
555
- constructor() {
556
- this._onWillExecuteCommand = new u();
557
- this.onWillExecuteCommand = this._onWillExecuteCommand.event;
558
- this._onDidExecuteCommand = new u();
559
- this.onDidExecuteCommand = this._onDidExecuteCommand.event;
560
- this.registry = new p();
561
- this._starActivation = null;
562
- }
563
- _activateStar() {
564
- return this._starActivation || (this._starActivation = M(3e4)), this._starActivation;
565
- }
566
- async executeCommand(e, ...r) {
567
- return this.registry.getCommand(e) ? this._tryExecuteCommand(e, r) : (await Promise.all([Promise.race([this._activateStar(), h.toPromise(h.filter(this.registry.onDidRegisterCommand, (o) => o === e))])]), this._tryExecuteCommand(e, r));
568
- }
569
- executeCommandThowErr(e, ...r) {
570
- if (!!!this.registry.getCommand(e)) throw new Error(`command '${e}' not found`);
571
- let o = this.registry.getCommand(e);
572
- this._onWillExecuteCommand.fire({ commandId: e, args: r });
573
- let i = this.invokeFunction(o.handler, ...r);
574
- return this._onDidExecuteCommand.fire({ commandId: e, args: r }), i;
575
- }
576
- _tryExecuteCommand(e, r) {
577
- let t3 = this.registry.getCommand(e);
578
- if (!t3) return Promise.reject(new Error(`command '${e}' not found`));
579
- try {
580
- this._onWillExecuteCommand.fire({ commandId: e, args: r });
581
- let o = this.invokeFunction(t3.handler, ...r);
582
- return this._onDidExecuteCommand.fire({ commandId: e, args: r }), Promise.resolve(o);
583
- } catch (o) {
584
- return Promise.reject(o);
585
- }
586
- }
587
- invokeFunction(e, ...r) {
588
- let t3 = false;
589
- try {
590
- return e(...r);
591
- } finally {
592
- t3 = true;
593
- }
594
- }
595
- };
596
- y = g([x], y);
597
- P = Symbol.for("Jolibox.commands");
598
- }
599
- });
600
-
601
- // src/common/report/errors/report/index.ts
602
- function reportError(error, options = {}) {
603
- errorReportCollector.emit("ERROR_REPORT", {
604
- error,
605
- options
606
- });
607
- }
608
- var errorReportCollector, errorReportEmitter;
609
- var init_report = __esm({
610
- "src/common/report/errors/report/index.ts"() {
611
- "use strict";
612
- init_index_es();
613
- init_index_es();
614
- errorReportCollector = new _();
615
- errorReportEmitter = new _();
616
- reportError.debounce = Ue(reportError, 50, { leading: true });
617
- }
618
- });
619
-
620
- // src/common/report/errors/index.ts
621
- function formatErrorCode(method, code) {
622
- return `[${method}]:${code}`;
623
- }
624
- var createAPIError, createUserAPIError;
625
- var init_errors = __esm({
626
- "src/common/report/errors/index.ts"() {
627
- "use strict";
628
- init_report();
629
- init_index_es();
630
- init_report();
631
- createAPIError = (error, params) => {
632
- return new Q(params?.errMsg ?? error.msg ?? "", error.code, error.type);
633
- };
634
- createUserAPIError = (msg) => {
635
- return new v(msg);
636
- };
637
- }
638
- });
639
-
640
- // src/native/js-bridge/const.ts
641
- var BUFFER_METHODS, BACKGROUND_FORBIDDEN_METHODS, SYNC_METHODS;
642
- var init_const = __esm({
643
- "src/native/js-bridge/const.ts"() {
644
- "use strict";
645
- BUFFER_METHODS = [];
646
- BACKGROUND_FORBIDDEN_METHODS = [];
647
- SYNC_METHODS = ["env", "createRequestTask", "login"];
648
- }
649
- });
650
-
651
- // src/native/js-bridge/report.ts
652
- function createReportInvokeMetrics(jsCore2, onNative2) {
653
- if (!monitorHasInitialized) {
654
- invokeMonitor = new MetricsMonitor({
655
- eventName: "jolibox_invoke",
656
- tagNameOrder: ["status", "method", "errNo", "errMsg", "isForeground"],
657
- metricName: "duration",
658
- reporter(data) {
659
- jsCore2.invoke("track", JSON.stringify({ event: "reportMetrics", data }), -1);
660
- }
661
- });
662
- invokeJSToNativeMonitor = new MetricsMonitor({
663
- eventName: "jolibox_invoke_js2native",
664
- tagNameOrder: ["status", "method", "isForeground"],
665
- metricName: "duration",
666
- reporter(data) {
667
- jsCore2.invoke("track", JSON.stringify({ event: "reportMetrics", data }), -1);
668
- }
669
- });
670
- invokeNativeToJSMonitor = new MetricsMonitor({
671
- eventName: "jolibox_invoke_native2js",
672
- tagNameOrder: ["status", "method", "isForeground"],
673
- metricName: "duration",
674
- reporter(data) {
675
- jsCore2.invoke("track", JSON.stringify({ event: "reportMetrics", data }), -1);
676
- }
677
- });
678
- onNative2("onJoliboxEnterBackground", () => {
679
- invokeMonitor.flush();
680
- invokeJSToNativeMonitor.flush();
681
- invokeNativeToJSMonitor.flush();
682
- });
683
- monitorHasInitialized = true;
684
- }
685
- function report(invokeMetrics) {
686
- const {
687
- method,
688
- args,
689
- startTime,
690
- isForeground,
691
- errMsg = `${method}:fail no errMsg`,
692
- errNo = 0,
693
- __timing = {
694
- receiveJSInvoke: 0,
695
- invokeCallback: 0
696
- }
697
- } = invokeMetrics;
698
- const { receiveJSInvoke, invokeCallback } = __timing;
699
- const status = errMsg.match(/\S:(\S+)\s?/)?.[1] ?? "fail";
700
- invokeMonitor.report({
701
- status,
702
- method: normalizeMethod2(method, args),
703
- errNo: `${errNo}`,
704
- errMsg,
705
- isForeground,
706
- duration: Date.now() - startTime
707
- });
708
- if (startTime && receiveJSInvoke && invokeCallback) {
709
- invokeJSToNativeMonitor.report({
710
- status,
711
- method,
712
- isForeground,
713
- duration: Number((receiveJSInvoke - startTime).toFixed(3))
714
- });
715
- invokeNativeToJSMonitor.report({
716
- status,
717
- method,
718
- isForeground,
719
- duration: Number((Date.now() - invokeCallback).toFixed(3))
720
- });
721
- }
722
- }
723
- function normalizeMethod2(method, args) {
724
- if (method === "callHostMethod" || method === "callHostMethodSync") {
725
- if (args?.method) {
726
- return `${method}-${args.method}`;
727
- }
728
- }
729
- return method;
730
- }
731
- return report;
732
- }
733
- var getType, MetricsMonitor, monitorHasInitialized, invokeMonitor, invokeJSToNativeMonitor, invokeNativeToJSMonitor;
734
- var init_report2 = __esm({
735
- "src/native/js-bridge/report.ts"() {
736
- "use strict";
737
- init_index_es();
738
- getType = (type) => {
739
- if (type === "pv") return type;
740
- return "default";
741
- };
742
- MetricsMonitor = class {
743
- constructor(config2) {
744
- this.interval = 30;
745
- this.lastReportTime = 0;
746
- this.cache = {};
747
- const { reporter, interval = 30, eventName, tagNameOrder, metricName, type } = config2;
748
- this.reporter = reporter;
749
- this.interval = interval;
750
- this.eventName = eventName;
751
- this.tagNameOrder = tagNameOrder;
752
- this.metricName = metricName;
753
- this.type = getType(type);
754
- }
755
- report(point) {
756
- if (this.type === "pv") {
757
- this.addPVPoint(point);
758
- } else {
759
- this.addPoint(point);
760
- }
761
- this.tryReport(false);
762
- }
763
- flush() {
764
- this.tryReport(true);
765
- }
766
- tryReport(force) {
767
- if (!Object.keys(this.cache).length) {
768
- return;
769
- }
770
- if (force) {
771
- this.reporter(this.processPoints(this.cache));
772
- this.clearPoints();
773
- return;
774
- }
775
- this.lastReportTime = this.lastReportTime || Date.now();
776
- if (Date.now() - this.lastReportTime >= this.interval * 1e3) {
777
- this.reporter(this.processPoints(this.cache));
778
- this.clearPoints();
779
- this.lastReportTime = Date.now();
780
- }
781
- }
782
- addPoint(point) {
783
- const safeSetVal = (target, props, metricName, point2) => {
784
- const currentProp = props.shift();
785
- if (currentProp) {
786
- const currentVal = point2[currentProp];
787
- if (!target[currentVal]) target[currentVal] = {};
788
- safeSetVal(target[currentVal], props, metricName, point2);
789
- } else {
790
- if (!target[metricName]) target[metricName] = [];
791
- target[metricName].push(point2[metricName]);
792
- }
793
- };
794
- safeSetVal(this.cache, [...this.tagNameOrder], this.metricName, point);
795
- }
796
- addPVPoint(point) {
797
- const safeSetVal = (target, props, metricName, relation) => {
798
- const currentProp = props.shift();
799
- if (!currentProp && ie(relation)) {
800
- throw new X(
801
- `report value failed to match tagNameOrder, ${JSON.stringify(originParams)}`
802
- );
803
- }
804
- if (currentProp) {
805
- const keys = [];
806
- if (ie(relation)) {
807
- keys.push(...Object.keys(relation));
808
- } else if (b(relation)) {
809
- if (props.length > 0) {
810
- throw new X(
811
- `report value failed to match tagNameOrder, ${JSON.stringify(originParams)}`
812
- );
813
- }
814
- keys.push(relation);
815
- } else {
816
- throw new X(
817
- `expected metric value to be a string, but got a(n) ${typeof relation}, ${JSON.stringify(
818
- originParams
819
- )}`
820
- );
821
- }
822
- keys.forEach((key) => {
823
- if (!target[key]) target[key] = {};
824
- const value = ie(relation) ? relation[key] : relation;
825
- safeSetVal(target[key], [...props], metricName, value);
826
- });
827
- } else {
828
- if (!target[metricName]) {
829
- target[metricName] = 1;
830
- } else {
831
- target[metricName]++;
832
- }
833
- }
834
- };
835
- const originParams = {
836
- point,
837
- metricName: this.metricName,
838
- tagNameOrder: this.tagNameOrder
839
- };
840
- safeSetVal(this.cache, [...this.tagNameOrder], this.metricName, point);
841
- }
842
- processPoints(points) {
843
- return {
844
- eventName: this.eventName,
845
- tagNameOrder: this.tagNameOrder,
846
- metricName: this.metricName,
847
- metricAggregateType: this.type === "pv" ? "itoa" : "arr",
848
- data: points
849
- };
850
- }
851
- clearPoints() {
852
- this.cache = {};
853
- }
854
- };
855
- monitorHasInitialized = false;
856
- }
857
- });
858
-
859
- // src/native/js-bridge/invoke.ts
860
- function createInvoke(jsCore2, onNative2) {
861
- let resolveId = 0;
862
- let IS_FOREGROUND = true;
863
- const resolveMap = /* @__PURE__ */ new Map();
864
- const reportInvokeMetrics = createReportInvokeMetrics(jsCore2, onNative2);
865
- onNative2("onJoliboxEnterBackground", () => {
866
- IS_FOREGROUND = false;
867
- });
868
- onNative2("onJoliboxEnterForeground", () => {
869
- IS_FOREGROUND = true;
870
- asyncInvokes.forEach(async ({ method, args, resolve }) => {
871
- const res = await invokeNative2(method, args);
872
- resolve(res);
873
- });
874
- asyncInvokes.length = 0;
875
- });
876
- const invokeHandler2 = (resolveId2, data) => {
877
- q.info("----resolveId", resolveId2, data);
878
- const resolve = resolveMap.get(Number(resolveId2));
879
- if (!resolve) return;
880
- const response = unpack(data);
881
- resolve(response);
882
- resolveMap.delete(Number(resolveId2));
883
- };
884
- const invokeNative2 = (method, args) => {
885
- const startTime = Date.now();
886
- const isForeground = `${IS_FOREGROUND}`;
887
- resolveId += 1;
888
- const deferred = new L();
889
- resolveMap.set(resolveId, deferred.resolve);
890
- if (!IS_FOREGROUND && BACKGROUND_FORBIDDEN_METHODS.includes(method)) {
891
- return new Promise((resolve) => {
892
- asyncInvokes.push({ method, args, resolve });
893
- });
894
- }
895
- const basicReportParam = {
896
- method,
897
- startTime,
898
- args,
899
- isForeground
900
- };
901
- const invokeReportParam = {
902
- ...basicReportParam,
903
- invokeType: "js-bridge"
904
- };
905
- const useArrayBuffer = !NOT_SUPPORT_ARRAY_BUFFER && BUFFER_METHODS.includes(method);
906
- const payload = pack(args, useArrayBuffer);
907
- const params = useArrayBuffer ? payload : JSON.stringify(payload);
908
- let response;
909
- if (method.endsWith("Sync") || SYNC_METHODS.includes(method)) {
910
- response = jsCore2.call?.(method, payload, resolveId);
911
- } else {
912
- if (typeof params === "string") {
913
- console.log("-----params", method, resolveId);
914
- response = jsCore2.invoke(method, params, resolveId);
915
- } else {
916
- response = jsCore2.call?.(method, params, resolveId);
917
- }
918
- }
919
- if (response) {
920
- try {
921
- if (typeof response === "string") {
922
- response = JSON.parse(response);
923
- }
924
- response = unpack(response);
925
- } catch (error) {
926
- q.error(error);
927
- }
928
- resolveMap.delete(resolveId);
929
- if (response.errorCode) {
930
- response.errorCode = formatErrorCode(method, response.errorCode);
931
- }
932
- reportInvokeMetrics({ ...invokeReportParam, ...response });
933
- return response;
934
- }
935
- if (method.endsWith("Sync")) {
936
- resolveMap.delete(resolveId);
937
- }
938
- return deferred.promise.then((response2) => {
939
- if (response2.errorCode) {
940
- response2.errorCode = formatErrorCode(method, response2.errorCode);
941
- }
942
- reportInvokeMetrics({ ...invokeReportParam, ...response2 });
943
- return response2;
944
- });
945
- };
946
- const applyNative3 = (method, arg) => {
947
- const res = invokeNative2(method, arg);
948
- if (Oe(res)) {
949
- return res.then(
950
- (r) => ifThrowError(
951
- method,
952
- r
953
- )
954
- );
955
- }
956
- return ifThrowError(method, res);
957
- };
958
- return {
959
- invokeNative: invokeNative2,
960
- applyNative: applyNative3,
961
- invokeHandler: invokeHandler2
962
- };
963
- }
964
- function ifThrowError(method, res) {
965
- if (!ie(res)) {
966
- q.warn(`[Jolibox SDK]${method} no response value`);
967
- return;
968
- }
969
- const { errMsg, errNo, errorType, errorCode, ...data } = res;
970
- if (errMsg && errMsg !== `${method}:ok`) {
971
- throw new z(errMsg, errNo, errorType, errorCode);
972
- }
973
- return data;
974
- }
975
- var asyncInvokes, NOT_SUPPORT_ARRAY_BUFFER;
976
- var init_invoke = __esm({
977
- "src/native/js-bridge/invoke.ts"() {
978
- "use strict";
979
- init_utils();
980
- init_index_es();
981
- init_errors();
982
- init_const();
983
- init_report2();
984
- asyncInvokes = [];
985
- NOT_SUPPORT_ARRAY_BUFFER = false;
986
- }
987
- });
988
-
989
- // src/native/js-bridge/subscribe.ts
990
- function createSubscribe(jsCore2) {
991
- const nativeEmitter = new _();
992
- const publishMonitor = new MetricsMonitor({
993
- eventName: "jolibox_publish",
994
- tagNameOrder: ["type", "event"],
995
- metricName: "duration",
996
- reporter(data) {
997
- jsCore2.invoke("track", JSON.stringify({ event: "reportMetrics", data }), -1);
998
- }
999
- });
1000
- nativeEmitter.on("onJoliboxEnterBackground", () => {
1001
- publishMonitor.flush();
1002
- });
1003
- return {
1004
- onNative: nativeEmitter.on.bind(nativeEmitter),
1005
- offNative: nativeEmitter.off.bind(nativeEmitter),
1006
- subscribeHandler(event, data, webviewId) {
1007
- const unpackedData = unpack(data);
1008
- let originalParams;
1009
- if (unpackedData.__extra) {
1010
- originalParams = unpackedData.params;
1011
- const { type, startTime } = unpackedData.__extra;
1012
- publishMonitor.report({
1013
- type,
1014
- event,
1015
- duration: Date.now() - startTime
1016
- // ms
1017
- });
1018
- } else {
1019
- originalParams = unpackedData;
1020
- }
1021
- nativeEmitter.emit(event, originalParams, webviewId);
1022
- }
1023
- };
1024
- }
1025
- var init_subscribe = __esm({
1026
- "src/native/js-bridge/subscribe.ts"() {
1027
- "use strict";
1028
- init_index_es();
1029
- init_utils();
1030
- init_report2();
1031
- }
1032
- });
1033
-
1034
- // src/native/js-bridge/js-bridge.ts
1035
- function createBridge(jsCore2) {
1036
- const { subscribeHandler: subscribeHandler2, onNative: onNative2, offNative: offNative2 } = createSubscribe(jsCore2);
1037
- const { invokeNative: invokeNative2, invokeHandler: invokeHandler2, applyNative: applyNative3 } = createInvoke(jsCore2, onNative2);
1038
- return {
1039
- // 宿主调用
1040
- invokeHandler: invokeHandler2,
1041
- subscribeHandler: subscribeHandler2,
1042
- applyNative: applyNative3,
1043
- invokeNative: invokeNative2,
1044
- onNative: onNative2,
1045
- offNative: offNative2
1046
- };
1047
- }
1048
- var init_js_bridge = __esm({
1049
- "src/native/js-bridge/js-bridge.ts"() {
1050
- "use strict";
1051
- init_invoke();
1052
- init_subscribe();
1053
- }
1054
- });
1055
-
1056
- // src/native/js-bridge/types.ts
1057
- var init_types = __esm({
1058
- "src/native/js-bridge/types.ts"() {
1059
- "use strict";
1060
- }
1061
- });
1062
-
1063
- // src/native/js-bridge/index.ts
1064
- var init_js_bridge2 = __esm({
1065
- "src/native/js-bridge/index.ts"() {
1066
- "use strict";
1067
- init_js_bridge();
1068
- init_types();
1069
- }
1070
- });
1071
-
1072
- // src/native/js-core/jolibox-js-core.ts
1073
- var joliboxJSCore, RuntimeLoader, env;
1074
- var init_jolibox_js_core = __esm({
1075
- "src/native/js-core/jolibox-js-core.ts"() {
1076
- "use strict";
1077
- init_index_es();
1078
- init_report();
1079
- RuntimeLoader = {
1080
- trigger() {
1081
- },
1082
- exit() {
1083
- return false;
1084
- },
1085
- onReady(fn) {
1086
- RuntimeLoader.trigger = fn;
1087
- },
1088
- doExit(fn) {
1089
- RuntimeLoader.exit = fn;
1090
- }
1091
- };
1092
- env = () => {
1093
- const res = window.prompt(
1094
- "invoke",
1095
- JSON.stringify({
1096
- event: "envSync",
1097
- paramsString: JSON.stringify({})
1098
- })
1099
- );
1100
- if (!res) {
1101
- reportError(new J(`native env failed`));
1102
- } else {
1103
- const { data } = JSON.parse(res);
1104
- return data ?? void 0;
1105
- }
1106
- };
1107
- if (window.webkit) {
1108
- const _joliboxJSCore = window.webkit.messageHandlers;
1109
- const onDocumentReady = (path = "") => {
1110
- RuntimeLoader.trigger();
1111
- _joliboxJSCore.onDocumentReady.postMessage({ path });
1112
- };
1113
- const doExit = (uuid) => {
1114
- const shouldInterrupt = RuntimeLoader.exit();
1115
- _joliboxJSCore.doExit.postMessage({ uuid, shouldInterrupt });
1116
- };
1117
- joliboxJSCore = {
1118
- onDocumentReady,
1119
- doExit,
1120
- invoke(method, params, callbackId) {
1121
- _joliboxJSCore.invoke.postMessage({
1122
- event: method,
1123
- paramsString: params,
1124
- callbackId
1125
- });
1126
- },
1127
- // publish(event, params, webviewIds) {
1128
- // const data = normalizeParams(params as Record<string, unknown>, 'joliboxJSCore');
1129
- // _joliboxJSCore.publish.postMessage({
1130
- // event,
1131
- // paramsString: JSON.stringify(data),
1132
- // webviewIds: JSON.stringify(webviewIds)
1133
- // });
1134
- // },
1135
- call(method, params, callbackId) {
1136
- const res = window.prompt(
1137
- "invoke",
1138
- JSON.stringify({
1139
- event: method,
1140
- paramsString: JSON.stringify(params),
1141
- callbackId
1142
- })
1143
- );
1144
- if (res) {
1145
- return JSON.parse(res);
1146
- }
1147
- }
1148
- };
1149
- const devCore = { onDocumentReady, env };
1150
- globalThis.joliboxJSCore = {
1151
- ...devCore
1152
- };
1153
- }
1154
- if (window.JoliAndroidSDKBridge) {
1155
- const _joliboxJSCore = window.JoliAndroidSDKBridge;
1156
- const onDocumentReady = (path = "") => {
1157
- RuntimeLoader.trigger();
1158
- _joliboxJSCore.onDocumentReady(JSON.stringify({ path }));
1159
- };
1160
- const doExit = (uuid) => {
1161
- const shouldInterrupt = RuntimeLoader.exit();
1162
- _joliboxJSCore.doExit(JSON.stringify({ uuid, shouldInterrupt }));
1163
- };
1164
- joliboxJSCore = {
1165
- onDocumentReady,
1166
- invoke(method, params, callbackId) {
1167
- _joliboxJSCore.invoke(
1168
- JSON.stringify({
1169
- event: method,
1170
- paramsString: params,
1171
- callbackId
1172
- })
1173
- );
1174
- },
1175
- doExit,
1176
- // publish(event, params, webviewIds) {
1177
- // const data = normalizeParams(params as Record<string, unknown>, 'joliboxJSCore');
1178
- // _joliboxJSCore.publish({
1179
- // event,
1180
- // paramsString: JSON.stringify(data),
1181
- // webviewIds: JSON.stringify(webviewIds)
1182
- // });
1183
- // },
1184
- call(method, params, callbackId) {
1185
- const res = window.prompt(
1186
- "invoke",
1187
- JSON.stringify({
1188
- event: method,
1189
- paramsString: JSON.stringify(params),
1190
- callbackId
1191
- })
1192
- );
1193
- if (res) {
1194
- return JSON.parse(res);
1195
- }
1196
- }
1197
- };
1198
- const devCore = { onDocumentReady, env };
1199
- globalThis.joliboxJSCore = {
1200
- ...devCore
1201
- };
1202
- }
1203
- }
1204
- });
1205
-
1206
- // src/native/js-core/utils.ts
1207
- function normalizeParams(params, type) {
1208
- return {
1209
- params,
1210
- __extra: {
1211
- startTime: Date.now(),
1212
- type
1213
- }
1214
- };
1215
- }
1216
- var init_utils2 = __esm({
1217
- "src/native/js-core/utils.ts"() {
1218
- "use strict";
1219
- }
1220
- });
1221
-
1222
- // src/native/js-core/message-port.ts
1223
- function initMessagePort() {
1224
- globalThis.onmessage = function(msg) {
1225
- if (msg.data !== "msg:setup") {
1226
- return;
1227
- }
1228
- [messagePort] = msg.ports;
1229
- messagePort.onmessage = function(message) {
1230
- const data = JSON.parse(message.data);
1231
- if (data[0] === "publish") {
1232
- globalThis.ttJSBridge.subscribeHandler(data[1], data[2]);
1233
- } else if (data[0] === "invoke") {
1234
- globalThis.ttJSBridge.invokeHandler(data[1], data[2]);
1235
- }
1236
- };
1237
- messagePort.publish = function(event, params) {
1238
- const data = normalizeParams(params, "messagePort");
1239
- messagePort.postMessage(JSON.stringify(["publish", event, JSON.stringify(data)]));
1240
- };
1241
- messagePort.postMessage("msg:setup:ok");
1242
- };
1243
- }
1244
- var messagePort;
1245
- var init_message_port = __esm({
1246
- "src/native/js-core/message-port.ts"() {
1247
- "use strict";
1248
- init_utils2();
1249
- }
1250
- });
1251
-
1252
- // src/native/js-core/index.ts
1253
- var init_js_core = __esm({
1254
- "src/native/js-core/index.ts"() {
1255
- "use strict";
1256
- init_jolibox_js_core();
1257
- init_message_port();
1258
- init_utils2();
1259
- }
1260
- });
1261
-
1262
- // src/native/bootstrap/bridge.ts
1263
- var jsCore, core, bridge, invokeHandler, applyNative, invokeNative, onNative, offNative, subscribeHandler;
1264
- var init_bridge = __esm({
1265
- "src/native/bootstrap/bridge.ts"() {
1266
- "use strict";
1267
- init_js_bridge2();
1268
- init_js_core();
1269
- init_errors();
1270
- init_index_es();
1271
- init_js_core();
1272
- jsCore = joliboxJSCore;
1273
- if (!jsCore) {
1274
- throw new B("No joliboxJScore is found, native bridge not found.");
1275
- }
1276
- initMessagePort();
1277
- core = {
1278
- ...jsCore
1279
- // publish(event: string, params: Record<string, unknown>, webviewIds: number[]) {
1280
- // if (messagePort) {
1281
- // messagePort.publish(event, params);
1282
- // return;
1283
- // }
1284
- // jsCore.publish(event, params, webviewIds);
1285
- // }
1286
- };
1287
- bridge = createBridge(core);
1288
- ({ invokeHandler } = bridge);
1289
- ({ applyNative, invokeNative, onNative, offNative, subscribeHandler } = bridge);
1290
- globalThis.joliboxJSBridge = {
1291
- callHandler: invokeHandler,
1292
- invokeHandler,
1293
- subscribeHandler
1294
- };
1295
- }
1296
- });
1297
-
1298
- // src/common/context/url-parse.ts
1299
- var base64UrlDecode, parseUrlQuery;
1300
- var init_url_parse = __esm({
1301
- "src/common/context/url-parse.ts"() {
1302
- "use strict";
1303
- init_index_es();
1304
- init_report();
1305
- base64UrlDecode = (input) => {
1306
- const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
1307
- const padding = base64.length % 4 === 0 ? "" : "=".repeat(4 - base64.length % 4);
1308
- const jsonStr = atob(base64 + padding);
1309
- try {
1310
- return JSON.parse(jsonStr);
1311
- } catch (e) {
1312
- return {};
1313
- }
1314
- };
1315
- parseUrlQuery = (url) => {
1316
- try {
1317
- const urlObj = new URL(url);
1318
- const params = urlObj.searchParams;
1319
- const joli_source = params.get("joliSource")?.split(".");
1320
- if (joli_source?.length) {
1321
- const [headerJsonStr, payloadJsonStr, signatureJsonStr] = joli_source;
1322
- return {
1323
- headerJson: base64UrlDecode(headerJsonStr),
1324
- payloadJson: base64UrlDecode(payloadJsonStr),
1325
- signature: base64UrlDecode(signatureJsonStr)
1326
- };
1327
- } else {
1328
- throw `joli_source is missing`;
1329
- }
1330
- } catch (e) {
1331
- reportError(new H(`${url} not a valid schema: ${e}`));
1332
- return {
1333
- headerJson: {},
1334
- payloadJson: {},
1335
- signature: {}
1336
- };
1337
- }
1338
- };
1339
- }
1340
- });
1341
-
1342
- // src/common/http/uuid.ts
1343
- var uuidv4;
1344
- var init_uuid = __esm({
1345
- "src/common/http/uuid.ts"() {
1346
- "use strict";
1347
- uuidv4 = () => {
1348
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1349
- const r = Math.random() * 16 | 0;
1350
- const v2 = c === "x" ? r : r & 3 | 8;
1351
- return v2.toString(16);
1352
- });
1353
- };
1354
- }
1355
- });
1356
-
1357
- // src/common/http/xua.ts
1358
- var platform, getPlatform, jssdkVersion, getAppVersion, DEVICE_ID, ADVERTISING_ID, getStorage, getDeviceId, getAdvertisingId, firstCharUpperCase, getUtmSource, xUserAgent;
1359
- var init_xua = __esm({
1360
- "src/common/http/xua.ts"() {
1361
- "use strict";
1362
- init_uuid();
1363
- platform = {
1364
- isiOS: navigator.userAgent.includes("iPhone") || navigator.userAgent.includes("iPod") || navigator.userAgent.includes("iPad") || navigator.userAgent.includes("iPhone OS"),
1365
- iosVersion: () => {
1366
- const v2 = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
1367
- return [parseInt(v2[1], 10), parseInt(v2[2], 10), parseInt(v2[3] || "0", 10)];
1368
- },
1369
- isAndroid: navigator.userAgent.includes("Android"),
1370
- isMac: navigator.userAgent.includes("Mac"),
1371
- isFacebook: navigator.userAgent.includes("FB_IAB"),
1372
- isPC: !navigator.userAgent.includes("iPhone") && !navigator.userAgent.includes("Android")
1373
- };
1374
- getPlatform = () => {
1375
- if (platform.isiOS) {
1376
- return "iOS";
1377
- } else if (platform.isAndroid) {
1378
- return "Android";
1379
- } else if (platform.isMac) {
1380
- return "Mac";
1381
- } else if (platform.isFacebook) {
1382
- return "Facebook";
1383
- } else {
1384
- return "PC";
1385
- }
1386
- };
1387
- jssdkVersion = "1.1.4-beta.9";
1388
- getAppVersion = () => {
1389
- return jssdkVersion;
1390
- };
1391
- DEVICE_ID = "device_id";
1392
- ADVERTISING_ID = "advertising_id";
1393
- getStorage = (cookieKey) => {
1394
- if (!localStorage.getItem(cookieKey)) {
1395
- localStorage.setItem(cookieKey, uuidv4());
1396
- }
1397
- return localStorage.getItem(cookieKey);
1398
- };
1399
- getDeviceId = () => {
1400
- return getStorage(DEVICE_ID);
1401
- };
1402
- getAdvertisingId = () => {
1403
- return getStorage(ADVERTISING_ID);
1404
- };
1405
- firstCharUpperCase = (chars) => chars.charAt(0).toUpperCase() + chars.slice(1);
1406
- getUtmSource = () => {
1407
- const urlParams = new URLSearchParams(window.location.search);
1408
- return firstCharUpperCase(urlParams.get("utm_source") ?? "") || "JoliboxSDK";
1409
- };
1410
- xUserAgent = () => {
1411
- const applicationName = "JoliboxWebSDK";
1412
- const thePlatform = getPlatform();
1413
- const locale = navigator.language;
1414
- const deviceId = getDeviceId();
1415
- const adid = getAdvertisingId();
1416
- const appVersion = getAppVersion();
1417
- const deviceModel = "UnknownModel";
1418
- const systemVersion = "UnknownSystemVersion";
1419
- return `${applicationName} (${getUtmSource()}${thePlatform}; ${deviceModel}; ${systemVersion}; ${locale}) uuid/${deviceId} adid/${adid} version/${appVersion || ""}`;
1420
- };
1421
- }
1422
- });
1423
-
1424
- // src/common/context/index.ts
1425
- var defaultEnv, nativeEnv, env2, wrapContext, context;
1426
- var init_context = __esm({
1427
- "src/common/context/index.ts"() {
1428
- "use strict";
1429
- init_index_es();
1430
- init_url_parse();
1431
- init_xua();
1432
- defaultEnv = {
1433
- deviceInfo: {
1434
- brand: "UnknownBrand",
1435
- model: "UnknownModel",
1436
- did: getDeviceId(),
1437
- pixelRatio: window.devicePixelRatio || 1,
1438
- platform: "h5",
1439
- system: "UnknownSystemVersion",
1440
- lang: "zh"
1441
- },
1442
- sdkInfo: {
1443
- nativeSDKVersion: "",
1444
- jssdkVersion: getAppVersion()
1445
- },
1446
- schema: "",
1447
- platform: "h5"
1448
- };
1449
- nativeEnv = globalThis.joliboxJSCore?.env;
1450
- env2 = Object.assign({}, nativeEnv?.() ?? defaultEnv);
1451
- wrapContext = () => {
1452
- const { payloadJson, headerJson } = parseUrlQuery(env2.schema);
1453
- const defaultSessionId = `${env2.deviceInfo.did}-${(/* @__PURE__ */ new Date()).getTime()}`;
1454
- const urlParams = new URLSearchParams(window.location.search);
1455
- const defaultGameID = urlParams.get("appId") ?? urlParams.get("gameId") ?? "";
1456
- const sessionId = payloadJson.sessionId ?? urlParams.get("sessionId") ?? defaultSessionId;
1457
- const testAdsMode = !!(payloadJson.testAdsMode ?? urlParams.get("testAdsMode") === "true");
1458
- const joliboxEnv = payloadJson.joliboxEnv ?? urlParams.get("joliboxEnv") ?? "production";
1459
- const testMode = joliboxEnv === "staging";
1460
- return {
1461
- get testMode() {
1462
- return testMode;
1463
- },
1464
- get testAdsMode() {
1465
- return testAdsMode;
1466
- },
1467
- get joliboxEnv() {
1468
- return joliboxEnv;
1469
- },
1470
- get mpId() {
1471
- return defaultGameID ?? payloadJson["id"];
1472
- },
1473
- get mpVersion() {
1474
- return headerJson.ver ?? getAppVersion();
1475
- },
1476
- get platform() {
1477
- return env2.platform;
1478
- },
1479
- get deviceInfo() {
1480
- return env2.deviceInfo;
1481
- },
1482
- get sdkInfo() {
1483
- return env2.sdkInfo;
1484
- },
1485
- get hostInfo() {
1486
- return env2.hostInfo;
1487
- },
1488
- get hostUserInfo() {
1489
- return env2.hostUserInfo;
1490
- },
1491
- get sessionId() {
1492
- return env2.clientSessionId ?? sessionId ?? defaultSessionId;
1493
- },
1494
- onEnvConfigChanged: (newConfig) => {
1495
- ke(env2, newConfig, Le);
1496
- }
1497
- };
1498
- };
1499
- context = wrapContext();
1500
- }
1501
- });
1502
-
1503
- // src/common/report/errors/report/listeners.ts
1504
- var reportFlag, hasIn, isBaseError, toCamelCase, innerErrorReport, isUserError;
1505
- var init_listeners = __esm({
1506
- "src/common/report/errors/report/listeners.ts"() {
1507
- "use strict";
1508
- init_index_es();
1509
- init_report();
1510
- init_context();
1511
- init_index_es();
1512
- reportFlag = false;
1513
- hasIn = (object, path) => {
1514
- if (object == null) return false;
1515
- return path in object;
1516
- };
1517
- isBaseError = (error) => {
1518
- return hasIn(error, "kind");
1519
- };
1520
- toCamelCase = (snakeStr) => {
1521
- const words = snakeStr.toLowerCase().split("_");
1522
- return words[0] + words.slice(1).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
1523
- };
1524
- innerErrorReport = (error, options = {}, isFromUser) => {
1525
- const priority = error.priority ?? "P1";
1526
- const common = {
1527
- user_id: context.hostUserInfo?.uid ?? "",
1528
- device_id: context.deviceInfo.did ?? "",
1529
- timestamp: Date.now(),
1530
- tag: toCamelCase(error.name)
1531
- };
1532
- const reports = { ...common, env: options.environment, isFromUser };
1533
- if (isFromUser) {
1534
- errorReportEmitter.emit("GLOBAL_USER_ERROR", error, reports);
1535
- } else {
1536
- errorReportEmitter.emit("GLOBAL_ERROR", error, reports);
1537
- }
1538
- };
1539
- isUserError = (error) => {
1540
- return hasIn(error, "kind") && error["kind"] === "USER_ERROR";
1541
- };
1542
- errorReportCollector.on("ERROR_REPORT", ({ error, options }) => {
1543
- if (reportFlag) return;
1544
- reportFlag = true;
1545
- const raw = isBaseError(error) && error.raw ? error.raw : error;
1546
- try {
1547
- const isFromUser = isUserError(error);
1548
- innerErrorReport(error, options, isFromUser);
1549
- } catch (err) {
1550
- const message = err instanceof Error ? err.message : String(err);
1551
- const reportError2 = new Y(`${message}, origin error: ${raw.message}`);
1552
- q.error(reportError2);
1553
- innerErrorReport(
1554
- new Y(reportError2.message),
1555
- {
1556
- environment: options.environment
1557
- },
1558
- false
1559
- );
1560
- } finally {
1561
- reportFlag = false;
1562
- }
1563
- });
1564
- }
1565
- });
1566
-
1567
- // src/native/report/errors/index.ts
1568
- var init_errors2 = __esm({
1569
- "src/native/report/errors/index.ts"() {
1570
- "use strict";
1571
- init_listeners();
1572
- init_errors();
1573
- init_index_es();
1574
- init_bridge();
1575
- errorReportEmitter.on("GLOBAL_ERROR", (error, errorData) => {
1576
- const extra = {
1577
- message: error.message,
1578
- stack: error.stack ?? "",
1579
- errorType: error.name,
1580
- source: 0
1581
- };
1582
- invokeNative("trackAsync", {
1583
- event: "reportJsError",
1584
- data: extra
1585
- });
1586
- });
1587
- errorReportEmitter.on("GLOBAL_USER_ERROR", (error, errorData) => {
1588
- q.log("UserError", error, errorData);
1589
- });
1590
- }
1591
- });
1592
-
1593
- // src/common/report/types.ts
1594
- var init_types2 = __esm({
1595
- "src/common/report/types.ts"() {
1596
- "use strict";
1597
- }
1598
- });
1599
-
1600
- // src/common/report/track.ts
1601
- function createTrack(reportHandler, common) {
1602
- const track2 = (tag, info, webviewId) => {
1603
- const data = {
1604
- tag,
1605
- ...common,
1606
- extra: {
1607
- ...info
1608
- }
1609
- };
1610
- if (tag == "globalJsError") {
1611
- reportError(new $(JSON.stringify(data), "P0"));
1612
- } else {
1613
- reportHandler("systemLog", data, webviewId);
1614
- }
1615
- };
1616
- track2.debounce = Ue(track2, 500, { leading: true });
1617
- return track2;
1618
- }
1619
- function createTrackPerformance(track2) {
1620
- const trackPerformance2 = (type, duration, data) => {
1621
- const length = (data && JSON.stringify(data)) ?? 0;
1622
- const info = {
1623
- speed_value_type: type,
1624
- total_duration: duration
1625
- };
1626
- if (length) {
1627
- Object.assign(info, { extra: length });
1628
- }
1629
- track2("joliboxSpeedAnalysis", info);
1630
- };
1631
- trackPerformance2.debounce = Ue(trackPerformance2, 500, {
1632
- leading: true
1633
- });
1634
- return trackPerformance2;
1635
- }
1636
- var init_track = __esm({
1637
- "src/common/report/track.ts"() {
1638
- "use strict";
1639
- init_index_es();
1640
- init_index_es();
1641
- init_report();
1642
- }
1643
- });
1644
-
1645
- // src/common/report/create-trace.ts
1646
- function createTracks(reportHandler, common) {
1647
- const track2 = createTrack(reportHandler, common);
1648
- const trackPerformance2 = createTrackPerformance(track2);
1649
- return {
1650
- track: track2,
1651
- trackPerformance: trackPerformance2
1652
- };
1653
- }
1654
- var init_create_trace = __esm({
1655
- "src/common/report/create-trace.ts"() {
1656
- "use strict";
1657
- init_track();
1658
- }
1659
- });
1660
-
1661
- // src/common/report/base-tracker.ts
1662
- var init_base_tracker = __esm({
1663
- "src/common/report/base-tracker.ts"() {
1664
- "use strict";
1665
- init_context();
1666
- init_index_es();
1667
- }
1668
- });
1669
-
1670
- // src/common/report/index.ts
1671
- var init_report3 = __esm({
1672
- "src/common/report/index.ts"() {
1673
- "use strict";
1674
- init_create_trace();
1675
- init_types2();
1676
- init_base_tracker();
1677
- }
1678
- });
1679
-
1680
- // src/common/report/task-track/index.ts
1681
- var TaskTracker;
1682
- var init_task_track = __esm({
1683
- "src/common/report/task-track/index.ts"() {
1684
- "use strict";
1685
- TaskTracker = class {
1686
- constructor(eventEmitter, interval) {
1687
- this.lastReportTime = 0;
1688
- this.visible = true;
1689
- this.timer = this.createRAFTimer((duration) => {
1690
- this.reporter({
1691
- event: "PLAY_GAME",
1692
- params: {
1693
- duration: duration / 1e3
1694
- // second
1695
- }
1696
- });
1697
- this.tracker("PlayGame", { duration: duration / 1e3 });
1698
- });
1699
- this.interval = interval ?? 5 * 1e3;
1700
- eventEmitter.on("visible", (visible) => {
1701
- this.visible = visible;
1702
- });
1703
- }
1704
- start(duration) {
1705
- this.reporter({
1706
- event: "OPEN_GAME",
1707
- params: {
1708
- timestamp: Date.now(),
1709
- duration: duration ?? 0 / 1e3
1710
- // second
1711
- }
1712
- });
1713
- this.tracker("OpenGame", { duration: duration ?? 0 / 1e3 });
1714
- this.timer.start();
1715
- }
1716
- close(duration) {
1717
- this.reporter({
1718
- event: "CLOSE_GAME",
1719
- params: {
1720
- timestamp: Date.now(),
1721
- duration: duration / 1e3
1722
- // second
1723
- }
1724
- });
1725
- this.tracker("CloseGame", { duration: duration / 1e3 });
1726
- this.timer.stop();
1727
- }
1728
- createRAFTimer(callback) {
1729
- let lastTime = performance.now();
1730
- let rafId;
1731
- let isRunning = false;
1732
- let totalTime = 0;
1733
- const tick = (currentTime) => {
1734
- if (!isRunning) return;
1735
- const deltaTime = currentTime - lastTime;
1736
- if (deltaTime >= this.interval) {
1737
- if (this.visible) {
1738
- totalTime += deltaTime;
1739
- callback(totalTime);
1740
- }
1741
- lastTime = currentTime;
1742
- }
1743
- rafId = requestAnimationFrame(tick);
1744
- };
1745
- return {
1746
- start() {
1747
- if (!isRunning) {
1748
- isRunning = true;
1749
- lastTime = performance.now();
1750
- rafId = requestAnimationFrame(tick);
1751
- }
1752
- },
1753
- stop() {
1754
- isRunning = false;
1755
- if (rafId) {
1756
- cancelAnimationFrame(rafId);
1757
- }
1758
- }
1759
- };
1760
- }
1761
- };
1762
- }
1763
- });
1764
-
1765
- // src/native/network/types.ts
1766
- var init_types3 = __esm({
1767
- "src/native/network/types.ts"() {
1768
- "use strict";
1769
- }
1770
- });
1771
-
1772
- // src/native/network/report.ts
1773
- function reportNetworkAPI(method, url, options) {
1774
- const { response, startTime, endTime, requestFrom } = options;
1775
- const { errMsg = "", profile = {} } = response;
1776
- const duration = endTime - startTime;
1777
- const trackData = {
1778
- duration,
1779
- request_type: method,
1780
- url: url.split("?")[0],
1781
- result: options.state,
1782
- error_msg: options.state === "fail" ? errMsg : "",
1783
- socket_reused: profile.socketReused ? 1 : 0,
1784
- request_from: requestFrom
1785
- };
1786
- if (requestFrom === "public" /* PUBLIC */ && requestNumber < requestNumberLimit || requestFrom === "inner" /* INNER */) {
1787
- trackData.joli_request_number = requestNumber++;
1788
- setTimeout(() => {
1789
- track("joliboxNetRequestResult", trackData);
1790
- }, 500);
1791
- }
1792
- }
1793
- var requestNumber, requestNumberLimit;
1794
- var init_report4 = __esm({
1795
- "src/native/network/report.ts"() {
1796
- "use strict";
1797
- init_types3();
1798
- init_report5();
1799
- requestNumber = 0;
1800
- requestNumberLimit = 10;
1801
- }
1802
- });
1803
-
1804
- // src/native/network/create-fetch.ts
1805
- function createFetch(createMethod, operateMethod, options) {
1806
- const promiseMap = /* @__PURE__ */ new Map();
1807
- const baseUrl = options?.baseUrl ?? `https://api.jolibox.com`;
1808
- const type = options?.type ?? "public";
1809
- const defaultHeaders = options?.defaultHeaders ?? {};
1810
- onNative("onRequestTaskStateChange", (res) => {
1811
- if (typeof res.requestTaskId !== "string") return;
1812
- const task = promiseMap.get(res.requestTaskId);
1813
- if (!task) return;
1814
- if (res.state === "success") {
1815
- const { requestTaskId, state, ...rest } = res;
1816
- task.resolve(rest);
1817
- promiseMap.delete(requestTaskId);
1818
- } else if (res.state === "fail") {
1819
- const { requestTaskId, state, ...rest } = res;
1820
- task.reject(rest);
1821
- promiseMap.delete(requestTaskId);
1822
- } else {
1823
- q.warn(`onRequestTaskStateChange unknown event`, res);
1824
- }
1825
- });
1826
- En.on("onLoginComplete", ({ isLogin, token }) => {
1827
- if (isLogin && token) {
1828
- defaultHeaders["X-JOLI-TOKEN"] = token;
1829
- }
1830
- });
1831
- const fetch = async (originUrl, options2 = {}) => {
1832
- const startTime = Date.now();
1833
- const url = processUrl(originUrl, { ...options2, baseUrl });
1834
- const {
1835
- method = "GET",
1836
- responseType = "text",
1837
- dataType = "json",
1838
- timeout,
1839
- enableCache = false,
1840
- appendHostCookie = true
1841
- } = options2;
1842
- const header = Object.assign({ "content-type": "application/json" }, defaultHeaders, options2.header);
1843
- const params = {
1844
- url,
1845
- method,
1846
- header,
1847
- enableCache,
1848
- responseType,
1849
- appendHostCookie
1850
- };
1851
- if (method == "POST" || method == "PUT") {
1852
- const data = normalizeData(options2.data, header["content-type"]);
1853
- params["data"] = data;
1854
- }
1855
- if (timeout) {
1856
- Object.assign(params, { timeout });
1857
- }
1858
- const {
1859
- data: { requestTaskId }
1860
- } = invokeNative(createMethod, params);
1861
- if (typeof requestTaskId !== "string") {
1862
- throw createAPIError({
1863
- code: -1,
1864
- msg: "requestTaskId is not a string"
1865
- });
1866
- }
1867
- const report = (state, response) => {
1868
- reportNetworkAPI("request", url, {
1869
- state,
1870
- startTime,
1871
- endTime: Date.now(),
1872
- params,
1873
- response,
1874
- requestId: requestTaskId,
1875
- requestFrom: type == "public" ? "public" /* PUBLIC */ : "inner" /* INNER */
1876
- });
1877
- };
1878
- const { resolve, reject, promise } = new L();
1879
- promiseMap.set(requestTaskId, { resolve, reject });
1880
- try {
1881
- const res = await promise;
1882
- report("success", res);
1883
- let { data } = res;
1884
- if (dataType === "json" && typeof data === "string") {
1885
- data = parseJSON(data);
1886
- }
1887
- return {
1888
- url,
1889
- timeout,
1890
- method,
1891
- response: { ...res, data }
1892
- };
1893
- } catch (err) {
1894
- const error = err;
1895
- if (ie(error)) {
1896
- const { errMsg, prefetchDetail, isPrefetch, errNo } = error;
1897
- if (b(errMsg)) {
1898
- report("fail", {
1899
- errMsg,
1900
- isPrefetch,
1901
- prefetchDetail
1902
- });
1903
- reportError(createAPIError({ code: -1, msg: errMsg }, { errNo, errMsg }));
1904
- }
1905
- }
1906
- throw err;
1907
- }
1908
- };
1909
- return fetch;
1910
- }
1911
- function parseJSON(data) {
1912
- try {
1913
- return JSON.parse(data.trim());
1914
- } catch {
1915
- return data;
1916
- }
1917
- }
1918
- function normalizeData(data, contentType = "application/json") {
1919
- const type = contentType.toLowerCase();
1920
- if (data === void 0) {
1921
- return "";
1922
- }
1923
- if (typeof data === "string" || data instanceof ArrayBuffer) {
1924
- return data;
1925
- }
1926
- if (type.includes("application/x-www-form-urlencoded")) {
1927
- return JSON.stringify(data);
1928
- }
1929
- if (type.includes("application/json")) {
1930
- return JSON.stringify(data);
1931
- }
1932
- if (typeof data === "object") {
1933
- return JSON.stringify(data);
1934
- }
1935
- return String(data);
1936
- }
1937
- var processUrl;
1938
- var init_create_fetch = __esm({
1939
- "src/native/network/create-fetch.ts"() {
1940
- "use strict";
1941
- init_index_es();
1942
- init_report4();
1943
- init_types3();
1944
- init_bridge();
1945
- init_report();
1946
- init_errors();
1947
- processUrl = (url, options) => {
1948
- if (/^https?:\/\//.test(url)) {
1949
- return url;
1950
- }
1951
- const query = options?.query;
1952
- const searchParams = new URLSearchParams(query);
1953
- const search = searchParams.toString();
1954
- return options?.baseUrl ? `${options.baseUrl}${url}${search ? `?${search}` : ""}` : `${url}${search ? `?${search}` : ""}`;
1955
- };
1956
- }
1957
- });
1958
-
1959
- // src/native/network/index.ts
1960
- var innerFetch;
1961
- var init_network = __esm({
1962
- "src/native/network/index.ts"() {
1963
- "use strict";
1964
- init_xua();
1965
- init_create_fetch();
1966
- init_context();
1967
- innerFetch = createFetch("createRequestTaskSync", "operateRequestTaskSync", {
1968
- type: "inner",
1969
- baseUrl: context.testMode ? "https://stg-api.jolibox.com" : "https://api.jolibox.com",
1970
- defaultHeaders: {
1971
- "x-user-agent": xUserAgent(),
1972
- "X-JOLI-TOKEN": context.hostUserInfo?.token ?? ""
1973
- }
1974
- });
1975
- }
1976
- });
1977
-
1978
- // src/native/report/task-tracker.ts
1979
- var NativeTaskTracker;
1980
- var init_task_tracker = __esm({
1981
- "src/native/report/task-tracker.ts"() {
1982
- "use strict";
1983
- init_context();
1984
- init_task_track();
1985
- init_network();
1986
- init_bridge();
1987
- NativeTaskTracker = class extends TaskTracker {
1988
- constructor(track2, eventEmitter, interval) {
1989
- super(eventEmitter, interval);
1990
- this.gameId = context.mpId;
1991
- this.sessionId = context.sessionId;
1992
- this.track = track2;
1993
- }
1994
- async reporter(point) {
1995
- const { event, params } = point;
1996
- const reportTasks = [];
1997
- reportTasks.push(
1998
- innerFetch(`/api/base/app-event`, {
1999
- method: "POST",
2000
- data: {
2001
- eventType: event,
2002
- gameInfo: {
2003
- gameId: this.gameId,
2004
- sessionId: this.sessionId,
2005
- ...params
2006
- }
2007
- }
2008
- })
2009
- );
2010
- await Promise.all(reportTasks);
2011
- }
2012
- async reportToNative(point) {
2013
- const { event, params } = point;
2014
- await applyNative("userTrackAsync", {
2015
- event,
2016
- params: {
2017
- ...params
2018
- },
2019
- gameId: this.gameId
2020
- });
2021
- }
2022
- tracker(event, info = null) {
2023
- this.track(event, info);
2024
- }
2025
- };
2026
- }
2027
- });
2028
-
2029
- // src/native/report/index.ts
2030
- var reportNative, track, trackPerformance, commands, nativeTaskEmitter, taskTracker;
2031
- var init_report5 = __esm({
2032
- "src/native/report/index.ts"() {
2033
- "use strict";
2034
- init_errors2();
2035
- init_index_es();
2036
- init_types2();
2037
- init_report3();
2038
- init_context();
2039
- init_task_tracker();
2040
- init_bridge();
2041
- reportNative = (event, data, webviewId) => {
2042
- const _data = data;
2043
- const originExtra = ie(_data.extra) ? _data.extra : b(_data.extra) ? JSON.parse(_data.extra) : {};
2044
- const extra = {
2045
- ...originExtra,
2046
- mp_id: _data.mp_id ?? "",
2047
- mp_version: _data.mp_version ?? ""
2048
- };
2049
- invokeNative("trackAsync", {
2050
- event,
2051
- data: extra,
2052
- webviewId
2053
- });
2054
- };
2055
- ({ track, trackPerformance } = createTracks(reportNative, {
2056
- type: "app-sdk" /* AppSDK */,
2057
- platform: "native",
2058
- jssdk_version: context.sdkInfo?.jssdkVersion ?? "1.0.0",
2059
- mp_id: context.mpId,
2060
- mp_version: context.mpVersion
2061
- }));
2062
- commands = Vn();
2063
- commands.registerCommand("ReportSDK.traceSystemTimeline", ({ event, duration }) => {
2064
- trackPerformance(event, duration);
2065
- });
2066
- commands.registerCommand("ReportSDK.traceSystem", ({ event, info }) => {
2067
- track(event, info);
2068
- });
2069
- nativeTaskEmitter = new _();
2070
- taskTracker = new NativeTaskTracker(track, nativeTaskEmitter);
2071
- }
2072
- });
2073
-
2074
- // src/common/can-i-use.ts
2075
- function registerCanIUseFactory(platform2) {
2076
- let configMap = Be.config[platform2];
2077
- if (!configMap) {
2078
- configMap = {};
2079
- Be.config[platform2] = configMap;
2080
- }
2081
- return (name, config2) => {
2082
- if (configMap[name]) {
2083
- q.warn(`[can i use] ${name} already registered`);
2084
- return;
2085
- }
2086
- configMap[name] = {
2087
- ...config2
2088
- };
2089
- };
2090
- }
2091
- var init_can_i_use = __esm({
2092
- "src/common/can-i-use.ts"() {
2093
- "use strict";
2094
- init_index_es();
2095
- }
2096
- });
2097
-
2098
- // src/common/api-factory/validator/validate.ts
2099
- function setCollect(flag) {
2100
- collectError = flag;
2101
- }
2102
- function deepClone(obj) {
2103
- if (obj === null || typeof obj !== "object") {
2104
- return obj;
2105
- }
2106
- if (Array.isArray(obj)) {
2107
- return obj.map((item) => deepClone(item));
2108
- }
2109
- return Object.keys(obj).reduce((acc, key) => {
2110
- acc[key] = deepClone(obj[key]);
2111
- return acc;
2112
- }, {});
2113
- }
2114
- function isNumber(x2) {
2115
- return typeof x2 === "number";
2116
- }
2117
- function echo(x2) {
2118
- const s = getType2(x2);
2119
- switch (s) {
2120
- case "string":
2121
- return `"${x2}"`;
2122
- case "number":
2123
- case "boolean":
2124
- case "null":
2125
- case "undefined":
2126
- return String(x2);
2127
- default:
2128
- return `a(n) ${s}`;
2129
- }
2130
- }
2131
- function getType2(x2) {
2132
- if (typeof x2 === "function") return "function";
2133
- const type = Object.prototype.toString.call(x2).slice(8).slice(0, -1);
2134
- return type.toLowerCase();
2135
- }
2136
- var collectError, Validator, $number, $boolean, $string, $symbol, $any, $undefined, $null, $function, $enum, $array, $record, $object, $literal, $or, $tuple, $arraybuffer, $typedarray;
2137
- var init_validate = __esm({
2138
- "src/common/api-factory/validator/validate.ts"() {
2139
- "use strict";
2140
- collectError = false;
2141
- Validator = class {
2142
- constructor() {
2143
- this.errors = [];
2144
- this.hasFallback = false;
2145
- this.hasDefault = false;
2146
- this._optional = false;
2147
- }
2148
- fail(options) {
2149
- if (collectError) {
2150
- if (typeof options === "string") {
2151
- this.errors.push(options);
2152
- } else {
2153
- let message = `${this.path} should be ${options.expect}`;
2154
- if (this._optional && options.expect !== "undefined") {
2155
- message += " or undefined, ";
2156
- } else {
2157
- message += ", ";
2158
- }
2159
- message += `but got ${echo(options.actual)}`;
2160
- this.errors.push(message);
2161
- }
2162
- }
2163
- return false;
2164
- }
2165
- fallback(v2) {
2166
- this.hasFallback = true;
2167
- this._fallback = v2;
2168
- return this;
2169
- }
2170
- get fallbackValue() {
2171
- return deepClone(this._fallback);
2172
- }
2173
- default(v2) {
2174
- this.hasDefault = true;
2175
- this._default = v2;
2176
- return this;
2177
- }
2178
- get defaultValue() {
2179
- if (typeof this._default === "function") {
2180
- return this._default;
2181
- }
2182
- return deepClone(this._default);
2183
- }
2184
- optional() {
2185
- this._optional = true;
2186
- return this;
2187
- }
2188
- };
2189
- $number = class extends Validator {
2190
- validate(x2) {
2191
- if (this._optional && x2 === void 0) return true;
2192
- if (!isNumber(x2)) {
2193
- return this.fail({ expect: "number", actual: x2 });
2194
- }
2195
- if (isNumber(this._min) && x2 < this._min) {
2196
- return this.fail(`the value of ${this.path} should be greater than or equal to ${this._min}`);
2197
- }
2198
- if (isNumber(this._max) && x2 > this._max) {
2199
- return this.fail(`the value of ${this.path} should be less than or equal to ${this._max}`);
2200
- }
2201
- if (isNumber(this._greater) && x2 <= this._greater) {
2202
- return this.fail(`the value of ${this.path} should be greater than ${this._greater}`);
2203
- }
2204
- if (this._isInt && x2 !== Math.floor(x2)) {
2205
- return this.fail(`the value of ${this.path} should be integer but got ${x2}`);
2206
- }
2207
- return true;
2208
- }
2209
- min(v2) {
2210
- this._min = v2;
2211
- return this;
2212
- }
2213
- max(v2) {
2214
- this._max = v2;
2215
- return this;
2216
- }
2217
- isInt(v2) {
2218
- this._isInt = v2;
2219
- return this;
2220
- }
2221
- greater(v2) {
2222
- this._greater = v2;
2223
- return this;
2224
- }
2225
- };
2226
- $boolean = class extends Validator {
2227
- validate(x2) {
2228
- if (this._optional && x2 === void 0) return true;
2229
- if (typeof x2 !== "boolean") {
2230
- return this.fail({ expect: "boolean", actual: x2 });
2231
- }
2232
- return true;
2233
- }
2234
- };
2235
- $string = class extends Validator {
2236
- validate(x2) {
2237
- if (this._optional && x2 === void 0) return true;
2238
- if (typeof x2 !== "string") {
2239
- return this.fail({ expect: "string", actual: x2 });
2240
- }
2241
- if (isNumber(this._maxLength) && x2.length > this._maxLength) {
2242
- return this.fail(`the length of ${this.path} should be less than or equal to ${this._maxLength}`);
2243
- }
2244
- if (isNumber(this._minLength) && x2.length < this._minLength) {
2245
- return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minLength}`);
2246
- }
2247
- if (typeof this._pattern === "string") {
2248
- const reg = new RegExp(this._pattern);
2249
- if (!reg.test(x2)) {
2250
- return this.fail(`${this.path} should match pattern "${this._pattern}"`);
2251
- }
2252
- } else if (this._pattern) {
2253
- if (!this._pattern.test(x2)) {
2254
- return this.fail(`${this.path} should match pattern "${this._pattern.toString()}"`);
2255
- }
2256
- }
2257
- return true;
2258
- }
2259
- minLength(len) {
2260
- this._minLength = len;
2261
- return this;
2262
- }
2263
- maxLength(len) {
2264
- this._maxLength = len;
2265
- return this;
2266
- }
2267
- pattern(patten) {
2268
- this._pattern = patten;
2269
- return this;
2270
- }
2271
- };
2272
- $symbol = class extends Validator {
2273
- validate(x2) {
2274
- if (this._optional && x2 === void 0) return true;
2275
- if (typeof x2 !== "symbol") {
2276
- return this.fail({ expect: "symbol", actual: x2 });
2277
- }
2278
- return true;
2279
- }
2280
- };
2281
- $any = class extends Validator {
2282
- // eslint-disable-next-line class-methods-use-this
2283
- validate(x2) {
2284
- return true;
2285
- }
2286
- };
2287
- $undefined = class extends Validator {
2288
- validate(x2) {
2289
- if (x2 !== void 0) {
2290
- return this.fail({ expect: "undefined", actual: x2 });
2291
- }
2292
- return true;
2293
- }
2294
- };
2295
- $null = class extends Validator {
2296
- validate(x2) {
2297
- if (this._optional && x2 === void 0) return true;
2298
- if (x2 !== null) {
2299
- return this.fail({ expect: "null", actual: x2 });
2300
- }
2301
- return true;
2302
- }
2303
- };
2304
- $function = class extends Validator {
2305
- validate(x2) {
2306
- if (this._optional && x2 === void 0) return true;
2307
- if (typeof x2 !== "function") {
2308
- return this.fail({ expect: "function", actual: x2 });
2309
- }
2310
- return true;
2311
- }
2312
- };
2313
- $enum = class extends Validator {
2314
- constructor(..._items) {
2315
- super();
2316
- this._items = _items;
2317
- }
2318
- validate(x2) {
2319
- if (this._optional && x2 === void 0) return true;
2320
- if (!this._items.includes(x2)) {
2321
- const enums = this._items.map((i) => JSON.stringify(i)).join(", ");
2322
- return this.fail(`expect ${this.path} to be one of ${enums}, but got ${echo(x2)}`);
2323
- }
2324
- return true;
2325
- }
2326
- };
2327
- $array = class extends Validator {
2328
- constructor(_item) {
2329
- super();
2330
- this._item = _item;
2331
- }
2332
- validate(x2) {
2333
- if (this._optional && x2 === void 0) return true;
2334
- if (!Array.isArray(x2)) {
2335
- return this.fail({ expect: "array", actual: x2 });
2336
- }
2337
- if (isNumber(this._minItems) && x2.length < this._minItems) {
2338
- return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minItems}`);
2339
- }
2340
- if (isNumber(this._maxItems) && x2.length > this._maxItems) {
2341
- return this.fail(`the length of ${this.path} should be less than or equal to ${this._maxItems}`);
2342
- }
2343
- if (isNumber(this._length) && x2.length !== this._length) {
2344
- return this.fail(`the length of ${this.path} should be equal to ${this._length}`);
2345
- }
2346
- const validator = this._item;
2347
- if (!validator) return true;
2348
- let result = true;
2349
- x2.forEach((item, index) => {
2350
- validator.path = `${this.path}[${index}]`;
2351
- validator.errors = this.errors;
2352
- if (item === void 0 && validator.hasDefault) {
2353
- x2[index] = validator.defaultValue;
2354
- return;
2355
- }
2356
- if (!validator.validate(item)) {
2357
- if (validator.hasFallback) {
2358
- x2[index] = validator.fallbackValue;
2359
- } else {
2360
- result = false;
2361
- }
2362
- }
2363
- });
2364
- if (this._uniqueItems) {
2365
- const map = /* @__PURE__ */ new Map();
2366
- for (const i in x2) {
2367
- if (map.has(x2[i])) {
2368
- result = this.fail(
2369
- `${this.path} should NOT have duplicate items (${this.path}[${map.get(x2[i])}] and ${this.path}[${i}] are identical)`
2370
- );
2371
- } else {
2372
- map.set(x2[i], i);
2373
- }
2374
- }
2375
- }
2376
- return result;
2377
- }
2378
- minItems(len) {
2379
- this._minItems = len;
2380
- return this;
2381
- }
2382
- maxItems(len) {
2383
- this._maxItems = len;
2384
- return this;
2385
- }
2386
- uniqueItems() {
2387
- this._uniqueItems = true;
2388
- return this;
2389
- }
2390
- length(len) {
2391
- this._length = len;
2392
- return this;
2393
- }
2394
- };
2395
- $record = class extends Validator {
2396
- constructor(_value) {
2397
- super();
2398
- this._value = _value;
2399
- }
2400
- validate(x2) {
2401
- if (this._optional && x2 === void 0) return true;
2402
- const type = getType2(x2);
2403
- if (type !== "object") {
2404
- return this.fail({ expect: "object", actual: x2 });
2405
- }
2406
- const values = x2;
2407
- const validator = this._value;
2408
- validator.errors = this.errors;
2409
- let result = true;
2410
- for (const k2 in values) {
2411
- const value = values[k2];
2412
- if (/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(k2)) {
2413
- validator.path = `${this.path}.${k2}`;
2414
- } else {
2415
- validator.path = `${this.path}["${k2}"]`;
2416
- }
2417
- if (value === void 0 && validator._optional) {
2418
- continue;
2419
- }
2420
- if (value === void 0 && validator.hasDefault) {
2421
- values[k2] = validator.defaultValue;
2422
- continue;
2423
- }
2424
- if (!validator.validate(value)) {
2425
- if (validator.hasFallback) {
2426
- values[k2] = validator.fallbackValue;
2427
- } else {
2428
- result = false;
2429
- }
2430
- }
2431
- }
2432
- return result;
2433
- }
2434
- };
2435
- $object = class extends Validator {
2436
- constructor(_object = {}) {
2437
- super();
2438
- this._object = _object;
2439
- }
2440
- validate(x2) {
2441
- if (this._optional && x2 === void 0) return true;
2442
- if (getType2(x2) !== "object") {
2443
- return this.fail({ expect: "object", actual: x2 });
2444
- }
2445
- const values = x2;
2446
- let result = true;
2447
- for (const k2 in this._object) {
2448
- const value = values[k2];
2449
- const validator = this._object[k2];
2450
- validator.errors = this.errors;
2451
- if (/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(k2)) {
2452
- validator.path = `${this.path}.${k2}`;
2453
- } else {
2454
- validator.path = `${this.path}["${k2}"]`;
2455
- }
2456
- if (validator._optional && value === void 0) {
2457
- continue;
2458
- }
2459
- if (value === void 0 && validator.hasDefault) {
2460
- values[k2] = validator.defaultValue;
2461
- continue;
2462
- }
2463
- if (!validator.validate(value)) {
2464
- if (validator.hasFallback) {
2465
- values[k2] = validator.fallbackValue;
2466
- } else {
2467
- result = false;
2468
- }
2469
- }
2470
- }
2471
- return result;
2472
- }
2473
- };
2474
- $literal = class extends Validator {
2475
- constructor(value) {
2476
- super();
2477
- this.value = value;
2478
- }
2479
- validate(x2) {
2480
- if (x2 === void 0 && this._optional) return true;
2481
- if (x2 !== this.value) {
2482
- return this.fail({ expect: echo(this.value), actual: x2 });
2483
- }
2484
- return true;
2485
- }
2486
- };
2487
- $or = class extends Validator {
2488
- constructor(..._items) {
2489
- super();
2490
- this._items = _items;
2491
- }
2492
- validate(x2) {
2493
- if (x2 === void 0 && this._optional) return true;
2494
- const orErrors = [];
2495
- let result = false;
2496
- const itemLength = this._items.length;
2497
- for (let i = 0; i < itemLength; i++) {
2498
- const validator = this._items[i];
2499
- validator.errors = [];
2500
- validator.path = this.path;
2501
- if (!validator.validate(x2)) {
2502
- orErrors.push(validator.errors.join("; "));
2503
- } else if (!result) {
2504
- result = true;
2505
- break;
2506
- }
2507
- }
2508
- if (!result) {
2509
- const grouped = orErrors.join("\nor ");
2510
- this.errors.push(grouped);
2511
- }
2512
- return result;
2513
- }
2514
- };
2515
- $tuple = class extends Validator {
2516
- constructor(..._items) {
2517
- super();
2518
- this._items = _items;
2519
- let optionalCount = 0;
2520
- let i = _items.length - 1;
2521
- for (; i >= 0; i--) {
2522
- const validator = _items[i];
2523
- if (validator._optional || validator.hasDefault) {
2524
- optionalCount += 1;
2525
- } else {
2526
- break;
2527
- }
2528
- }
2529
- this._minItems = _items.length - optionalCount;
2530
- }
2531
- validate(x2) {
2532
- if (x2 === void 0 && this._optional) return true;
2533
- if (!Array.isArray(x2)) {
2534
- return this.fail({ expect: "array", actual: x2 });
2535
- }
2536
- if (x2.length < this._minItems) {
2537
- return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minItems}`);
2538
- }
2539
- let result = true;
2540
- this._items.forEach((validator, index) => {
2541
- validator.path = `${this.path}[${index}]`;
2542
- validator.errors = this.errors;
2543
- const item = x2[index];
2544
- if (item === void 0 && validator.hasDefault) {
2545
- x2[index] = validator.defaultValue;
2546
- return;
2547
- }
2548
- if (!validator.validate(x2[index])) {
2549
- if (validator.hasFallback) {
2550
- x2[index] = validator._fallback;
2551
- } else {
2552
- result = false;
2553
- }
2554
- }
2555
- });
2556
- return result;
2557
- }
2558
- };
2559
- $arraybuffer = class extends Validator {
2560
- validate(x2) {
2561
- if (x2 === void 0 && this._optional) return true;
2562
- if (x2 instanceof ArrayBuffer) {
2563
- return true;
2564
- }
2565
- return this.fail({ expect: "arraybuffer", actual: x2 });
2566
- }
2567
- };
2568
- $typedarray = class extends Validator {
2569
- constructor(ctor) {
2570
- super();
2571
- this._ctor = ctor;
2572
- }
2573
- validate(x2) {
2574
- if (x2 === void 0 && this._optional) return true;
2575
- if (x2 instanceof this._ctor) {
2576
- return true;
2577
- }
2578
- return this.fail({ expect: `typedarray of ${this._ctor.name}`, actual: x2 });
2579
- }
2580
- };
2581
- }
2582
- });
2583
-
2584
- // src/common/api-factory/validator/index.ts
2585
- function typeAsserts(validator, x2, path = "param") {
2586
- validator.errors = [];
2587
- validator.path = path;
2588
- setCollect(true);
2589
- if (!validator.validate(x2)) {
2590
- const messages = validator.errors.join("\n");
2591
- validator.errors.length = 0;
2592
- setCollect(false);
2593
- throw new TypeError(messages);
2594
- }
2595
- }
2596
- var t;
2597
- var init_validator = __esm({
2598
- "src/common/api-factory/validator/index.ts"() {
2599
- "use strict";
2600
- init_validate();
2601
- init_validate();
2602
- t = {
2603
- object(schemas) {
2604
- return new $object(schemas);
2605
- },
2606
- array(schema) {
2607
- return new $array(schema);
2608
- },
2609
- tuple(...schemas) {
2610
- return new $tuple(...schemas);
2611
- },
2612
- literal(v2) {
2613
- return new $literal(v2);
2614
- },
2615
- or(...schemas) {
2616
- return new $or(...schemas);
2617
- },
2618
- symbol() {
2619
- return new $symbol();
2620
- },
2621
- record(schema) {
2622
- return new $record(schema);
2623
- },
2624
- function() {
2625
- return new $function();
2626
- },
2627
- boolean() {
2628
- return new $boolean();
2629
- },
2630
- string() {
2631
- return new $string();
2632
- },
2633
- number() {
2634
- return new $number();
2635
- },
2636
- undefined() {
2637
- return new $undefined();
2638
- },
2639
- null() {
2640
- return new $null();
2641
- },
2642
- unknown() {
2643
- return new $any();
2644
- },
2645
- any() {
2646
- return new $any();
2647
- },
2648
- as() {
2649
- return new $any();
2650
- },
2651
- arraybuffer() {
2652
- return new $arraybuffer();
2653
- },
2654
- enum(...values) {
2655
- return new $enum(...values);
2656
- },
2657
- typedarray(ctor) {
2658
- return new $typedarray(ctor);
2659
- }
2660
- };
2661
- }
2662
- });
2663
-
2664
- // src/common/api-factory/index.ts
2665
- var traceId, createAPIFactory;
2666
- var init_api_factory = __esm({
2667
- "src/common/api-factory/index.ts"() {
2668
- "use strict";
2669
- init_index_es();
2670
- init_report();
2671
- init_validator();
2672
- init_errors();
2673
- traceId = 1;
2674
- createAPIFactory = (track2) => {
2675
- function createSyncAPI2(method, config2) {
2676
- return (...inputs) => {
2677
- const startTime = Date.now();
2678
- const reportExtra = { method, trace_id: traceId };
2679
- traceId += 1;
2680
- let status = "SUCCESS";
2681
- let errMsg = `${method}:ok`;
2682
- let errNo = 0;
2683
- try {
2684
- if (config2.paramsSchema) {
2685
- try {
2686
- typeAsserts(config2.paramsSchema, inputs, "params");
2687
- } catch (err) {
2688
- const error = err;
2689
- throw createUserAPIError(`${method}:fail ${error.message}`);
2690
- }
2691
- }
2692
- const res = config2.implement(...inputs);
2693
- let data = res;
2694
- let message = `${method}:ok`;
2695
- if (res && "code" in res) {
2696
- const {
2697
- code,
2698
- data: originData,
2699
- message: originMessage
2700
- } = res;
2701
- status = code;
2702
- data = originData;
2703
- message = originMessage;
2704
- }
2705
- return {
2706
- code: status,
2707
- message,
2708
- data
2709
- };
2710
- } catch (error) {
2711
- const _error = error;
2712
- errNo = _error.code ?? _error.errNo ?? 2e3;
2713
- status = "FAILURE";
2714
- const msg = _error.message ?? _error.errMsg ?? `${error}`;
2715
- errMsg = `${method}:${status} ${msg.replace(/^\S+:(fail|cancel)\s?/, "")}`;
2716
- reportError(new Q(errMsg, errNo));
2717
- return {
2718
- code: status,
2719
- message: errMsg
2720
- };
2721
- } finally {
2722
- const duration = Date.now() - startTime;
2723
- track2("apiInvoked", { ...reportExtra, duration, status });
2724
- }
2725
- };
2726
- }
2727
- function createAPI2(method, config2) {
2728
- return async (..._inputs) => {
2729
- const inputs = Ce(_inputs) ? _inputs : [_inputs];
2730
- const startTime = Date.now();
2731
- const reportExtra = { method, trace_id: traceId };
2732
- traceId += 1;
2733
- let message = `${method}:ok`;
2734
- let status = "SUCCESS";
2735
- const res = {
2736
- code: status,
2737
- message
2738
- };
2739
- try {
2740
- if (config2.paramsSchema) {
2741
- try {
2742
- typeAsserts(config2.paramsSchema, inputs, "params");
2743
- } catch (error) {
2744
- throw createUserAPIError(error.message);
2745
- }
2746
- }
2747
- const data = await config2.implement(...inputs);
2748
- let ret = data;
2749
- if (ret && "code" in ret) {
2750
- const {
2751
- code,
2752
- data: originData,
2753
- message: originMessage
2754
- } = ret;
2755
- status = code;
2756
- message = originMessage;
2757
- ret = originData;
2758
- }
2759
- Object.assign(res, {
2760
- code: status,
2761
- message,
2762
- data: ret
2763
- });
2764
- return res;
2765
- } catch (error) {
2766
- const _error = error;
2767
- const errNo = _error.code ?? _error.errNo ?? 2e3;
2768
- status = "FAILURE";
2769
- const msg = _error.message ?? _error.errMsg ?? `${error}`;
2770
- const errMsg = `${method}:${status} ${msg.replace(/^\S+:(fail|cancel)\s?/, "")}`;
2771
- Object.assign(res, {
2772
- code: status,
2773
- message: errMsg
2774
- });
2775
- reportError(new Q(errMsg, errNo));
2776
- return res;
2777
- } finally {
2778
- const duration = Date.now() - startTime;
2779
- track2("apiInvoked", { ...reportExtra, duration, status });
2780
- }
2781
- };
2782
- }
2783
- return { createAPI: createAPI2, createSyncAPI: createSyncAPI2 };
2784
- };
2785
- }
2786
- });
2787
-
2788
- // src/native/api/base.ts
2789
- var createAPI, createSyncAPI, registerCanIUse;
2790
- var init_base = __esm({
2791
- "src/native/api/base.ts"() {
2792
- "use strict";
2793
- init_can_i_use();
2794
- init_report5();
2795
- init_api_factory();
2796
- init_validator();
2797
- ({ createAPI, createSyncAPI } = createAPIFactory(track));
2798
- registerCanIUse = registerCanIUseFactory("native");
2799
- }
2800
- });
2801
-
2802
- // src/native/api/lifecycle.ts
2803
- var require_lifecycle = __commonJS({
2804
- "src/native/api/lifecycle.ts"(exports) {
2805
- "use strict";
2806
- init_index_es();
2807
- init_base();
2808
- init_report();
2809
- init_bridge();
2810
- init_report5();
2811
- var EXIT_GAME = "exitGame";
2812
- var ON_READY = "onReady";
2813
- var ON_SHOW = "onJoliboxShow";
2814
- var ON_HIDE = "onJoliboxHide";
2815
- var commands9 = Vn();
2816
- var safeCallbackWrapper2 = He(reportError);
2817
- var exitGame = createAPI(EXIT_GAME, {
2818
- paramsSchema: t.tuple(t.function()),
2819
- implement: async (onBeforeExit) => {
2820
- const safeCallback = safeCallbackWrapper2(onBeforeExit);
2821
- safeCallback.call(exports);
2822
- await applyNative("exitAppAsync");
2823
- }
2824
- });
2825
- var onShow = createSyncAPI(ON_SHOW, {
2826
- paramsSchema: t.tuple(t.function()),
2827
- implement(callback) {
2828
- const safeCallback = safeCallbackWrapper2(callback);
2829
- onNative("onJoliboxEnterForeground", () => {
2830
- safeCallback.call(this);
2831
- nativeTaskEmitter.emit("visible", true);
2832
- });
2833
- }
2834
- });
2835
- var onHide = createSyncAPI(ON_HIDE, {
2836
- paramsSchema: t.tuple(t.function()),
2837
- implement(callback) {
2838
- const safeCallback = safeCallbackWrapper2(callback);
2839
- onNative("onJoliboxEnterBackground", () => {
2840
- safeCallback.call(this);
2841
- nativeTaskEmitter.emit("visible", false);
2842
- });
2843
- }
2844
- });
2845
- var onReadyHandler = createSyncAPI(ON_READY, {
2846
- paramsSchema: t.tuple(t.function()),
2847
- implement(callback) {
2848
- const safeCallback = safeCallbackWrapper2(callback);
2849
- En.on("LifecycleEvent.onReady", (info) => {
2850
- safeCallback(info);
2851
- });
2852
- }
2853
- });
2854
- commands9.registerCommand("LifecycleSDK.exit", exitGame);
2855
- commands9.registerCommand("LifecycleSDK.onReady", onReadyHandler);
2856
- commands9.registerCommand("LifecycleSDK.onJoliboxShow", onShow);
2857
- commands9.registerCommand("LifecycleSDK.onJoliboxHide", onHide);
2858
- registerCanIUse("lifeCycle.exit", {
2859
- version: "1.0.0"
2860
- // mock
2861
- });
2862
- registerCanIUse("lifeCycle.onReady", {
2863
- version: "1.0.0"
2864
- // mock
2865
- });
2866
- registerCanIUse("lifeCycle.onJoliboxShow", {
2867
- version: "1.0.0"
2868
- // mock
2869
- });
2870
- registerCanIUse("lifeCycle.onJoliboxHide", {
2871
- version: "1.0.0"
2872
- // mock
2873
- });
2874
- }
2875
- });
2876
-
2877
- // src/native/bootstrap/index.ts
2878
- init_bridge();
2879
- init_js_core();
2880
- init_context();
2881
- init_index_es();
2882
- init_report5();
2883
- RuntimeLoader.onReady(() => {
2884
- });
2885
- RuntimeLoader.doExit(() => {
2886
- track("onBeforeExit", {
2887
- timestamp: Date.now()
2888
- });
2889
- taskTracker.close(Date.now() - start_timestamp);
2890
- return false;
2891
- });
2892
- function addWebviewReadyListener() {
2893
- En.on("onDocumentReady", () => {
2894
- joliboxJSCore?.onDocumentReady(window.location.href);
2895
- track("onDocumentReady", {
2896
- start_timestamp,
2897
- timestamp: Date.now()
2898
- });
2899
- });
2900
- }
2901
- function addGameServiceReadyListener() {
2902
- onNative("onJoliboxServiceReady", ({ runtimeInfo, loadDuration }) => {
2903
- runtimeInfo && context.onEnvConfigChanged({ hostUserInfo: runtimeInfo });
2904
- En.emit("LifecycleEvent.onReady", {
2905
- ...context.hostUserInfo ? context.hostUserInfo : { isLogin: false }
2906
- });
2907
- track("joliboxServiceReady", {
2908
- start_timestamp,
2909
- timestamp: Date.now()
2910
- });
2911
- taskTracker.start(loadDuration);
2912
- });
2913
- onNative("onBeforeExit", ({ uuid }) => {
2914
- joliboxJSCore?.doExit(uuid);
2915
- });
2916
- }
2917
- var start_timestamp;
2918
- function config() {
2919
- start_timestamp = Date.now();
2920
- addGameServiceReadyListener();
2921
- addWebviewReadyListener();
2922
- }
2923
-
2924
- // src/native/api/get-system-info.ts
2925
- init_index_es();
2926
- init_base();
2927
- init_bridge();
2928
- var commands2 = Vn();
2929
- var API_ENV = "env";
2930
- var API_GET_SYSTEM_SYNC = "getSystemInfoSync";
2931
- var getSystemInfoSync = createSyncAPI(API_GET_SYSTEM_SYNC, {
2932
- implement: () => {
2933
- const res = invokeNative("envSync");
2934
- const { data } = res;
2935
- return {
2936
- system: data.deviceInfo.system,
2937
- platform: data.platform,
2938
- version: data.sdkInfo.jssdkVersion,
2939
- pixelRatio: data.deviceInfo.pixelRatio,
2940
- language: data.deviceInfo.lang
2941
- };
2942
- }
2943
- });
2944
- var getEnv = createSyncAPI(API_ENV, {
2945
- implement: () => {
2946
- const res = invokeNative("envSync");
2947
- return res?.data ?? void 0;
2948
- }
2949
- });
2950
- commands2.registerCommand("API.getSystemInfoSync", getSystemInfoSync);
2951
- commands2.registerCommand("API.env", getEnv);
2952
- registerCanIUse("env", {
2953
- version: "1.0.0"
2954
- });
2955
- registerCanIUse("getSystemInfoSync", {
2956
- version: "1.0.0"
2957
- });
2958
-
2959
- // src/native/api/index.ts
2960
- var import_lifecycle = __toESM(require_lifecycle());
2961
-
2962
- // src/native/api/request.ts
2963
- init_errors();
2964
- init_create_fetch();
2965
- init_base();
2966
-
2967
- // src/native/network/utils.ts
2968
- init_index_es();
2969
- function normalizeHeader(header) {
2970
- const normalized = {};
2971
- if (!ie(header)) {
2972
- return normalized;
2973
- }
2974
- for (const [_key, value] of Object.entries(header)) {
2975
- const key = _key.toLocaleLowerCase();
2976
- if (!value) {
2977
- normalized[key] = "";
2978
- } else if (typeof value === "object") {
2979
- normalized[key] = Object.prototype.toString.call(value);
2980
- } else {
2981
- normalized[key] = String(value);
2982
- }
2983
- }
2984
- return normalized;
2985
- }
2986
- function normalizeMethod(method = "GET") {
2987
- if (method === "") {
2988
- return "POST";
2989
- }
2990
- const _method = method.toUpperCase();
2991
- if (["GET", "OPTIONS", "HEAD", "POST", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH"].includes(_method)) {
2992
- return _method;
2993
- }
2994
- return "GET";
2995
- }
2996
- function normalizeTimeout(time, unlimited = false) {
2997
- if (!time) return void 0;
2998
- if (unlimited || time > 0 && time <= 6e4) return Math.ceil(time);
2999
- return 6e4;
3000
- }
3001
- function dirtyURL(url, method, data) {
3002
- if (["POST", "PUT", "PATCH"].includes(method)) return url;
3003
- if (!ie(data)) return url;
3004
- const [_url, search = ""] = url.split("?");
3005
- const query = JSON.stringify({
3006
- ...JSON.parse(search),
3007
- ...data
3008
- });
3009
- return `${_url}?${query}`;
3010
- }
3011
-
3012
- // src/native/api/request.ts
3013
- init_index_es();
3014
- init_report();
3015
- var LIMIT = 15;
3016
- var publicFetch = createFetch("createRequestTaskSync", "operateRequestTaskSync", {
3017
- type: "public"
3018
- });
3019
- var activeCount = 0;
3020
- var deferQueue = [];
3021
- var safeCallbackWrapper = He(reportError);
3022
- var remove = (array, predicate) => {
3023
- const removedElements = array.filter(predicate);
3024
- const remainingElements = array.filter((item) => !predicate(item));
3025
- array.length = 0;
3026
- array.push(...remainingElements);
3027
- return removedElements;
3028
- };
3029
- var request = (_params) => {
3030
- const deferred = new L();
3031
- let teardown = () => {
3032
- };
3033
- const _request = createAPI("request", {
3034
- paramsSchema: t.tuple(
3035
- t.object({
3036
- url: t.string(),
3037
- method: t.string(),
3038
- header: t.object(),
3039
- data: t.object().optional(),
3040
- query: t.object().optional(),
3041
- dataType: t.string().default("json"),
3042
- responseType: t.string().default("text"),
3043
- enableCache: t.boolean().default(false),
3044
- appendHostCookie: t.boolean().default(true),
3045
- timeout: t.number().default(3e4),
3046
- success: t.function(),
3047
- fail: t.function()
3048
- })
3049
- ),
3050
- implement(params) {
3051
- const action = async () => {
3052
- const failCallback = safeCallbackWrapper(params.fail);
3053
- try {
3054
- activeCount += 1;
3055
- if (deferred.state !== "pending") {
3056
- return;
3057
- }
3058
- const { data, dataType, responseType, enableCache, appendHostCookie } = params;
3059
- const header = normalizeHeader(params.header);
3060
- const method = normalizeMethod(params.method);
3061
- const timeout = normalizeTimeout(params.timeout);
3062
- const url = dirtyURL(params.url, method, data);
3063
- const successCallback = safeCallbackWrapper(params.success);
3064
- const _params2 = Object.assign({}, params, {
3065
- method,
3066
- header,
3067
- data: method === "GET" || method === "HEAD" ? void 0 : data,
3068
- // GET HEAD 请求不需要 data 参数
3069
- enableCache,
3070
- query: params.query ?? {},
3071
- dataType,
3072
- responseType,
3073
- appendHostCookie
3074
- });
3075
- if (timeout) _params2["timeout"] = timeout;
3076
- const task = publicFetch(url, _params2);
3077
- {
3078
- const { response } = await task;
3079
- const { code, data: data2, message } = response;
3080
- deferred.resolve({
3081
- code: code ?? "SUCCESS",
3082
- data: data2,
3083
- message: message ?? "request:ok"
3084
- });
3085
- successCallback({
3086
- code: "SUCCESS",
3087
- message: "request:ok",
3088
- data: data2
3089
- });
3090
- }
3091
- } catch (err) {
3092
- deferred.reject(err);
3093
- failCallback({
3094
- code: "FAILURE",
3095
- message: "httpRequst: failed"
3096
- });
3097
- } finally {
3098
- activeCount -= 1;
3099
- deferQueue.shift()?.();
3100
- }
3101
- };
3102
- if (activeCount >= LIMIT) {
3103
- teardown = () => {
3104
- remove(deferQueue, (i) => i === action);
3105
- };
3106
- deferQueue.push(action);
3107
- } else {
3108
- void action();
3109
- }
3110
- return deferred.promise;
3111
- }
3112
- });
3113
- _request(_params);
3114
- return {
3115
- /**
3116
- * 1. requesting...
3117
- * 2. not in deferred
3118
- */
3119
- abort() {
3120
- deferred.reject(createAPIError({ code: -1, msg: "request:fail abort" }));
3121
- teardown();
3122
- }
3123
- };
3124
- };
3125
- var commands3 = Vn();
3126
- commands3.registerCommand("HttpSDK.request", request);
3127
- registerCanIUse("request", {
3128
- version: "1.0.0"
3129
- });
3130
-
3131
- // src/native/api/storage.ts
3132
- init_base();
3133
- init_bridge();
3134
- init_index_es();
3135
- init_network();
3136
- init_context();
3137
- var commands4 = Vn();
3138
- var getStorage2 = createAPI("getLocalStorage", {
3139
- paramsSchema: t.tuple(t.string()),
3140
- async implement(key) {
3141
- const { response } = await innerFetch(`/api/games/user-storage/${context.mpId}`, {
3142
- method: "GET",
3143
- responseType: "json",
3144
- appendHostCookie: true,
3145
- query: {
3146
- key
3147
- }
3148
- });
3149
- const {
3150
- data: { code, message, data: originData }
3151
- } = await response;
3152
- if (code === "SUCCESS") {
3153
- return {
3154
- code,
3155
- message,
3156
- data: originData?.value
3157
- };
3158
- }
3159
- try {
3160
- const {
3161
- data: { data, dataType }
3162
- } = await applyNative("getLocalStorageAsync", { key });
3163
- const parsedData = parse(data, dataType);
3164
- return {
3165
- code,
3166
- message: `${message}. fallback to native`,
3167
- data: parsedData
3168
- };
3169
- } catch (error) {
3170
- return {
3171
- code: "INTERNAL_ERROR",
3172
- message: "[Jolibox SDK] get local storage failed",
3173
- data: null
3174
- };
3175
- }
3176
- }
3177
- });
3178
- commands4.registerCommand("StorageSDK.getItem", getStorage2);
3179
- registerCanIUse("storage.getItem", {
3180
- version: "1.0.0",
3181
- properties: {
3182
- key: "1.0.0",
3183
- value: "1.0.0"
3184
- }
3185
- });
3186
- var setStorage = createAPI("setStorage", {
3187
- paramsSchema: t.tuple(t.string(), t.or(t.string(), t.boolean(), t.number())),
3188
- async implement(key, value) {
3189
- const gameId = context.mpId;
3190
- const valueToStore = typeof value == "string" ? value : String(value);
3191
- const { response } = await innerFetch(`/api/games/user-storage/${gameId}`, {
3192
- method: "POST",
3193
- responseType: "json",
3194
- appendHostCookie: true,
3195
- data: {
3196
- key,
3197
- value: valueToStore
3198
- }
3199
- });
3200
- const {
3201
- data: { code, message }
3202
- } = response;
3203
- const dataType = getType3(value);
3204
- const data = stringify(value, dataType);
3205
- await applyNative("setLocalStorageAsync", {
3206
- key,
3207
- data,
3208
- dataType
3209
- });
3210
- if (code == "SUCCESS") {
3211
- return {
3212
- code,
3213
- message
3214
- };
3215
- } else {
3216
- return {
3217
- code,
3218
- message: `${message}. fallback to native`
3219
- };
3220
- }
3221
- }
3222
- });
3223
- commands4.registerCommand("StorageSDK.setItem", setStorage);
3224
- registerCanIUse("storage.setItem", {
3225
- version: "1.0.0",
3226
- properties: {
3227
- key: "1.0.0",
3228
- value: "1.0.0"
3229
- }
3230
- });
3231
- var removeStorage = createAPI("removeStorage", {
3232
- paramsSchema: t.tuple(t.string()),
3233
- async implement(key) {
3234
- const gameId = context.mpId;
3235
- const { response } = await innerFetch(`/api/games/user-storage/${gameId}/remove`, {
3236
- method: "POST",
3237
- responseType: "json",
3238
- appendHostCookie: true,
3239
- data: {
3240
- key
3241
- }
3242
- });
3243
- const {
3244
- data: { code, message }
3245
- } = response;
3246
- await applyNative("removeLocalStorageAsync", { key });
3247
- if (code === "SUCCESS") {
3248
- return {
3249
- code,
3250
- message
3251
- };
3252
- } else {
3253
- return {
3254
- code,
3255
- message: "[Jolibox SDK] remove item succ"
3256
- };
3257
- }
3258
- }
3259
- });
3260
- commands4.registerCommand("StorageSDK.removeItem", removeStorage);
3261
- registerCanIUse("storage.removeItem", {
3262
- version: "1.0.0",
3263
- properties: {
3264
- key: "1.0.0"
3265
- }
3266
- });
3267
- var clearStorage = createAPI("clearStorage", {
3268
- async implement() {
3269
- const gameId = context.mpId;
3270
- const { response } = await innerFetch(`/api/games/user-storage/${gameId}/clear`, {
3271
- method: "POST",
3272
- appendHostCookie: true
3273
- });
3274
- applyNative("clearLocalStorageAsync");
3275
- const {
3276
- data: { code, message }
3277
- } = response;
3278
- if (code === "SUCCESS") {
3279
- return {
3280
- code,
3281
- message
3282
- };
3283
- }
3284
- return {
3285
- code,
3286
- message: `${message}.fallback to native`
3287
- };
3288
- }
3289
- });
3290
- commands4.registerCommand("StorageSDK.clear", clearStorage);
3291
- registerCanIUse("storage.clear", {
3292
- version: "1.0.0"
3293
- });
3294
- var getStorageInfo = createAPI("getStorageInfo", {
3295
- async implement() {
3296
- const { data } = await applyNative("getStorageInfoAsync");
3297
- return data;
3298
- }
3299
- });
3300
- registerCanIUse("getStorageInfo", {
3301
- version: "1.0.0",
3302
- success: {
3303
- keys: "1.0.0",
3304
- // string[] 本地数据缓存中的所有键名列表,如本地数据则返回空数组
3305
- currentSize: "1.0.0",
3306
- // number 当前占用的空间大小,以 KB 为单位
3307
- limitSize: "1.0.0"
3308
- // number 存储空间上限,以 KB 为单位,一般来说会返回 10240
3309
- }
3310
- });
3311
- var getStorageInfoSync = createSyncAPI("getStorageInfoSync", {
3312
- implement() {
3313
- return invokeNative("getStorageInfoSync");
3314
- }
3315
- });
3316
- var DATA_TYPE = [
3317
- "string",
3318
- "number",
3319
- "boolean",
3320
- "object",
3321
- ""
3322
- // 表示不支持的类型
3323
- ];
3324
- function getType3(data) {
3325
- const type = Object.prototype.toString.call(data).split(" ")[1].split("]")[0].toLocaleLowerCase();
3326
- if (DATA_TYPE.includes(type)) {
3327
- return type;
3328
- }
3329
- return "";
3330
- }
3331
- function parse(str, type) {
3332
- try {
3333
- switch (type) {
3334
- case "string":
3335
- return str;
3336
- case "object":
3337
- return JSON.parse(str);
3338
- case "number":
3339
- return parseFloat(str);
3340
- case "boolean":
3341
- return str === "true";
3342
- default:
3343
- return "";
3344
- }
3345
- } catch {
3346
- return "";
3347
- }
3348
- }
3349
- function stringify(data, type) {
3350
- try {
3351
- switch (type) {
3352
- case "string":
3353
- case "number":
3354
- case "boolean":
3355
- return `${data}`;
3356
- case "object":
3357
- return JSON.stringify(data);
3358
- default:
3359
- return "";
3360
- }
3361
- } catch {
3362
- return "";
3363
- }
3364
- }
3365
-
3366
- // src/native/api/keyboard.ts
3367
- init_index_es();
3368
- init_bridge();
3369
- init_base();
3370
- var showKeyboard = createAPI("showKeyboard", {
3371
- paramsSchema: t.tuple(
3372
- t.object({
3373
- defaultValue: t.string().default(""),
3374
- multiple: t.boolean().default(false),
3375
- maxLength: t.unknown().optional().default(1e5)
3376
- })
3377
- ),
3378
- async implement(params) {
3379
- const maxLength = Math.floor(Number(params.maxLength) ?? 1e5);
3380
- let { defaultValue } = params;
3381
- if (defaultValue && maxLength) {
3382
- defaultValue = defaultValue.slice(0, maxLength);
3383
- }
3384
- applyNative("showKeyboardSync", { ...params, defaultValue, maxLength });
3385
- }
3386
- });
3387
- registerCanIUse("keyboard.showKeyboard", {
3388
- version: "1.0.0",
3389
- properties: {
3390
- params: {
3391
- defaultValue: "1.0.0",
3392
- multiple: "1.0.0",
3393
- confirmHold: "1.0.0",
3394
- confirmType: "1.0.0",
3395
- maxLength: "1.0.0"
3396
- }
3397
- },
3398
- success: {
3399
- errMsg: "1.0.0"
3400
- }
3401
- });
3402
- var updateKeyboard = createAPI("updateKeyboard", {
3403
- paramsSchema: t.tuple(
3404
- t.object({
3405
- value: t.string()
3406
- })
3407
- ),
3408
- async implement(params) {
3409
- applyNative("updateKeyboardSync", params);
3410
- }
3411
- });
3412
- registerCanIUse("keyboard.updateKeyboard", {
3413
- version: "1.0.0",
3414
- properties: {
3415
- params: {
3416
- value: "1.0.0"
3417
- }
3418
- }
3419
- });
3420
- var hideKeyboard = createAPI("hideKeyboard", {
3421
- async implement() {
3422
- applyNative("hideKeyboardSync");
3423
- }
3424
- });
3425
- registerCanIUse("keyboard.hideKeyboard", {
3426
- version: "1.0.0"
3427
- });
3428
- var commands5 = Vn();
3429
- commands5.registerCommand("KeyboardSDK.showKeyboard", showKeyboard);
3430
- commands5.registerCommand("KeyboardSDK.updateKeyboard", updateKeyboard);
3431
- commands5.registerCommand("KeyboardSDK.hideKeyboard", hideKeyboard);
3432
-
3433
- // src/native/api/task.ts
3434
- init_index_es();
3435
- init_base();
3436
- init_report5();
3437
- var commands6 = Vn();
3438
- var onLevelFinished = createAPI("levelFinished", {
3439
- paramsSchema: t.tuple(
3440
- t.string(),
3441
- t.object({
3442
- result: t.boolean(),
3443
- duration: t.number()
3444
- })
3445
- ),
3446
- implement: async (levelId, parmas) => {
3447
- const { result, duration } = parmas;
3448
- const tasks = [];
3449
- tasks.push(
3450
- taskTracker.tracker("LevelFinished", {
3451
- levelId,
3452
- result,
3453
- duration
3454
- })
3455
- );
3456
- tasks.push(
3457
- taskTracker.reporter({
3458
- event: "COMPLETE_GAME_LEVEL"
3459
- })
3460
- );
3461
- await Promise.all(tasks);
3462
- }
3463
- });
3464
- var onTaskFinished = createAPI("taskFinished", {
3465
- paramsSchema: t.tuple(
3466
- t.string(),
3467
- t.object({
3468
- duration: t.number()
3469
- })
3470
- ),
3471
- implement: async (taskId, params) => {
3472
- const { duration } = params;
3473
- return await taskTracker.reportToNative({
3474
- event: "TaskFinished",
3475
- params: {
3476
- duration,
3477
- taskId
3478
- }
3479
- });
3480
- }
3481
- });
3482
- var onLevelUpgrade = createAPI("levelUpgrade", {
3483
- paramsSchema: t.tuple(t.string(), t.string()),
3484
- implement: async (levelId, name) => {
3485
- const tasks = [];
3486
- tasks.push(
3487
- taskTracker.reportToNative({
3488
- event: "LevelUpgrade",
3489
- params: {
3490
- name,
3491
- levelId
3492
- }
3493
- })
3494
- );
3495
- await Promise.all(tasks);
3496
- }
3497
- });
3498
- var onHistoryUserLevel = createAPI("onHistoryUserLevel", {
3499
- paramsSchema: t.tuple(t.number()),
3500
- implement: async (level) => {
3501
- return await taskTracker.reportToNative({
3502
- event: "HistoryUserLevel",
3503
- params: {
3504
- level
3505
- }
3506
- });
3507
- }
3508
- });
3509
- var onHistoryUserScore = createAPI("onHistoryUserScore", {
3510
- paramsSchema: t.tuple(t.number()),
3511
- implement: async (score) => {
3512
- return await taskTracker.reportToNative({
3513
- event: "HistoryUserScore",
3514
- params: {
3515
- score
3516
- }
3517
- });
3518
- }
3519
- });
3520
- var onTaskEvent = createAPI("taskEvent", {
3521
- paramsSchema: t.tuple(
3522
- t.string(),
3523
- t.object({
3524
- tools: t.array(
3525
- t.object({
3526
- id: t.string(),
3527
- name: t.string(),
3528
- count: t.number(),
3529
- description: t.string().optional(),
3530
- price: t.object({
3531
- amount: t.number(),
3532
- unit: t.string()
3533
- }).optional()
3534
- })
3535
- ).optional(),
3536
- awards: t.array(
3537
- t.object({
3538
- id: t.string(),
3539
- name: t.string()
3540
- })
3541
- ).optional()
3542
- })
3543
- ),
3544
- implement: async (taskId, params) => {
3545
- const tasks = [];
3546
- tasks.push(
3547
- taskTracker.reportToNative({
3548
- event: "TaskEvent",
3549
- params: {
3550
- taskId,
3551
- ...params
3552
- }
3553
- })
3554
- );
3555
- if (params.tools?.length ?? 0 > 0) {
3556
- tasks.push(
3557
- taskTracker.reporter({
3558
- event: "USE_GAME_ITEM"
3559
- })
3560
- );
3561
- tasks.push(
3562
- taskTracker.reportToNative({
3563
- event: "UseGameItem",
3564
- params: {
3565
- taskId,
3566
- ...params
3567
- }
3568
- })
3569
- );
3570
- }
3571
- await Promise.all(tasks);
3572
- }
3573
- });
3574
- commands6.registerCommand("TaskTrackerSDK.levelFinished", onLevelFinished);
3575
- commands6.registerCommand("TaskTrackerSDK.taskFinished", onTaskFinished);
3576
- commands6.registerCommand("TaskTrackerSDK.levelUpgrade", onLevelUpgrade);
3577
- commands6.registerCommand("TaskTrackerSDK.historyUserLevel", onHistoryUserLevel);
3578
- commands6.registerCommand("TaskTrackerSDK.historyUserScore", onHistoryUserScore);
3579
- commands6.registerCommand("TaskTrackerSDK.taskEvent", onTaskEvent);
3580
- registerCanIUse("TaskTrackerSDK.onLevelFinished", {
3581
- version: "1.0.0",
3582
- properties: {
3583
- levelId: "1.0.0",
3584
- params: {
3585
- result: "1.0.0",
3586
- duration: "1.0.0"
3587
- }
3588
- }
3589
- });
3590
- registerCanIUse("TaskTrackerSDK.onTaskFinished", {
3591
- version: "1.0.0",
3592
- properties: {
3593
- taskId: "1.0.0",
3594
- duration: "1.0.0"
3595
- }
3596
- });
3597
- registerCanIUse("TaskTrackerSDK.onLevelUpgrade", {
3598
- version: "1.0.0",
3599
- properties: {
3600
- levelId: "1.0.0",
3601
- name: "1.0.0"
3602
- }
3603
- });
3604
- registerCanIUse("TaskTrackerSDK.onHistoryUserLevel", {
3605
- version: "1.0.0",
3606
- properties: {
3607
- level: "1.0.0"
3608
- }
3609
- });
3610
- registerCanIUse("TaskTrackerSDK.onHistoryUserScore", {
3611
- version: "1.0.0",
3612
- properties: {
3613
- score: "1.0.0"
3614
- }
3615
- });
3616
- registerCanIUse("TaskTrackerSDK.onTaskEvent", {
3617
- version: "1.0.0",
3618
- properties: {
3619
- taskId: "1.0.0",
3620
- params: {
3621
- tools: {
3622
- id: "1.0.0",
3623
- name: "1.0.0",
3624
- count: "1.0.0",
3625
- description: "1.0.0",
3626
- price: {
3627
- amount: "1.0.0",
3628
- unit: "1.0.0"
3629
- }
3630
- },
3631
- awards: {
3632
- id: "1.0.0",
3633
- name: "1.0.0"
3634
- }
3635
- }
3636
- }
3637
- });
3638
-
3639
- // src/native/api/login.ts
3640
- init_context();
3641
- init_bridge();
3642
- init_base();
3643
- init_index_es();
3644
- init_errors();
3645
- registerCanIUse("login", {
3646
- version: "1.0.0",
3647
- properties: {
3648
- force: "1.0.0"
3649
- },
3650
- success: {
3651
- errMsg: "1.0.0",
3652
- code: "1.0.0",
3653
- token: "1.0.0",
3654
- isLogin: "1.0.0"
3655
- }
3656
- });
3657
- registerCanIUse("checkSession", {
3658
- version: "1.0.0",
3659
- success: {
3660
- errMsg: "1.0.0"
3661
- }
3662
- });
3663
- var login = createAPI("login", {
3664
- async implement() {
3665
- const {
3666
- data: { isLogin }
3667
- } = await applyNative("checkLoginAsync");
3668
- if (isLogin) {
3669
- return { isLogin: true, token: context.hostUserInfo?.token };
3670
- }
3671
- onNative("onLoginStateChange", ({ isLogin: isLogin2, token, uuid }) => {
3672
- if (uuid == loginUUID) {
3673
- resolve({ isLogin: isLogin2, token });
3674
- }
3675
- });
3676
- const res = invokeNative("loginSync");
3677
- const {
3678
- data: { uuid: loginUUID }
3679
- } = res;
3680
- if (!loginUUID) {
3681
- throw createAPIError({
3682
- code: -1,
3683
- msg: "login failed"
3684
- });
3685
- }
3686
- const { promise, resolve } = new L();
3687
- const loginRes = await promise;
3688
- context.onEnvConfigChanged({ hostUserInfo: loginRes });
3689
- En.emit("onLoginComplete", loginRes);
3690
- return loginRes;
3691
- }
3692
- });
3693
- var checkSession = createAPI("checkSession", {
3694
- async implement() {
3695
- const {
3696
- data: { isLogin }
3697
- } = await applyNative("checkLoginAsync");
3698
- return {
3699
- isLogin
3700
- };
3701
- }
3702
- });
3703
- var commands7 = Vn();
3704
- commands7.registerCommand("API.login", login);
3705
- commands7.registerCommand("API.checkSession", checkSession);
3706
-
3707
- // src/native/api/ads.ts
3708
- init_index_es();
3709
- init_base();
3710
- var commands8 = Vn();
3711
- var adInit = createSyncAPI("adInit", {
3712
- implement: (config2) => {
3713
- q.log("[JoliboxAdsSDK] adInit", config2);
3714
- }
3715
- });
3716
- var adConfig = createSyncAPI("adConfig", {
3717
- implement: (params) => {
3718
- q.log("[JoliboxAdsSDK] adConfig", params);
3719
- }
3720
- });
3721
- var adBreak = createSyncAPI("adBreak", {
3722
- implement: (params) => {
3723
- q.log("[JoliboxAdsSDK] adBreak", params);
3724
- }
3725
- });
3726
- var adUnit = createSyncAPI("adUnit", {
3727
- implement: (params) => {
3728
- q.log("[JoliboxAdsSDK] adUnit", params);
3729
- }
3730
- });
3731
- commands8.registerCommand("AdsSDK.init", adInit);
3732
- commands8.registerCommand("AdsSDK.adConfig", adConfig);
3733
- commands8.registerCommand("AdsSDK.adBreak", adBreak);
3734
- commands8.registerCommand("AdsSDK.adUnit", adUnit);
3735
- registerCanIUse("AdsSDK.init", {
3736
- version: "1.0.0"
3737
- });
3738
- registerCanIUse("AdsSDK.adConfig", {
3739
- version: "1.0.0"
3740
- });
3741
- registerCanIUse("AdsSDK.adBreak", {
3742
- version: "1.0.0"
3743
- });
3744
- registerCanIUse("AdsSDK.adUnit", {
3745
- version: "1.0.0"
3746
- });
3747
-
3748
- // src/index.native.ts
3749
- init_report5();
3750
- config();
1
+ var yn=Object.create;var Vt=Object.defineProperty;var bn=Object.getOwnPropertyDescriptor;var Tn=Object.getOwnPropertyNames;var kn=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var Sn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var In=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Tn(t))!En.call(e,s)&&s!==r&&Vt(e,s,{get:()=>t[s],enumerable:!(n=bn(t,s))||n.enumerable});return e};var wn=(e,t,r)=>(r=e!=null?yn(kn(e)):{},In(t||!e||!e.__esModule?Vt(r,"default",{value:e,enumerable:!0}):r,e));function Rn(e){return!!e?.__nativeBuffers__}function de(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return{}}if(typeof e!="object"||e===null)return{};if(!Rn(e))return e;let t=e.__nativeBuffers__;if(delete e.__nativeBuffers__,t)for(let r=0;r<t.length;r++){let n=t[r];if(n){let s;n.value?s=n.value:n.base64&&(s=_n(n.base64)),typeof s<"u"&&s instanceof ArrayBuffer&&(e[n.key]=s)}}return e}function $t(e={},t=!1){let r=e,n=[];for(let[s,o]of Object.entries(r))if(o!==void 0&&o instanceof ArrayBuffer&&o.byteLength!==void 0){let i=t?{value:o,key:s}:{base64:An(o),key:s};n.push(i),delete r[s]}return n.length>0&&(r.__nativeBuffers__=n),r}var _n,An,ot=h(()=>{"use strict";_n=e=>{let t=atob(e),r=t.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=t.charCodeAt(s);return n.buffer};An=e=>{let t="",r=new Uint8Array(e),n=r.byteLength;for(let s=0;s<n;s++)t+=String.fromCharCode(r[s]);return btoa(t)}});function Pn(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function te(e){return typeof e=="string"}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Gt(e){return typeof e=="object"&&Array.isArray(e)}function Nn(e){return typeof e>"u"}function On(e){return Nn(e)||e===null}function zt(e){return typeof e=="function"}function Wt(e){return C(e)&&zt(e.then)}function Yt(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}function Qt(e,t,r){if(typeof r!="function")throw new Error("[Jolibox SDK]Customizer must be a function");function n(s,o){for(let i in o)if(Object.prototype.hasOwnProperty.call(o,i)){let a=s[i],d=o[i],l=r(a,d,i,s,o);l!==void 0?s[i]=l:Ht(d)&&Ht(a)?s[i]=n({...a},d):Array.isArray(d)&&Array.isArray(a)?s[i]=[...a,...d]:s[i]=d}return s}return n(e,t)}function Ht(e){return e&&typeof e=="object"&&e.constructor===Object}function Xt(e,t){if(Array.isArray(e))return e.concat(t)}function pe(e,t,r={}){let n=null,s,o,i,{leading:a=!1,trailing:d=!0}=r,l=()=>(i=e.apply(o,s),s=void 0,o=void 0,i),u=function(...p){s=p,o=this;let m=a&&!n;if(n&&clearTimeout(n),n=setTimeout(()=>{n=null,d&&!m&&l()},t),m)return l()};return u.cancel=()=>{n&&clearTimeout(n),n=null,s=o=void 0},u.flush=()=>{if(n)return clearTimeout(n),n=null,l()},u}function Un(e,t){return(...r)=>t(e,...r)}function ke(e){return t=>Un(t,function(r,...n){if(typeof r=="function")try{return r.apply(this,n)}catch(s){e(new Dn(`${s}`))}})}function ue(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}function Yn(e){return new Promise(t=>lr(e)(t))}function lr(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function Qn(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new me(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}function Zn(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)es(e[n],t[n])}function es(e,t){if(te(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(zt(t)){try{if(e instanceof t)return}catch{}if(!On(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}function w(){if(globalThis[at])return globalThis[at];let e=new be,t=new lt,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[at]=r,r}var Kt,xn,Cn,qt,Y,Fn,dt,re,Zt,er,Dn,tr,rr,nr,sr,or,fe,Te,ut,P,ir,Mn,mt,Ln,pt,jn,Bn,ge,Jn,Vn,$n,ar,ft,Hn,Kn,qn,cr,T,Gn,zn,ve,me,Q,ct,Wn,it,Xn,H,be,lt,at,v=h(()=>{"use strict";Kt=Object.defineProperty,xn=Object.getOwnPropertyDescriptor,Cn=(e,t)=>{for(var r in t)Kt(e,r,{get:t[r],enumerable:!0})},qt=(e,t,r,n)=>{for(var s=n>1?void 0:n?xn(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&Kt(t,r,s),s};Y=class{constructor(){this.state="pending",this.promise=new Promise((e,t)=>{this.resolve=r=>{this.state==="pending"&&(this.state="fulfilled",e(r))},this.reject=r=>{this.state==="pending"&&(this.state="rejected",t(r))}})}};Fn=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Fn||{}),dt=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},re=class extends dt{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}},Zt=class extends dt{constructor(){super(...arguments),this.kind="USER_ERROR"}},er=class extends Zt{constructor(){super(...arguments),this.name="USER_VALIDATE_ERROR"}},Dn=class extends Zt{constructor(e,t,r){super(e),this.message=e,this.errNo=t,this.name="USER_CUSTOM_ERROR",this.errMsg=e,r&&(this.extra=Object.assign({},this.extra,r))}},tr=class extends re{constructor(){super(...arguments),this.name="INTERNAL_SCHEMA_PARSE_ERROR",this.priority="P0"}},rr=class extends re{constructor(){super(...arguments),this.name="INTERNAL_INVOKE_NATIVE_ERROR"}},nr=class extends re{constructor(e,t,r,n){super(e),this.errNo=t,this.name="INTERNAL_APPLY_NATIVE_ERROR",this.errorType=r,this.errorCode=n}},sr=class extends re{constructor(){super(...arguments),this.name="INTERNAL_JSCORE_ERROR",this.priority="P0"}},or=class extends re{constructor(){super(...arguments),this.name="INTERNAL_GLOBAL_JS_ERROR",this.priority="P1"}},fe=class extends dt{constructor(e,t,r,n,s){super(e),this.message=e,this.code=t,this.kind="API_ERROR",this.name="API_ERROR",r&&(this.errorType=r),n!==void 0&&(this.stack=n),s&&(this.priority=s)}toJSON(){return{message:this.message,stack:this.stack,name:this.name,code:this.code,errorType:this.errorType}}},Te=class extends re{constructor(){super(...arguments),this.name="INTERNAL_METRIC_REPORT_ERROR"}},ut=class extends re{constructor(){super(...arguments),this.name="INTERNAL_REPORTER_ERROR"}};P={log:ue("log"),warn:ue("warn"),info:ue("info"),error:ue("error"),debug:ue("debug")};Object.assign(globalThis,{logger:P});ir=Symbol.for("Jolibox.canIUseMap"),Mn={};globalThis[ir]=Mn;mt={get config(){return globalThis[ir]}},Ln=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(Ln||{}),pt=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(pt||{}),jn=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(jn||{}),Bn=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)}),ge={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},Jn=()=>ge.isiOS?"iOS":ge.isAndroid?"Android":ge.isMac?"Mac":ge.isFacebook?"Facebook":"PC",Vn="device_id",$n="advertising_id",ar=e=>(localStorage.getItem(e)||localStorage.setItem(e,Bn()),localStorage.getItem(e)),ft=()=>ar(Vn),Hn=()=>ar($n),Kn=e=>e.charAt(0).toUpperCase()+e.slice(1),qn=()=>{let e=new URLSearchParams(window.location.search);return Kn(e.get("utm_source")??"")||"JoliboxSDK"},cr=e=>{let t="JoliboxWebSDK",r=Jn(),n=navigator.language,s=ft(),o=Hn();return`${t} (${qn()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},T=class ye{static{this.Undefined=new ye(void 0)}constructor(t){this.element=t,this.next=ye.Undefined,this.prev=ye.Undefined}},Gn=class{constructor(){this._first=T.Undefined,this._last=T.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===T.Undefined}clear(){let e=this._first;for(;e!==T.Undefined;){let t=e.next;e.prev=T.Undefined,e.next=T.Undefined,e=t}this._first=T.Undefined,this._last=T.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new T(e);if(this._first===T.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==T.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==T.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==T.Undefined&&e.next!==T.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===T.Undefined&&e.next===T.Undefined?(this._first=T.Undefined,this._last=T.Undefined):e.next===T.Undefined?(this._last=this._last.prev,this._last.next=T.Undefined):e.prev===T.Undefined&&(this._first=this._first.next,this._first.prev=T.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==T.Undefined;)yield e.element,e=e.next}},zn=0,ve=class{constructor(e){this.value=e,this.id=zn++}},me=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof ve&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new ve(e);this._listeners?this._listeners instanceof ve?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof ve?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},Q=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new me,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Gn,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},ct={};Cn(ct,{None:()=>Wn,filter:()=>Qn,once:()=>lr,toPromise:()=>Yn});Wn=()=>{console.log("[Jolibox SDK] None Event")};it=Symbol.for("Jolibox.hostEmitter"),Xn=()=>{let e=new Q;return globalThis[it]||(globalThis[it]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[it]},H=Xn();be=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new me,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Zn(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};be=qt([Yt],be);lt=class{constructor(){this._onWillExecuteCommand=new me,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new me,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new be,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Pn(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),ct.toPromise(ct.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};lt=qt([Yt],lt);at=Symbol.for("Jolibox.commands")});function A(e,t={}){ht.emit("ERROR_REPORT",{error:e,options:t})}var ht,ne,L=h(()=>{"use strict";v();v();ht=new Q,ne=new Q;A.debounce=pe(A,50,{leading:!0})});function Ee(e,t){return`[${e}]:${t}`}var se,gt,X=h(()=>{"use strict";L();v();L();se=(e,t)=>new fe(t?.errMsg??e.msg??"",e.code,e.type),gt=e=>new er(e)});var dr,ur,mr,pr=h(()=>{"use strict";dr=[],ur=[],mr=["env","createRequestTask","login"]});function hr(e,t){fr||(vt=new oe({eventName:"jolibox_invoke",tagNameOrder:["status","method","errNo","errMsg","isForeground"],metricName:"duration",reporter(s){e.invoke("track",JSON.stringify({event:"reportMetrics",data:s}),-1)}}),yt=new oe({eventName:"jolibox_invoke_js2native",tagNameOrder:["status","method","isForeground"],metricName:"duration",reporter(s){e.invoke("track",JSON.stringify({event:"reportMetrics",data:s}),-1)}}),bt=new oe({eventName:"jolibox_invoke_native2js",tagNameOrder:["status","method","isForeground"],metricName:"duration",reporter(s){e.invoke("track",JSON.stringify({event:"reportMetrics",data:s}),-1)}}),t("onJoliboxEnterBackground",()=>{vt.flush(),yt.flush(),bt.flush()}),fr=!0);function r(s){let{method:o,args:i,startTime:a,isForeground:d,errMsg:l=`${o}:fail no errMsg`,errNo:u=0,__timing:p={receiveJSInvoke:0,invokeCallback:0}}=s,{receiveJSInvoke:m,invokeCallback:f}=p,b=l.match(/\S:(\S+)\s?/)?.[1]??"fail";vt.report({status:b,method:n(o,i),errNo:`${u}`,errMsg:l,isForeground:d,duration:Date.now()-a}),a&&m&&f&&(yt.report({status:b,method:o,isForeground:d,duration:Number((m-a).toFixed(3))}),bt.report({status:b,method:o,isForeground:d,duration:Number((Date.now()-f).toFixed(3))}))}function n(s,o){return(s==="callHostMethod"||s==="callHostMethodSync")&&o?.method?`${s}-${o.method}`:s}return r}var ts,oe,fr,vt,yt,bt,Tt=h(()=>{"use strict";v();ts=e=>e==="pv"?e:"default",oe=class{constructor(t){this.interval=30;this.lastReportTime=0;this.cache={};let{reporter:r,interval:n=30,eventName:s,tagNameOrder:o,metricName:i,type:a}=t;this.reporter=r,this.interval=n,this.eventName=s,this.tagNameOrder=o,this.metricName=i,this.type=ts(a)}report(t){this.type==="pv"?this.addPVPoint(t):this.addPoint(t),this.tryReport(!1)}flush(){this.tryReport(!0)}tryReport(t){if(Object.keys(this.cache).length){if(t){this.reporter(this.processPoints(this.cache)),this.clearPoints();return}this.lastReportTime=this.lastReportTime||Date.now(),Date.now()-this.lastReportTime>=this.interval*1e3&&(this.reporter(this.processPoints(this.cache)),this.clearPoints(),this.lastReportTime=Date.now())}}addPoint(t){let r=(n,s,o,i)=>{let a=s.shift();if(a){let d=i[a];n[d]||(n[d]={}),r(n[d],s,o,i)}else n[o]||(n[o]=[]),n[o].push(i[o])};r(this.cache,[...this.tagNameOrder],this.metricName,t)}addPVPoint(t){let r=(s,o,i,a)=>{let d=o.shift();if(!d&&C(a))throw new Te(`report value failed to match tagNameOrder, ${JSON.stringify(n)}`);if(d){let l=[];if(C(a))l.push(...Object.keys(a));else if(te(a)){if(o.length>0)throw new Te(`report value failed to match tagNameOrder, ${JSON.stringify(n)}`);l.push(a)}else throw new Te(`expected metric value to be a string, but got a(n) ${typeof a}, ${JSON.stringify(n)}`);l.forEach(u=>{s[u]||(s[u]={});let p=C(a)?a[u]:a;r(s[u],[...o],i,p)})}else s[i]?s[i]++:s[i]=1},n={point:t,metricName:this.metricName,tagNameOrder:this.tagNameOrder};r(this.cache,[...this.tagNameOrder],this.metricName,t)}processPoints(t){return{eventName:this.eventName,tagNameOrder:this.tagNameOrder,metricName:this.metricName,metricAggregateType:this.type==="pv"?"itoa":"arr",data:t}}clearPoints(){this.cache={}}},fr=!1});function vr(e,t){let r=0,n=!0,s=new Map,o=hr(e,t);t("onJoliboxEnterBackground",()=>{n=!1}),t("onJoliboxEnterForeground",()=>{n=!0,kt.forEach(async({method:l,args:u,resolve:p})=>{let m=await a(l,u);p(m)}),kt.length=0});let i=(l,u)=>{P.info("----resolveId",l,u);let p=s.get(Number(l));if(!p)return;let m=de(u);p(m),s.delete(Number(l))},a=(l,u)=>{let p=Date.now(),m=`${n}`;r+=1;let f=new Y;if(s.set(r,f.resolve),!n&&ur.includes(l))return new Promise(x=>{kt.push({method:l,args:u,resolve:x})});let _={...{method:l,startTime:p,args:u,isForeground:m},invokeType:"js-bridge"},N=!rs&&dr.includes(l),z=$t(u,N),W=N?z:JSON.stringify(z),k;if(l.endsWith("Sync")||mr.includes(l)?k=e.call?.(l,z,r):typeof W=="string"?(console.log("-----params",l,r),k=e.invoke(l,W,r)):k=e.call?.(l,W,r),k){try{typeof k=="string"&&(k=JSON.parse(k)),k=de(k)}catch(x){P.error(x)}return s.delete(r),k.errorCode&&(k.errorCode=Ee(l,k.errorCode)),o({..._,...k}),k}return l.endsWith("Sync")&&s.delete(r),f.promise.then(x=>(x.errorCode&&(x.errorCode=Ee(l,x.errorCode)),o({..._,...x}),x))};return{invokeNative:a,applyNative:(l,u)=>{let p=a(l,u);return Wt(p)?p.then(m=>gr(l,m)):gr(l,p)},invokeHandler:i}}function gr(e,t){if(!C(t)){P.warn(`[Jolibox SDK]${e} no response value`);return}let{errMsg:r,errNo:n,errorType:s,errorCode:o,...i}=t;if(r&&r!==`${e}:ok`)throw new nr(r,n,s,o);return i}var kt,rs,yr=h(()=>{"use strict";ot();v();X();pr();Tt();kt=[],rs=!1});function br(e){let t=new Q,r=new oe({eventName:"jolibox_publish",tagNameOrder:["type","event"],metricName:"duration",reporter(n){e.invoke("track",JSON.stringify({event:"reportMetrics",data:n}),-1)}});return t.on("onJoliboxEnterBackground",()=>{r.flush()}),{onNative:t.on.bind(t),offNative:t.off.bind(t),subscribeHandler(n,s,o){let i=de(s),a;if(i.__extra){a=i.params;let{type:d,startTime:l}=i.__extra;r.report({type:d,event:n,duration:Date.now()-l})}else a=i;t.emit(n,a,o)}}}var Tr=h(()=>{"use strict";v();ot();Tt()});function Et(e){let{subscribeHandler:t,onNative:r,offNative:n}=br(e),{invokeNative:s,invokeHandler:o,applyNative:i}=vr(e,r);return{invokeHandler:o,subscribeHandler:t,applyNative:i,invokeNative:s,onNative:r,offNative:n}}var kr=h(()=>{"use strict";yr();Tr()});var Er=h(()=>{"use strict"});var Sr=h(()=>{"use strict";kr();Er()});var Z,j,Ir,wr=h(()=>{"use strict";v();L();j={trigger(){},exit(){return!1},onReady(e){j.trigger=e},doExit(e){j.exit=e}},Ir=()=>{let e=window.prompt("invoke",JSON.stringify({event:"envSync",paramsString:JSON.stringify({})}));if(!e)A(new rr("native env failed"));else{let{data:t}=JSON.parse(e);return t??void 0}};if(window.webkit){let e=window.webkit.messageHandlers,t=(s="")=>{j.trigger(),e.onDocumentReady.postMessage({path:s})};Z={onDocumentReady:t,doExit:s=>{let o=j.exit();e.doExit.postMessage({uuid:s,shouldInterrupt:o})},invoke(s,o,i){e.invoke.postMessage({event:s,paramsString:o,callbackId:i})},call(s,o,i){let a=window.prompt("invoke",JSON.stringify({event:s,paramsString:JSON.stringify(o),callbackId:i}));if(a)return JSON.parse(a)}};let n={onDocumentReady:t,env:Ir};globalThis.joliboxJSCore={...n}}if(window.JoliAndroidSDKBridge){let e=window.JoliAndroidSDKBridge,t=(s="")=>{j.trigger(),e.onDocumentReady(JSON.stringify({path:s}))};Z={onDocumentReady:t,invoke(s,o,i){e.invoke(JSON.stringify({event:s,paramsString:o,callbackId:i}))},doExit:s=>{let o=j.exit();e.doExit(JSON.stringify({uuid:s,shouldInterrupt:o}))},call(s,o,i){let a=window.prompt("invoke",JSON.stringify({event:s,paramsString:JSON.stringify(o),callbackId:i}));if(a)return JSON.parse(a)}};let n={onDocumentReady:t,env:Ir};globalThis.joliboxJSCore={...n}}});function St(e,t){return{params:e,__extra:{startTime:Date.now(),type:t}}}var It=h(()=>{"use strict"});function wt(){globalThis.onmessage=function(e){e.data==="msg:setup"&&([ie]=e.ports,ie.onmessage=function(t){let r=JSON.parse(t.data);r[0]==="publish"?globalThis.ttJSBridge.subscribeHandler(r[1],r[2]):r[0]==="invoke"&&globalThis.ttJSBridge.invokeHandler(r[1],r[2])},ie.publish=function(t,r){let n=St(r,"messagePort");ie.postMessage(JSON.stringify(["publish",t,JSON.stringify(n)]))},ie.postMessage("msg:setup:ok"))}}var ie,Rr=h(()=>{"use strict";It()});var Se=h(()=>{"use strict";wr();Rr();It()});var Ar,ns,xr,_r,O,I,V,Ei,ss,U=h(()=>{"use strict";Sr();Se();X();v();Se();Ar=Z;if(!Ar)throw new sr("No joliboxJScore is found, native bridge not found.");wt();ns={...Ar},xr=Et(ns),{invokeHandler:_r}=xr,{applyNative:O,invokeNative:I,onNative:V,offNative:Ei,subscribeHandler:ss}=xr;globalThis.joliboxJSBridge={callHandler:_r,invokeHandler:_r,subscribeHandler:ss}});var Rt,Cr,Pr=h(()=>{"use strict";v();L();Rt=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?"":"=".repeat(4-t.length%4),n=atob(t+r);try{return JSON.parse(n)}catch{return{}}},Cr=e=>{try{let n=new URL(e).searchParams.get("joliSource")?.split(".");if(n?.length){let[s,o,i]=n;return{headerJson:Rt(s),payloadJson:Rt(o),signature:Rt(i)}}else throw"joli_source is missing"}catch(t){return A(new tr(`${e} not a valid schema: ${t}`)),{headerJson:{},payloadJson:{},signature:{}}}}});var os,Ie,Nr,_t=h(()=>{"use strict";v();os="1.1.5",Ie=()=>os,Nr=()=>{let e=Ie();return`${cr(e)}`}});var is,as,F,cs,y,B=h(()=>{"use strict";v();Pr();_t();v();is={deviceInfo:{brand:"UnknownBrand",model:"UnknownModel",did:ft(),pixelRatio:window.devicePixelRatio||1,platform:"h5",system:"UnknownSystemVersion",lang:"zh"},sdkInfo:{nativeSDKVersion:"",jssdkVersion:Ie()},schema:window.location.href,platform:"h5"},as=globalThis.joliboxJSCore?.env,F=Object.assign({},as?.()??is),cs=()=>{let{payloadJson:e,headerJson:t}=F.schema.length?Cr(F.schema):{},r=`${F.deviceInfo.did}-${new Date().getTime()}`,s=new URL(F.schema.length?F.schema:window.location.href).searchParams,o=s.get("mpId")??s.get("appId")??s.get("gameId")??"",i=e?.sessionId??s.get("sessionId")??r,a=!!(e?.testAdsMode??s.get("testAdsMode")==="true"),d=e?.joliboxEnv??s.get("joliboxEnv")??"production",l=d==="staging",u=t?.channel;return{get testMode(){return l},get testAdsMode(){return a},get joliboxEnv(){return d},get joliSource(){return s.get("joliSource")??null},get mpId(){return o??e?.id??""},get mpVersion(){return t?.ver??Ie()},get platform(){return F.platform??F.deviceInfo.platform},get deviceInfo(){return F.deviceInfo},get sdkInfo(){return F.sdkInfo},get hostInfo(){return F.hostInfo},get hostUserInfo(){return F.hostUserInfo},get sessionId(){return F.clientSessionId??i??r},get channel(){return u},onEnvConfigChanged:p=>{Qt(F,p,Xt)}}},y=cs()});var At,Fr,ls,ds,Or,us,Dr=h(()=>{"use strict";v();L();B();v();At=!1,Fr=(e,t)=>e==null?!1:t in e,ls=e=>Fr(e,"kind"),ds=e=>{let t=e.toLowerCase().split("_");return t[0]+t.slice(1).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")},Or=(e,t={},r)=>{let s={...{user_id:y.hostUserInfo?.uid??"",device_id:y.deviceInfo.did??"",timestamp:Date.now(),tag:ds(e.name)},env:t.environment,isFromUser:r};r?ne.emit("GLOBAL_USER_ERROR",e,s):ne.emit("GLOBAL_ERROR",e,s)},us=e=>Fr(e,"kind")&&e.kind==="USER_ERROR";ht.on("ERROR_REPORT",({error:e,options:t})=>{if(At)return;At=!0;let r=ls(e)&&e.raw?e.raw:e;try{let n=us(e);Or(e,t,n)}catch(n){let s=n instanceof Error?n.message:String(n),o=new ut(`${s}, origin error: ${r.message}`);P.error(o),Or(new ut(o.message),{environment:t.environment},!1)}finally{At=!1}})});var Ur=h(()=>{"use strict";Dr();X();v();U();ne.on("GLOBAL_ERROR",(e,t)=>{let r={message:e.message,stack:e.stack??"",errorType:e.name,source:0};I("trackAsync",{event:"reportJsError",data:r})});ne.on("GLOBAL_USER_ERROR",(e,t)=>{P.log("UserError",e,t)})});var xt=h(()=>{"use strict"});function Mr(e,t){let r=(n,s,o)=>{let i={tag:n,...t,extra:{...s}};n=="globalJsError"?A(new or(JSON.stringify(i))):e("systemLog",i,o)};return r.debounce=pe(r,500,{leading:!0}),r}function Lr(e){let t=(r,n,s)=>{let o=(s&&JSON.stringify(s))??0,i={speed_value_type:r,total_duration:n};o&&Object.assign(i,{extra:o}),e("joliboxSpeedAnalysis",i)};return t.debounce=pe(t,500,{leading:!0}),t}var jr=h(()=>{"use strict";v();v();L()});function Br(e,t){let r=Mr(e,t),n=Lr(r);return{track:r,trackPerformance:n}}var Jr=h(()=>{"use strict";jr()});var Vr=h(()=>{"use strict";B();v();v()});var $r=h(()=>{"use strict";Jr();xt();Vr()});var we,Hr=h(()=>{"use strict";we=class{constructor(t,r){this.eventEmitter=t;this.lastReportTime=0;this.visible=!0;this.timer=this.createRAFTimer(t=>{this.reporter({event:"PLAY_GAME",params:{duration:t}}),this.tracker("PlayGame",{duration:t})});this.interval=r??5*1e3,t.on("visible",n=>{this.visible=n})}start(t){this.reporter({event:"OPEN_GAME",params:{timestamp:Date.now(),duration:t??0}}),this.tracker("OpenGame",{duration:t??0}),this.timer.start()}close(t){this.reporter({event:"CLOSE_GAME",params:{timestamp:Date.now(),duration:t}}),this.tracker("CloseGame",{duration:t}),this.timer.stop()}createRAFTimer(t){let r=Date.now(),n,s,o=!1,i=0,a=()=>{if(!o)return;let f=Date.now(),b=f-r;b>=this.interval&&(this.visible&&(i+=b,t(i)),r=f),n=requestAnimationFrame(a)},d=()=>{u(),r=Date.now(),s=window.setInterval(()=>{if(!o)return;let f=Date.now();f-r>=this.interval&&(r=f)},this.interval)},l=()=>{p(),r=Date.now(),n=requestAnimationFrame(a)},u=()=>{n&&(cancelAnimationFrame(n),n=0)},p=()=>{s&&(clearInterval(s),s=0)};this.eventEmitter.on("visible",f=>{o&&(console.log("visible",f),f?l():d())});let m=this.visible;return{start(){o||(o=!0,m?l():d())},stop(){o=!1,u(),p()}}}}});var Ct=h(()=>{"use strict"});function qr(e,t,r){let{response:n,startTime:s,endTime:o,requestFrom:i}=r,{errMsg:a="",profile:d={}}=n,u={duration:o-s,request_type:e,url:t.split("?")[0],result:r.state,error_msg:r.state==="fail"?a:"",socket_reused:d.socketReused?1:0,request_from:i};(i==="public"&&Kr<ps||i==="inner")&&(u.joli_request_number=Kr++,setTimeout(()=>{M("joliboxNetRequestResult",u)},500))}var Kr,ps,Gr=h(()=>{"use strict";Ct();ee();Kr=0,ps=10});function Re(e,t,r){let n=new Map,s=r?.baseUrl??"https://api.jolibox.com",o=r?.type??"public",i=r?.defaultHeaders??{};return V("onRequestTaskStateChange",d=>{if(typeof d.requestTaskId!="string")return;let l=n.get(d.requestTaskId);if(l)if(d.state==="success"){let{requestTaskId:u,state:p,...m}=d;l.resolve(m),n.delete(u)}else if(d.state==="fail"){let{requestTaskId:u,state:p,...m}=d;l.reject(m),n.delete(u)}else P.warn("onRequestTaskStateChange unknown event",d)}),H.on("onLoginComplete",({isLogin:d,token:l})=>{d&&l&&(i["X-JOLI-TOKEN"]=l)}),async(d,l={})=>{let u=Date.now(),p=fs(d,{...l,baseUrl:s}),{method:m="GET",responseType:f="text",dataType:b="json",timeout:_,enableCache:N=!1,appendHostCookie:z=!0}=l,W=Object.assign({"content-type":"application/json"},i,l.header),k={url:p,method:m,header:W,enableCache:N,responseType:f,appendHostCookie:z};if(m=="POST"||m=="PUT"){let J=gs(l.data,W["content-type"]);k.data=J}_&&Object.assign(k,{timeout:_});let{data:{requestTaskId:x}}=I(e,k);if(typeof x!="string")throw se({code:-1,msg:"requestTaskId is not a string"});let le=(J,$)=>{qr("request",p,{state:J,startTime:u,endTime:Date.now(),params:k,response:$,requestId:x,requestFrom:o=="public"?"public":"inner"})},{resolve:st,reject:pn,promise:fn}=new Y;n.set(x,{resolve:st,reject:pn});try{let J=await fn;le("success",J);let{data:$}=J;return b==="json"&&typeof $=="string"&&($=hs($)),{url:p,timeout:_,method:m,response:{...J,data:$}}}catch(J){let $=J;if(C($)){let{errMsg:he,prefetchDetail:hn,isPrefetch:gn,errNo:vn}=$;te(he)&&(le("fail",{errMsg:he,isPrefetch:gn,prefetchDetail:hn}),A(se({code:-1,msg:he},{errNo:vn,errMsg:he})))}throw J}}}function hs(e){try{return JSON.parse(e.trim())}catch{return e}}function gs(e,t="application/json"){let r=t.toLowerCase();return e===void 0?"":typeof e=="string"||e instanceof ArrayBuffer?e:r.includes("application/x-www-form-urlencoded")||r.includes("application/json")||typeof e=="object"?JSON.stringify(e):String(e)}var fs,Pt=h(()=>{"use strict";v();Gr();Ct();U();L();X();fs=(e,t)=>{if(/^https?:\/\//.test(e))return e;let r=t?.query,s=new URLSearchParams(r).toString();return t?.baseUrl?`${t.baseUrl}${e}${s?`?${s}`:""}`:`${e}${s?`?${s}`:""}`}});var Nt,K,_e=h(()=>{"use strict";_t();Pt();B();Nt={"x-user-agent":Nr()};y.hostUserInfo?.token&&(Nt["x-joli-token"]=y.hostUserInfo.token);y.joliSource&&(Nt["x-joli-source"]=y.joliSource);K=Re("createRequestTaskSync","operateRequestTaskSync",{type:"inner",baseUrl:y.testMode?"https://stg-api.jolibox.com":"https://api.jolibox.com",defaultHeaders:Nt})});var Ae,zr=h(()=>{"use strict";B();Hr();_e();U();Ae=class extends we{constructor(t,r,n){super(r,n),this.gameId=y.mpId,this.sessionId=y.sessionId,this.track=t}async reporter(t){let{event:r,params:n}=t,s=[];s.push(K("/api/base/app-event",{method:"POST",data:{eventType:r,gameInfo:{gameId:this.gameId,sessionId:this.sessionId,...n}}})),await Promise.all(s)}async reportToNative(t){let{event:r,params:n}=t;await O("userTrackAsync",{event:r,params:{...n},gameId:this.gameId})}tracker(t,r=null){this.track(t,r)}}});var vs,M,ys,Wr,xe,D,ee=h(()=>{"use strict";Ur();v();xt();$r();B();zr();U();vs=(e,t,r)=>{let n=t,o={...C(n.extra)?n.extra:te(n.extra)?JSON.parse(n.extra):{},mp_id:n.mp_id??"",mp_version:n.mp_version??""};I("trackAsync",{event:e,data:o,webviewId:r})},{track:M,trackPerformance:ys}=Br(vs,{type:pt.AppSDK,platform:"native",jssdk_version:y.sdkInfo?.jssdkVersion??"1.0.0",mp_id:y.mpId,mp_version:y.mpVersion}),Wr=w();Wr.registerCommand("ReportSDK.traceSystemTimeline",({event:e,duration:t,extra:r})=>{ys(e,t,r)});Wr.registerCommand("ReportSDK.traceSystem",({event:e,info:t})=>{M(e,t)});xe=new Q,D=new Ae(M,xe)});function Qr(e){let t=mt.config[e];return t||(t={},mt.config[e]=t),(r,n)=>{if(t[r]){P.warn(`[can i use] ${r} already registered`);return}t[r]={...n}}}var Xr=h(()=>{"use strict";v()});function Ot(e){Zr=e}function Pe(e){return e===null||typeof e!="object"?e:Array.isArray(e)?e.map(t=>Pe(t)):Object.keys(e).reduce((t,r)=>(t[r]=Pe(e[r]),t),{})}function q(e){return typeof e=="number"}function Ft(e){let t=Dt(e);switch(t){case"string":return`"${e}"`;case"number":case"boolean":case"null":case"undefined":return String(e);default:return`a(n) ${t}`}}function Dt(e){return typeof e=="function"?"function":Object.prototype.toString.call(e).slice(8).slice(0,-1).toLowerCase()}var Zr,E,Ne,Oe,Fe,De,ae,Ue,Me,Le,je,Be,Je,Ve,$e,He,Ke,qe,Ge,Ut=h(()=>{"use strict";Zr=!1;E=class{constructor(){this.errors=[];this.hasFallback=!1;this.hasDefault=!1;this._optional=!1}fail(t){if(Zr)if(typeof t=="string")this.errors.push(t);else{let r=`${this.path} should be ${t.expect}`;this._optional&&t.expect!=="undefined"?r+=" or undefined, ":r+=", ",r+=`but got ${Ft(t.actual)}`,this.errors.push(r)}return!1}fallback(t){return this.hasFallback=!0,this._fallback=t,this}get fallbackValue(){return Pe(this._fallback)}default(t){return this.hasDefault=!0,this._default=t,this}get defaultValue(){return typeof this._default=="function"?this._default:Pe(this._default)}optional(){return this._optional=!0,this}};Ne=class extends E{validate(t){return this._optional&&t===void 0?!0:q(t)?q(this._min)&&t<this._min?this.fail(`the value of ${this.path} should be greater than or equal to ${this._min}`):q(this._max)&&t>this._max?this.fail(`the value of ${this.path} should be less than or equal to ${this._max}`):q(this._greater)&&t<=this._greater?this.fail(`the value of ${this.path} should be greater than ${this._greater}`):this._isInt&&t!==Math.floor(t)?this.fail(`the value of ${this.path} should be integer but got ${t}`):!0:this.fail({expect:"number",actual:t})}min(t){return this._min=t,this}max(t){return this._max=t,this}isInt(t){return this._isInt=t,this}greater(t){return this._greater=t,this}},Oe=class extends E{validate(t){return this._optional&&t===void 0?!0:typeof t!="boolean"?this.fail({expect:"boolean",actual:t}):!0}},Fe=class extends E{validate(t){if(this._optional&&t===void 0)return!0;if(typeof t!="string")return this.fail({expect:"string",actual:t});if(q(this._maxLength)&&t.length>this._maxLength)return this.fail(`the length of ${this.path} should be less than or equal to ${this._maxLength}`);if(q(this._minLength)&&t.length<this._minLength)return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minLength}`);if(typeof this._pattern=="string"){if(!new RegExp(this._pattern).test(t))return this.fail(`${this.path} should match pattern "${this._pattern}"`)}else if(this._pattern&&!this._pattern.test(t))return this.fail(`${this.path} should match pattern "${this._pattern.toString()}"`);return!0}minLength(t){return this._minLength=t,this}maxLength(t){return this._maxLength=t,this}pattern(t){return this._pattern=t,this}},De=class extends E{validate(t){return this._optional&&t===void 0?!0:typeof t!="symbol"?this.fail({expect:"symbol",actual:t}):!0}},ae=class extends E{validate(t){return!0}},Ue=class extends E{validate(t){return t!==void 0?this.fail({expect:"undefined",actual:t}):!0}},Me=class extends E{validate(t){return this._optional&&t===void 0?!0:t!==null?this.fail({expect:"null",actual:t}):!0}},Le=class extends E{validate(t){return this._optional&&t===void 0?!0:typeof t!="function"?this.fail({expect:"function",actual:t}):!0}},je=class extends E{constructor(...t){super(),this._items=t}validate(t){if(this._optional&&t===void 0)return!0;if(!this._items.includes(t)){let r=this._items.map(n=>JSON.stringify(n)).join(", ");return this.fail(`expect ${this.path} to be one of ${r}, but got ${Ft(t)}`)}return!0}},Be=class extends E{constructor(r){super();this._item=r}validate(r){if(this._optional&&r===void 0)return!0;if(!Array.isArray(r))return this.fail({expect:"array",actual:r});if(q(this._minItems)&&r.length<this._minItems)return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minItems}`);if(q(this._maxItems)&&r.length>this._maxItems)return this.fail(`the length of ${this.path} should be less than or equal to ${this._maxItems}`);if(q(this._length)&&r.length!==this._length)return this.fail(`the length of ${this.path} should be equal to ${this._length}`);let n=this._item;if(!n)return!0;let s=!0;if(r.forEach((o,i)=>{if(n.path=`${this.path}[${i}]`,n.errors=this.errors,o===void 0&&n.hasDefault){r[i]=n.defaultValue;return}n.validate(o)||(n.hasFallback?r[i]=n.fallbackValue:s=!1)}),this._uniqueItems){let o=new Map;for(let i in r)o.has(r[i])?s=this.fail(`${this.path} should NOT have duplicate items (${this.path}[${o.get(r[i])}] and ${this.path}[${i}] are identical)`):o.set(r[i],i)}return s}minItems(r){return this._minItems=r,this}maxItems(r){return this._maxItems=r,this}uniqueItems(){return this._uniqueItems=!0,this}length(r){return this._length=r,this}},Je=class extends E{constructor(r){super();this._value=r}validate(r){if(this._optional&&r===void 0)return!0;if(Dt(r)!=="object")return this.fail({expect:"object",actual:r});let s=r,o=this._value;o.errors=this.errors;let i=!0;for(let a in s){let d=s[a];if(/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(a)?o.path=`${this.path}.${a}`:o.path=`${this.path}["${a}"]`,!(d===void 0&&o._optional)){if(d===void 0&&o.hasDefault){s[a]=o.defaultValue;continue}o.validate(d)||(o.hasFallback?s[a]=o.fallbackValue:i=!1)}}return i}},Ve=class extends E{constructor(r={}){super();this._object=r}validate(r){if(this._optional&&r===void 0)return!0;if(Dt(r)!=="object")return this.fail({expect:"object",actual:r});let n=r,s=!0;for(let o in this._object){let i=n[o],a=this._object[o];if(a.errors=this.errors,/^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(o)?a.path=`${this.path}.${o}`:a.path=`${this.path}["${o}"]`,!(a._optional&&i===void 0)){if(i===void 0&&a.hasDefault){n[o]=a.defaultValue;continue}a.validate(i)||(a.hasFallback?n[o]=a.fallbackValue:s=!1)}}return s}},$e=class extends E{constructor(r){super();this.value=r}validate(r){return r===void 0&&this._optional?!0:r!==this.value?this.fail({expect:Ft(this.value),actual:r}):!0}},He=class extends E{constructor(...t){super(),this._items=t}validate(t){if(t===void 0&&this._optional)return!0;let r=[],n=!1,s=this._items.length;for(let o=0;o<s;o++){let i=this._items[o];if(i.errors=[],i.path=this.path,!i.validate(t))r.push(i.errors.join("; "));else if(!n){n=!0;break}}if(!n){let o=r.join(`
2
+ or `);this.errors.push(o)}return n}},Ke=class extends E{constructor(...t){super(),this._items=t;let r=0,n=t.length-1;for(;n>=0;n--){let s=t[n];if(s._optional||s.hasDefault)r+=1;else break}this._minItems=t.length-r}validate(t){if(t===void 0&&this._optional)return!0;if(!Array.isArray(t))return this.fail({expect:"array",actual:t});if(t.length<this._minItems)return this.fail(`the length of ${this.path} should be greater than or equal to ${this._minItems}`);let r=!0;return this._items.forEach((n,s)=>{if(n.path=`${this.path}[${s}]`,n.errors=this.errors,t[s]===void 0&&n.hasDefault){t[s]=n.defaultValue;return}n.validate(t[s])||(n.hasFallback?t[s]=n._fallback:r=!1)}),r}},qe=class extends E{validate(t){return t===void 0&&this._optional||t instanceof ArrayBuffer?!0:this.fail({expect:"arraybuffer",actual:t})}},Ge=class extends E{constructor(t){super(),this._ctor=t}validate(t){return t===void 0&&this._optional||t instanceof this._ctor?!0:this.fail({expect:`typedarray of ${this._ctor.name}`,actual:t})}}});function Mt(e,t,r="param"){if(e.errors=[],e.path=r,Ot(!0),!e.validate(t)){let n=e.errors.join(`
3
+ `);throw e.errors.length=0,Ot(!1),new TypeError(n)}}var c,Lt=h(()=>{"use strict";Ut();Ut();c={object(e){return new Ve(e)},array(e){return new Be(e)},tuple(...e){return new Ke(...e)},literal(e){return new $e(e)},or(...e){return new He(...e)},symbol(){return new De},record(e){return new Je(e)},function(){return new Le},boolean(){return new Oe},string(){return new Fe},number(){return new Ne},undefined(){return new Ue},null(){return new Me},unknown(){return new ae},any(){return new ae},as(){return new ae},arraybuffer(){return new qe},enum(...e){return new je(...e)},typedarray(e){return new Ge(e)}}});var ze,en,tn=h(()=>{"use strict";v();L();Lt();X();ze=1,en=e=>{function t(n,s){return(...o)=>{let i=Date.now(),a={method:n,trace_id:ze};ze+=1;let d="SUCCESS",l=`${n}:ok`,u=0;try{if(s.paramsSchema)try{Mt(s.paramsSchema,o,"params")}catch(b){throw gt(`${n}:fail ${b.message}`)}let p=s.implement(...o),m=p,f=`${n}:ok`;if(p&&"code"in p){let{code:b,data:_,message:N}=p;d=b,m=_,f=N}return{code:d,message:f,data:m}}catch(p){let m=p;u=m.code??m.errNo??2e3,d="FAILURE";let f=m.message??m.errMsg??`${p}`;return l=`${n}:${d} ${f.replace(/^\S+:(fail|cancel)\s?/,"")}`,A(new fe(l,u)),{code:d,message:l}}finally{let p=Date.now()-i;e("apiInvoked",{...a,duration:p,status:d})}}}function r(n,s){return async(...o)=>{let i=Gt(o)?o:[o],a=Date.now(),d={method:n,trace_id:ze};ze+=1;let l=`${n}:ok`,u="SUCCESS",p={code:u,message:l};try{if(s.paramsSchema)try{Mt(s.paramsSchema,i,"params")}catch(b){throw gt(b.message)}let f=await s.implement(...i);if(f&&"code"in f){let{code:b,data:_,message:N}=f;u=b,l=N,f=_}return Object.assign(p,{code:u,message:l,data:f}),p}catch(m){let f=m,b=f.code??f.errNo??2e3;u="FAILURE";let _=f.message??f.errMsg??`${m}`,N=`${n}:${u} ${_.replace(/^\S+:(fail|cancel)\s?/,"")}`;return Object.assign(p,{code:u,message:N}),A(new fe(N,b)),p}finally{let m=Date.now()-a;e("apiInvoked",{...d,duration:m,status:u})}}}return{createAPI:r,createSyncAPI:t}}});var S,R,g,G=h(()=>{"use strict";Xr();ee();tn();Lt();({createAPI:S,createSyncAPI:R}=en(M)),g=Qr("native")});var sn=Sn(nn=>{"use strict";v();G();L();U();ee();var Rs="exitGame",_s="onReady",As="onJoliboxShow",xs="onJoliboxHide",We=w(),Ye=ke(A),Cs=S(Rs,{paramsSchema:c.tuple(c.function()),implement:async e=>{Ye(e).call(nn),await O("exitAppAsync")}}),Ps=R(As,{paramsSchema:c.tuple(c.function()),implement(e){let t=Ye(e);V("onJoliboxEnterForeground",()=>{t.call(this),xe.emit("visible",!0)})}}),Ns=R(xs,{paramsSchema:c.tuple(c.function()),implement(e){let t=Ye(e);V("onJoliboxEnterBackground",()=>{t.call(this),xe.emit("visible",!1)})}}),Os=R(_s,{paramsSchema:c.tuple(c.function()),implement(e){let t=Ye(e);H.on("LifecycleEvent.onReady",r=>{t(r)})}});We.registerCommand("LifecycleSDK.exit",Cs);We.registerCommand("LifecycleSDK.onReady",Os);We.registerCommand("LifecycleSDK.onJoliboxShow",Ps);We.registerCommand("LifecycleSDK.onJoliboxHide",Ns);g("lifeCycle.exit",{version:"1.0.0"});g("lifeCycle.onReady",{version:"1.0.0"});g("lifeCycle.onJoliboxShow",{version:"1.0.0"});g("lifeCycle.onJoliboxHide",{version:"1.0.0"})});U();Se();B();v();ee();j.onReady(()=>{});j.doExit(()=>(M("onBeforeExit",{timestamp:Date.now()}),D.close(Date.now()-Ce),!1));function bs(){H.on("onDocumentReady",()=>{Z?.onDocumentReady(window.location.href),M("onDocumentReady",{start_timestamp:Ce,timestamp:Date.now()})})}function Ts(){V("onJoliboxServiceReady",({runtimeInfo:e,loadDuration:t})=>{e&&y.onEnvConfigChanged({hostUserInfo:e}),H.emit("LifecycleEvent.onReady",{...y.hostUserInfo?y.hostUserInfo:{isLogin:!1}}),M("joliboxServiceReady",{start_timestamp:Ce,timestamp:Date.now()}),D.start(t)}),V("onBeforeExit",({uuid:e})=>{Z?.doExit(e)})}var Ce;function Yr(){Ce=Date.now(),Ts(),bs()}v();G();U();var rn=w(),Es="env",Ss="getSystemInfoSync",Is=R(Ss,{implement:()=>{let e=I("envSync"),{data:t}=e;return{system:t.deviceInfo.system,platform:t.deviceInfo.platform,version:t.sdkInfo.jssdkVersion,pixelRatio:t.deviceInfo.pixelRatio,language:t.deviceInfo.lang,brand:t.deviceInfo.brand,appName:t.hostInfo?.appName,SDKVersion:t.sdkInfo.jssdkVersion}}}),ws=R(Es,{implement:()=>I("envSync")?.data??void 0});rn.registerCommand("API.getSystemInfoSync",Is);rn.registerCommand("API.env",ws);g("env",{version:"1.0.0"});g("getSystemInfoSync",{version:"1.0.0"});var Il=wn(sn());X();Pt();G();v();function on(e){let t={};if(!C(e))return t;for(let[r,n]of Object.entries(e)){let s=r.toLocaleLowerCase();n?typeof n=="object"?t[s]=Object.prototype.toString.call(n):t[s]=String(n):t[s]=""}return t}function an(e="GET"){if(e==="")return"POST";let t=e.toUpperCase();return["GET","OPTIONS","HEAD","POST","PUT","DELETE","TRACE","CONNECT","PATCH"].includes(t)?t:"GET"}function cn(e,t=!1){if(e)return t||e>0&&e<=6e4?Math.ceil(e):6e4}function ln(e,t,r){if(["POST","PUT","PATCH"].includes(t)||!C(r))return e;let[n,s=""]=e.split("?"),o=JSON.stringify({...JSON.parse(s),...r});return`${n}?${o}`}v();L();var Fs=15,Ds=Re("createRequestTaskSync","operateRequestTaskSync",{type:"public"}),jt=0,Bt=[],dn=ke(A),Us=(e,t)=>{let r=e.filter(t),n=e.filter(s=>!t(s));return e.length=0,e.push(...n),r},Ms=e=>{let t=new Y,r=()=>{};return S("request",{paramsSchema:c.tuple(c.object({url:c.string(),method:c.string(),header:c.object(),data:c.object().optional(),query:c.object().optional(),dataType:c.string().default("json"),responseType:c.string().default("text"),enableCache:c.boolean().default(!1),appendHostCookie:c.boolean().default(!0),timeout:c.number().default(3e4),success:c.function(),fail:c.function()})),implement(s){let o=async()=>{let i=dn(s.fail);try{if(jt+=1,t.state!=="pending")return;let{data:a,dataType:d,responseType:l,enableCache:u,appendHostCookie:p}=s,m=on(s.header),f=an(s.method),b=cn(s.timeout),_=ln(s.url,f,a),N=dn(s.success),z=Object.assign({},s,{method:f,header:m,data:f==="GET"||f==="HEAD"?void 0:a,enableCache:u,query:s.query??{},dataType:d,responseType:l,appendHostCookie:p});b&&(z.timeout=b);let W=Ds(_,z);{let{response:k}=await W,{code:x,data:le,message:st}=k;t.resolve({code:x??"SUCCESS",data:le,message:st??"request:ok"}),N({code:"SUCCESS",message:"request:ok",data:le})}}catch(a){t.reject(a),i({code:"FAILURE",message:"httpRequst: failed"})}finally{jt-=1,Bt.shift()?.()}};return jt>=Fs?(r=()=>{Us(Bt,i=>i===o)},Bt.push(o)):o(),t.promise}})(e),{abort(){t.reject(se({code:-1,msg:"request:fail abort"})),r()}}},Ls=w();Ls.registerCommand("HttpSDK.request",Ms);g("request",{version:"1.0.0"});G();U();v();_e();B();var Qe=w(),js=S("getLocalStorage",{paramsSchema:c.tuple(c.string()),async implement(e){let{response:t}=await K(`/api/games/user-storage/${y.mpId}`,{method:"GET",responseType:"json",appendHostCookie:!0,query:{key:e}}),{data:{code:r,message:n,data:s}}=await t;if(r==="SUCCESS")return{code:r,message:n,data:s?.value};try{let{data:{data:o,dataType:i}}=await O("getLocalStorageAsync",{key:e}),a=Ks(o,i);return{code:r,message:`${n}. fallback to native`,data:a}}catch{return{code:"INTERNAL_ERROR",message:"[Jolibox SDK] get local storage failed",data:null}}}});Qe.registerCommand("StorageSDK.getItem",js);g("storage.getItem",{version:"1.0.0",properties:{key:"1.0.0",value:"1.0.0"}});var Bs=S("setStorage",{paramsSchema:c.tuple(c.string(),c.or(c.string(),c.boolean(),c.number())),async implement(e,t){let r=y.mpId,n=typeof t=="string"?t:String(t),{response:s}=await K(`/api/games/user-storage/${r}`,{method:"POST",responseType:"json",appendHostCookie:!0,data:{key:e,value:n}}),{data:{code:o,message:i}}=s,a=Hs(t),d=qs(t,a);return await O("setLocalStorageAsync",{key:e,data:d,dataType:a}),o=="SUCCESS"?{code:o,message:i}:{code:o,message:`${i}. fallback to native`}}});Qe.registerCommand("StorageSDK.setItem",Bs);g("storage.setItem",{version:"1.0.0",properties:{key:"1.0.0",value:"1.0.0"}});var Js=S("removeStorage",{paramsSchema:c.tuple(c.string()),async implement(e){let t=y.mpId,{response:r}=await K(`/api/games/user-storage/${t}/remove`,{method:"POST",responseType:"json",appendHostCookie:!0,data:{key:e}}),{data:{code:n,message:s}}=r;return await O("removeLocalStorageAsync",{key:e}),n==="SUCCESS"?{code:n,message:s}:{code:n,message:"[Jolibox SDK] remove item succ"}}});Qe.registerCommand("StorageSDK.removeItem",Js);g("storage.removeItem",{version:"1.0.0",properties:{key:"1.0.0"}});var Vs=S("clearStorage",{async implement(){let e=y.mpId,{response:t}=await K(`/api/games/user-storage/${e}/clear`,{method:"POST",appendHostCookie:!0});O("clearLocalStorageAsync");let{data:{code:r,message:n}}=t;return r==="SUCCESS"?{code:r,message:n}:{code:r,message:`${n}.fallback to native`}}});Qe.registerCommand("StorageSDK.clear",Vs);g("storage.clear",{version:"1.0.0"});var Bc=S("getStorageInfo",{async implement(){let{data:e}=await O("getStorageInfoAsync");return e}});g("getStorageInfo",{version:"1.0.0",success:{keys:"1.0.0",currentSize:"1.0.0",limitSize:"1.0.0"}});var Jc=R("getStorageInfoSync",{implement(){return I("getStorageInfoSync")}}),$s=["string","number","boolean","object",""];function Hs(e){let t=Object.prototype.toString.call(e).split(" ")[1].split("]")[0].toLocaleLowerCase();return $s.includes(t)?t:""}function Ks(e,t){try{switch(t){case"string":return e;case"object":return JSON.parse(e);case"number":return parseFloat(e);case"boolean":return e==="true";default:return""}}catch{return""}}function qs(e,t){try{switch(t){case"string":case"number":case"boolean":return`${e}`;case"object":return JSON.stringify(e);default:return""}}catch{return""}}v();U();G();var Gs=R("showKeyboard",{paramsSchema:c.tuple(c.object({defaultValue:c.string().optional().default(""),multiple:c.boolean().optional().default(!1),maxLength:c.unknown().optional().default(1e5)})),implement(e){let t=Math.floor(Number(e.maxLength)??1e5),{defaultValue:r}=e;r&&t&&(r=r.slice(0,t)),I("showKeyboardSync",{...e,defaultValue:r,maxLength:t})}});g("keyboard.showKeyboard",{version:"1.0.0",properties:{params:{defaultValue:"1.0.0",multiple:"1.0.0",confirmHold:"1.0.0",confirmType:"1.0.0",maxLength:"1.0.0"}},success:{errMsg:"1.0.0"}});var zs=R("updateKeyboard",{paramsSchema:c.tuple(c.object({value:c.string()})),implement(e){I("updateKeyboardSync",e)}});g("keyboard.updateKeyboard",{version:"1.0.0",properties:{params:{value:"1.0.0"}}});var Ws=R("hideKeyboard",{implement(){I("hideKeyboardSync")}});g("keyboard.hideKeyboard",{version:"1.0.0"});var Jt=w();Jt.registerCommand("KeyboardSDK.showKeyboard",Gs);Jt.registerCommand("KeyboardSDK.updateKeyboard",zs);Jt.registerCommand("KeyboardSDK.hideKeyboard",Ws);v();G();ee();var ce=w(),Ys=S("levelFinished",{paramsSchema:c.tuple(c.string(),c.object({result:c.boolean(),duration:c.number()})),implement:async(e,t)=>{let{result:r,duration:n}=t,s=[];s.push(D.tracker("LevelFinished",{levelId:e,result:r,duration:n})),s.push(D.reporter({event:"COMPLETE_GAME_LEVEL"})),await Promise.all(s)}}),Qs=S("taskFinished",{paramsSchema:c.tuple(c.string(),c.object({duration:c.number()})),implement:async(e,t)=>{let{duration:r}=t;return await D.reportToNative({event:"TaskFinished",params:{duration:r,taskId:e}})}}),Xs=S("levelUpgrade",{paramsSchema:c.tuple(c.string(),c.string()),implement:async(e,t)=>{let r=[];r.push(D.reportToNative({event:"LevelUpgrade",params:{name:t,levelId:e}})),await Promise.all(r)}}),Zs=S("onHistoryUserLevel",{paramsSchema:c.tuple(c.number()),implement:async e=>await D.reportToNative({event:"HistoryUserLevel",params:{level:e}})}),eo=S("onHistoryUserScore",{paramsSchema:c.tuple(c.number()),implement:async e=>await D.reportToNative({event:"HistoryUserScore",params:{score:e}})}),to=S("taskEvent",{paramsSchema:c.tuple(c.string(),c.object({tools:c.array(c.object({id:c.string(),name:c.string(),count:c.number(),description:c.string().optional(),price:c.object({amount:c.number(),unit:c.string()}).optional()})).optional(),awards:c.array(c.object({id:c.string(),name:c.string()})).optional()})),implement:async(e,t)=>{let r=[];r.push(D.reportToNative({event:"TaskEvent",params:{taskId:e,...t}})),(t.tools?.length??!1)&&(r.push(D.reporter({event:"USE_GAME_ITEM"})),r.push(D.reportToNative({event:"UseGameItem",params:{taskId:e,...t}}))),await Promise.all(r)}});ce.registerCommand("TaskTrackerSDK.levelFinished",Ys);ce.registerCommand("TaskTrackerSDK.taskFinished",Qs);ce.registerCommand("TaskTrackerSDK.levelUpgrade",Xs);ce.registerCommand("TaskTrackerSDK.historyUserLevel",Zs);ce.registerCommand("TaskTrackerSDK.historyUserScore",eo);ce.registerCommand("TaskTrackerSDK.taskEvent",to);g("TaskTrackerSDK.onLevelFinished",{version:"1.0.0",properties:{levelId:"1.0.0",params:{result:"1.0.0",duration:"1.0.0"}}});g("TaskTrackerSDK.onTaskFinished",{version:"1.0.0",properties:{taskId:"1.0.0",duration:"1.0.0"}});g("TaskTrackerSDK.onLevelUpgrade",{version:"1.0.0",properties:{levelId:"1.0.0",name:"1.0.0"}});g("TaskTrackerSDK.onHistoryUserLevel",{version:"1.0.0",properties:{level:"1.0.0"}});g("TaskTrackerSDK.onHistoryUserScore",{version:"1.0.0",properties:{score:"1.0.0"}});g("TaskTrackerSDK.onTaskEvent",{version:"1.0.0",properties:{taskId:"1.0.0",params:{tools:{id:"1.0.0",name:"1.0.0",count:"1.0.0",description:"1.0.0",price:{amount:"1.0.0",unit:"1.0.0"}},awards:{id:"1.0.0",name:"1.0.0"}}}});B();U();G();v();X();g("login",{version:"1.0.0",properties:{force:"1.0.0"},success:{errMsg:"1.0.0",code:"1.0.0",token:"1.0.0",isLogin:"1.0.0"}});g("checkSession",{version:"1.0.0",success:{errMsg:"1.0.0"}});var ro=S("login",{async implement(){let{data:{isLogin:e}}=await O("checkLoginAsync");if(e)return{isLogin:!0,token:y.hostUserInfo?.token};V("onLoginStateChange",({isLogin:i,token:a,uuid:d})=>{d==r&&s({isLogin:i,token:a})});let t=I("loginSync"),{data:{uuid:r}}=t;if(!r)throw se({code:-1,msg:"login failed"});let{promise:n,resolve:s}=new Y,o=await n;return y.onEnvConfigChanged({hostUserInfo:o}),H.emit("onLoginComplete",o),o}}),no=S("checkSession",{async implement(){let{data:{isLogin:e}}=await O("checkLoginAsync");return{isLogin:e}}}),un=w();un.registerCommand("API.login",ro);un.registerCommand("API.checkSession",no);v();G();var Xe=class{constructor(t){this.track=t;this.adBreakIsShowing=!1;this.reportPageJumpOut=()=>{this.track("AdBreakJumpOut",{context:"AdsActionDetection"})};this.reportPageHide=()=>{this.track("AdBreakHide",{context:"AdsActionDetection"})};window.addEventListener("visibilitychange",()=>{document.hidden&&this.adBreakIsShowing&&this.reportPageHide()}),window.addEventListener("beforeunload",r=>{this.adBreakIsShowing&&this.reportPageJumpOut()})}};var mn="jolibox-sdk-ads-callbreak-timestamps",Ze=class{constructor(t,r){this.checkNetwork=t;this.maxAllowedAdsForTime=8;this.bannedForTimeThreshold=6e4;this.bannedReleaseTime=6e4;this.isBanningForTime=!1;this.releaseBannedForTimeTimeout=null;this.maxAllowedAdsForSession=200;this.bannedForSessionThreshold=6e5;this.isBanningForSession=!1;this.initialThreshold=2e3;this._callAdsTimestampsForTime=[];this.callAdsTimestampsForSession=[];this.initTimestamp=0;this.initCallAdsTimestampsForTime=()=>{try{let t=JSON.parse(window.localStorage.getItem(mn)??"[]");Array.isArray(t)?this._callAdsTimestampsForTime=t:this._callAdsTimestampsForTime=[]}catch{this._callAdsTimestampsForTime=[]}};this.setReleaseBannedForTime=()=>{this.releaseBannedForTimeTimeout&&(window.clearTimeout(this.releaseBannedForTimeTimeout),this.releaseBannedForTimeTimeout=null),this.releaseBannedForTimeTimeout=window.setTimeout(()=>{this.isBanningForTime=!1,this.releaseBannedForTimeTimeout=null},this.bannedReleaseTime)};this.checkShouldBannedInitial=()=>{if(Date.now()-this.initTimestamp<=this.initialThreshold)return"BLOCK_INITIAL"};this.checkShouldBannedForSession=t=>{if(this.isBanningForSession)return"BANNED_FOR_SESSION";let r=Date.now();if(this.callAdsTimestampsForSession=this.callAdsTimestampsForSession.concat({timestamp:r,type:t}),this.callAdsTimestampsForSession.length!==1&&(this.callAdsTimestampsForSession.length>this.maxAllowedAdsForSession&&(this.callAdsTimestampsForSession=this.callAdsTimestampsForSession.slice(-this.maxAllowedAdsForSession)),this.callAdsTimestampsForSession.length===this.maxAllowedAdsForSession&&r-this.callAdsTimestampsForSession[0].timestamp<=this.bannedForSessionThreshold))return this.isBanningForSession=!0,"BANNED_FOR_SESSION"};this.checkShouldBannedForTime=t=>{if(this.isBanningForTime)return"WAITING_BANNED_RELEASE";let r=Date.now();if(this.callAdsTimestampsForTime=this.callAdsTimestampsForTime.concat({timestamp:r,type:t}),this.callAdsTimestampsForTime.length!==1&&(this.callAdsTimestampsForTime.length>this.maxAllowedAdsForTime&&(this.callAdsTimestampsForTime=this.callAdsTimestampsForTime.slice(-this.maxAllowedAdsForTime)),this.callAdsTimestampsForTime.length===this.maxAllowedAdsForTime&&r-this.callAdsTimestampsForTime[0].timestamp<=this.bannedForTimeThreshold))return this.isBanningForTime=!0,this.setReleaseBannedForTime(),"BANNED_FOR_TIME"};this.checkAdsDisplayPermission=t=>{if(!this.checkNetwork())return"NETWORK_NOT_OK";let r=this.checkShouldBannedInitial();if(r)return r;let n=this.checkShouldBannedForSession(t);if(n)return n;let s=this.checkShouldBannedForTime(t);return s||"ALLOWED"};if(this.maxAllowedAdsForTime=r?.maxAllowedAdsForTime??8,this.bannedForTimeThreshold=r?.bannedForTimeThreshold??6e4,this.bannedReleaseTime=r?.bannedReleaseTime??6e4,this.maxAllowedAdsForSession=r?.maxAllowedAdsForSession??200,this.bannedForSessionThreshold=r?.bannedForSessionThreshold??6e5,this.initialThreshold=r?.initialThreshold??2e3,this.maxAllowedAdsForTime<=1)throw new Error("maxAllowedAdsForTime must be greater than 1");if(this.bannedForTimeThreshold<0)throw new Error("bannedForTimeThreshold must be greater than or equal to 0");if(this.bannedReleaseTime<this.bannedForTimeThreshold)throw new Error("bannedReleaseTime must be greater than or equal to bannedForTimeThreshold");if(this.initialThreshold<0)throw new Error("initialThreshold must be greater than or equal to 0");this.initCallAdsTimestampsForTime(),this.initTimestamp=Date.now()}get callAdsTimestampsForTime(){return this._callAdsTimestampsForTime}set callAdsTimestampsForTime(t){try{window.localStorage.setItem(mn,JSON.stringify(t))}catch{console.error("Failed to save timestamps")}this._callAdsTimestampsForTime=t}};B();B();var et=class{constructor(t){this.httpClient=t;this.configs=null;this.firstRun=!0;this.init()}async init(){try{this.configs=await this.httpClient.get("/api/fe-configs/js-sdk/ads-channel-config")}catch{}}shouldBypassCallingInterstitial(){let t;if(!this.configs)this.init(),t=!this.firstRun;else{let r=y.channel??"",s=this.configs[r]?.interstitialRate??1;t=Math.random()<s}return this.firstRun=!1,t}};var tt=class{constructor(t,r,n){this.track=t;this.httpClient=r;this.checkNetwork=n;this.configured=!1;this.config={};this.getGameId=()=>y.mpId;this.getTestAdsMode=()=>y.testAdsMode;this.asyncLoad=async()=>{let t="ca-pub-7171363994453626",r,n,s=window.encodeURIComponent(window.btoa(this.getGameId()??"")),o=this.getTestAdsMode()??!1;try{let i=await this.httpClient.get("/public/ads",{query:{objectId:s,testAdsMode:`${o}`}});t=i.data?.clientId,r=i.data?.channelId,n=i.data?.unitId}catch(i){console.error("Failed to fetch client info",i)}this.clientId=t,this.channelId=r,this.unitId=n};this.asyncInit=async t=>{if(typeof window>"u")return;await this.asyncLoad();let r="google-adsense",n=this.getTestAdsMode()??!1;if(!document.getElementById(r)&&this.clientId){let s=document.createElement("script");s.id=r,s.async=!0,s.crossOrigin="anonymous",s.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${this.clientId}`,n&&s.setAttribute("data-adbreak-test","on"),this.channelId&&s.setAttribute("data-ad-channel",this.channelId),document.head.appendChild(s),this.track("LoadAdsenseCompleted",null)}};this.push=(t={})=>{window.adsbygoogle.push(t)};this.adConfig=t=>{let{onReady:r,...n}=t;this.track("CallAdConfig",n),this.configured?console.warn("Ad config already set, skipping"):(this.configured=!0,this.push(t))};this.adBreak=t=>{if(!this.getGameId()){console.warn("Game ID is not set, skip calling adBreak");return}if(t.type!=="reward"&&!this.channelPolicy.shouldBypassCallingInterstitial()){t.adBreakDone?.({breakType:t.type,breakName:"skipInterstitials",breakFormat:"interstitial",breakStatus:"viewed"});return}let r=this.antiCheating.checkAdsDisplayPermission(t.type==="reward"?"reward":"interstitial");switch(r){case"NETWORK_NOT_OK":case"BANNED_FOR_SESSION":console.warn("Ads not allowed",r),t.adBreakDone?.({breakType:t.type,breakName:r,breakFormat:t.type==="reward"?"reward":"interstitial",breakStatus:"noAdPreloaded"}),this.track("PreventAdsCheating",{reason:r});return;case"BLOCK_INITIAL":case"BANNED_FOR_TIME":case"WAITING_BANNED_RELEASE":console.warn("Ads not allowed",r),t.adBreakDone?.({breakType:t.type,breakFormat:t.type==="reward"?"reward":"interstitial",breakStatus:"viewed"}),this.track("PreventAdsCheating",{reason:r});return;default:break}let n=t.type,s=t.adBreakDone,o=a=>{this.adsActionDetection.adBreakIsShowing=!1,this.track("CallAdBreakDone",{breakType:a.breakType,breakName:a.breakName??"",breakFormat:a.breakFormat,breakStatus:a.breakStatus}),s&&s(a)};if(t.adBreakDone=o,t.type==="reward"){let a=t.beforeReward,d=u=>()=>{this.track("CallShowAdFn",null),u()},l=u=>{a&&a(d(u))};t.beforeReward=l}let i;switch(n){case"preroll":i={type:n};break;case"start":case"pause":case"next":case"browse":case"reward":i={type:n,name:t.name??""};break}this.adsActionDetection.adBreakIsShowing=!0,this.track("CallAdBreak",i),this.push(t),window.JoliTesterBridge&&console.log("joli-fullscreen-ad-show")};this.adUnit=async t=>{if(this.track("CallAdUnit",{adFormat:t.adFormat?.toString()??null,fullWidthResponsive:t.fullWidthResponsive??null}),this.clientId||await this.asyncLoad(),document.querySelector("#jolibox-ads")){console.warn("Ad unit already set, skipping");return}let{el:r,slot:n,adFormat:s,fullWidthResponsive:o,style:i}=t,a;if(!r)throw new Error("targeting element is required");if(typeof r=="string"?a=document.querySelector(r):a=r,!a)throw new Error("targeting element not found");let d=n;if(d||(d=this.unitId),!d)throw new Error("slot is required");let l=typeof s=="object"&&Array.isArray(s)?s.join(", "):s,u=document.createElement("ins");if(u.className="adsbygoogle",u.id="jolibox-ads",u.style.display="block",u.setAttribute("data-ad-client",this.clientId),u.setAttribute("data-ad-slot",d),l&&u.setAttribute("data-ad-format",l),o&&u.setAttribute("data-full-width-responsive",o),i&&u.setAttribute("style",i),this.getTestAdsMode()??!1){let m=document.createElement("div");m.style.position="absolute",m.style.top="0",m.style.left="0",m.style.width="100%",m.style.height="100%",m.style.display="flex",m.style.justifyContent="center",m.style.alignItems="center",m.style.backgroundColor="rgba(0, 0, 0, 0.5)",m.style.color="white",m.innerHTML="Test Ad",u.style.position="relative",a.appendChild(u),u.appendChild(m)}else a.appendChild(u),new MutationObserver(f=>{f.forEach(b=>{if(b.type==="attributes"&&b.attributeName==="data-ad-status"){let _=u.getAttribute("data-ad-status");this.track("AdSenseUnitStatusChanged",{status:_??"null"})}})}).observe(u,{attributes:!0,attributeFilter:["data-ad-status"]}),this.push({})};this.antiCheating=new Ze(n),this.adsActionDetection=new Xe(this.track),this.channelPolicy=new et(r)}init(t){this.track("CallAdsInit",null),!(typeof window>"u")&&(this.config=t??{},window.adsbygoogle=window.adsbygoogle||[],this.asyncInit(t))}};ee();_e();U();var rt=w(),so=()=>{let{data:e}=I("getNetworkStatusSync");return!!e?.isConnected},nt=new tt(M,{get:(e,t)=>K(e,{method:"GET",responseType:"json",appendHostCookie:!0,...t}).then(r=>r.response.data)},so),oo=R("adInit",{implement:e=>{nt.init(e)}}),io=R("adConfig",{implement:e=>{nt.adConfig(e)}}),ao=R("adBreak",{implement:e=>{nt.adBreak(e)}}),co=R("adUnit",{implement:e=>{nt.adUnit(e)}});rt.registerCommand("AdsSDK.init",oo);rt.registerCommand("AdsSDK.adConfig",io);rt.registerCommand("AdsSDK.adBreak",ao);rt.registerCommand("AdsSDK.adUnit",co);g("AdsSDK.init",{version:"1.0.0"});g("AdsSDK.adConfig",{version:"1.0.0"});g("AdsSDK.adBreak",{version:"1.0.0"});g("AdsSDK.adUnit",{version:"1.0.0"});ee();Yr();