@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.js CHANGED
@@ -7,20 +7,22 @@ import 'core-js/modules/es.typed-array.sort.js';
7
7
  import 'core-js/modules/es.typed-array.to-locale-string.js';
8
8
  import 'core-js/modules/es.promise.js';
9
9
  import 'core-js/modules/es.regexp.exec.js';
10
+ import 'core-js/modules/es.string.match.js';
11
+ import 'core-js/modules/es.string.replace.js';
10
12
  import 'core-js/modules/es.regexp.to-string.js';
11
13
  import 'core-js/modules/web.dom-collections.iterator.js';
12
14
  import 'core-js/modules/es.object.assign.js';
13
15
  import 'core-js/modules/es.number.parse-int.js';
14
16
  import jwt_decode from 'jwt-decode';
15
- import 'core-js/modules/es.string.match.js';
16
- import 'core-js/modules/es.string.replace.js';
17
17
  import 'core-js/modules/web.url-search-params.js';
18
18
  import 'core-js/modules/es.string.search.js';
19
19
  import 'core-js/modules/es.typed-array.uint32-array.js';
20
- import Lottie from 'lottie-web';
21
- import 'core-js/modules/es.array.sort.js';
22
20
  import 'core-js/modules/es.array.includes.js';
23
21
  import 'core-js/modules/es.string.includes.js';
22
+ import { saveAs } from 'file-saver';
23
+ import JSZip from 'jszip';
24
+ import Lottie from 'lottie-web';
25
+ import 'core-js/modules/es.array.sort.js';
24
26
  import 'core-js/modules/es.parse-int.js';
25
27
  import 'core-js/modules/es.string.trim.js';
26
28
  import 'core-js/modules/es.string.starts-with.js';
@@ -290,6 +292,7 @@ function getOsVersion(userAgent) {
290
292
 
291
293
  class State {
292
294
  constructor(initialValue = null) {
295
+ this._effects = [];
293
296
  this._value = initialValue;
294
297
  }
295
298
  getValue() {
@@ -297,10 +300,22 @@ class State {
297
300
  }
298
301
  setValue(newValue) {
299
302
  this._value = newValue;
303
+ this._runEffects(newValue);
304
+ }
305
+ addEffect(effect) {
306
+ this._effects.push(effect);
307
+ }
308
+ _runEffects(value) {
309
+ for (const effect of this._effects) {
310
+ effect(value);
311
+ }
300
312
  }
301
313
  }
302
- function useState(initialValue = null, subscription) {
314
+ function useState(initialValue = null, subscription, effects = []) {
303
315
  const state = new State(initialValue);
316
+ for (const effect of effects) {
317
+ state.addEffect(effect);
318
+ }
304
319
  function getValue() {
305
320
  return state.getValue();
306
321
  }
@@ -376,9 +391,6 @@ function retryPromiseWithCondition(promiseFactory, conditionFactory) {
376
391
  }
377
392
  });
378
393
  }
379
- function getUserAgent() {
380
- return `platform: ${navigator === null || navigator === void 0 ? void 0 : navigator.platform}`;
381
- }
382
394
  function isMobileOrTablet() {
383
395
  return function (a) {
384
396
  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);
@@ -389,6 +401,25 @@ function isMobile() {
389
401
  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));
390
402
  }(navigator.userAgent || navigator.vendor || window.opera);
391
403
  }
404
+ function osVersion() {
405
+ let version = '';
406
+ const android = navigator.userAgent.match(/Android\s+([\d\\.]+)/i);
407
+ if (android) {
408
+ version = android[0];
409
+ }
410
+ const ios = navigator.userAgent.match(/OS\s+([\d\\_]+)/i);
411
+ if (ios) {
412
+ version = ios[0].replace('OS ', 'iOS');
413
+ }
414
+ const win = navigator.userAgent.match(/Windows NT (\d+\.\d+)/);
415
+ if (win) {
416
+ version = win[0];
417
+ }
418
+ if (!version) {
419
+ version = navigator.platform;
420
+ }
421
+ return version;
422
+ }
392
423
  function splitResult(result) {
393
424
  if (result.address) {
394
425
  const originAddress = result.address;
@@ -471,6 +502,44 @@ const isIphone14proOrProMax = () => {
471
502
  return isIphone() && (screen.width === 430 && screen.height === 932 || screen.width === 393 && screen.height === 852);
472
503
  };
473
504
 
505
+ function fileSaverService() {
506
+ const filesQueue = [];
507
+ function pushFile(file) {
508
+ filesQueue.push(file);
509
+ }
510
+ function popAllFiles() {
511
+ filesQueue.splice(0, filesQueue.length);
512
+ }
513
+ function saveFiles(fileName, json) {
514
+ return __awaiter(this, void 0, void 0, function* () {
515
+ const zip = new JSZip();
516
+ filesQueue.forEach(fileItem => {
517
+ zip.file(fileItem.name, fileItem.file);
518
+ });
519
+ if (json) zip.file('data.json', JSON.stringify(json));
520
+ const content = yield zip.generateAsync({
521
+ type: 'blob'
522
+ });
523
+ saveAs(content, `${fileName}.zip`);
524
+ popAllFiles();
525
+ });
526
+ }
527
+ return {
528
+ pushFile,
529
+ saveFiles
530
+ };
531
+ }
532
+
533
+ const {
534
+ saveFiles,
535
+ pushFile
536
+ } = fileSaverService();
537
+ var RUN_FUNCTION_NAME;
538
+ (function (RUN_FUNCTION_NAME) {
539
+ RUN_FUNCTION_NAME["RECOGNITION"] = "service.recognition";
540
+ RUN_FUNCTION_NAME["ANTI_FARUD_RECOGNITION"] = "antiFraudInstance.recognition";
541
+ RUN_FUNCTION_NAME["API_REQUEST"] = "api.request";
542
+ })(RUN_FUNCTION_NAME || (RUN_FUNCTION_NAME = {}));
474
543
  function debugLog(message, ...others) {
475
544
  if (new URLSearchParams(location.search).get('authme-debug') === 'true') {
476
545
  console.log(message, ...others);
@@ -492,35 +561,49 @@ function generateUniqueId(length = 32) {
492
561
  }
493
562
  return result;
494
563
  }
495
- function downloadObjectAsJson(exportObj, exportName) {
496
- const dataStr = `data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=${exportName}.json,${encodeURIComponent(JSON.stringify(exportObj, null, 4))}`;
497
- //'data:text/json;charset=utf-8,' +
498
- const downloadAnchorNode = document.createElement('a');
499
- downloadAnchorNode.setAttribute('href', dataStr);
500
- downloadAnchorNode.setAttribute('download', exportName + '.json');
501
- document.body.appendChild(downloadAnchorNode); // required for firefox
502
- downloadAnchorNode.click();
503
- downloadAnchorNode.remove();
504
- }
505
- function debugTools(config) {
564
+ function debugTools() {
565
+ const debugMode = new URLSearchParams(location.search).get('authme-debug') === 'true';
566
+ const debugModeUI = new URLSearchParams(location.search).get('authme-debug-info') === 'true';
567
+ const shouldGetDebugImage = new URLSearchParams(location.search).get('authme-debug-get-image') === 'true';
506
568
  const debugLogs = [];
569
+ const logInfo = {
570
+ userAgent: navigator.userAgent,
571
+ token: '',
572
+ message: ''
573
+ };
507
574
  let currentRoundId = generateUniqueId(8);
508
575
  let currentType = null;
576
+ const interiaTimeObj = {};
509
577
  function pushNewDebugLog(logParams) {
510
578
  var _a;
511
- if (!config.debugMode) return;
579
+ if (!debugMode) return;
512
580
  const now = new Date();
513
581
  const _logParams = JSON.parse(JSON.stringify(logParams));
514
582
  if (_logParams.result) {
515
583
  (_a = _logParams.result) === null || _a === void 0 ? true : delete _a.imageData;
516
584
  }
517
- const newDebugLog = Object.assign({
518
- time: now.getTime(),
585
+ const newDebugLog = Object.assign(Object.assign({
519
586
  dateTime: now.toLocaleString(),
520
587
  roundId: currentRoundId,
521
588
  type: currentType !== null && currentType !== void 0 ? currentType : undefined
522
- }, _logParams);
589
+ }, _logParams), {
590
+ time: now.getTime(),
591
+ _id: generateUniqueId()
592
+ });
523
593
  debugLogs.push(newDebugLog);
594
+ return newDebugLog;
595
+ }
596
+ function pushNewDebugImage(image, log, options) {
597
+ var _a, _b;
598
+ if (!debugMode) return;
599
+ const newLog = pushNewDebugLog(log);
600
+ const recognitionFunctions = [RUN_FUNCTION_NAME.ANTI_FARUD_RECOGNITION, RUN_FUNCTION_NAME.RECOGNITION];
601
+ 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));
602
+ const imageStatus = (_a = currentRoundRecognitionResultItem === null || currentRoundRecognitionResultItem === void 0 ? void 0 : currentRoundRecognitionResultItem.result) === null || _a === void 0 ? void 0 : _a.eStatus;
603
+ pushFile({
604
+ 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`,
605
+ file: image
606
+ });
524
607
  }
525
608
  function functionLogging(func, logParams) {
526
609
  return new Promise((resolve, reject) => {
@@ -544,28 +627,209 @@ function debugTools(config) {
544
627
  });
545
628
  });
546
629
  }
630
+ function renderDebugTips() {
631
+ if (document.getElementById('debug-tips')) {
632
+ return;
633
+ }
634
+ const debugTips = document.createElement('div');
635
+ debugTips.style.position = 'fixed';
636
+ debugTips.style.top = '50px';
637
+ debugTips.style.right = '0';
638
+ debugTips.style.zIndex = '999';
639
+ debugTips.innerHTML = 'Debug Mode';
640
+ debugTips.style.color = 'red';
641
+ debugTips.style.fontWeight = 'bold';
642
+ debugTips.setAttribute('id', 'debug-tips');
643
+ document.body.appendChild(debugTips);
644
+ }
645
+ function renderDebugUI() {
646
+ if (document.getElementById('debug-ui')) {
647
+ return;
648
+ }
649
+ const debugUI = document.createElement('div');
650
+ debugUI.style.position = 'fixed';
651
+ debugUI.style.top = '0';
652
+ debugUI.style.right = '0';
653
+ debugUI.style.zIndex = '777';
654
+ debugUI.style.backgroundColor = 'black';
655
+ debugUI.style.color = 'white';
656
+ debugUI.style.padding = '10px';
657
+ debugUI.style.paddingRight = '150px';
658
+ debugUI.style.fontSize = '12px';
659
+ debugUI.style.opacity = '0.7';
660
+ debugUI.style.boxSizing = 'border-box';
661
+ debugUI.style.width = '100%';
662
+ debugUI.style.maxHeight = '50vh';
663
+ debugUI.style.overflow = 'auto';
664
+ debugUI.setAttribute('id', 'debug-ui');
665
+ const closeUI = document.createElement('button');
666
+ closeUI.style.position = 'fixed';
667
+ closeUI.style.top = '0';
668
+ closeUI.style.right = '100px';
669
+ closeUI.innerHTML = 'close';
670
+ closeUI.addEventListener('click', () => {
671
+ debugUI.style.display = 'none';
672
+ });
673
+ debugUI.appendChild(closeUI);
674
+ const accordionUI = document.createElement('button');
675
+ accordionUI.style.position = 'fixed';
676
+ accordionUI.style.top = '0';
677
+ accordionUI.style.right = '0';
678
+ accordionUI.innerHTML = '收合/展開';
679
+ accordionUI.addEventListener('click', () => {
680
+ if (debugUI.style.maxHeight === '50vh') {
681
+ debugUI.style.maxHeight = '5vh';
682
+ } else {
683
+ debugUI.style.maxHeight = '50vh';
684
+ }
685
+ });
686
+ debugUI.appendChild(accordionUI);
687
+ document.body.appendChild(debugUI);
688
+ }
689
+ function setTimeStart(behavior) {
690
+ if (!debugModeUI) {
691
+ return;
692
+ }
693
+ const dStart = new Date();
694
+ const nStart = dStart.getTime();
695
+ if (interiaTimeObj && interiaTimeObj[behavior]) {
696
+ console.error('debugmode: setTimeStart duplicate', behavior);
697
+ return false;
698
+ }
699
+ interiaTimeObj[behavior] = {
700
+ behavior,
701
+ start: nStart / 1000,
702
+ duration: 0,
703
+ end: 0
704
+ };
705
+ // console.log(interiaTimeObj[behavior])
706
+ renderTimeInfo(behavior);
707
+ return interiaTimeObj[behavior];
708
+ }
709
+ function setTimeEnd(behavior) {
710
+ if (!debugModeUI) {
711
+ return;
712
+ }
713
+ const dEnd = new Date();
714
+ const nEnd = dEnd.getTime();
715
+ if (!interiaTimeObj[behavior]) {
716
+ console.error('debugmode: setTimeEnd not found', behavior);
717
+ return false;
718
+ }
719
+ interiaTimeObj[behavior].end = nEnd / 1000;
720
+ interiaTimeObj[behavior].duration = interiaTimeObj[behavior].end - interiaTimeObj[behavior].start;
721
+ // console.log(interiaTimeObj[behavior])
722
+ renderTimeInfo(behavior);
723
+ return interiaTimeObj[behavior];
724
+ }
725
+ function setTimeDuration(behavior) {
726
+ const ts = Date.now();
727
+ setTimeStart(`${behavior}_${ts}`);
728
+ return {
729
+ end: () => {
730
+ setTimeEnd(`${behavior}_${ts}`);
731
+ }
732
+ };
733
+ }
734
+ function renderTimeInfo(behavior) {
735
+ const dom = document.querySelector(`#debug-ui-${behavior}`);
736
+ const info = `{"behavior":<span style="color:green;">"${behavior}"</span>, "start": ${interiaTimeObj[behavior].start}, "duration": ${interiaTimeObj[behavior].duration}, "end": ${interiaTimeObj[behavior].end}}`;
737
+ // const info = `<span style="color:green;">${behavior}</span>: Duration: ${interiaTimeObj[behavior].duration}s`;
738
+ if (dom) {
739
+ dom.innerHTML = info;
740
+ return;
741
+ }
742
+ const debugUI = document.getElementById('debug-ui');
743
+ const div = document.createElement('div');
744
+ div.setAttribute('class', 'debug-ui-item');
745
+ div.setAttribute('id', `debug-ui-${behavior}`);
746
+ div.innerHTML = info;
747
+ debugUI.appendChild(div);
748
+ }
749
+ function functionRunTime() {
750
+ const arr = [];
751
+ const items = document.querySelectorAll('.debug-ui-item');
752
+ items.forEach(item => {
753
+ arr.push(JSON.parse(item.innerText));
754
+ });
755
+ return arr;
756
+ }
757
+ if (debugMode) {
758
+ renderDebugTips();
759
+ // setRequestLoggingFunc(functionLogging)
760
+ }
761
+
762
+ if (debugModeUI) {
763
+ console.log('debugModeUI Init');
764
+ renderDebugUI();
765
+ }
766
+ function saveDebugImage({
767
+ getDebugImageData,
768
+ data,
769
+ width,
770
+ height,
771
+ result,
772
+ type
773
+ }) {
774
+ return __awaiter(this, void 0, void 0, function* () {
775
+ if (!debugMode || !shouldGetDebugImage) return;
776
+ const debugImage = yield getDebugImageData(data);
777
+ // 創建一個虛擬的 canvas
778
+ const canvas = document.createElement('canvas');
779
+ const ctx = canvas.getContext('2d');
780
+ // 設置 canvas 的尺寸
781
+ canvas.width = width;
782
+ canvas.height = height;
783
+ // 使用 Uint8ClampedArray 將圖像數據繪製到 canvas 上
784
+ const imgData = ctx === null || ctx === void 0 ? void 0 : ctx.createImageData(width, height);
785
+ if (imgData) {
786
+ imgData.data.set(debugImage);
787
+ ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(imgData, 0, 0);
788
+ canvas.toBlob(blob => {
789
+ if (blob) {
790
+ pushNewDebugImage(blob, {
791
+ result: result,
792
+ status: 'recognition',
793
+ type: type
794
+ }, {
795
+ prefix: 'debugImage_'
796
+ });
797
+ }
798
+ }, 'image/jpeg');
799
+ }
800
+ });
801
+ }
547
802
  return {
803
+ debugMode,
804
+ debugModeUI,
548
805
  pushNewDebugLog,
549
806
  getDebugLogs: () => debugLogs,
550
807
  getDebugLogsLength: () => debugLogs.length,
551
808
  modifyDeubgLog: (index, logParams) => {
552
- if (!config.debugMode) return;
809
+ if (!debugMode) return;
553
810
  debugLogs[index] = Object.assign(Object.assign({}, debugLogs[index]), logParams);
554
811
  },
555
812
  downloadDebugLogs: () => {
556
- if (!config.debugMode) return;
557
- downloadObjectAsJson(debugLogs, `debugLog${new Date().getTime().toString()}`);
813
+ if (!debugMode) return;
814
+ saveFiles(`debugLog${new Date().getTime().toString()}`, {
815
+ info: logInfo,
816
+ logs: debugLogs,
817
+ functionRunTime: functionRunTime()
818
+ });
558
819
  },
559
820
  functionLogging,
560
821
  nextDebugRound: type => {
561
- if (!config.debugMode) return;
822
+ if (!debugMode) return;
562
823
  currentRoundId = generateUniqueId(8);
563
824
  if (type) currentType = type;
564
825
  },
565
826
  modifyDebugType: type => {
566
- if (!config.debugMode) return;
827
+ if (!debugMode) return;
567
828
  currentType = type;
568
- }
829
+ },
830
+ pushNewDebugImage,
831
+ setTimeDuration: setTimeDuration,
832
+ saveDebugImage
569
833
  };
570
834
  }
571
835
 
@@ -758,8 +1022,9 @@ function showErrorMessage(text, showRetryBtn, callback, buttonText, _titleText)
758
1022
  errorMessagePanel.appendChild(retryText);
759
1023
  if (callback) {
760
1024
  retryText.addEventListener('click', e => {
761
- target.removeChild(errorMessagePanel);
762
- callback(e);
1025
+ callback(e, {
1026
+ hideErrorMessage
1027
+ });
763
1028
  });
764
1029
  }
765
1030
  }
@@ -819,23 +1084,22 @@ function asyncShowErrorMessage(text, showRetryBtn, options) {
819
1084
  });
820
1085
  });
821
1086
  }
822
- function asyncOnLineShowErrorMessage(text, showRetryBtn) {
1087
+ function asyncOnLineShowErrorMessage(text, buttonText, showRetryBtn) {
823
1088
  return __awaiter(this, void 0, void 0, function* () {
824
1089
  return new Promise((res, rej) => {
825
- const callback = () => {
1090
+ showErrorMessage(text, showRetryBtn, (_, tools) => {
826
1091
  if (window.navigator.onLine) {
827
1092
  res(true);
828
- hideErrorMessage();
1093
+ tools === null || tools === void 0 ? void 0 : tools.hideErrorMessage();
829
1094
  }
830
- };
831
- showErrorMessage(text, showRetryBtn, callback);
1095
+ }, buttonText);
832
1096
  });
833
1097
  });
834
1098
  }
835
- function checkOnlineStatus(msg) {
1099
+ function checkOnlineStatus(msg, buttonText) {
836
1100
  return __awaiter(this, void 0, void 0, function* () {
837
1101
  if (!window.navigator.onLine) {
838
- yield asyncOnLineShowErrorMessage(msg, true);
1102
+ yield asyncOnLineShowErrorMessage(msg, buttonText, true);
839
1103
  }
840
1104
  });
841
1105
  }
@@ -896,6 +1160,8 @@ var BROWSER_CAMERA_ERRORS;
896
1160
  BROWSER_CAMERA_ERRORS["NO_CAMERA"] = "NO_CAMERA";
897
1161
  BROWSER_CAMERA_ERRORS["NOT_ALLOWED_ERROR"] = "NotAllowedError";
898
1162
  BROWSER_CAMERA_ERRORS["NOT_FOUND_ERROR"] = "NotFoundError";
1163
+ BROWSER_CAMERA_ERRORS["NOT_READABLE_ERROR"] = "NotReadableError";
1164
+ BROWSER_CAMERA_ERRORS["ABORT_ERROR"] = "AbortError";
899
1165
  })(BROWSER_CAMERA_ERRORS || (BROWSER_CAMERA_ERRORS = {}));
900
1166
  let stream;
901
1167
  const videoConstraintsFactory = (isPC, facingMode) => {
@@ -986,22 +1252,27 @@ function switchCamera(deviceId, video) {
986
1252
  }
987
1253
  const constraints = {
988
1254
  video: {
989
- // 推測依然需要使用 width & height 的限制條件,
990
- // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
991
- width: {
992
- min: 1280,
993
- ideal: 1920,
994
- max: 1920
995
- },
996
- height: {
997
- min: 720,
998
- ideal: 1080,
999
- max: 1080
1000
- },
1255
+ width: {},
1256
+ height: {},
1001
1257
  focusMode: 'auto',
1002
1258
  deviceId: deviceId
1003
1259
  }
1004
1260
  };
1261
+ const constraint = localStorage.getItem('camera_constraint');
1262
+ if (!constraint) {
1263
+ // 推測依然需要使用 width & height 的限制條件,
1264
+ // 否則即使是高解析度相機,也有可能拿到低解析度的圖片。(待驗證)
1265
+ constraints.video.width = {
1266
+ min: 1280,
1267
+ ideal: 1920,
1268
+ max: 1920
1269
+ };
1270
+ constraints.video.height = {
1271
+ min: 720,
1272
+ ideal: 1080,
1273
+ max: 1080
1274
+ };
1275
+ }
1005
1276
  stream = yield navigator.mediaDevices.getUserMedia(constraints);
1006
1277
  video.srcObject = stream;
1007
1278
  yield video.play();
@@ -1016,7 +1287,6 @@ function switchCamera(deviceId, video) {
1016
1287
  });
1017
1288
  }
1018
1289
  function _requestCamera(video, facingMode) {
1019
- var _a;
1020
1290
  return __awaiter(this, void 0, void 0, function* () {
1021
1291
  if (!('mediaDevices' in navigator)) {
1022
1292
  throw BROWSER_CAMERA_ERRORS.NOT_SUPPORT;
@@ -1035,7 +1305,7 @@ function _requestCamera(video, facingMode) {
1035
1305
  // 輪詢取得攝影機 解析度等資訊
1036
1306
  const videoDevices = (yield navigator.mediaDevices.enumerateDevices()).filter(device => device.kind === 'videoinput');
1037
1307
  const deviceMetas = yield arrayFromAsync(asyncMap(device => __awaiter(this, void 0, void 0, function* () {
1038
- var _b, _c, _d, _e;
1308
+ var _a, _b, _c, _d;
1039
1309
  const stream = yield navigator.mediaDevices.getUserMedia({
1040
1310
  video: {
1041
1311
  deviceId: {
@@ -1043,10 +1313,10 @@ function _requestCamera(video, facingMode) {
1043
1313
  }
1044
1314
  }
1045
1315
  });
1046
- const track = (_b = stream.getVideoTracks()) === null || _b === void 0 ? void 0 : _b[0];
1047
- const capabilities = ((_c = track === null || track === void 0 ? void 0 : track.getCapabilities) !== null && _c !== void 0 ? _c : () => undefined).bind(track)(); // firefox 沒有 getCapabilities 可以用。
1048
- const widthMax = (_d = capabilities === null || capabilities === void 0 ? void 0 : capabilities.width) === null || _d === void 0 ? void 0 : _d.max;
1049
- const heightMax = (_e = capabilities === null || capabilities === void 0 ? void 0 : capabilities.height) === null || _e === void 0 ? void 0 : _e.max;
1316
+ const track = (_a = stream.getVideoTracks()) === null || _a === void 0 ? void 0 : _a[0];
1317
+ const capabilities = ((_b = track === null || track === void 0 ? void 0 : track.getCapabilities) !== null && _b !== void 0 ? _b : () => undefined).bind(track)(); // firefox 沒有 getCapabilities 可以用。
1318
+ const widthMax = (_c = capabilities === null || capabilities === void 0 ? void 0 : capabilities.width) === null || _c === void 0 ? void 0 : _c.max;
1319
+ const heightMax = (_d = capabilities === null || capabilities === void 0 ? void 0 : capabilities.height) === null || _d === void 0 ? void 0 : _d.max;
1050
1320
  const resolution = widthMax && heightMax ? widthMax * heightMax : 0;
1051
1321
  const facingModeFromLabel = inferFacingModeFromLabel(device === null || device === void 0 ? void 0 : device.label);
1052
1322
  const facingModeFromapabilities = inferFacingModeFromCapabilities(capabilities);
@@ -1065,7 +1335,7 @@ function _requestCamera(video, facingMode) {
1065
1335
  capabilities
1066
1336
  };
1067
1337
  }), videoDevices));
1068
- const firstDevice = (_a = deviceMetas.sort((a, b) => {
1338
+ const devices = deviceMetas.sort((a, b) => {
1069
1339
  // 若是 Samsung 手機且模式為後鏡頭,則優先使用Label為 camera2 0 的鏡頭
1070
1340
  let samsungCondition = 0;
1071
1341
  if (isSamsung && facingMode === 'back') {
@@ -1084,7 +1354,9 @@ function _requestCamera(video, facingMode) {
1084
1354
  }
1085
1355
  const resolutionCondition = b.meta.resolution - a.meta.resolution;
1086
1356
  return samsungCondition || cameraFacingCondition || resolutionCondition;
1087
- })) === null || _a === void 0 ? void 0 : _a[0];
1357
+ });
1358
+ const cameraIndex = window.localStorage.getItem('camera') || '0';
1359
+ const firstDevice = devices[parseInt(cameraIndex, 10)];
1088
1360
  const deviceId = firstDevice.device.deviceId;
1089
1361
  if (!deviceId) {
1090
1362
  throw BROWSER_CAMERA_ERRORS.NO_CAMERA;
@@ -1108,9 +1380,6 @@ function isOverconstrainedError(error) {
1108
1380
  }
1109
1381
  return 'constraint' in error;
1110
1382
  }
1111
- function sleep(ms) {
1112
- return new Promise(resolve => setTimeout(resolve, ms));
1113
- }
1114
1383
  function requestCamera({
1115
1384
  video,
1116
1385
  facingMode,
@@ -1119,44 +1388,31 @@ function requestCamera({
1119
1388
  }) {
1120
1389
  return __awaiter(this, void 0, void 0, function* () {
1121
1390
  try {
1122
- let perm = yield navigator.permissions.query({
1123
- name: 'camera'
1124
- });
1125
- if (perm.state == 'prompt') {
1126
- for (let i = 0; i < 5; ++i) {
1127
- try {
1128
- //for ios 17.4.1 hack, if you call getUserMedia too early will only get not allowed.
1129
- yield sleep(1000);
1130
- return yield _requestCamera(video, facingMode);
1131
- } catch (error) {
1132
- if ((error === null || error === void 0 ? void 0 : error.name) === BROWSER_CAMERA_ERRORS.NOT_ALLOWED_ERROR) {
1133
- perm = yield navigator.permissions.query({
1134
- name: 'camera'
1135
- });
1136
- } else {
1137
- throw error;
1138
- }
1139
- }
1140
- }
1141
- return yield _requestCamera(video, facingMode);
1142
- } else {
1143
- return yield _requestCamera(video, facingMode);
1144
- }
1391
+ return yield _requestCamera(video, facingMode);
1145
1392
  } catch (error) {
1146
1393
  if (error === BROWSER_CAMERA_ERRORS.NOT_SUPPORT) {
1147
- showMessage(translate('camera.error.notFound'));
1394
+ showMessage(translate('sdk.general.error.cameraNotFound.title'));
1148
1395
  throw new AuthmeError(ErrorCode.CAMERA_NOT_SUPPORT, 'Browser not support WebRTC, or https required.');
1149
1396
  }
1150
1397
  if (error === BROWSER_CAMERA_ERRORS.NO_CAMERA) {
1151
- showMessage(translate('camera.error.notFound'));
1398
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1152
1399
  throw new AuthmeError(ErrorCode.CAMERA_NOT_SUPPORT, 'camera not found');
1153
1400
  }
1154
1401
  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) {
1155
- showMessage(translate('camera.error.notFound'));
1402
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1403
+ throw new AuthmeError(ErrorCode.CAMERA_NOT_SUPPORT, error);
1404
+ }
1405
+ 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) {
1406
+ showMessage(translate('sdk.general.error.cameraNotFound.content'));
1407
+ /* NOT_READABLE_ERROR,ABORT_ERROR 這兩個錯誤是用戶授權了,但在呼叫裝置時出現錯誤,
1408
+ * 常發生在APP webview ,例如: 手機開啟 web 使用 sdk,儘管在 webview 層級上授權了,但手機在設定層級沒有授權 app 使用相機,會導致此問題。
1409
+ * 但每個 android 手機的在這方面的實作不一致,不是每個手機在這種情況下都會拋出錯誤。
1410
+ * 參考 https://developer.mozilla.org/zh-CN/docs/Web/API/MediaDevices/getUserMedia#notreadableerror
1411
+ */
1156
1412
  throw new AuthmeError(ErrorCode.CAMERA_NOT_SUPPORT, error);
1157
1413
  }
1158
1414
  if (isOverconstrainedError(error)) {
1159
- showMessage(translate('camera.error.lowResolution'));
1415
+ showMessage(translate('sdk.general.error.cameraLowResolution'));
1160
1416
  throw new AuthmeError(ErrorCode.CAMERA_NOT_SUPPORT, error);
1161
1417
  }
1162
1418
  throw error;
@@ -2150,15 +2406,40 @@ function RGBToLottieColor(color) {
2150
2406
  return color.map(c => c / 255);
2151
2407
  }
2152
2408
 
2153
- var name = "@authme/util";
2154
- var version$1 = "2.4.11";
2155
- var peerDependencies = {
2156
- "core-js": "^3.6.0"
2409
+ const QUEUE_LENGTH = 10;
2410
+ const requstQueue = [];
2411
+ function pushRequest(request) {
2412
+ if (requstQueue.length > QUEUE_LENGTH - 1) {
2413
+ requstQueue.shift();
2414
+ }
2415
+ requstQueue.push(request);
2416
+ }
2417
+ function clearRequest() {
2418
+ requstQueue.splice(0, requstQueue.length);
2419
+ }
2420
+ function backgroundRequest(request) {
2421
+ const requestPromise = request();
2422
+ requestPromise.catch(err => {
2423
+ if (err._code === ErrorCode.NETWORK_ERROR) {
2424
+ pushRequest(request);
2425
+ }
2426
+ });
2427
+ }
2428
+ window.ononline = () => {
2429
+ const tasks = [...requstQueue];
2430
+ clearRequest();
2431
+ tasks.forEach(request => {
2432
+ backgroundRequest(request);
2433
+ });
2157
2434
  };
2435
+
2436
+ var name = "authme/sdk";
2437
+ var version$1 = "2.7.1";
2438
+ var date = "2024-09-06T02:00:28+0000";
2158
2439
  var packageInfo = {
2159
2440
  name: name,
2160
2441
  version: version$1,
2161
- peerDependencies: peerDependencies
2442
+ date: date
2162
2443
  };
2163
2444
 
2164
2445
  var _a;
@@ -2167,4 +2448,4 @@ const version = packageInfo.version;
2167
2448
  (_a = (_b = window)[_c = Symbol.for('authme-sdk')]) !== null && _a !== void 0 ? _a : _b[_c] = {};
2168
2449
  window[Symbol.for('authme-sdk')][packageInfo.name] = version;
2169
2450
 
2170
- export { AuthmeError, ErrorCode, Icon, RGBToLottieColor, STORAGE_KEY, Storage, TIME_UNIT, UintArrayToBlob, asyncOnLineShowErrorMessage, asyncShowErrorMessage, asyncShowPopup, checkOnlineStatus, clearCanvas, colorStringToRGB, colorToRGB, combineResult, cropByRatio, dataURItoBlob, debugLog, debugTools, decodeToken, getCanvasSize, getCssVariable, getDeviceInfo, getImageData, getSystemInfo, getUserAgent, hexToRGB, hideElement, hideErrorMessage, hidePopup, isIphone14proOrProMax, isMobile, isMobileOrTablet, requestCamera, resize, retryPromiseWithCondition, showElement, showErrorMessage, showErrorMessageEventName, showPopup, splitResult, startLoadingSDK, startSpinner, stopLoadingSDK, stopSpinner, switchCamera, useState, version, videoConstraintsFactory, waitTime };
2451
+ export { AuthmeError, ErrorCode, Icon, RGBToLottieColor, RUN_FUNCTION_NAME, STORAGE_KEY, Storage, TIME_UNIT, UintArrayToBlob, asyncOnLineShowErrorMessage, asyncShowErrorMessage, asyncShowPopup, backgroundRequest, checkOnlineStatus, clearCanvas, colorStringToRGB, colorToRGB, combineResult, cropByRatio, dataURItoBlob, debugLog, debugTools, decodeToken, getCanvasSize, getCssVariable, getDeviceInfo, getImageData, getSystemInfo, hexToRGB, hideElement, hideErrorMessage, hidePopup, isIphone14proOrProMax, isMobile, isMobileOrTablet, osVersion, requestCamera, resize, retryPromiseWithCondition, showElement, showErrorMessage, showErrorMessageEventName, showPopup, splitResult, startLoadingSDK, startSpinner, stopLoadingSDK, stopSpinner, switchCamera, useState, version, videoConstraintsFactory, waitTime };