UNPKG

65.2 kBJavaScriptView Raw
1import {parseUrl}from'peeler-js/es/parseUrl';import {Logger}from'peeler-js/es/logger';import {getUA}from'peeler-js/es/getUA';import Request from'ajax-maker';import {storage}from'peeler-js/es/storage';import {isType}from'peeler-js/es/isType';import {Base64}from'js-base64';import require$$0 from'crypto';const logger = new Logger({
2 debug: true,
3 logLevel: 'detail',
4 logPrefix: getPrefix()
5});
6function getPrefix(scope, suffix) {
7 let str = 'Mixin-JSBridge';
8 if (scope && suffix) {
9 str = `${str} ${scope}-${suffix}`;
10 }
11 else if (scope) {
12 str = `${str} ${scope}`;
13 }
14 else if (suffix) {
15 str = `${str} ${suffix}`;
16 }
17 return str;
18}
19function getLogger(scope) {
20 return function (suffix) {
21 return logger.setPrefix(getPrefix(scope, suffix));
22 };
23}function env() {
24 var _a;
25 const ua = (_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent;
26 return Object.assign({}, getUA(ua));
27}function parseError(err) {
28 var _a, _b, _c;
29 const name = err === null || err === void 0 ? void 0 : err.name;
30 const message = (_c = (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : (_b = err === null || err === void 0 ? void 0 : err.toString) === null || _b === void 0 ? void 0 : _b.call(err)) !== null && _c !== void 0 ? _c : err;
31 const stack = err === null || err === void 0 ? void 0 : err.stack;
32 return {
33 name,
34 message,
35 stack
36 };
37}const { request, setting } = new Request({
38 codeMap: {
39 suc_code: 200,
40 err_code: -1
41 },
42 codeField: 'code'
43});let storageType = 'localStorage';
44const logger$1 = getLogger('storage');
45const store = {
46 get: (key) => storage.get(key, storageType),
47 set: (key, val) => {
48 try {
49 if (typeof val !== 'string') {
50 val = JSON.stringify(val);
51 }
52 return storage.set(key, val, storageType);
53 }
54 catch (err) {
55 logger$1().warn('set storage error', err);
56 return false;
57 }
58 },
59 clear: (key) => storage.clear(key, storageType)
60};function isObject(val) {
61 return isType('object')(val);
62}function uuid() {
63 let d = new Date().getTime();
64 const uuid = 'xxxxxxxx-yyyy-yyyy-yyyy-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
65 const r = (d + Math.random() * 16) % 16 | 0;
66 d = Math.floor(d / 16);
67 return (c === 'x'
68 ? r
69 : (r & 0x7) | 0x8).toString(16);
70 });
71 return uuid;
72}const logger$2 = getLogger('messager');
73function messager(type) {
74 var _a, _b, _c, _d, _e, _f, _g;
75 const envInfo = env();
76 const handler = envInfo.isIOS
77 ? type === 'getContext'
78 ? () => JSON.parse(prompt('MixinContext.getContext()'))
79 : (_c = (_b = (_a = window === null || window === void 0 ? void 0 : window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b[type]) === null || _c === void 0 ? void 0 : _c.postMessage.bind((_e = (_d = window === null || window === void 0 ? void 0 : window.webkit) === null || _d === void 0 ? void 0 : _d.messageHandlers) === null || _e === void 0 ? void 0 : _e[type])
80 : (_g = (_f = window === null || window === void 0 ? void 0 : window.MixinContext) === null || _f === void 0 ? void 0 : _f[type]) === null || _g === void 0 ? void 0 : _g.bind(window === null || window === void 0 ? void 0 : window.MixinContext);
81 return handler !== null && handler !== void 0 ? handler : (() => logger$2().warn(`The messager "${type}" is not support yet!`));
82}var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
83
84function createCommonjsModule(fn) {
85 var module = { exports: {} };
86 return fn(module, module.exports), module.exports;
87}
88
89function commonjsRequire (target) {
90 throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
91}var core = createCommonjsModule(function (module, exports) {
92(function (root, factory) {
93 {
94 // CommonJS
95 module.exports = exports = factory();
96 }
97}(commonjsGlobal, function () {
98
99 /*globals window, global, require*/
100
101 /**
102 * CryptoJS core components.
103 */
104 var CryptoJS = CryptoJS || (function (Math, undefined$1) {
105
106 var crypto;
107
108 // Native crypto from window (Browser)
109 if (typeof window !== 'undefined' && window.crypto) {
110 crypto = window.crypto;
111 }
112
113 // Native (experimental IE 11) crypto from window (Browser)
114 if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
115 crypto = window.msCrypto;
116 }
117
118 // Native crypto from global (NodeJS)
119 if (!crypto && typeof commonjsGlobal !== 'undefined' && commonjsGlobal.crypto) {
120 crypto = commonjsGlobal.crypto;
121 }
122
123 // Native crypto import via require (NodeJS)
124 if (!crypto && typeof commonjsRequire === 'function') {
125 try {
126 crypto = require$$0;
127 } catch (err) {}
128 }
129
130 /*
131 * Cryptographically secure pseudorandom number generator
132 *
133 * As Math.random() is cryptographically not safe to use
134 */
135 var cryptoSecureRandomInt = function () {
136 if (crypto) {
137 // Use getRandomValues method (Browser)
138 if (typeof crypto.getRandomValues === 'function') {
139 try {
140 return crypto.getRandomValues(new Uint32Array(1))[0];
141 } catch (err) {}
142 }
143
144 // Use randomBytes method (NodeJS)
145 if (typeof crypto.randomBytes === 'function') {
146 try {
147 return crypto.randomBytes(4).readInt32LE();
148 } catch (err) {}
149 }
150 }
151
152 throw new Error('Native crypto module could not be used to get secure random number.');
153 };
154
155 /*
156 * Local polyfill of Object.create
157
158 */
159 var create = Object.create || (function () {
160 function F() {}
161
162 return function (obj) {
163 var subtype;
164
165 F.prototype = obj;
166
167 subtype = new F();
168
169 F.prototype = null;
170
171 return subtype;
172 };
173 }());
174
175 /**
176 * CryptoJS namespace.
177 */
178 var C = {};
179
180 /**
181 * Library namespace.
182 */
183 var C_lib = C.lib = {};
184
185 /**
186 * Base object for prototypal inheritance.
187 */
188 var Base = C_lib.Base = (function () {
189
190
191 return {
192 /**
193 * Creates a new object that inherits from this object.
194 *
195 * @param {Object} overrides Properties to copy into the new object.
196 *
197 * @return {Object} The new object.
198 *
199 * @static
200 *
201 * @example
202 *
203 * var MyType = CryptoJS.lib.Base.extend({
204 * field: 'value',
205 *
206 * method: function () {
207 * }
208 * });
209 */
210 extend: function (overrides) {
211 // Spawn
212 var subtype = create(this);
213
214 // Augment
215 if (overrides) {
216 subtype.mixIn(overrides);
217 }
218
219 // Create default initializer
220 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
221 subtype.init = function () {
222 subtype.$super.init.apply(this, arguments);
223 };
224 }
225
226 // Initializer's prototype is the subtype object
227 subtype.init.prototype = subtype;
228
229 // Reference supertype
230 subtype.$super = this;
231
232 return subtype;
233 },
234
235 /**
236 * Extends this object and runs the init method.
237 * Arguments to create() will be passed to init().
238 *
239 * @return {Object} The new object.
240 *
241 * @static
242 *
243 * @example
244 *
245 * var instance = MyType.create();
246 */
247 create: function () {
248 var instance = this.extend();
249 instance.init.apply(instance, arguments);
250
251 return instance;
252 },
253
254 /**
255 * Initializes a newly created object.
256 * Override this method to add some logic when your objects are created.
257 *
258 * @example
259 *
260 * var MyType = CryptoJS.lib.Base.extend({
261 * init: function () {
262 * // ...
263 * }
264 * });
265 */
266 init: function () {
267 },
268
269 /**
270 * Copies properties into this object.
271 *
272 * @param {Object} properties The properties to mix in.
273 *
274 * @example
275 *
276 * MyType.mixIn({
277 * field: 'value'
278 * });
279 */
280 mixIn: function (properties) {
281 for (var propertyName in properties) {
282 if (properties.hasOwnProperty(propertyName)) {
283 this[propertyName] = properties[propertyName];
284 }
285 }
286
287 // IE won't copy toString using the loop above
288 if (properties.hasOwnProperty('toString')) {
289 this.toString = properties.toString;
290 }
291 },
292
293 /**
294 * Creates a copy of this object.
295 *
296 * @return {Object} The clone.
297 *
298 * @example
299 *
300 * var clone = instance.clone();
301 */
302 clone: function () {
303 return this.init.prototype.extend(this);
304 }
305 };
306 }());
307
308 /**
309 * An array of 32-bit words.
310 *
311 * @property {Array} words The array of 32-bit words.
312 * @property {number} sigBytes The number of significant bytes in this word array.
313 */
314 var WordArray = C_lib.WordArray = Base.extend({
315 /**
316 * Initializes a newly created word array.
317 *
318 * @param {Array} words (Optional) An array of 32-bit words.
319 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
320 *
321 * @example
322 *
323 * var wordArray = CryptoJS.lib.WordArray.create();
324 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
325 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
326 */
327 init: function (words, sigBytes) {
328 words = this.words = words || [];
329
330 if (sigBytes != undefined$1) {
331 this.sigBytes = sigBytes;
332 } else {
333 this.sigBytes = words.length * 4;
334 }
335 },
336
337 /**
338 * Converts this word array to a string.
339 *
340 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
341 *
342 * @return {string} The stringified word array.
343 *
344 * @example
345 *
346 * var string = wordArray + '';
347 * var string = wordArray.toString();
348 * var string = wordArray.toString(CryptoJS.enc.Utf8);
349 */
350 toString: function (encoder) {
351 return (encoder || Hex).stringify(this);
352 },
353
354 /**
355 * Concatenates a word array to this word array.
356 *
357 * @param {WordArray} wordArray The word array to append.
358 *
359 * @return {WordArray} This word array.
360 *
361 * @example
362 *
363 * wordArray1.concat(wordArray2);
364 */
365 concat: function (wordArray) {
366 // Shortcuts
367 var thisWords = this.words;
368 var thatWords = wordArray.words;
369 var thisSigBytes = this.sigBytes;
370 var thatSigBytes = wordArray.sigBytes;
371
372 // Clamp excess bits
373 this.clamp();
374
375 // Concat
376 if (thisSigBytes % 4) {
377 // Copy one byte at a time
378 for (var i = 0; i < thatSigBytes; i++) {
379 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
380 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
381 }
382 } else {
383 // Copy one word at a time
384 for (var i = 0; i < thatSigBytes; i += 4) {
385 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
386 }
387 }
388 this.sigBytes += thatSigBytes;
389
390 // Chainable
391 return this;
392 },
393
394 /**
395 * Removes insignificant bits.
396 *
397 * @example
398 *
399 * wordArray.clamp();
400 */
401 clamp: function () {
402 // Shortcuts
403 var words = this.words;
404 var sigBytes = this.sigBytes;
405
406 // Clamp
407 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
408 words.length = Math.ceil(sigBytes / 4);
409 },
410
411 /**
412 * Creates a copy of this word array.
413 *
414 * @return {WordArray} The clone.
415 *
416 * @example
417 *
418 * var clone = wordArray.clone();
419 */
420 clone: function () {
421 var clone = Base.clone.call(this);
422 clone.words = this.words.slice(0);
423
424 return clone;
425 },
426
427 /**
428 * Creates a word array filled with random bytes.
429 *
430 * @param {number} nBytes The number of random bytes to generate.
431 *
432 * @return {WordArray} The random word array.
433 *
434 * @static
435 *
436 * @example
437 *
438 * var wordArray = CryptoJS.lib.WordArray.random(16);
439 */
440 random: function (nBytes) {
441 var words = [];
442
443 for (var i = 0; i < nBytes; i += 4) {
444 words.push(cryptoSecureRandomInt());
445 }
446
447 return new WordArray.init(words, nBytes);
448 }
449 });
450
451 /**
452 * Encoder namespace.
453 */
454 var C_enc = C.enc = {};
455
456 /**
457 * Hex encoding strategy.
458 */
459 var Hex = C_enc.Hex = {
460 /**
461 * Converts a word array to a hex string.
462 *
463 * @param {WordArray} wordArray The word array.
464 *
465 * @return {string} The hex string.
466 *
467 * @static
468 *
469 * @example
470 *
471 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
472 */
473 stringify: function (wordArray) {
474 // Shortcuts
475 var words = wordArray.words;
476 var sigBytes = wordArray.sigBytes;
477
478 // Convert
479 var hexChars = [];
480 for (var i = 0; i < sigBytes; i++) {
481 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
482 hexChars.push((bite >>> 4).toString(16));
483 hexChars.push((bite & 0x0f).toString(16));
484 }
485
486 return hexChars.join('');
487 },
488
489 /**
490 * Converts a hex string to a word array.
491 *
492 * @param {string} hexStr The hex string.
493 *
494 * @return {WordArray} The word array.
495 *
496 * @static
497 *
498 * @example
499 *
500 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
501 */
502 parse: function (hexStr) {
503 // Shortcut
504 var hexStrLength = hexStr.length;
505
506 // Convert
507 var words = [];
508 for (var i = 0; i < hexStrLength; i += 2) {
509 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
510 }
511
512 return new WordArray.init(words, hexStrLength / 2);
513 }
514 };
515
516 /**
517 * Latin1 encoding strategy.
518 */
519 var Latin1 = C_enc.Latin1 = {
520 /**
521 * Converts a word array to a Latin1 string.
522 *
523 * @param {WordArray} wordArray The word array.
524 *
525 * @return {string} The Latin1 string.
526 *
527 * @static
528 *
529 * @example
530 *
531 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
532 */
533 stringify: function (wordArray) {
534 // Shortcuts
535 var words = wordArray.words;
536 var sigBytes = wordArray.sigBytes;
537
538 // Convert
539 var latin1Chars = [];
540 for (var i = 0; i < sigBytes; i++) {
541 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
542 latin1Chars.push(String.fromCharCode(bite));
543 }
544
545 return latin1Chars.join('');
546 },
547
548 /**
549 * Converts a Latin1 string to a word array.
550 *
551 * @param {string} latin1Str The Latin1 string.
552 *
553 * @return {WordArray} The word array.
554 *
555 * @static
556 *
557 * @example
558 *
559 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
560 */
561 parse: function (latin1Str) {
562 // Shortcut
563 var latin1StrLength = latin1Str.length;
564
565 // Convert
566 var words = [];
567 for (var i = 0; i < latin1StrLength; i++) {
568 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
569 }
570
571 return new WordArray.init(words, latin1StrLength);
572 }
573 };
574
575 /**
576 * UTF-8 encoding strategy.
577 */
578 var Utf8 = C_enc.Utf8 = {
579 /**
580 * Converts a word array to a UTF-8 string.
581 *
582 * @param {WordArray} wordArray The word array.
583 *
584 * @return {string} The UTF-8 string.
585 *
586 * @static
587 *
588 * @example
589 *
590 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
591 */
592 stringify: function (wordArray) {
593 try {
594 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
595 } catch (e) {
596 throw new Error('Malformed UTF-8 data');
597 }
598 },
599
600 /**
601 * Converts a UTF-8 string to a word array.
602 *
603 * @param {string} utf8Str The UTF-8 string.
604 *
605 * @return {WordArray} The word array.
606 *
607 * @static
608 *
609 * @example
610 *
611 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
612 */
613 parse: function (utf8Str) {
614 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
615 }
616 };
617
618 /**
619 * Abstract buffered block algorithm template.
620 *
621 * The property blockSize must be implemented in a concrete subtype.
622 *
623 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
624 */
625 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
626 /**
627 * Resets this block algorithm's data buffer to its initial state.
628 *
629 * @example
630 *
631 * bufferedBlockAlgorithm.reset();
632 */
633 reset: function () {
634 // Initial values
635 this._data = new WordArray.init();
636 this._nDataBytes = 0;
637 },
638
639 /**
640 * Adds new data to this block algorithm's buffer.
641 *
642 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
643 *
644 * @example
645 *
646 * bufferedBlockAlgorithm._append('data');
647 * bufferedBlockAlgorithm._append(wordArray);
648 */
649 _append: function (data) {
650 // Convert string to WordArray, else assume WordArray already
651 if (typeof data == 'string') {
652 data = Utf8.parse(data);
653 }
654
655 // Append
656 this._data.concat(data);
657 this._nDataBytes += data.sigBytes;
658 },
659
660 /**
661 * Processes available data blocks.
662 *
663 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
664 *
665 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
666 *
667 * @return {WordArray} The processed data.
668 *
669 * @example
670 *
671 * var processedData = bufferedBlockAlgorithm._process();
672 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
673 */
674 _process: function (doFlush) {
675 var processedWords;
676
677 // Shortcuts
678 var data = this._data;
679 var dataWords = data.words;
680 var dataSigBytes = data.sigBytes;
681 var blockSize = this.blockSize;
682 var blockSizeBytes = blockSize * 4;
683
684 // Count blocks ready
685 var nBlocksReady = dataSigBytes / blockSizeBytes;
686 if (doFlush) {
687 // Round up to include partial blocks
688 nBlocksReady = Math.ceil(nBlocksReady);
689 } else {
690 // Round down to include only full blocks,
691 // less the number of blocks that must remain in the buffer
692 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
693 }
694
695 // Count words ready
696 var nWordsReady = nBlocksReady * blockSize;
697
698 // Count bytes ready
699 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
700
701 // Process blocks
702 if (nWordsReady) {
703 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
704 // Perform concrete-algorithm logic
705 this._doProcessBlock(dataWords, offset);
706 }
707
708 // Remove processed words
709 processedWords = dataWords.splice(0, nWordsReady);
710 data.sigBytes -= nBytesReady;
711 }
712
713 // Return processed words
714 return new WordArray.init(processedWords, nBytesReady);
715 },
716
717 /**
718 * Creates a copy of this object.
719 *
720 * @return {Object} The clone.
721 *
722 * @example
723 *
724 * var clone = bufferedBlockAlgorithm.clone();
725 */
726 clone: function () {
727 var clone = Base.clone.call(this);
728 clone._data = this._data.clone();
729
730 return clone;
731 },
732
733 _minBufferSize: 0
734 });
735
736 /**
737 * Abstract hasher template.
738 *
739 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
740 */
741 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
742 /**
743 * Configuration options.
744 */
745 cfg: Base.extend(),
746
747 /**
748 * Initializes a newly created hasher.
749 *
750 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
751 *
752 * @example
753 *
754 * var hasher = CryptoJS.algo.SHA256.create();
755 */
756 init: function (cfg) {
757 // Apply config defaults
758 this.cfg = this.cfg.extend(cfg);
759
760 // Set initial values
761 this.reset();
762 },
763
764 /**
765 * Resets this hasher to its initial state.
766 *
767 * @example
768 *
769 * hasher.reset();
770 */
771 reset: function () {
772 // Reset data buffer
773 BufferedBlockAlgorithm.reset.call(this);
774
775 // Perform concrete-hasher logic
776 this._doReset();
777 },
778
779 /**
780 * Updates this hasher with a message.
781 *
782 * @param {WordArray|string} messageUpdate The message to append.
783 *
784 * @return {Hasher} This hasher.
785 *
786 * @example
787 *
788 * hasher.update('message');
789 * hasher.update(wordArray);
790 */
791 update: function (messageUpdate) {
792 // Append
793 this._append(messageUpdate);
794
795 // Update the hash
796 this._process();
797
798 // Chainable
799 return this;
800 },
801
802 /**
803 * Finalizes the hash computation.
804 * Note that the finalize operation is effectively a destructive, read-once operation.
805 *
806 * @param {WordArray|string} messageUpdate (Optional) A final message update.
807 *
808 * @return {WordArray} The hash.
809 *
810 * @example
811 *
812 * var hash = hasher.finalize();
813 * var hash = hasher.finalize('message');
814 * var hash = hasher.finalize(wordArray);
815 */
816 finalize: function (messageUpdate) {
817 // Final message update
818 if (messageUpdate) {
819 this._append(messageUpdate);
820 }
821
822 // Perform concrete-hasher logic
823 var hash = this._doFinalize();
824
825 return hash;
826 },
827
828 blockSize: 512/32,
829
830 /**
831 * Creates a shortcut function to a hasher's object interface.
832 *
833 * @param {Hasher} hasher The hasher to create a helper for.
834 *
835 * @return {Function} The shortcut function.
836 *
837 * @static
838 *
839 * @example
840 *
841 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
842 */
843 _createHelper: function (hasher) {
844 return function (message, cfg) {
845 return new hasher.init(cfg).finalize(message);
846 };
847 },
848
849 /**
850 * Creates a shortcut function to the HMAC's object interface.
851 *
852 * @param {Hasher} hasher The hasher to use in this HMAC helper.
853 *
854 * @return {Function} The shortcut function.
855 *
856 * @static
857 *
858 * @example
859 *
860 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
861 */
862 _createHmacHelper: function (hasher) {
863 return function (message, key) {
864 return new C_algo.HMAC.init(hasher, key).finalize(message);
865 };
866 }
867 });
868
869 /**
870 * Algorithm namespace.
871 */
872 var C_algo = C.algo = {};
873
874 return C;
875 }(Math));
876
877
878 return CryptoJS;
879
880}));
881});var encBase64 = createCommonjsModule(function (module, exports) {
882(function (root, factory) {
883 {
884 // CommonJS
885 module.exports = exports = factory(core);
886 }
887}(commonjsGlobal, function (CryptoJS) {
888
889 (function () {
890 // Shortcuts
891 var C = CryptoJS;
892 var C_lib = C.lib;
893 var WordArray = C_lib.WordArray;
894 var C_enc = C.enc;
895
896 /**
897 * Base64 encoding strategy.
898 */
899 var Base64 = C_enc.Base64 = {
900 /**
901 * Converts a word array to a Base64 string.
902 *
903 * @param {WordArray} wordArray The word array.
904 *
905 * @return {string} The Base64 string.
906 *
907 * @static
908 *
909 * @example
910 *
911 * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
912 */
913 stringify: function (wordArray) {
914 // Shortcuts
915 var words = wordArray.words;
916 var sigBytes = wordArray.sigBytes;
917 var map = this._map;
918
919 // Clamp excess bits
920 wordArray.clamp();
921
922 // Convert
923 var base64Chars = [];
924 for (var i = 0; i < sigBytes; i += 3) {
925 var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
926 var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
927 var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
928
929 var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
930
931 for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
932 base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
933 }
934 }
935
936 // Add padding
937 var paddingChar = map.charAt(64);
938 if (paddingChar) {
939 while (base64Chars.length % 4) {
940 base64Chars.push(paddingChar);
941 }
942 }
943
944 return base64Chars.join('');
945 },
946
947 /**
948 * Converts a Base64 string to a word array.
949 *
950 * @param {string} base64Str The Base64 string.
951 *
952 * @return {WordArray} The word array.
953 *
954 * @static
955 *
956 * @example
957 *
958 * var wordArray = CryptoJS.enc.Base64.parse(base64String);
959 */
960 parse: function (base64Str) {
961 // Shortcuts
962 var base64StrLength = base64Str.length;
963 var map = this._map;
964 var reverseMap = this._reverseMap;
965
966 if (!reverseMap) {
967 reverseMap = this._reverseMap = [];
968 for (var j = 0; j < map.length; j++) {
969 reverseMap[map.charCodeAt(j)] = j;
970 }
971 }
972
973 // Ignore padding
974 var paddingChar = map.charAt(64);
975 if (paddingChar) {
976 var paddingIndex = base64Str.indexOf(paddingChar);
977 if (paddingIndex !== -1) {
978 base64StrLength = paddingIndex;
979 }
980 }
981
982 // Convert
983 return parseLoop(base64Str, base64StrLength, reverseMap);
984
985 },
986
987 _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
988 };
989
990 function parseLoop(base64Str, base64StrLength, reverseMap) {
991 var words = [];
992 var nBytes = 0;
993 for (var i = 0; i < base64StrLength; i++) {
994 if (i % 4) {
995 var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
996 var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
997 var bitsCombined = bits1 | bits2;
998 words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
999 nBytes++;
1000 }
1001 }
1002 return WordArray.create(words, nBytes);
1003 }
1004 }());
1005
1006
1007 return CryptoJS.enc.Base64;
1008
1009}));
1010});var sha256 = createCommonjsModule(function (module, exports) {
1011(function (root, factory) {
1012 {
1013 // CommonJS
1014 module.exports = exports = factory(core);
1015 }
1016}(commonjsGlobal, function (CryptoJS) {
1017
1018 (function (Math) {
1019 // Shortcuts
1020 var C = CryptoJS;
1021 var C_lib = C.lib;
1022 var WordArray = C_lib.WordArray;
1023 var Hasher = C_lib.Hasher;
1024 var C_algo = C.algo;
1025
1026 // Initialization and round constants tables
1027 var H = [];
1028 var K = [];
1029
1030 // Compute constants
1031 (function () {
1032 function isPrime(n) {
1033 var sqrtN = Math.sqrt(n);
1034 for (var factor = 2; factor <= sqrtN; factor++) {
1035 if (!(n % factor)) {
1036 return false;
1037 }
1038 }
1039
1040 return true;
1041 }
1042
1043 function getFractionalBits(n) {
1044 return ((n - (n | 0)) * 0x100000000) | 0;
1045 }
1046
1047 var n = 2;
1048 var nPrime = 0;
1049 while (nPrime < 64) {
1050 if (isPrime(n)) {
1051 if (nPrime < 8) {
1052 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
1053 }
1054 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
1055
1056 nPrime++;
1057 }
1058
1059 n++;
1060 }
1061 }());
1062
1063 // Reusable object
1064 var W = [];
1065
1066 /**
1067 * SHA-256 hash algorithm.
1068 */
1069 var SHA256 = C_algo.SHA256 = Hasher.extend({
1070 _doReset: function () {
1071 this._hash = new WordArray.init(H.slice(0));
1072 },
1073
1074 _doProcessBlock: function (M, offset) {
1075 // Shortcut
1076 var H = this._hash.words;
1077
1078 // Working variables
1079 var a = H[0];
1080 var b = H[1];
1081 var c = H[2];
1082 var d = H[3];
1083 var e = H[4];
1084 var f = H[5];
1085 var g = H[6];
1086 var h = H[7];
1087
1088 // Computation
1089 for (var i = 0; i < 64; i++) {
1090 if (i < 16) {
1091 W[i] = M[offset + i] | 0;
1092 } else {
1093 var gamma0x = W[i - 15];
1094 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
1095 ((gamma0x << 14) | (gamma0x >>> 18)) ^
1096 (gamma0x >>> 3);
1097
1098 var gamma1x = W[i - 2];
1099 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
1100 ((gamma1x << 13) | (gamma1x >>> 19)) ^
1101 (gamma1x >>> 10);
1102
1103 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
1104 }
1105
1106 var ch = (e & f) ^ (~e & g);
1107 var maj = (a & b) ^ (a & c) ^ (b & c);
1108
1109 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
1110 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
1111
1112 var t1 = h + sigma1 + ch + K[i] + W[i];
1113 var t2 = sigma0 + maj;
1114
1115 h = g;
1116 g = f;
1117 f = e;
1118 e = (d + t1) | 0;
1119 d = c;
1120 c = b;
1121 b = a;
1122 a = (t1 + t2) | 0;
1123 }
1124
1125 // Intermediate hash value
1126 H[0] = (H[0] + a) | 0;
1127 H[1] = (H[1] + b) | 0;
1128 H[2] = (H[2] + c) | 0;
1129 H[3] = (H[3] + d) | 0;
1130 H[4] = (H[4] + e) | 0;
1131 H[5] = (H[5] + f) | 0;
1132 H[6] = (H[6] + g) | 0;
1133 H[7] = (H[7] + h) | 0;
1134 },
1135
1136 _doFinalize: function () {
1137 // Shortcuts
1138 var data = this._data;
1139 var dataWords = data.words;
1140
1141 var nBitsTotal = this._nDataBytes * 8;
1142 var nBitsLeft = data.sigBytes * 8;
1143
1144 // Add padding
1145 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
1146 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
1147 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
1148 data.sigBytes = dataWords.length * 4;
1149
1150 // Hash final blocks
1151 this._process();
1152
1153 // Return final computed hash
1154 return this._hash;
1155 },
1156
1157 clone: function () {
1158 var clone = Hasher.clone.call(this);
1159 clone._hash = this._hash.clone();
1160
1161 return clone;
1162 }
1163 });
1164
1165 /**
1166 * Shortcut function to the hasher's object interface.
1167 *
1168 * @param {WordArray|string} message The message to hash.
1169 *
1170 * @return {WordArray} The hash.
1171 *
1172 * @static
1173 *
1174 * @example
1175 *
1176 * var hash = CryptoJS.SHA256('message');
1177 * var hash = CryptoJS.SHA256(wordArray);
1178 */
1179 C.SHA256 = Hasher._createHelper(SHA256);
1180
1181 /**
1182 * Shortcut function to the HMAC's object interface.
1183 *
1184 * @param {WordArray|string} message The message to hash.
1185 * @param {WordArray|string} key The secret key.
1186 *
1187 * @return {WordArray} The HMAC.
1188 *
1189 * @static
1190 *
1191 * @example
1192 *
1193 * var hmac = CryptoJS.HmacSHA256(message, key);
1194 */
1195 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
1196 }(Math));
1197
1198
1199 return CryptoJS.SHA256;
1200
1201}));
1202});const AUTHSCOPE = {
1203 phone: 'PHONE:READ',
1204 profile: 'PROFILE:READ',
1205 contacts: 'CONTACTS:READ',
1206 assets: 'ASSETS:READ',
1207 snapshots: 'SNAPSHOTS:READ',
1208 messages: 'MESSAGES:REPRESENT'
1209};
1210function base64URLEncode(str) {
1211 return str
1212 .replace(/\+/g, '-')
1213 .replace(/\//g, '_')
1214 .replace(/=/g, '');
1215}
1216function generateRandomString(len) {
1217 let text = '';
1218 const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1219 for (let i = 0; i < len; i++) {
1220 text += possible.charAt(Math.floor(Math.random() * possible.length));
1221 }
1222 return text;
1223}
1224function getAccessCode(params) {
1225 // eslint-disable-next-line prefer-const
1226 let { client_id, oauth_url = 'https://mixin.one/oauth/authorize', redirect_url = window.location.href, state, auth = {}, code_challenge = true } = params;
1227 const randomCode = generateRandomString(32);
1228 const verifier = base64URLEncode(Base64.encode(randomCode));
1229 let challenge = base64URLEncode(sha256(randomCode).toString(encBase64));
1230 verifier && store.set('$_mixin-code-verifier', verifier);
1231 let SCOPESTR = '';
1232 Object.keys(auth).forEach(scope => {
1233 if (!auth[scope])
1234 return;
1235 const scopeValue = AUTHSCOPE[scope];
1236 if (!SCOPESTR)
1237 SCOPESTR = scopeValue;
1238 else
1239 SCOPESTR += `+${scopeValue}`;
1240 });
1241 client_id = client_id ? `&client_id=${client_id}` : '';
1242 redirect_url = redirect_url ? `&redirect_url=${encodeURIComponent(redirect_url)}` : '';
1243 SCOPESTR = SCOPESTR ? `&scope=${SCOPESTR}` : '';
1244 challenge = (code_challenge && challenge) ? `&code_challenge=${challenge}` : '';
1245 let url = `${oauth_url}/?response_type=code${client_id}${redirect_url}${SCOPESTR}${challenge}`;
1246 if (state) {
1247 const str = encodeURIComponent(state);
1248 url += `&state=${str}`;
1249 }
1250 window.location.href = url;
1251}
1252function getAccessToken(params) {
1253 const data = Object.assign({}, params);
1254 return request({
1255 url: 'https://mixin-api.zeromesh.net/oauth/token',
1256 method: 'POST',
1257 data,
1258 withCredentials: false
1259 })
1260 .then(res => res.data.access_token);
1261}/*! *****************************************************************************
1262Copyright (c) Microsoft Corporation.
1263
1264Permission to use, copy, modify, and/or distribute this software for any
1265purpose with or without fee is hereby granted.
1266
1267THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1268REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1269AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1270INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1271LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1272OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1273PERFORMANCE OF THIS SOFTWARE.
1274***************************************************************************** */
1275
1276function __rest(s, e) {
1277 var t = {};
1278 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1279 t[p] = s[p];
1280 if (s != null && typeof Object.getOwnPropertySymbols === "function")
1281 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1282 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1283 t[p[i]] = s[p[i]];
1284 }
1285 return t;
1286}const logger$3 = getLogger('scheme');
1287const SCHEME = {
1288 prefix: 'mixin',
1289 loadScheme: function (url, open) {
1290 if (!url) {
1291 logger$3('loadScheme').error('The URL cannot be a falsy value!');
1292 return;
1293 }
1294 if (open) {
1295 window.open(url);
1296 }
1297 else {
1298 window.location.href = url;
1299 }
1300 return url;
1301 },
1302 getQuery: function (query) {
1303 if (!query) {
1304 return '';
1305 }
1306 let res = '';
1307 for (const k in query) {
1308 const val = query[k];
1309 if (val === null || val === undefined)
1310 continue;
1311 res += `&${k}=${val}`;
1312 }
1313 return res.replace(/^&?/, '?');
1314 },
1315 pay: function (params) {
1316 const _params = this.getQuery(params);
1317 const _url = `${this.prefix}://pay${_params}`;
1318 logger$3('pay').log(_url);
1319 return this.loadScheme(_url);
1320 },
1321 transfer: function (recipient) {
1322 const _url = `${this.prefix}://transfer/${recipient}`;
1323 logger$3('transfer').log(_url);
1324 return this.loadScheme(_url);
1325 },
1326 snapshots: function (params) {
1327 const { trace_id, snapshot_id } = params;
1328 if (!trace_id && !snapshot_id) {
1329 logger$3('snapshots').error('Must contain "trace_id" or "snapshot_id"!');
1330 return;
1331 }
1332 const _url = `${this.prefix}://snapshots${trace_id ? `?trace=${trace_id}` : `/${snapshot_id}`}`;
1333 logger$3('snapshots').log(_url);
1334 return this.loadScheme(_url);
1335 },
1336 withdrawal: function (params) {
1337 const _params = this.getQuery(params);
1338 const _url = `${this.prefix}://withdrawal${_params}`;
1339 logger$3('withdrawal').log(_url);
1340 return this.loadScheme(_url);
1341 },
1342 address: function (params) {
1343 const _params = this.getQuery(params);
1344 const _url = `${this.prefix}://address${_params}`;
1345 logger$3('address').log(_url);
1346 return this.loadScheme(_url);
1347 },
1348 send: function (params) {
1349 const data = encodeURIComponent(Base64.encode(typeof params.data === 'string' ? params.data : JSON.stringify(params.data)));
1350 const _params = this.getQuery(Object.assign(Object.assign({}, params), { data }));
1351 const _url = `${this.prefix}://send${_params}`;
1352 logger$3('send').log(_url);
1353 return this.loadScheme(_url, true);
1354 },
1355 users: function (user_id) {
1356 const _url = `${this.prefix}://users/${user_id}`;
1357 logger$3('users').log(_url);
1358 return this.loadScheme(_url);
1359 },
1360 apps: function (app_id, params) {
1361 const _params = this.getQuery(params);
1362 const _url = `${this.prefix}://apps/${app_id}${_params}`;
1363 logger$3('apps').log(_url);
1364 return this.loadScheme(_url);
1365 },
1366 conversations: function (conversation_id) {
1367 const _url = `${this.prefix}://conversations/${conversation_id}`;
1368 logger$3('conversations').log(_url);
1369 return this.loadScheme(_url);
1370 }
1371};
1372var scheme = {
1373 prefix: SCHEME.prefix,
1374 pay: function (params) {
1375 if (!params.recipient || !params.asset || !params.amount) {
1376 logger$3('pay').error('The "recipient", "asset" and "amount" is required!');
1377 return;
1378 }
1379 try {
1380 if (!params.trace)
1381 params.trace = uuid();
1382 if (params.memo) {
1383 if (isObject(params.memo)) {
1384 params.memo = JSON.stringify(params.memo);
1385 }
1386 params.memo = Base64.encode(params.memo);
1387 if (params.memo.length > 140) {
1388 logger$3('pay').warn('The memo max length is 140!');
1389 }
1390 }
1391 return {
1392 url: SCHEME.pay(params),
1393 params
1394 };
1395 }
1396 catch (err) {
1397 logger$3('pay').error(err);
1398 }
1399 },
1400 transfer: function (recipient) {
1401 if (!recipient) {
1402 logger$3('transfer').error('The "recipient" is required!');
1403 return;
1404 }
1405 try {
1406 return SCHEME.transfer(recipient);
1407 }
1408 catch (err) {
1409 logger$3('transfer').error(err);
1410 }
1411 },
1412 snapshot: function (params) {
1413 try {
1414 return SCHEME.snapshots(params);
1415 }
1416 catch (err) {
1417 logger$3('snapshot').error(err);
1418 }
1419 },
1420 withdrawal: function (params) {
1421 try {
1422 if (!params.trace)
1423 params.trace = uuid();
1424 if (params.memo) {
1425 if (isObject(params.memo)) {
1426 params.memo = JSON.stringify(params.memo);
1427 }
1428 params.memo = Base64.encode(params.memo);
1429 if (params.memo.length > 140) {
1430 logger$3('withdrawal').warn('The memo max length is 140!');
1431 }
1432 }
1433 return {
1434 url: SCHEME.withdrawal(params),
1435 params
1436 };
1437 }
1438 catch (err) {
1439 logger$3('withdrawal').error(err);
1440 }
1441 },
1442 addWithdrawalAddress: function (params) {
1443 if (!params.asset || !params.label || !params.destination) {
1444 logger$3('addWithdrawalAddress').error('The "asset", "label" and "destination" is required!');
1445 return;
1446 }
1447 try {
1448 return SCHEME.address(params);
1449 }
1450 catch (err) {
1451 logger$3('addWithdrawalAddress').error(err);
1452 }
1453 },
1454 delWithdrawalAddress: function (params) {
1455 if (!params.asset || !params.address) {
1456 logger$3('delWithdrawalAddress').error('The "asset" and "address" is required!');
1457 return;
1458 }
1459 try {
1460 return SCHEME.address(Object.assign(Object.assign({}, params), { action: 'delete' }));
1461 }
1462 catch (err) {
1463 logger$3('delWithdrawalAddress').error(err);
1464 }
1465 },
1466 shareText: function (txt) {
1467 if (!txt) {
1468 logger$3('shareText').error('The share text is required!');
1469 return;
1470 }
1471 try {
1472 return SCHEME.send({
1473 category: 'text',
1474 data: txt
1475 });
1476 }
1477 catch (err) {
1478 logger$3('shareText').error(err);
1479 }
1480 },
1481 shareImage: function (url) {
1482 if (!url) {
1483 logger$3('shareImage').error('The share image url is required!');
1484 return;
1485 }
1486 try {
1487 return SCHEME.send({
1488 category: 'image',
1489 data: { url }
1490 });
1491 }
1492 catch (err) {
1493 logger$3('shareImage').error(err);
1494 }
1495 },
1496 shareContact: function (user_id) {
1497 if (!user_id) {
1498 logger$3('shareContact').error('The "user_id" is required!');
1499 return;
1500 }
1501 try {
1502 return SCHEME.send({
1503 category: 'contact',
1504 data: { user_id }
1505 });
1506 }
1507 catch (err) {
1508 logger$3('shareContact').error(err);
1509 }
1510 },
1511 shareCard: function (data) {
1512 if (!data.action || !data.app_id) {
1513 logger$3('shareCard').error('The "action" and "app_id" is required!');
1514 return;
1515 }
1516 try {
1517 return SCHEME.send({
1518 category: 'app_card',
1519 data
1520 });
1521 }
1522 catch (err) {
1523 logger$3('shareCard').error(err);
1524 }
1525 },
1526 shareLive: function (data) {
1527 if (!data.url) {
1528 logger$3('shareLive').error('The "url" is required!');
1529 return;
1530 }
1531 try {
1532 if (!data.height)
1533 data.height = 720;
1534 if (!data.width)
1535 data.width = 1280;
1536 return SCHEME.send({
1537 category: 'live',
1538 data
1539 });
1540 }
1541 catch (err) {
1542 logger$3('shareLive').error(err);
1543 }
1544 },
1545 sharePost: function (content) {
1546 if (!content) {
1547 logger$3('sharePost').error('The share content is required!');
1548 return;
1549 }
1550 try {
1551 return SCHEME.send({
1552 category: 'post',
1553 data: content
1554 });
1555 }
1556 catch (err) {
1557 logger$3('sharePost').error(err);
1558 }
1559 },
1560 popupUser: function (user_id) {
1561 if (!user_id) {
1562 logger$3('popupUser').error('The "user_id" is required!');
1563 return;
1564 }
1565 try {
1566 return SCHEME.users(user_id);
1567 }
1568 catch (err) {
1569 logger$3('popupUser').error(err);
1570 }
1571 },
1572 popupBot: function (params) {
1573 const { app_id } = params, rest = __rest(params, ["app_id"]);
1574 if (!app_id) {
1575 logger$3('popupBot').error('The "app_id" is required!');
1576 return;
1577 }
1578 try {
1579 return SCHEME.apps(app_id, rest);
1580 }
1581 catch (err) {
1582 logger$3('popupBot').error(err);
1583 }
1584 },
1585 conversation: function (conversation_id) {
1586 if (!conversation_id) {
1587 logger$3('conversation').error('The "conversation_id" is required!');
1588 return;
1589 }
1590 try {
1591 return SCHEME.conversations(conversation_id);
1592 }
1593 catch (err) {
1594 logger$3('conversation').error(err);
1595 }
1596 }
1597};const SUPPORT_APIS = {
1598 address_add: false,
1599 address_del: false,
1600 conversation: false,
1601 getContext: false,
1602 getUserInfo: true,
1603 login: true,
1604 logout: true,
1605 payment: false,
1606 playlist: false,
1607 popup_user: false,
1608 popup_bot: false,
1609 reloadTheme: false,
1610 requestToken: true,
1611 share_text: false,
1612 share_image: false,
1613 share_contact: false,
1614 share_app_card: false,
1615 share_live: false,
1616 share_post: false,
1617 showToast: false,
1618 snapshot: false,
1619 transfer: false,
1620 withdrawal: false,
1621};
1622class Bridge {
1623 constructor(config) {
1624 const { debug, logLevel } = config || {};
1625 if (debug !== void 0)
1626 logger.setDebug(debug);
1627 if (logLevel !== void 0)
1628 logger.setLevel(logLevel);
1629 this.config = config;
1630 this._token = void 0;
1631 this._userInfo = void 0;
1632 this.logger = getLogger();
1633 // public
1634 this.getContext = this.getContext.bind(this);
1635 this.reloadTheme = this.reloadTheme.bind(this);
1636 this.playlist = this.playlist.bind(this);
1637 this.login = this.login.bind(this);
1638 this.logout = this.logout.bind(this);
1639 this.requestToken = this.requestToken.bind(this);
1640 this.getUserInfo = this.getUserInfo.bind(this);
1641 // private
1642 this.getCode = this.getCode.bind(this);
1643 this.handlerError = this.handlerError.bind(this);
1644 }
1645 /**
1646 * get the app version
1647 */
1648 get version() {
1649 let app;
1650 try {
1651 app = this.getContext();
1652 }
1653 catch (err) {
1654 this.logger('version').info(err);
1655 }
1656 return app === null || app === void 0 ? void 0 : app.app_version;
1657 }
1658 /**
1659 * get the code which be used to get access-token
1660 */
1661 get code() {
1662 return this.getCode();
1663 }
1664 /**
1665 * get the code-verifier which be used to get access-token
1666 */
1667 get codeVerifier() {
1668 return store.get('$_mixin-code-verifier');
1669 }
1670 /**
1671 * get conversation id
1672 */
1673 get conversationId() {
1674 var _a, _b;
1675 return (_b = (_a = this.getContext()) === null || _a === void 0 ? void 0 : _a.conversation_id) !== null && _b !== void 0 ? _b : void 0;
1676 }
1677 /**
1678 * get API support info
1679 */
1680 get supportAPIs() {
1681 const res = Object.assign({}, SUPPORT_APIS);
1682 if (this.isMixin) {
1683 const featVersion = {
1684 mixin: {
1685 address_add: 0,
1686 address_del: 0,
1687 conversation: 311,
1688 getContext: 0,
1689 getUserInfo: 0,
1690 login: 0,
1691 logout: 0,
1692 payment: 0,
1693 playlist: 300,
1694 popup_user: 0,
1695 popup_bot: 290,
1696 reloadTheme: 0,
1697 requestToken: 0,
1698 share_text: 0,
1699 share_image: 0,
1700 share_contact: 0,
1701 share_app_card: 0,
1702 share_live: 0,
1703 share_post: 0,
1704 showToast: 0,
1705 snapshot: 0,
1706 transfer: 0,
1707 withdrawal: 0
1708 },
1709 reborn: {
1710 address_add: 0,
1711 address_del: 0,
1712 conversation: 1121,
1713 getContext: 0,
1714 getUserInfo: 0,
1715 login: 0,
1716 logout: 0,
1717 payment: 0,
1718 playlist: 1100,
1719 popup_user: 0,
1720 popup_bot: 1100,
1721 reloadTheme: 0,
1722 requestToken: 0,
1723 share_text: 0,
1724 share_image: 0,
1725 share_contact: 0,
1726 share_app_card: 0,
1727 share_live: 0,
1728 share_post: 0,
1729 showToast: 0,
1730 snapshot: 0,
1731 transfer: 0,
1732 withdrawal: 0
1733 }
1734 };
1735 const verNum = +this.version.split('.').join('');
1736 const featList = featVersion[this.isReborn ? 'reborn' : 'mixin'];
1737 Object.keys(featList).forEach(feat => {
1738 res[feat] = verNum >= featList[feat];
1739 });
1740 }
1741 return res;
1742 }
1743 /**
1744 * judgement whether or not in mixin or reborn app
1745 */
1746 get isMixin() {
1747 var _a, _b, _c;
1748 const isIOS = env().isIOS;
1749 return !!(isIOS
1750 ? (_b = (_a = window === null || window === void 0 ? void 0 : window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.MixinContext : (window === null || window === void 0 ? void 0 : window.MixinContext) && typeof ((_c = window === null || window === void 0 ? void 0 : window.MixinContext) === null || _c === void 0 ? void 0 : _c.getContext) === 'function');
1751 }
1752 /**
1753 * judgement whether or not in reborn app
1754 */
1755 get isReborn() {
1756 return /XUEXI/.test(navigator.userAgent);
1757 }
1758 /**
1759 * get access token
1760 */
1761 get token() {
1762 var _a;
1763 return (_a = this._token) !== null && _a !== void 0 ? _a : store.get('$_mixin-token');
1764 }
1765 /**
1766 * get mixin app context
1767 */
1768 getContext() {
1769 if (!this.isMixin) {
1770 this.logger('getContext').log('Please call in reborn or mixin app!');
1771 return;
1772 }
1773 try {
1774 let ctx = messager('getContext')();
1775 if (typeof ctx === 'string') {
1776 try {
1777 ctx = JSON.parse(ctx);
1778 }
1779 catch (err) {
1780 this.logger('getContext').info(err);
1781 }
1782 }
1783 if (ctx)
1784 ctx.platform = (ctx === null || ctx === void 0 ? void 0 : ctx.platform) || (env().isIOS ? 'iOS' : 'Android');
1785 return ctx;
1786 }
1787 catch (err) {
1788 this.handlerError(err, 'getContext');
1789 return;
1790 }
1791 }
1792 /**
1793 * reload the theme according to theme-color
1794 */
1795 reloadTheme() {
1796 if (!this.isMixin) {
1797 this.logger('reloadTheme').log('Please call in reborn or mixin app!');
1798 return;
1799 }
1800 try {
1801 const reloadTheme = messager('reloadTheme');
1802 env().isIOS ? reloadTheme('') : reloadTheme();
1803 }
1804 catch (err) {
1805 this.handlerError(err, 'reloadTheme');
1806 }
1807 }
1808 /**
1809 * call native message window
1810 * Android Only
1811 */
1812 showToast(msg) {
1813 if (!this.isMixin) {
1814 this.logger('showToast').log('Please call in reborn or mixin app!');
1815 return;
1816 }
1817 try {
1818 messager('showToast')(msg);
1819 }
1820 catch (err) {
1821 this.handlerError(err, 'showToast');
1822 }
1823 }
1824 /**
1825 * play audio by mixin native player
1826 */
1827 playlist(src) {
1828 if (!this.isMixin) {
1829 this.logger('playlist').log('Please call in reborn or mixin app!');
1830 return;
1831 }
1832 try {
1833 messager('playlist')(src);
1834 }
1835 catch (err) {
1836 this.handlerError(err, 'playlist');
1837 }
1838 }
1839 /**
1840 * go login page
1841 * @type { phone?: boolean | number; profile?: boolean | number; contacts?: boolean | number; assets?: boolean | number; snapshots?: boolean | number; messages?: boolean | number; code_challenge?: boolean; } AUTH
1842 */
1843 login(auth, params) {
1844 const { client_id } = this.config || {};
1845 const cid = (params === null || params === void 0 ? void 0 : params.client_id) || client_id;
1846 if (!cid) {
1847 this.logger('login').warn('Please pass client_id first!');
1848 return;
1849 }
1850 getAccessCode(Object.assign(Object.assign({}, params), { client_id: cid, auth }));
1851 }
1852 /**
1853 * do logout
1854 * @param reload whether reload the page
1855 */
1856 logout(reload = true) {
1857 store.clear('$_mixin-token');
1858 store.clear('$_mixin-code-verifier');
1859 store.clear('$_mixin-user-info');
1860 if (reload)
1861 window.location.reload();
1862 }
1863 /**
1864 * request access-token by code
1865 * @param params request params
1866 * @param persistence whether persist the code
1867 * @returns
1868 */
1869 requestToken(params, persistence = true) {
1870 const { client_id: client_id_config } = this.config || {};
1871 const { code: code_params, code_verifier: code_verifier_params, client_id: client_id_params } = params || {};
1872 const client_id = client_id_params || client_id_config;
1873 const code = code_params || this.getCode();
1874 const code_verifier = code_verifier_params || store.get('$_mixin-code-verifier');
1875 if (!client_id || !code_verifier || !code) {
1876 this.logger('requestToken').warn('The request parameters which contain client_id, access_code and code_verifier is not correct!');
1877 return Promise.resolve(null);
1878 }
1879 return new Promise((resolve, reject) => {
1880 getAccessToken({
1881 code,
1882 code_verifier,
1883 client_id
1884 })
1885 .then(token => {
1886 this._token = token;
1887 if (persistence)
1888 store.set('$_mixin-token', token);
1889 resolve(token);
1890 })
1891 .catch(err => {
1892 this.handlerError(err, 'requestToken', 'get token failed!');
1893 reject(err);
1894 });
1895 });
1896 }
1897 /**
1898 * get user infomations by request https://api.mixin.one/me API
1899 */
1900 getUserInfo(token) {
1901 var _a, _b;
1902 if (token === void 0) { token = (_a = this.token) !== null && _a !== void 0 ? _a : ''; }
1903 if (!token) {
1904 this.logger('getUserInfo').warn('The access_token is invalid!');
1905 return Promise.resolve(null);
1906 }
1907 try {
1908 const cache = store.get('$_mixin-user-info');
1909 const userInfo = ((_b = this._userInfo) !== null && _b !== void 0 ? _b : cache) ? JSON.parse(cache) : '';
1910 if (userInfo) {
1911 this.logger('getUserInfo').log('through cache!');
1912 return Promise.resolve(userInfo);
1913 }
1914 }
1915 catch (err) {
1916 this.logger('getUserInfo').info(err);
1917 }
1918 this.logger('getUserInfo').log('http request!');
1919 return request({
1920 url: 'https://api.mixin.one/me',
1921 method: 'GET',
1922 headers: {
1923 'Content-Type': 'application/json',
1924 Authorization: `Bearer ${token}`
1925 },
1926 withCredentials: false
1927 }).then(res => {
1928 const data = res.data;
1929 if (data) {
1930 this._userInfo = data;
1931 store.set('$_mixin-user-info', JSON.stringify(data));
1932 }
1933 return data;
1934 });
1935 }
1936 /**
1937 * evoke payment checkout by generate pay scheme-url
1938 * @type { recipient: string; asset: string; amount: string; trace?: string; memo?: string | Record<string, string>; } PARAMS_PAYMENT
1939 */
1940 payment(params) {
1941 return scheme.pay(params);
1942 }
1943 /**
1944 * evoke transfer checkout by generate pay scheme-url
1945 * @param recipient recipient id
1946 */
1947 transfer(recipient) {
1948 return scheme.transfer(recipient);
1949 }
1950 /**
1951 * evoke transfer detail by generate snapshots scheme-url
1952 * @type { trace_id?: string; snapshot_id?: string; } PARAMS_SNAPSHOTS
1953 */
1954 snapshot(params) {
1955 return scheme.snapshot(params);
1956 }
1957 /**
1958 * evoke withdrawal of an asset by generate withdrawal scheme-url
1959 * @type { address: string; asset: string; amount: string; trace?: string; memo?: string | Record<string, string>; } PARAMS_WITHDRAWAL
1960 */
1961 withdrawal(params) {
1962 return scheme.withdrawal(params);
1963 }
1964 address(type, params) {
1965 switch (type) {
1966 case 'add':
1967 return scheme.addWithdrawalAddress(params);
1968 case 'del':
1969 return scheme.delWithdrawalAddress(params);
1970 }
1971 }
1972 share(category, params) {
1973 let shareAction;
1974 switch (category) {
1975 case 'text':
1976 shareAction = scheme.shareText;
1977 break;
1978 case 'post':
1979 shareAction = scheme.sharePost;
1980 break;
1981 case 'live':
1982 shareAction = scheme.shareLive;
1983 break;
1984 case 'image':
1985 shareAction = scheme.shareImage;
1986 break;
1987 case 'app_card':
1988 shareAction = scheme.shareCard;
1989 break;
1990 case 'contact':
1991 shareAction = scheme.shareContact;
1992 break;
1993 }
1994 return shareAction === null || shareAction === void 0 ? void 0 : shareAction(params);
1995 }
1996 popup(type, params) {
1997 switch (type) {
1998 case 'user':
1999 return scheme.popupUser(params);
2000 case 'bot':
2001 return scheme.popupBot(params);
2002 }
2003 }
2004 /**
2005 * evoke conversation by generate conversations scheme-url
2006 * @param recipient conversation id
2007 */
2008 conversation(conversation_id) {
2009 return scheme.conversation(conversation_id);
2010 }
2011 getCode() {
2012 var _a, _b, _c;
2013 const parseData = parseUrl(window.location.href);
2014 if (typeof parseData !== 'string') {
2015 const { hash, search } = parseData;
2016 const regExp = /code=([^&#]*)/g;
2017 const code = (_b = (_a = regExp.exec(search)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : (_c = regExp.exec(hash)) === null || _c === void 0 ? void 0 : _c[1];
2018 return code;
2019 }
2020 }
2021 handlerError(err, prefix = '', msg = 'oops! some error has ocurred!') {
2022 let {
2023 // eslint-disable-next-line prefer-const
2024 message = '', stack = '', name = '' } = parseError(err);
2025 if (name)
2026 name = `(${name}): `;
2027 if (stack)
2028 stack = ` at ${stack}`;
2029 this.logger(prefix).error(`👇 ${msg} ❌`, '\n', name, message, stack);
2030 }
2031}export default Bridge;export{Bridge};
\No newline at end of file