@authme/util 2.4.11 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -11,20 +11,22 @@ require('core-js/modules/es.typed-array.sort.js');
11
11
  require('core-js/modules/es.typed-array.to-locale-string.js');
12
12
  require('core-js/modules/es.promise.js');
13
13
  require('core-js/modules/es.regexp.exec.js');
14
+ require('core-js/modules/es.string.match.js');
15
+ require('core-js/modules/es.string.replace.js');
14
16
  require('core-js/modules/es.regexp.to-string.js');
15
17
  require('core-js/modules/web.dom-collections.iterator.js');
16
18
  require('core-js/modules/es.object.assign.js');
17
19
  require('core-js/modules/es.number.parse-int.js');
18
20
  var jwt_decode = require('jwt-decode');
19
- require('core-js/modules/es.string.match.js');
20
- require('core-js/modules/es.string.replace.js');
21
21
  require('core-js/modules/web.url-search-params.js');
22
22
  require('core-js/modules/es.string.search.js');
23
23
  require('core-js/modules/es.typed-array.uint32-array.js');
24
- var Lottie = require('lottie-web');
25
- require('core-js/modules/es.array.sort.js');
26
24
  require('core-js/modules/es.array.includes.js');
27
25
  require('core-js/modules/es.string.includes.js');
26
+ var fileSaver = require('file-saver');
27
+ var JSZip = require('jszip');
28
+ var Lottie = require('lottie-web');
29
+ require('core-js/modules/es.array.sort.js');
28
30
  require('core-js/modules/es.parse-int.js');
29
31
  require('core-js/modules/es.string.trim.js');
30
32
  require('core-js/modules/es.string.starts-with.js');
@@ -33,6 +35,7 @@ require('core-js/modules/es.symbol.description.js');
33
35
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
34
36
 
35
37
  var jwt_decode__default = /*#__PURE__*/_interopDefaultLegacy(jwt_decode);
38
+ var JSZip__default = /*#__PURE__*/_interopDefaultLegacy(JSZip);
36
39
  var Lottie__default = /*#__PURE__*/_interopDefaultLegacy(Lottie);
37
40
 
38
41
  const GLOBAL_KEY = '_AuthmeConfig';
@@ -299,6 +302,7 @@ function getOsVersion(userAgent) {
299
302
 
300
303
  class State {
301
304
  constructor(initialValue = null) {
305
+ this._effects = [];
302
306
  this._value = initialValue;
303
307
  }
304
308
  getValue() {
@@ -306,10 +310,22 @@ class State {
306
310
  }
307
311
  setValue(newValue) {
308
312
  this._value = newValue;
313
+ this._runEffects(newValue);
314
+ }
315
+ addEffect(effect) {
316
+ this._effects.push(effect);
317
+ }
318
+ _runEffects(value) {
319
+ for (const effect of this._effects) {
320
+ effect(value);
321
+ }
309
322
  }
310
323
  }
311
- function useState(initialValue = null, subscription) {
324
+ function useState(initialValue = null, subscription, effects = []) {
312
325
  const state = new State(initialValue);
326
+ for (const effect of effects) {
327
+ state.addEffect(effect);
328
+ }
313
329
  function getValue() {
314
330
  return state.getValue();
315
331
  }
@@ -385,9 +401,6 @@ function retryPromiseWithCondition(promiseFactory, conditionFactory) {
385
401
  }
386
402
  });
387
403
  }
388
- function getUserAgent() {
389
- return `platform: ${navigator === null || navigator === void 0 ? void 0 : navigator.platform}`;
390
- }
391
404
  function isMobileOrTablet() {
392
405
  return function (a) {
393
406
  return !!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0, 4)) || /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || navigator.maxTouchPoints && navigator.maxTouchPoints > 2);
@@ -398,6 +411,25 @@ function isMobile() {
398
411
  return !!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(a.substr(0, 4)) || /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
399
412
  }(navigator.userAgent || navigator.vendor || window.opera);
400
413
  }
414
+ function osVersion() {
415
+ let version = '';
416
+ const android = navigator.userAgent.match(/Android\s+([\d\\.]+)/i);
417
+ if (android) {
418
+ version = android[0];
419
+ }
420
+ const ios = navigator.userAgent.match(/OS\s+([\d\\_]+)/i);
421
+ if (ios) {
422
+ version = ios[0].replace('OS ', 'iOS');
423
+ }
424
+ const win = navigator.userAgent.match(/Windows NT (\d+\.\d+)/);
425
+ if (win) {
426
+ version = win[0];
427
+ }
428
+ if (!version) {
429
+ version = navigator.platform;
430
+ }
431
+ return version;
432
+ }
401
433
  function splitResult(result) {
402
434
  if (result.address) {
403
435
  const originAddress = result.address;
@@ -480,6 +512,44 @@ const isIphone14proOrProMax = () => {
480
512
  return isIphone() && (screen.width === 430 && screen.height === 932 || screen.width === 393 && screen.height === 852);
481
513
  };
482
514
 
515
+ function fileSaverService() {
516
+ const filesQueue = [];
517
+ function pushFile(file) {
518
+ filesQueue.push(file);
519
+ }
520
+ function popAllFiles() {
521
+ filesQueue.splice(0, filesQueue.length);
522
+ }
523
+ function saveFiles(fileName, json) {
524
+ return __awaiter(this, void 0, void 0, function* () {
525
+ const zip = new JSZip__default["default"]();
526
+ filesQueue.forEach(fileItem => {
527
+ zip.file(fileItem.name, fileItem.file);
528
+ });
529
+ if (json) zip.file('data.json', JSON.stringify(json));
530
+ const content = yield zip.generateAsync({
531
+ type: 'blob'
532
+ });
533
+ fileSaver.saveAs(content, `${fileName}.zip`);
534
+ popAllFiles();
535
+ });
536
+ }
537
+ return {
538
+ pushFile,
539
+ saveFiles
540
+ };
541
+ }
542
+
543
+ const {
544
+ saveFiles,
545
+ pushFile
546
+ } = fileSaverService();
547
+ exports.RUN_FUNCTION_NAME = void 0;
548
+ (function (RUN_FUNCTION_NAME) {
549
+ RUN_FUNCTION_NAME["RECOGNITION"] = "service.recognition";
550
+ RUN_FUNCTION_NAME["ANTI_FARUD_RECOGNITION"] = "antiFraudInstance.recognition";
551
+ RUN_FUNCTION_NAME["API_REQUEST"] = "api.request";
552
+ })(exports.RUN_FUNCTION_NAME || (exports.RUN_FUNCTION_NAME = {}));
483
553
  function debugLog(message, ...others) {
484
554
  if (new URLSearchParams(location.search).get('authme-debug') === 'true') {
485
555
  console.log(message, ...others);
@@ -501,35 +571,49 @@ function generateUniqueId(length = 32) {
501
571
  }
502
572
  return result;
503
573
  }
504
- function downloadObjectAsJson(exportObj, exportName) {
505
- const dataStr = `data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=${exportName}.json,${encodeURIComponent(JSON.stringify(exportObj, null, 4))}`;
506
- //'data:text/json;charset=utf-8,' +
507
- const downloadAnchorNode = document.createElement('a');
508
- downloadAnchorNode.setAttribute('href', dataStr);
509
- downloadAnchorNode.setAttribute('download', exportName + '.json');
510
- document.body.appendChild(downloadAnchorNode); // required for firefox
511
- downloadAnchorNode.click();
512
- downloadAnchorNode.remove();
513
- }
514
- function debugTools(config) {
574
+ function debugTools() {
575
+ const debugMode = new URLSearchParams(location.search).get('authme-debug') === 'true';
576
+ const debugModeUI = new URLSearchParams(location.search).get('authme-debug-info') === 'true';
577
+ const shouldGetDebugImage = new URLSearchParams(location.search).get('authme-debug-get-image') === 'true';
515
578
  const debugLogs = [];
579
+ const logInfo = {
580
+ userAgent: navigator.userAgent,
581
+ token: '',
582
+ message: ''
583
+ };
516
584
  let currentRoundId = generateUniqueId(8);
517
585
  let currentType = null;
586
+ const interiaTimeObj = {};
518
587
  function pushNewDebugLog(logParams) {
519
588
  var _a;
520
- if (!config.debugMode) return;
589
+ if (!debugMode) return;
521
590
  const now = new Date();
522
591
  const _logParams = JSON.parse(JSON.stringify(logParams));
523
592
  if (_logParams.result) {
524
593
  (_a = _logParams.result) === null || _a === void 0 ? true : delete _a.imageData;
525
594
  }
526
- const newDebugLog = Object.assign({
527
- time: now.getTime(),
595
+ const newDebugLog = Object.assign(Object.assign({
528
596
  dateTime: now.toLocaleString(),
529
597
  roundId: currentRoundId,
530
598
  type: currentType !== null && currentType !== void 0 ? currentType : undefined
531
- }, _logParams);
599
+ }, _logParams), {
600
+ time: now.getTime(),
601
+ _id: generateUniqueId()
602
+ });
532
603
  debugLogs.push(newDebugLog);
604
+ return newDebugLog;
605
+ }
606
+ function pushNewDebugImage(image, log, options) {
607
+ var _a, _b;
608
+ if (!debugMode) return;
609
+ const newLog = pushNewDebugLog(log);
610
+ const recognitionFunctions = [exports.RUN_FUNCTION_NAME.ANTI_FARUD_RECOGNITION, exports.RUN_FUNCTION_NAME.RECOGNITION];
611
+ const currentRoundRecognitionResultItem = debugLogs.find(item => item.roundId === (newLog === null || newLog === void 0 ? void 0 : newLog.roundId) && item.status === 'run-end' && (item.runFunction ? recognitionFunctions.includes(item.runFunction) : false));
612
+ const imageStatus = (_a = currentRoundRecognitionResultItem === null || currentRoundRecognitionResultItem === void 0 ? void 0 : currentRoundRecognitionResultItem.result) === null || _a === void 0 ? void 0 : _a.eStatus;
613
+ pushFile({
614
+ name: `${(_b = options === null || options === void 0 ? void 0 : options.prefix) !== null && _b !== void 0 ? _b : ''}${newLog === null || newLog === void 0 ? void 0 : newLog.time}-${newLog === null || newLog === void 0 ? void 0 : newLog._id}${imageStatus ? `__${imageStatus}` : ''}.jpeg`,
615
+ file: image
616
+ });
533
617
  }
534
618
  function functionLogging(func, logParams) {
535
619
  return new Promise((resolve, reject) => {
@@ -553,28 +637,209 @@ function debugTools(config) {
553
637
  });
554
638
  });
555
639
  }
640
+ function renderDebugTips() {
641
+ if (document.getElementById('debug-tips')) {
642
+ return;
643
+ }
644
+ const debugTips = document.createElement('div');
645
+ debugTips.style.position = 'fixed';
646
+ debugTips.style.top = '50px';
647
+ debugTips.style.right = '0';
648
+ debugTips.style.zIndex = '999';
649
+ debugTips.innerHTML = 'Debug Mode';
650
+ debugTips.style.color = 'red';
651
+ debugTips.style.fontWeight = 'bold';
652
+ debugTips.setAttribute('id', 'debug-tips');
653
+ document.body.appendChild(debugTips);
654
+ }
655
+ function renderDebugUI() {
656
+ if (document.getElementById('debug-ui')) {
657
+ return;
658
+ }
659
+ const debugUI = document.createElement('div');
660
+ debugUI.style.position = 'fixed';
661
+ debugUI.style.top = '0';
662
+ debugUI.style.right = '0';
663
+ debugUI.style.zIndex = '777';
664
+ debugUI.style.backgroundColor = 'black';
665
+ debugUI.style.color = 'white';
666
+ debugUI.style.padding = '10px';
667
+ debugUI.style.paddingRight = '150px';
668
+ debugUI.style.fontSize = '12px';
669
+ debugUI.style.opacity = '0.7';
670
+ debugUI.style.boxSizing = 'border-box';
671
+ debugUI.style.width = '100%';
672
+ debugUI.style.maxHeight = '50vh';
673
+ debugUI.style.overflow = 'auto';
674
+ debugUI.setAttribute('id', 'debug-ui');
675
+ const closeUI = document.createElement('button');
676
+ closeUI.style.position = 'fixed';
677
+ closeUI.style.top = '0';
678
+ closeUI.style.right = '100px';
679
+ closeUI.innerHTML = 'close';
680
+ closeUI.addEventListener('click', () => {
681
+ debugUI.style.display = 'none';
682
+ });
683
+ debugUI.appendChild(closeUI);
684
+ const accordionUI = document.createElement('button');
685
+ accordionUI.style.position = 'fixed';
686
+ accordionUI.style.top = '0';
687
+ accordionUI.style.right = '0';
688
+ accordionUI.innerHTML = '收合/展開';
689
+ accordionUI.addEventListener('click', () => {
690
+ if (debugUI.style.maxHeight === '50vh') {
691
+ debugUI.style.maxHeight = '5vh';
692
+ } else {
693
+ debugUI.style.maxHeight = '50vh';
694
+ }
695
+ });
696
+ debugUI.appendChild(accordionUI);
697
+ document.body.appendChild(debugUI);
698
+ }
699
+ function setTimeStart(behavior) {
700
+ if (!debugModeUI) {
701
+ return;
702
+ }
703
+ const dStart = new Date();
704
+ const nStart = dStart.getTime();
705
+ if (interiaTimeObj && interiaTimeObj[behavior]) {
706
+ console.error('debugmode: setTimeStart duplicate', behavior);
707
+ return false;
708
+ }
709
+ interiaTimeObj[behavior] = {
710
+ behavior,
711
+ start: nStart / 1000,
712
+ duration: 0,
713
+ end: 0
714
+ };
715
+ // console.log(interiaTimeObj[behavior])
716
+ renderTimeInfo(behavior);
717
+ return interiaTimeObj[behavior];
718
+ }
719
+ function setTimeEnd(behavior) {
720
+ if (!debugModeUI) {
721
+ return;
722
+ }
723
+ const dEnd = new Date();
724
+ const nEnd = dEnd.getTime();
725
+ if (!interiaTimeObj[behavior]) {
726
+ console.error('debugmode: setTimeEnd not found', behavior);
727
+ return false;
728
+ }
729
+ interiaTimeObj[behavior].end = nEnd / 1000;
730
+ interiaTimeObj[behavior].duration = interiaTimeObj[behavior].end - interiaTimeObj[behavior].start;
731
+ // console.log(interiaTimeObj[behavior])
732
+ renderTimeInfo(behavior);
733
+ return interiaTimeObj[behavior];
734
+ }
735
+ function setTimeDuration(behavior) {
736
+ const ts = Date.now();
737
+ setTimeStart(`${behavior}_${ts}`);
738
+ return {
739
+ end: () => {
740
+ setTimeEnd(`${behavior}_${ts}`);
741
+ }
742
+ };
743
+ }
744
+ function renderTimeInfo(behavior) {
745
+ const dom = document.querySelector(`#debug-ui-${behavior}`);
746
+ const info = `{"behavior":<span style="color:green;">"${behavior}"</span>, "start": ${interiaTimeObj[behavior].start}, "duration": ${interiaTimeObj[behavior].duration}, "end": ${interiaTimeObj[behavior].end}}`;
747
+ // const info = `<span style="color:green;">${behavior}</span>: Duration: ${interiaTimeObj[behavior].duration}s`;
748
+ if (dom) {
749
+ dom.innerHTML = info;
750
+ return;
751
+ }
752
+ const debugUI = document.getElementById('debug-ui');
753
+ const div = document.createElement('div');
754
+ div.setAttribute('class', 'debug-ui-item');
755
+ div.setAttribute('id', `debug-ui-${behavior}`);
756
+ div.innerHTML = info;
757
+ debugUI.appendChild(div);
758
+ }
759
+ function functionRunTime() {
760
+ const arr = [];
761
+ const items = document.querySelectorAll('.debug-ui-item');
762
+ items.forEach(item => {
763
+ arr.push(JSON.parse(item.innerText));
764
+ });
765
+ return arr;
766
+ }
767
+ if (debugMode) {
768
+ renderDebugTips();
769
+ // setRequestLoggingFunc(functionLogging)
770
+ }
771
+
772
+ if (debugModeUI) {
773
+ console.log('debugModeUI Init');
774
+ renderDebugUI();
775
+ }
776
+ function saveDebugImage({
777
+ getDebugImageData,
778
+ data,
779
+ width,
780
+ height,
781
+ result,
782
+ type
783
+ }) {
784
+ return __awaiter(this, void 0, void 0, function* () {
785
+ if (!debugMode || !shouldGetDebugImage) return;
786
+ const debugImage = yield getDebugImageData(data);
787
+ // 創建一個虛擬的 canvas
788
+ const canvas = document.createElement('canvas');
789
+ const ctx = canvas.getContext('2d');
790
+ // 設置 canvas 的尺寸
791
+ canvas.width = width;
792
+ canvas.height = height;
793
+ // 使用 Uint8ClampedArray 將圖像數據繪製到 canvas 上
794
+ const imgData = ctx === null || ctx === void 0 ? void 0 : ctx.createImageData(width, height);
795
+ if (imgData) {
796
+ imgData.data.set(debugImage);
797
+ ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(imgData, 0, 0);
798
+ canvas.toBlob(blob => {
799
+ if (blob) {
800
+ pushNewDebugImage(blob, {
801
+ result: result,
802
+ status: 'recognition',
803
+ type: type
804
+ }, {
805
+ prefix: 'debugImage_'
806
+ });
807
+ }
808
+ }, 'image/jpeg');
809
+ }
810
+ });
811
+ }
556
812
  return {
813
+ debugMode,
814
+ debugModeUI,
557
815
  pushNewDebugLog,
558
816
  getDebugLogs: () => debugLogs,
559
817
  getDebugLogsLength: () => debugLogs.length,
560
818
  modifyDeubgLog: (index, logParams) => {
561
- if (!config.debugMode) return;
819
+ if (!debugMode) return;
562
820
  debugLogs[index] = Object.assign(Object.assign({}, debugLogs[index]), logParams);
563
821
  },
564
822
  downloadDebugLogs: () => {
565
- if (!config.debugMode) return;
566
- downloadObjectAsJson(debugLogs, `debugLog${new Date().getTime().toString()}`);
823
+ if (!debugMode) return;
824
+ saveFiles(`debugLog${new Date().getTime().toString()}`, {
825
+ info: logInfo,
826
+ logs: debugLogs,
827
+ functionRunTime: functionRunTime()
828
+ });
567
829
  },
568
830
  functionLogging,
569
831
  nextDebugRound: type => {
570
- if (!config.debugMode) return;
832
+ if (!debugMode) return;
571
833
  currentRoundId = generateUniqueId(8);
572
834
  if (type) currentType = type;
573
835
  },
574
836
  modifyDebugType: type => {
575
- if (!config.debugMode) return;
837
+ if (!debugMode) return;
576
838
  currentType = type;
577
- }
839
+ },
840
+ pushNewDebugImage,
841
+ setTimeDuration: setTimeDuration,
842
+ saveDebugImage
578
843
  };
579
844
  }
580
845
 
@@ -767,8 +1032,9 @@ function showErrorMessage(text, showRetryBtn, callback, buttonText, _titleText)
767
1032
  errorMessagePanel.appendChild(retryText);
768
1033
  if (callback) {
769
1034
  retryText.addEventListener('click', e => {
770
- target.removeChild(errorMessagePanel);
771
- callback(e);
1035
+ callback(e, {
1036
+ hideErrorMessage
1037
+ });
772
1038
  });
773
1039
  }
774
1040
  }
@@ -828,23 +1094,22 @@ function asyncShowErrorMessage(text, showRetryBtn, options) {
828
1094
  });
829
1095
  });
830
1096
  }
831
- function asyncOnLineShowErrorMessage(text, showRetryBtn) {
1097
+ function asyncOnLineShowErrorMessage(text, buttonText, showRetryBtn) {
832
1098
  return __awaiter(this, void 0, void 0, function* () {
833
1099
  return new Promise((res, rej) => {
834
- const callback = () => {
1100
+ showErrorMessage(text, showRetryBtn, (_, tools) => {
835
1101
  if (window.navigator.onLine) {
836
1102
  res(true);
837
- hideErrorMessage();
1103
+ tools === null || tools === void 0 ? void 0 : tools.hideErrorMessage();
838
1104
  }
839
- };
840
- showErrorMessage(text, showRetryBtn, callback);
1105
+ }, buttonText);
841
1106
  });
842
1107
  });
843
1108
  }
844
- function checkOnlineStatus(msg) {
1109
+ function checkOnlineStatus(msg, buttonText) {
845
1110
  return __awaiter(this, void 0, void 0, function* () {
846
1111
  if (!window.navigator.onLine) {
847
- yield asyncOnLineShowErrorMessage(msg, true);
1112
+ yield asyncOnLineShowErrorMessage(msg, buttonText, true);
848
1113
  }
849
1114
  });
850
1115
  }
@@ -905,6 +1170,8 @@ var BROWSER_CAMERA_ERRORS;
905
1170
  BROWSER_CAMERA_ERRORS["NO_CAMERA"] = "NO_CAMERA";
906
1171
  BROWSER_CAMERA_ERRORS["NOT_ALLOWED_ERROR"] = "NotAllowedError";
907
1172
  BROWSER_CAMERA_ERRORS["NOT_FOUND_ERROR"] = "NotFoundError";
1173
+ BROWSER_CAMERA_ERRORS["NOT_READABLE_ERROR"] = "NotReadableError";
1174
+ BROWSER_CAMERA_ERRORS["ABORT_ERROR"] = "AbortError";
908
1175
  })(BROWSER_CAMERA_ERRORS || (BROWSER_CAMERA_ERRORS = {}));
909
1176
  let stream;
910
1177
  const videoConstraintsFactory = (isPC, facingMode) => {
@@ -995,22 +1262,27 @@ function switchCamera(deviceId, video) {
995
1262
  }
996
1263
  const constraints = {
997
1264
  video: {
998
- // 推測依然需要使用 width & height 的限制條件,
999
- // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
1000
- width: {
1001
- min: 1280,
1002
- ideal: 1920,
1003
- max: 1920
1004
- },
1005
- height: {
1006
- min: 720,
1007
- ideal: 1080,
1008
- max: 1080
1009
- },
1265
+ width: {},
1266
+ height: {},
1010
1267
  focusMode: 'auto',
1011
1268
  deviceId: deviceId
1012
1269
  }
1013
1270
  };
1271
+ const constraint = localStorage.getItem('camera_constraint');
1272
+ if (!constraint) {
1273
+ // 推測依然需要使用 width & height 的限制條件,
1274
+ // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
1275
+ constraints.video.width = {
1276
+ min: 1280,
1277
+ ideal: 1920,
1278
+ max: 1920
1279
+ };
1280
+ constraints.video.height = {
1281
+ min: 720,
1282
+ ideal: 1080,
1283
+ max: 1080
1284
+ };
1285
+ }
1014
1286
  stream = yield navigator.mediaDevices.getUserMedia(constraints);
1015
1287
  video.srcObject = stream;
1016
1288
  yield video.play();
@@ -1025,7 +1297,6 @@ function switchCamera(deviceId, video) {
1025
1297
  });
1026
1298
  }
1027
1299
  function _requestCamera(video, facingMode) {
1028
- var _a;
1029
1300
  return __awaiter(this, void 0, void 0, function* () {
1030
1301
  if (!('mediaDevices' in navigator)) {
1031
1302
  throw BROWSER_CAMERA_ERRORS.NOT_SUPPORT;
@@ -1044,7 +1315,7 @@ function _requestCamera(video, facingMode) {
1044
1315
  // 輪詢取得攝影機 解析度等資訊
1045
1316
  const videoDevices = (yield navigator.mediaDevices.enumerateDevices()).filter(device => device.kind === 'videoinput');
1046
1317
  const deviceMetas = yield arrayFromAsync(asyncMap(device => __awaiter(this, void 0, void 0, function* () {
1047
- var _b, _c, _d, _e;
1318
+ var _a, _b, _c, _d;
1048
1319
  const stream = yield navigator.mediaDevices.getUserMedia({
1049
1320
  video: {
1050
1321
  deviceId: {
@@ -1052,10 +1323,10 @@ function _requestCamera(video, facingMode) {
1052
1323
  }
1053
1324
  }
1054
1325
  });
1055
- const track = (_b = stream.getVideoTracks()) === null || _b === void 0 ? void 0 : _b[0];
1056
- const capabilities = ((_c = track === null || track === void 0 ? void 0 : track.getCapabilities) !== null && _c !== void 0 ? _c : () => undefined).bind(track)(); // firefox 沒有 getCapabilities 可以用。
1057
- const widthMax = (_d = capabilities === null || capabilities === void 0 ? void 0 : capabilities.width) === null || _d === void 0 ? void 0 : _d.max;
1058
- const heightMax = (_e = capabilities === null || capabilities === void 0 ? void 0 : capabilities.height) === null || _e === void 0 ? void 0 : _e.max;
1326
+ const track = (_a = stream.getVideoTracks()) === null || _a === void 0 ? void 0 : _a[0];
1327
+ const capabilities = ((_b = track === null || track === void 0 ? void 0 : track.getCapabilities) !== null && _b !== void 0 ? _b : () => undefined).bind(track)(); // firefox 沒有 getCapabilities 可以用。
1328
+ const widthMax = (_c = capabilities === null || capabilities === void 0 ? void 0 : capabilities.width) === null || _c === void 0 ? void 0 : _c.max;
1329
+ const heightMax = (_d = capabilities === null || capabilities === void 0 ? void 0 : capabilities.height) === null || _d === void 0 ? void 0 : _d.max;
1059
1330
  const resolution = widthMax && heightMax ? widthMax * heightMax : 0;
1060
1331
  const facingModeFromLabel = inferFacingModeFromLabel(device === null || device === void 0 ? void 0 : device.label);
1061
1332
  const facingModeFromapabilities = inferFacingModeFromCapabilities(capabilities);
@@ -1074,7 +1345,7 @@ function _requestCamera(video, facingMode) {
1074
1345
  capabilities
1075
1346
  };
1076
1347
  }), videoDevices));
1077
- const firstDevice = (_a = deviceMetas.sort((a, b) => {
1348
+ const devices = deviceMetas.sort((a, b) => {
1078
1349
  // 若是 Samsung 手機且模式為後鏡頭,則優先使用Label為 camera2 0 的鏡頭
1079
1350
  let samsungCondition = 0;
1080
1351
  if (isSamsung && facingMode === 'back') {
@@ -1093,7 +1364,9 @@ function _requestCamera(video, facingMode) {
1093
1364
  }
1094
1365
  const resolutionCondition = b.meta.resolution - a.meta.resolution;
1095
1366
  return samsungCondition || cameraFacingCondition || resolutionCondition;
1096
- })) === null || _a === void 0 ? void 0 : _a[0];
1367
+ });
1368
+ const cameraIndex = window.localStorage.getItem('camera') || '0';
1369
+ const firstDevice = devices[parseInt(cameraIndex, 10)];
1097
1370
  const deviceId = firstDevice.device.deviceId;
1098
1371
  if (!deviceId) {
1099
1372
  throw BROWSER_CAMERA_ERRORS.NO_CAMERA;
@@ -1117,9 +1390,6 @@ function isOverconstrainedError(error) {
1117
1390
  }
1118
1391
  return 'constraint' in error;
1119
1392
  }
1120
- function sleep(ms) {
1121
- return new Promise(resolve => setTimeout(resolve, ms));
1122
- }
1123
1393
  function requestCamera({
1124
1394
  video,
1125
1395
  facingMode,
@@ -1128,44 +1398,31 @@ function requestCamera({
1128
1398
  }) {
1129
1399
  return __awaiter(this, void 0, void 0, function* () {
1130
1400
  try {
1131
- let perm = yield navigator.permissions.query({
1132
- name: 'camera'
1133
- });
1134
- if (perm.state == 'prompt') {
1135
- for (let i = 0; i < 5; ++i) {
1136
- try {
1137
- //for ios 17.4.1 hack, if you call getUserMedia too early will only get not allowed.
1138
- yield sleep(1000);
1139
- return yield _requestCamera(video, facingMode);
1140
- } catch (error) {
1141
- if ((error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_ALLOWED_ERROR) {
1142
- perm = yield navigator.permissions.query({
1143
- name: 'camera'
1144
- });
1145
- } else {
1146
- throw error;
1147
- }
1148
- }
1149
- }
1150
- return yield _requestCamera(video, facingMode);
1151
- } else {
1152
- return yield _requestCamera(video, facingMode);
1153
- }
1401
+ return yield _requestCamera(video, facingMode);
1154
1402
  } catch (error) {
1155
1403
  if (error === BROWSER_CAMERA_ERRORS.NOT_SUPPORT) {
1156
- showMessage(translate('camera.error.notFound'));
1404
+ showMessage(translate('sdk.general.error.cameraNotFound.title'));
1157
1405
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, 'Browser not support WebRTC, or https required.');
1158
1406
  }
1159
1407
  if (error === BROWSER_CAMERA_ERRORS.NO_CAMERA) {
1160
- showMessage(translate('camera.error.notFound'));
1408
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1161
1409
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, 'camera not found');
1162
1410
  }
1163
1411
  if ((error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_ALLOWED_ERROR || (error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_FOUND_ERROR) {
1164
- showMessage(translate('camera.error.notFound'));
1412
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1413
+ throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
1414
+ }
1415
+ if ((error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_READABLE_ERROR || (error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.ABORT_ERROR) {
1416
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1417
+ /* NOT_READABLE_ERROR,ABORT_ERROR 這兩個錯誤是用戶授權了,但在呼叫裝置時出現錯誤,
1418
+ * 常發生在APP webview ,例如: 手機開啟 web 使用 sdk,儘管在 webview 層級上授權了,但手機在設定層級沒有授權 app 使用相機,會導致此問題。
1419
+ * 但每個 android 手機的在這方面的實作不一致,不是每個手機在這種情況下都會拋出錯誤。
1420
+ * 參考 https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia#notreadableerror
1421
+ */
1165
1422
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
1166
1423
  }
1167
1424
  if (isOverconstrainedError(error)) {
1168
- showMessage(translate('camera.error.lowResolution'));
1425
+ showMessage(translate('sdk.general.error.cameraLowResolution'));
1169
1426
  throw new AuthmeError(exports.ErrorCode.CAMERA_NOT_SUPPORT, error);
1170
1427
  }
1171
1428
  throw error;
@@ -2159,15 +2416,40 @@ function RGBToLottieColor(color) {
2159
2416
  return color.map(c => c / 255);
2160
2417
  }
2161
2418
 
2162
- var name = "@authme/util";
2163
- var version$1 = "2.4.11";
2164
- var peerDependencies = {
2165
- "core-js": "^3.6.0"
2419
+ const QUEUE_LENGTH = 10;
2420
+ const requstQueue = [];
2421
+ function pushRequest(request) {
2422
+ if (requstQueue.length > QUEUE_LENGTH - 1) {
2423
+ requstQueue.shift();
2424
+ }
2425
+ requstQueue.push(request);
2426
+ }
2427
+ function clearRequest() {
2428
+ requstQueue.splice(0, requstQueue.length);
2429
+ }
2430
+ function backgroundRequest(request) {
2431
+ const requestPromise = request();
2432
+ requestPromise.catch(err => {
2433
+ if (err._code === exports.ErrorCode.NETWORK_ERROR) {
2434
+ pushRequest(request);
2435
+ }
2436
+ });
2437
+ }
2438
+ window.ononline = () => {
2439
+ const tasks = [...requstQueue];
2440
+ clearRequest();
2441
+ tasks.forEach(request => {
2442
+ backgroundRequest(request);
2443
+ });
2166
2444
  };
2445
+
2446
+ var name = "authme/sdk";
2447
+ var version$1 = "2.7.1";
2448
+ var date = "2024-09-06T02:00:28+0000";
2167
2449
  var packageInfo = {
2168
2450
  name: name,
2169
2451
  version: version$1,
2170
- peerDependencies: peerDependencies
2452
+ date: date
2171
2453
  };
2172
2454
 
2173
2455
  var _a;
@@ -2183,6 +2465,7 @@ exports.UintArrayToBlob = UintArrayToBlob;
2183
2465
  exports.asyncOnLineShowErrorMessage = asyncOnLineShowErrorMessage;
2184
2466
  exports.asyncShowErrorMessage = asyncShowErrorMessage;
2185
2467
  exports.asyncShowPopup = asyncShowPopup;
2468
+ exports.backgroundRequest = backgroundRequest;
2186
2469
  exports.checkOnlineStatus = checkOnlineStatus;
2187
2470
  exports.clearCanvas = clearCanvas;
2188
2471
  exports.colorStringToRGB = colorStringToRGB;
@@ -2198,7 +2481,6 @@ exports.getCssVariable = getCssVariable;
2198
2481
  exports.getDeviceInfo = getDeviceInfo;
2199
2482
  exports.getImageData = getImageData;
2200
2483
  exports.getSystemInfo = getSystemInfo;
2201
- exports.getUserAgent = getUserAgent;
2202
2484
  exports.hexToRGB = hexToRGB;
2203
2485
  exports.hideElement = hideElement;
2204
2486
  exports.hideErrorMessage = hideErrorMessage;
@@ -2206,6 +2488,7 @@ exports.hidePopup = hidePopup;
2206
2488
  exports.isIphone14proOrProMax = isIphone14proOrProMax;
2207
2489
  exports.isMobile = isMobile;
2208
2490
  exports.isMobileOrTablet = isMobileOrTablet;
2491
+ exports.osVersion = osVersion;
2209
2492
  exports.requestCamera = requestCamera;
2210
2493
  exports.resize = resize;
2211
2494
  exports.retryPromiseWithCondition = retryPromiseWithCondition;