UNPKG

dynamsoft-mrz-scanner

Version:

Dynamsoft MRZ Scanner JavaScript Edition is a ready-to-use SDK for web applications that accurately recognizes and parses Machine-Readable Zones on Machine-Readable Travel Documents.

2 lines (1 loc) 49.1 kB
import{EnumCapturedResultItemType as e,EnumImagePixelFormat as n,CoreModule as t}from"dynamsoft-core";export*from"dynamsoft-core";import{LicenseManager as i}from"dynamsoft-license";export*from"dynamsoft-license";import{CapturedResultReceiver as s,CaptureVisionRouter as a}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";import{Feedback as o,CameraView as r,CameraEnhancer as l}from"dynamsoft-camera-enhancer";export*from"dynamsoft-camera-enhancer";import{LabelRecognizerModule as c}from"dynamsoft-label-recognizer";export*from"dynamsoft-label-recognizer";import{EnumValidationStatus as d,CodeParserModule as h}from"dynamsoft-code-parser";export*from"dynamsoft-code-parser";import{MultiFrameResultCrossFilter as u}from"dynamsoft-utility";export*from"dynamsoft-utility";var m,g,p;!function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2",e.PassportAndTD1="passportAndTd1",e.PassportAndTD2="passportAndTd2",e.TD1AndTD2="td1AndTd2",e.All="all"}(m||(m={})),function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2"}(g||(g={})),function(e){e.Scanner="scanner",e.Result="scan-result"}(p||(p={}));const f={[m.Passport]:"ReadPassport",[m.TD1]:"ReadId-TD1",[m.TD2]:"ReadId-TD2",[m.PassportAndTD1]:"ReadPassportAndId-TD1",[m.PassportAndTD2]:"ReadPassportAndId-TD2",[m.TD1AndTD2]:"ReadId",[m.All]:"ReadPassportAndId"};var y;function w(e){if("string"==typeof e){const n=document.querySelector(e);if(!n)throw new Error("Element not found");return n}return e instanceof HTMLElement?e:null}!function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(y||(y={}));function v(e,n){if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent=n,document.head.appendChild(t)}}const S=e=>!e||0===Object.keys(e).length;function E(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const D={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function R(e,n={}){const{message:t,spinnerSize:i=32}=n,s=document.createElement("div");s.className="dynamsoft-mrz-loading-screen";const a=document.createElement("div");a.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n <svg \n xmlns="http://www.w3.org/2000/svg" \n viewBox="0 0 24 24" \n fill="none" \n stroke="white" \n stroke-linecap="round" \n stroke-linejoin="round" \n width="${i}" \n height="${i}" \n stroke-width="0.75"\n > \n <path d="M12 3a9 9 0 1 0 9 9"></path> \n </svg>\n `;if(o.innerHTML=r,t){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=t,o.appendChild(e)}return a.appendChild(o),s.appendChild(a),e.appendChild(s),{element:s,updateMessage:e=>{let n=a.querySelector(".dynamsoft-mrz-loading-message");null!==e?n?n.textContent=e:(n=document.createElement("div"),n.className="dynamsoft-mrz-loading-message",n.textContent=e,o.appendChild(n)):null==n||n.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=s.parentNode)||void 0===e||e.removeChild(s)}),200))}}}const C='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var T;!function(e){e.InvalidFields="invalidFields",e.DocumentType="documentType",e.DocumentNumber="documentNumber",e.MRZText="mrzText",e.FirstName="firstName",e.LastName="lastName",e.Age="age",e.Sex="sex",e.IssuingState="issuingState",e.Nationality="nationality",e.DateOfBirth="dateOfBirth",e.DateOfExpiry="dateOfExpiry"}(T||(T={}));const M={[T.InvalidFields]:"Invalid Fields",[T.DocumentType]:"Document Type",[T.DocumentNumber]:"Document Number",[T.MRZText]:"MRZ Text",[T.FirstName]:"Given Name(s)",[T.LastName]:"Surname",[T.Age]:"Age",[T.Sex]:"Sex",[T.IssuingState]:"Issuing State",[T.Nationality]:"Nationality",[T.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[T.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function x(e,n,t,i=!1){const s=parseInt(e,10);let a;if(i)a=s>=60?1900+s:2e3+s;else{a=s>(new Date).getFullYear()%100?1900+s:2e3+s}return{year:a,month:parseInt(n,10),day:parseInt(t,10)}}function b(e){const n=e=>{var n;return 1===(null===(n=`${e}`)||void 0===n?void 0:n.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${n(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${n(null==e?void 0:e.day)}`}`}function z(e,n){const t=[],i=e=>n.getFieldValidationStatus(e)===d.VS_FAILED,s=n.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return g.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return g.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return g.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(s),r=a===g.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",l=x(n.getFieldValue("birthYear"),n.getFieldValue("birthMonth"),n.getFieldValue("birthDay")),c=x(n.getFieldValue("expiryYear"),n.getFieldValue("expiryMonth"),n.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{i(e)&&t.push(T.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{i(e)&&t.push(T.DateOfExpiry)}));const h={[T.LastName]:n.getFieldValue("primaryIdentifier"),[T.FirstName]:n.getFieldValue("secondaryIdentifier"),[T.Nationality]:n.getFieldRawValue("nationality"),[T.DocumentNumber]:n.getFieldValue(r)||n.getFieldValue("longDocumentNumber"),[T.IssuingState]:n.getFieldRawValue("issuingState"),[T.Sex]:E(n.getFieldValue("sex"))};Object.keys(h).forEach((e=>{let n=!1;switch(e){case T.FirstName:n=i("secondaryIdentifier");break;case T.LastName:n=i("primaryIdentifier");break;case T.DocumentNumber:n=i(r)||i("longDocumentNumber");break;default:n=i(e)}n&&t.push(e)}));const u=function(e){const n=new Date,t=n.getMonth()+1>e.month||n.getMonth()+1===e.month&&n.getDate()>=e.day;return n.getFullYear()-e.year-(t?0:1)}(l);u<1&&t.push(T.Age);return{[T.InvalidFields]:t,[T.FirstName]:h[T.FirstName],[T.LastName]:h[T.LastName],[T.Age]:u,[T.DateOfBirth]:l,[T.Sex]:h[T.Sex],[T.Nationality]:h[T.Nationality],[T.DocumentNumber]:h[T.DocumentNumber],[T.DateOfExpiry]:c,[T.IssuingState]:h[T.IssuingState],[T.DocumentType]:E(o),[T.MRZText]:e}}const V={[g.TD1]:{width:85.6,height:53.98},[g.TD2]:{width:105,height:74},[g.Passport]:{width:125,height:88}};class I{showScannerLoadingOverlay(e){const n=w(this.config.container);this.loadingScreen=R(n,{message:e}),n.style.display="block",n.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(w(this.config.container).style.display="none"))}constructor(e,n){this.resources=e,this.config=n,this.isSoundFeedbackOn=!1,this.scanModeManager={[g.Passport]:!0,[g.TD1]:!0,[g.TD2]:!0},this.currentScanMode=m.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),v("dynamsoft-mrz-loading-screen-style",C);try{const{cameraView:n,cameraEnhancer:t,cvRouter:i}=this.resources;if(n.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),n.setVideoFit("cover"),i.setInput(t),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const n=new u;n.enableResultCrossVerification(e.CRIT_TEXT_LINE,!0),n.enableResultDeduplication(e.CRIT_TEXT_LINE,!0),await i.addResultFilter(n)}const a=new s;a.onCapturedResultReceived=e=>this.handleMRZResult(e),await i.addResultReceiver(a),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(t)}}}initializeElements(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case m.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case m.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case m.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case m.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(g.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(g.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(g.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:y.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...n.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...n.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async n=>{const i=e.getAttribute("data-davice-id"),s=e.getAttribute("data-height"),a=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):s&&a&&this.resources.cameraEnhancer.setResolution({width:parseInt(a),height:parseInt(s)}).then((()=>{this.toggleScanGuide()})),"none"!==t.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=t.querySelectorAll(".dce-mn-camera-option"),s=t.querySelectorAll(".dce-mn-resolution-option"),a=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const n=e;n.getAttribute("data-davice-id")===(null==a?void 0:a.deviceId)?n.style.border="2px solid #fe814a":n.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const n=e.width*e.height,t=e.width/e.height;let i="480p",s=Number.MAX_VALUE;for(const[e,a]of Object.entries(D)){const o=a.width*a.height,r=a.width/a.height,l=.7*Math.abs(o-n)+Math.abs(r-t)*o*.3;l<s&&(s=l,i=e)}return i}(o);s.forEach((e=>{const n=e,t=n.getAttribute("data-height");n.style.border=t===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),t.click()}async uploadImage(){var n,t,i;const{cvRouter:s}=this.resources,a=document.createElement("input");a.type="file",a.accept="image/*",a.style.display="none",document.body.appendChild(a);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const o=await new Promise(((e,n)=>{a.onchange=t=>{var i;const s=null===(i=t.target.files)||void 0===i?void 0:i[0];(null==s?void 0:s.type.startsWith("image/"))?e(s):n(new Error("Please select an image file"))},a.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),a.click()}));if(!o)return this.hideScannerLoadingOverlay(!1),void await this.launch();const r=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await s.getSimplifiedSettings(r);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(r,e)}const l=await s.capture(o,r);this.capturedResultItems=l.items;const c=this.capturedResultItems.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;c.toCanvas=()=>{const e=document.createElement("canvas");e.width=c.width,e.height=c.height;const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");const t=new ImageData(new Uint8ClampedArray(c.bytes.buffer),c.width,c.height);return n.putImageData(t,0,0),e},this.originalImageData=c;const d=null==l?void 0:l.textLineResultItems,h=null==l?void 0:l.parsedResultItems;let u={};if(null==d?void 0:d.length){const e=(null===(n=d[0])||void 0===n?void 0:n.text)||"";u=z(e,h[0])}const m={status:{code:y.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:u};null===(i=(t=this.resources).onResultUpdated)||void 0===i||i.call(t,m),this.currentScanResolver(m),this.hideScannerLoadingOverlay(!0)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(t)}finally{document.body.removeChild(a)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const n=w(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-mn-sound-feedback"),s=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",s.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:n,cameraView:t}=this.resources;if(!n||!n.isOpen())return;const i=t.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const s=t.getVideoElement(),a=s.videoWidth,o=s.videoHeight,r=V[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,h=l*r.height,u=(i.width-d)/2,m=(c-h)/2,g=u,p=u+d,f=m,y=m+h,w=(i.x+g)/a*100,v=(i.x+p)/a*100,S=(i.y+f)/o*100,E=(i.y+y)/o*100,D={left:Math.round(w),right:Math.round(v),top:Math.round(S),bottom:Math.round(E),isMeasuredInPercentage:!0};null==t||t.setScanRegionMaskVisible(!0),n.setScanRegion(D)}toggleScanGuide(e){const n=w(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-scanguide-passport"),s=t.shadowRoot.querySelector(".dce-scanguide-td1"),a=t.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return i.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case m.All:case m.Passport:case m.PassportAndTD1:case m.PassportAndTD2:i.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(g.Passport);break;case m.TD1:case m.TD1AndTD2:i.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(g.TD1);break;case m.TD2:i.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(g.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:n}=this.resources,t=w(this.config.container);if(t.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=n.getUIElement();i.parentElement||t.append(i),await e.open()}!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(t)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:n,cameraView:t}=this.resources,i=w(this.config.container);i.style.display=e?"none":"block",(null==t?void 0:t.getUIElement().parentElement)&&i.removeChild(t.getUIElement()),n.close(),this.stopCapturing()}catch(e){let n=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${n}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:n}=this.resources;n.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(n){var t;if(this.capturedResultItems=n.items,!(n.items.length<=1))try{const{onResultUpdated:i}=this.resources,s=n.items.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE));this.originalImageData=s.length&&s[0].imageData;const a=null==n?void 0:n.textLineResultItems,r=null==n?void 0:n.parsedResultItems;if(a){this.isSoundFeedbackOn&&o.beep();const e=(null===(t=null==a?void 0:a[0])||void 0===t?void 0:t.text)||"",n=z(e,r[0]);this.closeCamera();const s={status:{code:y.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:n};null==i||i(s),this.currentScanResolver(s)}}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(t)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[g.Passport]:!0,[g.TD1]:!0,[g.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(e)?e:[e]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([e,n])=>n)).map((([e])=>e)).sort().join(",");return{[g.Passport]:m.Passport,[g.TD1]:m.TD1,[g.TD2]:m.TD2,[`${g.Passport},${g.TD1}`]:m.PassportAndTD1,[`${g.Passport},${g.TD2}`]:m.PassportAndTD2,[`${g.TD1},${g.TD2}`]:m.TD1AndTD2,[`${g.Passport},${g.TD1},${g.TD2}`]:m.All,"":m.All}[e]}DCEShowToast(e,n=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),n))}async startCapturing(){const{cvRouter:e,cameraEnhancer:t}=this.resources,i=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const n=await e.getSimplifiedSettings(i);n.roiMeasuredInPercentage=!0,n.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(i,n)}await e.startCapturing(i),t.setPixelFormat(n.IPF_ABGR_8888)}catch(e){let n=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",n),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:y.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([n,t])=>t&&n!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[g.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[g.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[g.Passport])}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(t)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:n}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&n.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(t)}}}const L={rescan:'<svg id="re-take" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="28.761" height="23" viewBox="0 0 28.761 23">\n<defs>\n<clipPath id="retakeclip-path">\n <rect id="Rectangle_2773" data-name="Rectangle 2773" width="28.761" height="23" fill="#fff"/>\n</clipPath>\n</defs>\n<g id="Group_580" data-name="Group 580" clip-path="url(#retakeclip-path)">\n<path id="Path_1522" data-name="Path 1522" d="M25.877,3.639H21.663a.7.7,0,0,1-.575-.288l-.575-.764C19.264.961,18.59,0,17.44,0H11.4C10.151,0,9.486.961,8.336,2.588l-.674.764a.7.7,0,0,1-.575.288H2.875C.476,3.639,0,5.077,0,6.227v13.9C0,22.041,1.051,23,2.974,23H25.787c1.914,0,2.974-.961,2.974-2.776v-14c-.008-1.147-.485-2.585-2.884-2.585m-.1,18.411H2.974c-1.339,0-2.013-.575-2.013-1.824v-14c0-.863.189-1.626,1.914-1.626H7.188a1.666,1.666,0,0,0,1.339-.674L9.1,3.162c1.15-1.626,1.536-2.2,2.2-2.2H17.34c.674,0,1.15.575,2.3,2.2l.575.764a1.562,1.562,0,0,0,1.339.674h4.313c1.725,0,1.914.764,1.914,1.626v14h.009c0,1.249-.673,1.824-2.012,1.824" fill="#fff"/>\n<path id="Path_1523" data-name="Path 1523" d="M15.978,9.16H9.462l1.745-1.743A.5.5,0,0,0,10.5,6.71l-2.6,2.6a.484.484,0,0,0-.108.162.5.5,0,0,0,0,.382.479.479,0,0,0,.108.163l2.6,2.6a.5.5,0,0,0,.708-.708L9.462,10.16h6.516a4.028,4.028,0,0,1,0,8.055H10.255a.5.5,0,1,0,0,1h5.723a5.028,5.028,0,0,0,0-10.055" fill="#fff"/>\n</g>\n</svg>\n',complete:'\n<svg id="continue" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">\n<defs>\n<clipPath id="continueclip-path">\n <rect id="Rectangle_2774" data-name="Rectangle 2774" width="24" height="24" fill="currentColor"/>\n</clipPath>\n</defs>\n<g id="Group_582" data-name="Group 582" clip-path="url(#continueclip-path)">\n<path id="Path_1524" data-name="Path 1524" d="M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0m0,23A11,11,0,1,1,23,12,11.013,11.013,0,0,1,12,23" fill="currentColor"/>\n<path id="Path_1525" data-name="Path 1525" d="M19.862,12a.17.17,0,0,0,0-.024.512.512,0,0,0-.033-.168.532.532,0,0,0-.113-.17l-4.219-4.29a.5.5,0,0,0-.714,0,.51.51,0,0,0,0,.719l3.371,3.428H4.643a.509.509,0,0,0,0,1.018h13.5l-3.373,3.428a.512.512,0,0,0,0,.72.5.5,0,0,0,.714,0l4.224-4.295a.438.438,0,0,0,.056-.086.5.5,0,0,0,.051-.078A.521.521,0,0,0,19.862,12h0" fill="currentColor"/>\n</g>\n</svg>\n',failed:'\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n viewBox="0 0 20 20"\n fill="none"\n stroke="#ef4444"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M18 6l-12 12" />\n <path d="M6 6l12 12" />\n</svg>\n',info:'\n<svg\n xmlns="http://www.w3.org/2000/svg"\n width="24"\n height="24"\n viewBox="0 0 24 24"\n fill="none"\n stroke="white"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n>\n <path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0" />\n <path d="M12 9h.01" />\n <path d="M11 12h1v4h1" />\n</svg>\n'};class N{constructor(e,n,t){this.resources=e,this.config=n,this.scannerView=t,this.editedFields={}}async launch(){try{return w(this.config.container).textContent="",await this.initialize(),w(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let n=(null==e?void 0:e.message)||e;throw console.error(n),n}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const n=await this.scannerView.launch();if((null===(e=null==n?void 0:n.status)||void 0===e?void 0:e.code)===y.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(n));this.resources.onResultUpdated&&((null==n?void 0:n.status.code)===y.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==n?void 0:n.status.code)===y.RS_SUCCESS&&this.resources.onResultUpdated(n)),this.dispose(!0),await this.initialize(),w(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,n;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!S(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(n=this.config)||void 0===n?void 0:n.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var e,n,t,i,s,a,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){v("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const n=document.createElement("div");return n.className="dynamsoft-mrz-controls",e.forEach((e=>{const t=document.createElement("div");t.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(s=e.icon).trim().startsWith("<svg")&&s.trim().endsWith("</svg>"))i.innerHTML=e.icon;else{const n=document.createElement("img");n.src=e.icon,n.alt=e.label,n.width=24,n.height=24,i.appendChild(n)}var s;const a=document.createElement("div");a.className="dynamsoft-mrz-control-text",a.textContent=e.label,e.isDisabled&&t.classList.add("disabled"),e.isHidden&&t.classList.add("hide"),t.appendChild(i),t.appendChild(a),e.onClick&&!e.isDisabled&&t.addEventListener("click",e.onClick),n.appendChild(t)})),n}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||L.rescan,label:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.icon)||L.complete,label:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,n){if(e===T.DateOfBirth||e===T.DateOfExpiry)try{const[t,i,s]=n.split(/[\/\-\.]/);s&&i&&t&&(this.editedFields[e]={day:parseInt(s,10),month:parseInt(i,10),year:parseInt(t,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[e]=n}createMRZDataDisplay(){var e;const n=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},t=!!this.config.allowResultEditing,i=n.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",S(n)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(i.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n <div class="dynamsoft-mrz-error-icon">${L.failed}</div>\n <div class="dynamsoft-mrz-error-message">\n ${t?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n </div>\n `,s.appendChild(e)}else if(0===i.length&&t){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n <div class="dynamsoft-mrz-info-icon">${L.info}</div>\n <div class="dynamsoft-mrz-info-message">\n Please review all fields to ensure the information is correct.\n </div>\n `,s.appendChild(e)}return Object.entries(n).forEach((([e,n])=>{var a;if(e===T.InvalidFields||!n)return;if(e===T.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const r=i.includes(e);r&&o.classList.add("invalid-field");const l=[T.MRZText,T.DocumentType],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=M[e]||e,r){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=L.failed,c.appendChild(e),t){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",c.appendChild(e)}}const d=document.createElement("div");if(d.className="dynamsoft-mrz-data-value",t&&!l.includes(e)){const t=document.createElement("input");t.className="dynamsoft-mrz-data-input",r&&t.classList.add("invalid"),e===T.DateOfBirth||e===T.DateOfExpiry?(t.value=b(n),t.setAttribute("placeholder","YYYY-MM-DD")):t.value=n,t.addEventListener("input",(n=>{if(this.handleFieldEdit(e,n.target.value),r){t.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...i]);const n=this.editedFields.invalidFields.indexOf(e);n>-1&&this.editedFields.invalidFields.splice(n,1)}})),d.appendChild(t)}else e===T.MRZText?(d.classList.add("code"),d.innerText=n):e===T.DateOfBirth||e===T.DateOfExpiry?d.innerText=b(n):d.innerText=n,r&&d.classList.add("invalid-value");o.appendChild(c),o.appendChild(d),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");v("dynamsoft-mrz-result-view-style",_);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const n=this.resources.result.originalImageResult,t=document.createElement("div");let i;t.className="dynamsoft-mrz-result-view-image-container",(null==n?void 0:n.toCanvas)&&(i=null==n?void 0:n.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),t.appendChild(i),e.appendChild(t)}const n=this.createMRZDataDisplay();e.appendChild(n);const t=this.createControls();e.appendChild(t),w(this.config.container).appendChild(e)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n)}}hideView(){w(this.config.container).style.display="none"}dispose(e=!1){w(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const _="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",k={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class F{showLoadingOverlay(e){var n,t;const i=w(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||w(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen=R(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var n,t,i;const s=w(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||w(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(s.style.display="none",(null===(i=this.config)||void 0===i?void 0:i.container)&&(w(this.config.container).style.display="none")))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};v("dynamsoft-mrz-loading-screen-style",C),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new I(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new N(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const n=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return alert(n),console.error(n),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,n,s;try{return i.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",!0),t.engineResourcePaths=S(null===(n=this.config)||void 0===n?void 0:n.engineResourcePaths)?k:this.config.engineResourcePaths,t.loadWasm(["DLR","DCP"]),h.loadSpec("MRTD_TD3_PASSPORT"),h.loadSpec("MRTD_TD1_ID"),h.loadSpec("MRTD_TD2_ID"),c.loadRecognitionData("MRZ"),this.resources.cameraView=await r.createInstance(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.cameraEnhancerUIPath),this.resources.cameraEnhancer=await l.createInstance(this.resources.cameraView),this.resources.cvRouter=await a.createInstance(),!0}catch(e){let n=(null==e?void 0:e.message)||e;if(null==n?void 0:n.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${n}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,n;const t=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container));return t&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,n,t,i,s,a,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!w(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)&&!w(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!w(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const n=`Error accessing container references: ${e.message}`;return alert(n),console.error(n),!1}return!0}showResultView(){var e,n;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container))}initializeMRZScannerConfig(){var e,n,t,i,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=w(this.config.container));const r=this.config.container?this.createViewContainers(w(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(m).map((e=>{var n;return[e,(null===(n=this.config.utilizedTemplateNames)||void 0===n?void 0:n[e])||f[e]]}))),templateFilePath:(null===(n=this.config)||void 0===n?void 0:n.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:r[p.Scanner]||w(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||null,cameraEnhancerUIPath:(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:r[p.Result]||w(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:c,resultViewConfig:d})),!0}createViewContainers(e){e.textContent="";const n=[p.Scanner];return this.showResultView()&&n.push(p.Result),n.reduce(((n,t)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${t}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(i),n[t]=i,n}),{})}dispose(){var e,n;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const t=e=>{const n=w(e);n&&(n.style.display="none",n.textContent="")};t(this.config.container),t(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),t(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:e}=await this.initialize();if(S(e))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(w(this.config.container).style.display="block"),!e.scannerView&&this.resources.result&&e.resultView)return await e.resultView.launch();if(!e.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(e.scannerView){const n=await e.scannerView.launch();if((null==n?void 0:n.status.code)!==y.RS_SUCCESS)return{status:{code:null==n?void 0:n.status.code,message:(null==n?void 0:n.status.message)||"Failed to capture image"}};if(e.resultView)return await e.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const O={MRZScanner:F,MRZScannerView:I,MRZResultView:N};export{f as DEFAULT_TEMPLATE_NAMES,O as DynamsoftMRZScanner,T as EnumMRZData,g as EnumMRZDocumentType,m as EnumMRZScanMode,p as EnumMRZScannerViews,y as EnumResultStatus,M as MRZDataLabel,N as MRZResultView,F as MRZScanner,I as MRZScannerView,b as displayMRZDate};