l||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=Vr._onLog)||void 0===n||n.call(Vr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Wn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Wn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Mn(this,Kn,!0)}}Jn=new WeakMap,Kn=new WeakMap;const Ur=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Gr{static get version(){return"2.0.18"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const a=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return a?a.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Vn.OS))return Gr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Vn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const a=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let o=!1;const l=()=>{o=!0,s&&clearTimeout(s),a(),n(t)},h=t=>{s&&clearTimeout(s),a(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},d=()=>{l()},f=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!o){i&&(s=setTimeout((()=>{a(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!o)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Ln(this,ur,"f"))return"closed";if("pending"===Ln(this,ur,"f"))return"opening";if("fulfilled"===Ln(this,ur,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Gr.isStorageAvailable("localStorage")?Mn(this,or,!0):(Mn(this,or,!1),console.warn("Local storage is unavailable")):Mn(this,or,!1)}get ifSaveLastUsedCamera(){return Ln(this,or,"f")}get isVideoPlaying(){return!(!Ln(this,tr,"f")||Ln(this,tr,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Ln(this,_r,"f"))||void 0===e||e.removeEventListener("click",Ln(this,pr,"f")),null===(i=Ln(this,_r,"f"))||void 0===i||i.removeEventListener("touchend",Ln(this,pr,"f")),null===(n=Ln(this,_r,"f"))||void 0===n||n.removeEventListener("touchmove",Ln(this,mr,"f")),Mn(this,_r,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)?(t.addEventListener("touchend",Ln(this,pr,"f")),t.addEventListener("touchmove",Ln(this,mr,"f"))):t.addEventListener("click",Ln(this,pr,"f")))}get tapFocusEventBoundEl(){return Ln(this,_r,"f")}get disposed(){return Ln(this,Ir,"f")}constructor(t){var e,i;Qn.add(this),tr.set(this,null),er.set(this,void 0),ir.set(this,(()=>{"opened"===this.state&&Ln(this,Er,"f").fire("resumed",null,{target:this,async:!1})})),nr.set(this,(()=>{Ln(this,Er,"f").fire("paused",null,{target:this,async:!1})})),rr.set(this,void 0),sr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ar.set(this,void 0),or.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,lr.set(this,void 0),hr.set(this,!0),cr.set(this,void 0),ur.set(this,void 0),dr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},fr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ln(this,tr,"f")).objectFit,s=this.getResolution(),a=Ln(this,tr,"f").getBoundingClientRect(),o=a.left,l=a.top,{width:h,height:c}=Ln(this,tr,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=h/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=h/s.width,i=(t-o)/f,n=(e-l-(c-h/d)/2)/f):(f=c/s.height,n=(e-l)/f,i=(t-o-(h-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-l)/f,i=(t-o+(c*d-h)/2)/f):(f=h/s.width,i=(t-o)/f,n=(e-l+(h/d-c)/2)/f)}return{x:i,y:n}},gr.set(this,!1),mr.set(this,(()=>{Mn(this,gr,!0)})),pr.set(this,(async t=>{var e;if(Ln(this,gr,"f"))return void Mn(this,gr,!1);if(!Ln(this,fr,"f"))return;if(!this.isVideoPlaying)return;if(!Ln(this,er,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let a;try{a=this.calculateCoordInVideo(i,n)}catch(t){}if(a.x<0||a.x>r.width||a.y<0||a.y>r.height)return;const o={x:a.x+"px",y:a.y+"px"},l=s+"px",h=l;let c;Gr._onLog&&(c=Date.now());try{await Ln(this,Qn,"m",kr).call(this,o,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Gr._onLog)throw Gr._onLog(t),t}Gr._onLog&&Gr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Gr._onLog&&Gr._onLog("Back to continuous focus."),null===(t=Ln(this,er,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Ln(this,Er,"f").fire("tapfocus",null,{target:this,async:!1})})),_r.set(this,null),vr.set(this,1),yr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ln(this,tr,"f"))return;const t=Ln(this,vr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ln(this,tr,"f").style.transform="";else{const e=window.getComputedStyle(Ln(this,tr,"f")).objectFit,i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight,{width:r,height:s}=Ln(this,tr,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const a=r/s,o=i/n;let l=1;"contain"===e?l=aa?s/(i/t):r/(n/t));const h=l*(1-1/t)*(i/2-Ln(this,yr,"f").x),c=l*(1-1/t)*(n/2-Ln(this,yr,"f").y);Ln(this,tr,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},wr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Wn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Gr._onLog&&Gr._onLog("document visible. video paused: "+(null===(t=Ln(this,tr,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}}}else"hidden"===document.visibilityState&&(Gr._onLog&&Gr._onLog("document hidden. video paused: "+(null===(e=Ln(this,tr,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Ir.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Gr.onWarning&&Gr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Mn(this,Er,new jr),this.imageDataGetter=new Vr,document.addEventListener("visibilitychange",Ln(this,br,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ln(this,ir,"f")),t.addEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,t)}getVideoEl(){return Ln(this,tr,"f")}releaseVideoEl(){var t,e;null===(t=Ln(this,tr,"f"))||void 0===t||t.removeEventListener("play",Ln(this,ir,"f")),null===(e=Ln(this,tr,"f"))||void 0===e||e.removeEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,null)}isVideoLoaded(){return!!Ln(this,tr,"f")&&4==Ln(this,tr,"f").readyState}async open(){if(Ln(this,cr,"f")&&!Ln(this,hr,"f")){if("pending"===Ln(this,ur,"f"))return Ln(this,cr,"f");if("fulfilled"===Ln(this,ur,"f"))return}Ln(this,Er,"f").fire("before:open",null,{target:this}),await Ln(this,Qn,"m",Ar).call(this),Ln(this,Er,"f").fire("played",null,{target:this,async:!1}),Ln(this,Er,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ln(this,Er,"f").fire("before:close",null,{target:this});const t=Ln(this,cr,"f");if(Ln(this,Qn,"m",Mr).call(this),t&&"pending"===Ln(this,ur,"f")){try{await t}catch(t){}if(!1===Ln(this,hr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Mn(this,cr,null),Mn(this,ur,null),Ln(this,Er,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Ln(this,tr,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Ln(this,tr,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),delete Ln(this,rr,"f").video.facingMode,Ln(this,rr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),(null==t?void 0:t.resolution)&&(Ln(this,rr,"f").video.width={ideal:t.resolution.width},Ln(this,rr,"f").video.height={ideal:t.resolution.height}),delete Ln(this,rr,"f").video.deviceId,Ln(this,rr,"f").video.facingMode={exact:"user"},Mn(this,ar,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}getCamera(){var t;if(Ln(this,sr,"f"))return Ln(this,sr,"f");{let e=(null===(t=Ln(this,rr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),i?(Ln(this,rr,"f").video.width={exact:t},Ln(this,rr,"f").video.height={exact:e}):(Ln(this,rr,"f").video.width={ideal:t},Ln(this,rr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))return null;Ln(this,Er,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Ln(this,tr,"f"))return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};if(Ln(this,er,"f")){const t=Ln(this,er,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};{const t={width:0,height:0};let e=Ln(this,rr,"f").video.width||0,i=Ln(this,rr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,a,o,l,h,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Ln(this,Sr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Ln(this,sr,"f"))||void 0===u?void 0:u.deviceId;let e=Ln(this,Sr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ln(this,Sr,"f").set(d,e),Mn(this,dr,!0);try{for(let t of this.detectedResolutions){await Ln(this,er,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ln(this,Qn,"m",Rr).call(this);const i=Ln(this,er,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,dr,!1),t}try{await Ln(this,Qn,"m",Ar).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Mn(this,dr,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let a=null;try{const t=s[0].getSettings();a={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,a={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),a};let i=(null===(s=null===(r=null===(n=Ln(this,rr,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(l=null===(o=null===(a=Ln(this,rr,"f"))||void 0===a?void 0:a.video)||void 0===o?void 0:o.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Ln(this,rr,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ln(this,Sr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ln(this,Sr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Mn(this,rr,JSON.parse(JSON.stringify(t))),Mn(this,ar,null),e&&Ln(this,Qn,"m",Lr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ln(this,rr,"f")))}resetMediaStreamConstraints(){Mn(this,rr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getCapabilities?Ln(this,er,"f").getCapabilities():{}}getCameraSettings(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getSettings()}async turnOnTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Ln(this,er,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ur(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Ln(this,Qn,"m",kr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Mn(this,fr,!0)}disableTapToFocus(){Mn(this,fr,!1)}isTapToFocusEnabled(){return Ln(this,fr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Ln(this,Qn,"m",Nr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ln(this,Qn,"m",Br).call(this,Ln(this,yr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Ln(this,vr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Ln(this,Qn,"m",Nr).call(this,e),Mn(this,vr,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ln(this,vr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Mn(this,yr,{x:t.width/2,y:t.height/2})}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Ln(this,dr,"f"))return null;const e=Date.now();Gr._onLog&&Gr._onLog("getFrameData() START: "+e);const i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=Wn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let a=Ln(this,vr,"f");(null==t?void 0:t.scale)&&(a=t.scale);let o=Ln(this,yr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");o.x=Math.round(e),o.y=Math.round(r)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==a&&(r.sWidth=Math.round(r.sWidth/a),r.sHeight=Math.round(r.sHeight/a),r.sx=Math.round((1-1/a)*o.x+r.sx/a),r.sy=Math.round((1-1/a)*o.y+r.sy/a));const h=this.imageDataGetter.getImageData(Ln(this,tr,"f"),r,{pixelFormat:s,bufferContainer:l});if(!h)return null;const c=Date.now();return Gr._onLog&&Gr._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ln(this,wr,"f")}}on(t,e){if(!Ln(this,Cr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ln(this,Er,"f").on(t,e)}off(t,e){Ln(this,Er,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ln(this,Er,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ln(this,br,"f")),Mn(this,Ir,!0)}}var Wr,Yr,zr,Hr,Xr,Zr,qr,Jr,Kr,$r,Qr,ts,es,is,ns,rs,ss,as,os,ls,hs,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Es,Cs,Ss;tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,ar=new WeakMap,or=new WeakMap,lr=new WeakMap,hr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Er=new WeakMap,Cr=new WeakMap,Sr=new WeakMap,Tr=new WeakMap,br=new WeakMap,Ir=new WeakMap,Qn=new WeakSet,xr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ln(this,ar,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ln(this,ar,"f")};else if(this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)?(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)||(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Rr=function(){if(Ln(this,hr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Or=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Gr._onLog&&Gr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Ln(this,Qn,"m",Rr).call(this));try{Gr._onLog&&Gr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ln(this,Qn,"m",Rr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Gr._onLog&&Gr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Dr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Mn(this,er,null)},Ar=async function(){Mn(this,hr,!1);const t=Mn(this,lr,Symbol());if(Ln(this,cr,"f")&&"pending"===Ln(this,ur,"f")){try{await Ln(this,cr,"f")}catch(t){}Ln(this,Qn,"m",Rr).call(this)}if(t!==Ln(this,lr,"f"))return;const e=Mn(this,cr,(async()=>{Mn(this,ur,"pending");try{if(this.videoSrc){if(!Ln(this,tr,"f"))throw new Error("'videoEl' should be set.");await Gr.playVideo(Ln(this,tr,"f"),this.videoSrc,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)}else{let t=await Ln(this,Qn,"m",xr).call(this);Ln(this,Qn,"m",Dr).call(this);let e=await Ln(this,Qn,"m",Or).call(this,t);await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Ln(this,rr,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Ln(this,ar,"f")||this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Gr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Ln(this,Qn,"m",Or).call(this,t),Ln(this,Qn,"m",Rr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Mn(this,ar,r&&r.deviceId),this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ln(this,ar,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Ln(this,tr,"f")&&(await Gr.playVideo(Ln(this,tr,"f"),e,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Mn(this,er,s[0]),Mn(this,sr,r)}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,ur,null),t}Mn(this,ur,"fulfilled")})());return e},Lr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ln(this,sr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ln(this,Qn,"m",Ar).call(this);const n=this.getResolution();e&&e!==Ln(this,sr,"f").deviceId&&Ln(this,Er,"f").fire("camera:changed",[Ln(this,sr,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ln(this,Er,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ln(this,Er,"f").fire("played",null,{target:this,async:!1})},Mr=function(){Ln(this,Qn,"m",Dr).call(this),Mn(this,sr,null),Ln(this,tr,"f")&&(Ln(this,tr,"f").srcObject=null,this.videoSrc&&(Ln(this,tr,"f").pause(),Ln(this,tr,"f").currentTime=0)),Mn(this,hr,!0);try{this.resetSoftwareScale()}catch(t){}},Fr=async function t(e,i){const n=t=>{if(!Ln(this,er,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ln(this,er,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ur(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,l=e.focusH;const h=this.getResolution();s=Math.round(s),a=Math.round(a),o=Math.round(o),l=Math.round(l),o>h.width&&(o=h.width),l>h.height&&(l=h.height),s<0?s=0:s+o>h.width&&(s=h.width-o),a<0?a=0:a+l>h.height&&(a=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*o*l;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Ln(this,tr,"f"),{sx:s,sy:a,sWidth:o,sHeight:l,dWidth:o,dHeight:l},{pixelFormat:Wn.RGBA,bufferContainer:d}))return Ln(this,Qn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;to&&ou)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,u)}else{let l=await Ln(this,Qn,"m",Fr).call(this,e,c);if(o>l)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,l);if(o==l)return await Ln(this,Qn,"m",t).call(this,e,a,o,c,l);let u=await Ln(this,Qn,"m",Fr).call(this,e,h);if(u>o&&oa.width||l<0||l>a.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*a.width}if(isNaN(h)||h<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*a.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Ln(this,vr,"f")){const t=Ln(this,vr,"f"),e=Ln(this,yr,"f");h/=t,c/=t,o=(1-1/t)*e.x+o/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:o,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Ur(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ur(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ur(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Ln(this,Qn,"m",Fr).call(this,t,s),o=await Ln(this,Qn,"m",Fr).call(this,t,r),l=await Ln(this,Qn,"m",Fr).call(this,t,n);if(o>l&&la&&o>a){let e=await Ln(this,Qn,"m",Fr).call(this,t,i);const r=await Ln(this,Qn,"m",Pr).call(this,t,n,l,i,e,s,a);return this._focusParameters.isDoingFocus=0,r}if(o==l&&l l){const e=await Ln(this,Qn,"m",Pr).call(this,t,n,l,s,a);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Nr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Mn(this,yr,{x:i,y:n})},Br=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Gr.browserInfo=Vn,Gr.onWarning=null===($n=null===window||void 0===window?void 0:window.console)||void 0===$n?void 0:$n.warn;class Ts{constructor(t){Wr.add(this),Yr.set(this,void 0),zr.set(this,0),Hr.set(this,void 0),Xr.set(this,0),Zr.set(this,!1),Xe(this,Yr,t)}startCharging(){He(this,Zr,"f")||(Ts._onLog&&Ts._onLog("start charging."),He(this,Wr,"m",Jr).call(this),Xe(this,Zr,!0))}stopCharging(){He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),He(this,Zr,"f")&&(Ts._onLog&&Ts._onLog("stop charging."),Xe(this,zr,Date.now()-He(this,Xr,"f")),Xe(this,Zr,!1))}}Yr=new WeakMap,zr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,Wr=new WeakSet,qr=function(){gt.cfd(1),Ts._onLog&&Ts._onLog("charge 1.")},Jr=function t(){0==He(this,zr,"f")&&He(this,Wr,"m",qr).call(this),Xe(this,Xr,Date.now()),He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),Xe(this,Hr,setTimeout((()=>{Xe(this,zr,0),He(this,Wr,"m",t).call(this)}),He(this,Yr,"f")-He(this,zr,"f")))};class bs{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-He(this,Kr,"f",ts)<100)){if(Xe(this,Kr,e,0,ts),He(this,Kr,"f",$r).size&&(t=He(this,Kr,"f",$r).values().next().value,this.beepSoundSource==t.src?(He(this,Kr,"f",$r).delete(t),t.play()):t=null),!t)if(He(this,Kr,"f",Qr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{He(this,Kr,"f",Qr).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,He(this,Kr,"f",Qr).delete(t),He(this,Kr,"f",$r).add(t)}))}else He(this,Kr,"f",es)||(Xe(this,Kr,!0,0,es),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&He(this,Kr,"f",Qr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(bs.vibrateDuration)}}}Kr=bs,$r={value:new Set},Qr={value:new Set},ts={value:0},es={value:!1},bs.allowBeep=!0,bs.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",bs.allowVibrate=!0,bs.vibrateDuration=300;const Is=new Map([[Wn.GREY,l.IPF_GRAYSCALED],[Wn.RGBA,l.IPF_ABGR_8888]]),xs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Rs extends X{static set _onLog(t){Xe(Rs,ns,t,0,rs),Gr._onLog=t,Ts._onLog=t}static get _onLog(){return He(Rs,ns,"f",rs)}static async detectEnvironment(){return await(async()=>({wasm:Ze,worker:qe,getUserMedia:Je,camera:await Ke(),browser:ze.browser,version:ze.version,OS:ze.OS}))()}static async testCameraAccess(){const t=await Gr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof An))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await gt.loadWasm(["license"]),await ct.license.dynamsoft()}const n=new Rs(t);return Rs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Xe(this,os,t)}get singleFrameMode(){return He(this,os,"f")}get _isFetchingStarted(){return He(this,fs,"f")}get disposed(){return He(this,vs,"f")}constructor(t){if(super(),is.add(this),ss.set(this,"closed"),as.set(this,void 0),this.isTorchOn=void 0,os.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ls.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});let h=null;if(o){const t=Date.now();let a;a=o.pixelFormat===Wn.GREY?o.width:4*o.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:o.data,width:o.width,height:o.height,stride:a,format:Is.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:o.width,currentHeight:o.height,timeSpent:t-r,timeStamp:t},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=He(this,ls,"f").call(this,t,t.width,t.height,e);He(this,as,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},hs.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===l.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ze.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{He(this,ms,"f").tapToFocus&&He(this,_s,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(He(this,is,"m",ys).call(this)||!this.isOpen()||this.isPaused())return;const a=t.intermediateResultUnits;Rs._onLog&&(Rs._onLog("intermediateResultUnits:"),Rs._onLog(a));let o=!1,l=!1;for(let t of a){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){o=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(Rs._onLog&&(Rs._onLog("hasLocalizedBarcodes:"),Rs._onLog(l)),He(this,ms,"f").autoZoom||He(this,ms,"f").enhancedFocus)if(o)He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").autoZoomOutFrameCount=0,He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),He(this,ms,"f").autoZoom&&He(this,_s,"f").startCharging()},o=async t=>{await this.setFocus(t),He(this,ms,"f").enhancedFocus&&He(this,_s,"f").startCharging()};if(l){const l=a[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=l.cropRegion)||void 0===r?void 0:r.right)?l.cropRegion.right-h:l.originalWidth,d=(null===(s=l.cropRegion)||void 0===s?void 0:s.bottom)?l.cropRegion.bottom-c:l.originalHeight,f=l.currentWidth,g=l.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-He(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+He(this,ps,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-He(this,ps,"f").autoZoomDetectionArea)/2,a=s,o=this.video.videoHeight*(1+He(this,ps,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:a},{x:i,y:o},{x:n,y:o}]}Rs._onLog&&(Rs._onLog("detectionArea:"),Rs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ui(o.y-i)>0&&Ui(e-(i-a.y)*(a.x-o.x)/(a.y-o.y)-a.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Gi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of a)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{An._transformCoordinates(t,h,c,u,d,f,g)})),t(r,e)&&s.push(i)}if(Rs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=bn.createDrawingStyle({strokeStyle:"red"}));for(let i of a)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ii({points:i},e);t.addDrawingItems([r])}}}if(Rs._onLog&&(Rs._onLog("intersectedResults:"),Rs._onLog(s)),!s.length)return;let o;if(s.length){let t=s.filter((t=>t.possibleFormats==xs.BF_QR_CODE||t.possibleFormats==xs.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==xs.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};o=t[0];let i=e(o);if(1!=t.length)for(let n=1;n1.1*o.confidence||t[n].confidence>.9*o.confidence&&ri&&s>i&&a>i&&l>i&&m.result.moduleSize{})),He(this,ps,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoZoomInFrameLimit[1]){He(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-a),(.5-n)/(.5-l)].filter((t=>t>0)),o=Math.min(...i,He(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*o,1/He(this,ps,"f").autoZoomInMaxTimes),He(this,ps,"f").autoZoomInMinStep);c=Math.min(c,o);let u=h*c;u=Math.max(He(this,ps,"f").minValue,u),u=Math.min(He(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").frameArrayInIdealZoom.push(!0),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=He(this,ps,"f").frameLimitInIdealZoom[1]&&(He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ms,"f").enhancedFocus)){const e=m.points;try{await o({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.push(!0),He(this,ps,"f").autoFocusFrameArray.splice(0,He(this,ps,"f").autoFocusFrameArray.length-He(this,ps,"f").autoFocusFrameLimit[0]),He(this,ps,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoFocusFrameLimit[1])){He(this,ps,"f").autoFocusFrameArray.length=0;try{const t=m.points;await o({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(He(this,ms,"f").autoZoom){if(He(this,ps,"f").autoZoomInFrameArray.push(!1),He(this,ps,"f").autoZoomInFrameArray.splice(0,He(this,ps,"f").autoZoomInFrameArray.length-He(this,ps,"f").autoZoomInFrameLimit[0]),He(this,ps,"f").autoZoomOutFrameCount++,He(this,ps,"f").frameArrayInIdealZoom.push(!1),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").autoZoomOutFrameCount>=He(this,ps,"f").autoZoomOutFrameLimit){He(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*He(this,ps,"f").autoZoomOutStepRate,He(this,ps,"f").autoZoomOutMinStep);n=Math.max(He(this,ps,"f").minValue,n),n=Math.min(He(this,ps,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}He(this,ms,"f").enhancedFocus&&o({mode:"continuous"}).catch((()=>{}))}!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.length=0,o({mode:"continuous"}).catch((()=>{})))}}},Xe(this,_s,new Ts(1e4))}setCameraView(t){if(!(t instanceof An))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),He(this,is,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;He(this,is,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return He(this,is,"m",ys).call(this)?He(this,ss,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,He(this,is,"m",ys).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(He(this,is,"m",ys).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),a=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"");let o=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),l=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let h,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",h=n.elZoomSpan=c.querySelector("span"));let u=n.elToast=n.querySelector(".dce-mn-toast"),d=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{bs.allowBeep=!bs.allowBeep,s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"")};for(let t of[a,s])null==t||t.addEventListener("pointerdown",w);const E=()=>{bs.allowVibrate=!bs.allowVibrate,o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":"")};for(let t of[l,o])null==t||t.addEventListener("pointerdown",E);const C=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",C);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&h&&(h.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),a=null==s?void 0:s.indexOf("front");-1===a&&(a=null==s?void 0:s.indexOf("前"));let o=null==s?void 0:s.indexOf("back");-1===o&&(o=null==s?void 0:s.indexOf("后")),"number"==typeof a&&-1!==a?i=!0:"number"==typeof o&&-1!==o&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",R);let O=-1/0,D=1;const A=t=>{let e=Date.now();e-O>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),O=e};i.addEventListener("wheel",A);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let a=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),o=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(M||l-O<100)return;l-O>1e3&&(D=this.getZoomSettings().factor),D*=o/a,D>20&&(D=20),D<1&&(D=1);let h=!1;"safari"==(null===(e=null==ze?void 0:ze.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(o/a>1&&D<2?(D=2,h=!0):o/a<1&&D<2&&(D=1,h=!0)),M=!0,h&&b("zooming..."),await this.setZoom({factor:D}),h&&(u.textContent=""),M=!1,O=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[a,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[l,o])null==t||t.removeEventListener("pointerdown",E);n.removeEventListener("click",C),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",R),i.removeEventListener("wheel",A),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Xe(this,ss,"open"),t&&(t._innerComponent.style.display="",He(this,is,"m",ys).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),He(this,as,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),He(this,is,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Xe(this,ss,"closed"),He(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",He(this,is,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),He(this,as,"f").fire("closed",null,{target:this,async:!1})}pause(){if(He(this,is,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!He(this,is,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(He(this,is,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(He(this,is,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let o=0;if(l.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Rs._onLog)||void 0===t||t.call(Rs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(He(this,is,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(He(this,is,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){He(this,ps,"f").minValue=t.min,He(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:He(this,ps,"f").minValue,max:He(this,ps,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==gt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!0),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!0),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),He(this,is,"m",Es).call(this)&&He(this,is,"m",ws).call(this)||He(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");Xe(this,us,t?JSON.parse(JSON.stringify(t)):null),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(He(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Xe(this,cs,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||He(this,is,"m",ys).call(this))}startFetching(){if(He(this,is,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");He(this,fs,"f")||(Xe(this,fs,!0),He(this,is,"m",Cs).call(this))}stopFetching(){He(this,fs,"f")&&(Rs._onLog&&Rs._onLog("DCE: stop fetching loop: "+Date.now()),He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,fs,!1))}fetchImage(){if(He(this,is,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});if(!r)return null;let s;s=r.pixelFormat===Wn.GREY?r.width:4*r.width;let a=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:Is.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,He(this,fs,"f")&&(He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",Cs).call(this)}),t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Xe(this,ds,t)}getPixelFormat(){return He(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(He(this,is,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=ki.convert(He(this,us,"f"),r,s);a||(a={x:0,y:0,width:r,height:s});const o=He(this,ls,"f").call(this,n,r,s,a);t&&t(o)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!He(this,us,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=He(this,us,"f").left||He(this,us,"f").x||0,r=He(this,us,"f").top||He(this,us,"f").y||0;if(!He(this,us,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Xe(this,vs,!0)}}var Os,Ds,As,Ls,Ms,Fs,Ps,ks;ns=Rs,ss=new WeakMap,as=new WeakMap,os=new WeakMap,ls=new WeakMap,hs=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,is=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Es=function(){for(let t in He(this,ms,"f"))if(1==He(this,ms,"f")[t])return!0;return!1},Cs=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!He(this,fs,"f"))return He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),void Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval));const e=()=>{var t;let e;Rs._onLog&&Rs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=He(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=He(this,cs,"f"))||void 0===t||t.onErrorReceived(_t.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Rs._onLog&&Rs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),He(this,as,"f").fire("frameAddedToBuffer",null,{async:!1})):Rs._onLog&&Rs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case a.BOPM_BLOCK:break;case a.BOPM_UPDATE:e()}else e();He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval))},Ss=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:a,height:o}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||o<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const u=a/o,d=l/h;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(He(this,Ls,"f")||Xe(this,Ls,new Ns),!He(this,Ls,"f").magnifierCanvas)return;document.body.contains(He(this,Ls,"f").magnifierCanvas)||(He(this,Ls,"f").magnifierCanvas.style.position="fixed",He(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",He(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(He(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void He(this,Fs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,a=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];He(this,Ls,"f").update(s,t.pointer,r,a);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(He(this,Ls,"f").magnifierCanvas.style.left="auto",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="0"):(He(this,Ls,"f").magnifierCanvas.style.left="0",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="auto")}He(this,Ls,"f").show()})),Fs.set(this,(()=>{He(this,Ls,"f")&&He(this,Ls,"f").hide()})),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(y(t)){Xe(this,As,t);const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===l.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ai.Control({positionHandler:Ci,actionHandler:bi(i>0?i-1:n,Ti),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ai.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){He(this,Oi,"f")&&this.setLine(He(this,Oi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!C(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Xe(this,Oi,JSON.parse(JSON.stringify(t)))}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return He(this,Oi,"f")?JSON.parse(JSON.stringify(He(this,Oi,"f"))):null}},QuadDrawingItem:Ai,RectDrawingItem:Ei,TextDrawingItem:Ri});function Gs(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Ws(e,t,"map"),t.getFieldRawValue=t=>Ws(e,t,"raw"),t.getFieldMappingStatus=t=>Ys(e,t),t.getFieldValidationStatus=t=>zs(e,t),delete t.fullCodeString}function Ws(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Ws(r,e,i);if(void 0!==t)return t}}}function Ys(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Vs[i.MappingStatus]):Vs.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Ys(n,e);if(void 0!==t)return t}}}function zs(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(js[i.ValidationStatus]):js.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=zs(n,e);if(void 0!==t)return t}}}function Hs(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Vs||(Vs={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(js||(js={}));const Xs=t=>t&&"object"==typeof t&&"function"==typeof t.then,Zs=(async()=>{})().constructor;let qs=class extends Zs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xs(t)?e=t:"function"==typeof t&&(e=new Zs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Xs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Js="undefined"==typeof self,Ks="function"==typeof importScripts,$s=(()=>{if(!Ks){if(!Js&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();gt.engineResourcePaths.dcp={version:"2.4.32",path:$s,isInternal:!0},ut.dcp={js:!0,wasm:!0,deps:["license"]},ct.dcp={handleParsedResultItem:Gs};const Qs="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,Qs)<0&&(gt.engineResourcePaths.std={version:Qs,path:(t=>{if(null==t&&(t="./"),Js||Ks);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})($s+`../../dynamsoft-capture-vision-std@${Qs}/dist/`),isInternal:!0});let ta=class{static getVersion(){const t=ht.dcp&&ht.dcp.wasm;return`2.4.32(Worker: ${ht.dcp&&ht.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await ft("dcp"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],a=O(gt.engineResourcePaths);et.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||a.dcp+"specification/",specificationNames:s}})}))}};var ea=Object.freeze({__proto__:null,CodeParser:class t{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft("dcp");const e=new t,i=new qs;let n=nt();return rt[n]=async t=>{if(t.success)e._instanceID=t.instanceID,i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},et.postMessage({type:"dcp_createInstance",id:n}),i}async dispose(){Hs(this);let t=nt();this.bDestroyed=!0,rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return Hs(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await x(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))):console.error("Invalid settings.")}async resetSettings(){return Hs(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})}))}async parse(t,e=""){if(Hs(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise(((i,n)=>{let r=nt();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Gs(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})}))}},CodeParserModule:ta,get EnumMappingStatus(){return Vs},get EnumValidationStatus(){return js}});const ia="undefined"==typeof self,na="function"==typeof importScripts,ra=(()=>{if(!na){if(!ia&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),sa=t=>{if(null==t&&(t="./"),ia||na);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.dlr={version:"3.4.32",path:ra,isInternal:!0},null==gt.engineResourcePaths.dlrData&&(gt.engineResourcePaths.dlrData={version:"1.0.11",path:sa(ra+"../../dynamsoft-label-recognizer-data@1.0.11/dist/"),isInternal:!0}),ut.dlr={js:!0,wasm:!0,deps:["license","dip","dnn"]},ut.dnn={wasm:!0,deps:["dip"]};const aa="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,aa)<0&&(gt.engineResourcePaths.std={version:aa,path:sa(ra+`../../dynamsoft-capture-vision-std@${aa}/dist/`),isInternal:!0});const oa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,oa)<0)&&(gt.engineResourcePaths.dip={version:oa,path:sa(ra+`../../dynamsoft-image-processing@${oa}/dist/`),isInternal:!0});const la="1.0.20";(!gt.engineResourcePaths.dnn||"string"!=typeof gt.engineResourcePaths.dnn&&R(gt.engineResourcePaths.dnn.version,la)<0)&&(gt.engineResourcePaths.dnn={version:la,path:sa(ra+`../../dynamsoft-capture-vision-dnn@${la}/dist/`),isInternal:!0});let ha=!1,ca=class{static getVersion(){const t=ht.dlr&&ht.dlr.wasm;return`3.4.32(Worker: ${ht.dlr&&ht.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadRecognitionData(t,e){return await ft("dlr"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const e=t.result;if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,n(t)}return e.isModel||(ha=!0),i(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=O(gt.engineResourcePaths);e||"ConfusableChars"!==t||(e=s.dlr),et.postMessage({type:"dlr_loadData",id:r,body:{dataName:t,dataPath:e||s.dlrData}})}))}};ct.dlr={loadRecognitionData:ca.loadRecognitionData,get bLoadConfusableCharsData(){return ha}};const ua={filterVINResult:function(t){let e="";if(18===t.characterResults.length){let e=t.characterResults[9].location.points[0].x-t.characterResults[8].location.points[1].x;e<2&&(e=2);let i=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,n=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,r=2===e?3:e;i-e>=r&&n-e=r&&i-et.characterResults[17].characterHConfidence?t.characterResults.pop():t.characterResults.shift()}else if(19===t.characterResults.length){let e=t.characterResults[10].location.points[0].x-t.characterResults[9].location.points[1].x;e<2&&(e=2);let i,n,r,s=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,a=t.characterResults[18].location.points[0].x-t.characterResults[17].location.points[1].x,o=t.characterResults[2].location.points[0].x-t.characterResults[1].location.points[1].x,l=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,h=2===e?3:e;if("1"===t.characterResults[1].characterH||"1"===t.characterResults[2].characterH||"1"===t.characterResults[16].characterH||"1"===t.characterResults[17].characterH){for(let e=9;e=(i||h)&&l-e<(n||h))t.characterResults.splice(0,2);else if(l-e>=(n||h)&&o-e<(i||h))t.characterResults.splice(17,2);else if(s>e&&a>e)t.characterResults.pop(),t.characterResults.shift();else{let e=t.characterResults[0].characterHConfidence+t.characterResults[1].characterHConfidence,i=t.characterResults[17].characterHConfidence+t.characterResults[18].characterHConfidence,n=t.characterResults[0].characterHConfidence+t.characterResults[18].characterHConfidence,r=Math.min(e,i,n);r===e?t.characterResults.splice(0,2):r===i?t.characterResults.splice(17,2):r===n&&(t.characterResults.pop(),t.characterResults.shift())}}for(let i of t.characterResults)e+=i.characterH;return e},checkValidVIN:function(t){return!(!t||17!=t.length)&&(t=>{const e=new Map([["A",1],["B",2],["C",3],["D",4],["E",5],["F",6],["G",7],["H",8],["J",1],["K",2],["L",3],["M",4],["N",5],["P",7],["R",9],["S",2],["T",3],["U",4],["V",5],["W",6],["X",7],["Y",8],["Z",9],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9]]),i=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];let n=0;for(let r=0;r{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=t.slice(0,10)+t.slice(13,20)+t.slice(21,43),n=e(t,0,8).toString(),r=e(t,13,18).toString(),s=e(t,21,26).toString(),a=e(t,28,41).toString(),o=e(i,0,i.length).toString();return n===t[9]&&r===t[19]&&s===t[27]&&a===t[42]&&o===t[43]},checkValidMRV:function(t){if(!t||44!=t.length&&36!=t.length)return!1;const e=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=e(t,0,8).toString(),n=e(t,13,18).toString(),r=e(t,21,26).toString();return i===t[9]&&n===t[19]&&r===t[27]},checkValidIDCard:function(t,e){if(!t||30!=t.length&&36!=t.length)return!1;const i=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10};if(30===t.length){if(e&&t===e)return i(t,5,13).toString()===t[14];if(e&&t!==e){const n=`${e.substring(5,30)}${t.substring(0,7)}${t.substring(8,15)}${t.substring(18,29)}`;return i(n,0,n.length-1).toString()===t[29]}}else if(36===t.length){const e=i(t,0,8).toString(),n=i(t,13,18).toString(),r=i(t,21,26).toString(),s=`${t.substring(0,10)}${t.substring(13,20)}${t.substring(21,28)}`,a=i(s,0,s.length-1).toString();return e===t[9]&&n===t[19]&&r===t[27]&&a===t[35]}}};var da;!function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(da||(da={})),rt[-1]=async t=>{ca.onDataLoadProgressChanged&&ca.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};var fa=Object.freeze({__proto__:null,get EnumRawTextLineStatus(){return da},LabelRecognizerModule:ca,utilsFuncs:ua});const ga=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const ma="undefined"==typeof self,pa="function"==typeof importScripts,_a=(()=>{if(!pa){if(!ma&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),va=t=>{if(null==t&&(t="./"),ma||pa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.utility={version:"1.4.32",path:_a,isInternal:!0},ut.utility={js:!0,wasm:!0};const ya="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,ya)<0&&(gt.engineResourcePaths.std={version:ya,path:va(_a+`../../dynamsoft-capture-vision-std@${ya}/dist/`),isInternal:!0});const wa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,wa)<0)&&(gt.engineResourcePaths.dip={version:wa,path:va(_a+`../../dynamsoft-image-processing@${wa}/dist/`),isInternal:!0});function Ea(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var Ca,Sa,Ta,ba,Ia;function xa(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(h-o)**2);{const t=r+u*(a-r),e=s+u*(o-s);return Math.sqrt((l-t)**2+(h-e)**2)}}function Da(t){const e=[];for(let i=0;i=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*r,y:t.y+h*s}:null}function Ma(t){let e=0;for(let i=0;i0}function Pa(t,e){for(let i=0;i<4;i++)if(!Fa(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function ka(t,e,i,n){const r=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const o=Da(r)[3],l=Da(r)[1],h=Da(s)[3],c=Da(s)[1];let u,d=0;if(u=Math.max(Math.abs(Oa(o,e.points[0])),Math.abs(Oa(o,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(l,e.points[1])),Math.abs(Oa(l,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(h,t.points[0])),Math.abs(Oa(h,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(c,t.points[1])),Math.abs(Oa(c,t.points[2]))),u>d&&(d=u),d>a)return!1;const f=Aa(Da(r)[0]),g=Aa(Da(r)[2]),m=Aa(Da(s)[0]),p=Aa(Da(s)[2]),_=Ra(f,p),v=Ra(m,g),y=_>v,w=Math.min(_,v),E=Ra(f,g),C=Ra(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),a=0,o=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,o+=s[t];a/=4,o/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1}return e.x=a,e.y=o,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Pa(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Pa(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Pa(t,this.location.points[e]))return!0;if(Pa(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Oa(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=La(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{xa(e,t)&&i.push(t)})),e.forEach((e=>{xa(t,e)&&i.push(e)})),Ma(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Ba={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Va={barcode:2,text_line:4,detected_quad:8,normalized_image:16},ja=t=>Object.values(Va).includes(t)||Va.hasOwnProperty(t),Ua=(t,e)=>"string"==typeof t?e[Va[t]]:e[t],Ga=(t,e,i)=>{"string"==typeof t?e[Va[t]]=i:e[t]=i},Wa=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Ga(e,this.verificationEnabled,t)})),Ea(this,Sa,"f").forEach(((t,e)=>{Ga(e,this.duplicateFilterEnabled,t)})),Ea(this,Ta,"f").forEach(((t,e)=>{Ga(e,this.duplicateForgetTime,t)})),Ea(this,ba,"f").forEach(((t,e)=>{Ga(e,this.latestOverlappingEnabled,t)})),Ea(this,Ia,"f").forEach(((t,e)=>{Ga(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){ja(t)&&Ea(this,Ca,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ja(t)&&Ua(t,this.verificationEnabled)}enableResultDeduplication(t,e){ja(t)&&(e&&this.enableLatestOverlapping(t,!1),Ea(this,Sa,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ja(t)&&Ua(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ja(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Ea(this,Ta,"f").set(t,e))}getDuplicateForgetTime(t){return ja(t)?Ua(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){ja(t)&&Ea(this,Ia,"f").set(t,e)}getMaxOverlappingFrames(t){return ja(t)?Ua(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){ja(t)&&(e&&this.enableResultDeduplication(t,!1),Ea(this,ba,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!ja(t)&&Ua(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[mt.CRIT_BARCODE,mt.CRIT_TEXT_LINE,mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0);return new Na(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),Wa(this,t.items,mt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Wa(this,t.items,mt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Wa(this,t.items,mt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Wa(this,t.items,mt.CRIT_NORMALIZED_IMAGE)}}Ca=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,ba=new WeakMap,Ia=new WeakMap;var za,Ha,Xa,Za=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=M(t);return D(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let a;if(t instanceof Blob)a=await ga(t);else if("string"==typeof t){let e=await x(t,"blob");a=await ga(e)}return await new Promise(((t,o)=>{let l=nt();rt[l]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}},et.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}},MultiFrameResultCrossFilter:Ya,UtilityModule:class{static getVersion(){return`1.4.32(Worker: ${ht.utility&&ht.utility.worker||"Not Loaded"}, Wasm: ${ht.utility&&ht.utility.wasm||"Not Loaded"})`}}});t.EnumMRZScanMode=void 0,(za=t.EnumMRZScanMode||(t.EnumMRZScanMode={})).Passport="passport",za.TD1="td1",za.TD2="td2",za.PassportAndTD1="passportAndTd1",za.PassportAndTD2="passportAndTd2",za.TD1AndTD2="td1AndTd2",za.All="all",t.EnumMRZDocumentType=void 0,(Ha=t.EnumMRZDocumentType||(t.EnumMRZDocumentType={})).Passport="passport",Ha.TD1="td1",Ha.TD2="td2",t.EnumMRZScannerViews=void 0,(Xa=t.EnumMRZScannerViews||(t.EnumMRZScannerViews={})).Scanner="scanner",Xa.Result="scan-result";const qa={[t.EnumMRZScanMode.Passport]:"ReadPassport",[t.EnumMRZScanMode.TD1]:"ReadId-TD1",[t.EnumMRZScanMode.TD2]:"ReadId-TD2",[t.EnumMRZScanMode.PassportAndTD1]:"ReadPassportAndId-TD1",[t.EnumMRZScanMode.PassportAndTD2]:"ReadPassportAndId-TD2",[t.EnumMRZScanMode.TD1AndTD2]:"ReadId",[t.EnumMRZScanMode.All]:"ReadPassportAndId"};var Ja;function Ka(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}t.EnumResultStatus=void 0,(Ja=t.EnumResultStatus||(t.EnumResultStatus={}))[Ja.RS_SUCCESS=0]="RS_SUCCESS",Ja[Ja.RS_CANCELLED=1]="RS_CANCELLED",Ja[Ja.RS_FAILED=2]="RS_FAILED";function $a(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}const Qa=t=>!t||0===Object.keys(t).length;function to(t){return t?t.charAt(0).toUpperCase()+t.slice(1):""}const eo={"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 io(t,e={}){const{message:i,spinnerSize:n=32}=e,r=document.createElement("div");r.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const a=document.createElement("div");a.className="dynamsoft-mrz-loading-content";const o=`\n \n \n \n `;if(a.innerHTML=o,i){const t=document.createElement("div");t.className="dynamsoft-mrz-loading-message",t.textContent=i,a.appendChild(t)}return s.appendChild(a),r.appendChild(s),t.appendChild(r),{element:r,updateMessage:t=>{let e=s.querySelector(".dynamsoft-mrz-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dynamsoft-mrz-loading-message",e.textContent=t,a.appendChild(e)):null==e||e.remove()},hide:()=>{r&&r.parentNode&&(r.classList.add("fade-out"),setTimeout((()=>{var t;null===(t=r.parentNode)||void 0===t||t.removeChild(r)}),200))}}}const no='\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 ro;t.EnumMRZData=void 0,(ro=t.EnumMRZData||(t.EnumMRZData={})).InvalidFields="invalidFields",ro.DocumentType="documentType",ro.DocumentNumber="documentNumber",ro.MRZText="mrzText",ro.FirstName="firstName",ro.LastName="lastName",ro.Age="age",ro.Sex="sex",ro.IssuingState="issuingState",ro.IssuingStateRaw="issuingStateRaw",ro.Nationality="nationality",ro.NationalityRaw="nationalityRaw",ro.DateOfBirth="dateOfBirth",ro.DateOfExpiry="dateOfExpiry";const so={[t.EnumMRZData.InvalidFields]:"Invalid Fields",[t.EnumMRZData.DocumentType]:"Document Type",[t.EnumMRZData.DocumentNumber]:"Document Number",[t.EnumMRZData.MRZText]:"MRZ Text",[t.EnumMRZData.FirstName]:"Given Name(s)",[t.EnumMRZData.LastName]:"Surname",[t.EnumMRZData.Age]:"Age",[t.EnumMRZData.Sex]:"Sex",[t.EnumMRZData.IssuingState]:"Issuing State",[t.EnumMRZData.IssuingStateRaw]:"Issuing State (Raw Value)",[t.EnumMRZData.Nationality]:"Nationality",[t.EnumMRZData.NationalityRaw]:"Nationality State (Raw Value)",[t.EnumMRZData.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[t.EnumMRZData.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function ao(t,e,i,n=!1){const r=parseInt(t,10);let s;if(n)s=r>=60?1900+r:2e3+r;else{s=r>(new Date).getFullYear()%100?1900+r:2e3+r}return{year:s,month:parseInt(e,10),day:parseInt(i,10)}}function oo(t){const e=t=>{var e;return 1===(null===(e=`${t}`)||void 0===e?void 0:e.length)?`0${t}`:t};return`${null==t?void 0:t.year}-${e(null==t?void 0:t.month)}${(null==t?void 0:t.day)&&`-${e(null==t?void 0:t.day)}`}`}function lo(t){return"D<<"===t?"D":t}function ho(e,i){const n=[],r=t=>i.getFieldValidationStatus(t)===js.VS_FAILED,s=i.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return t.EnumMRZDocumentType.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return t.EnumMRZDocumentType.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return t.EnumMRZDocumentType.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(t){switch(t){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: ${t}`)}}(s),l=a===t.EnumMRZDocumentType.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",h=ao(i.getFieldValue("birthYear"),i.getFieldValue("birthMonth"),i.getFieldValue("birthDay")),c=ao(i.getFieldValue("expiryYear"),i.getFieldValue("expiryMonth"),i.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfExpiry)}));const u={[t.EnumMRZData.LastName]:i.getFieldValue("primaryIdentifier"),[t.EnumMRZData.FirstName]:i.getFieldValue("secondaryIdentifier"),[t.EnumMRZData.Nationality]:i.getFieldValue("nationality"),[t.EnumMRZData.NationalityRaw]:lo(i.getFieldRawValue("nationality")),[t.EnumMRZData.DocumentNumber]:i.getFieldValue(l)||i.getFieldValue("longDocumentNumber"),[t.EnumMRZData.IssuingState]:i.getFieldValue("issuingState"),[t.EnumMRZData.IssuingStateRaw]:lo(i.getFieldRawValue("issuingState")),[t.EnumMRZData.Sex]:to(i.getFieldValue("sex"))};Object.keys(u).forEach((e=>{let i=!1;switch(e){case t.EnumMRZData.FirstName:i=r("secondaryIdentifier");break;case t.EnumMRZData.LastName:i=r("primaryIdentifier");break;case t.EnumMRZData.DocumentNumber:i=r(l)||r("longDocumentNumber");break;default:i=r(e)}i&&n.push(e)}));const d=function(t){const e=new Date,i=e.getMonth()+1>t.month||e.getMonth()+1===t.month&&e.getDate()>=t.day;return e.getFullYear()-t.year-(i?0:1)}(h);d<1&&n.push(t.EnumMRZData.Age);return{[t.EnumMRZData.InvalidFields]:n,[t.EnumMRZData.FirstName]:u[t.EnumMRZData.FirstName],[t.EnumMRZData.LastName]:u[t.EnumMRZData.LastName],[t.EnumMRZData.Age]:d,[t.EnumMRZData.DateOfBirth]:h,[t.EnumMRZData.Sex]:u[t.EnumMRZData.Sex],[t.EnumMRZData.Nationality]:u[t.EnumMRZData.Nationality],[t.EnumMRZData.NationalityRaw]:u[t.EnumMRZData.NationalityRaw],[t.EnumMRZData.DocumentNumber]:u[t.EnumMRZData.DocumentNumber],[t.EnumMRZData.DateOfExpiry]:c,[t.EnumMRZData.IssuingState]:u[t.EnumMRZData.IssuingState],[t.EnumMRZData.IssuingStateRaw]:u[t.EnumMRZData.IssuingStateRaw],[t.EnumMRZData.DocumentType]:to(o),[t.EnumMRZData.MRZText]:e}}const co={[t.EnumMRZDocumentType.TD1]:{width:85.6,height:53.98},[t.EnumMRZDocumentType.TD2]:{width:105,height:74},[t.EnumMRZDocumentType.Passport]:{width:125,height:88}};class uo{showScannerLoadingOverlay(t){const e=Ka(this.config.container);this.loadingScreen=io(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(Ka(this.config.container).style.display="none"))}constructor(e,i){this.resources=e,this.config=i,this.isSoundFeedbackOn=!1,this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},this.currentScanMode=t.EnumMRZScanMode.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(),$a("dynamsoft-mrz-loading-screen-style",no);try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(e),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new Ya;t.enableResultCrossVerification(mt.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(mt.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const n=new Pe;n.onCapturedResultReceived=t=>this.handleMRZResult(t),await i.addResultReceiver(n),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(n)}}}initializeElements(){var t;const e=Ka(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:i.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:i.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:i.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:i.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:i.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:i.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td2"),toast:i.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.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(t=this.config)||void 0===t?void 0:t.showPoweredByDynamsoft)){i.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case t.EnumMRZScanMode.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case t.EnumMRZScanMode.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case t.EnumMRZScanMode.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case t.EnumMRZScanMode.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.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((t=>{t.addEventListener("click",(async e=>{const n=t.getAttribute("data-davice-id"),r=t.getAttribute("data-height"),s=t.getAttribute("data-width");n?this.resources.cameraEnhancer.selectCamera(n).then((()=>{this.toggleScanGuide()})):r&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(r)}).then((()=>{this.toggleScanGuide()})),"none"!==i.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),n=i.querySelectorAll(".dce-mn-camera-option"),r=i.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),a=this.resources.cameraEnhancer.getResolution();n.forEach((t=>{const e=t;e.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"}));const o={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",r=Number.MAX_VALUE;for(const[t,s]of Object.entries(eo)){const a=s.width*s.height,o=s.width/s.height,l=.7*Math.abs(a-e)+Math.abs(o-i)*a*.3;l{const e=t,i=e.getAttribute("data-height");e.style.border=i===o[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click()}async relaunch(){}async uploadFile(){var e,i,n,r;const{cvRouter:s}=this.resources,a=document.createElement("input");a.type="file",a.accept=null!==(e=this.config.uploadAcceptedTypes)&&void 0!==e?e:"image/*",a.style.display="none",document.body.appendChild(a);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const e=await new Promise(((t,e)=>{a.onchange=i=>{var n;const r=null===(n=i.target.files)||void 0===n?void 0:n[0];r?t(r):e(new Error("No file selected"))},a.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),a.click()}));if(!e)return;let o;if(this.config.uploadFileConverter&&!e.type.startsWith("image/"))try{o=await this.config.uploadFileConverter(e)}catch(t){throw new Error(`Error converting file: ${t.message}`)}else{if(!e.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");o=e}const l=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const t=await s.getSimplifiedSettings(l);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(l,t)}const h=await s.capture(o,l);this.capturedResultItems=h.items;const c=this.capturedResultItems.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE));if(0===c.length)throw new Error("No image data found in the captured result");const u=c[0].imageData;u.toCanvas=()=>A(u),u.toBlob=async()=>await L("image/png",u),this.originalImageData=u;const d=null==h?void 0:h.textLineResultItems,f=null==h?void 0:h.parsedResultItems;let g={};if(null==d?void 0:d.length){const t=(null===(i=d[0])||void 0===i?void 0:i.text)||"";g=ho(t,f[0])}const m={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:g,imageData:!0,_imageData:this.originalImageData};null===(r=(n=this.resources).onResultUpdated)||void 0===r||r.call(n,m),this.currentScanResolver(m)}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:`Error processing file: ${i}`}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(a)}}toggleSoundFeedback(t){this.isSoundFeedbackOn=void 0!==t?t:!this.isSoundFeedbackOn;const e=Ka(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-sound-feedback"),r=n.querySelector(".dce-mn-sound-feedback-on");n.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",r.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(t){const{cameraEnhancer:e,cameraView:i}=this.resources;if(!e||!e.isOpen())return;const n=i.getVisibleRegionOfVideo({inPixels:!0});if(!n)return;const r=i.getVideoElement(),s=r.videoWidth,a=r.videoHeight,o=co[t];let l;const h=n.height-80;if(n.width>n.height){l=.75*h/o.height;l*o.width>.9*n.width&&(l=.9*n.width/o.width)}else{l=.9*n.width/o.width;l*o.height>.75*h&&(l=.75*h/o.height)}const c=l*o.width,u=l*o.height,d=(n.width-c)/2,f=(h-u)/2,g=d,m=d+c,p=f,_=f+u,v=(n.x+g)/s*100,y=(n.x+m)/s*100,w=(n.y+p)/a*100,E=(n.y+_)/a*100,C={left:Math.round(v),right:Math.round(y),top:Math.round(w),bottom:Math.round(E),isMeasuredInPercentage:!0};null==i||i.setScanRegionMaskVisible(!0),e.setScanRegion(C)}toggleScanGuide(e){const i=Ka(this.config.container),n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const r=n.shadowRoot.querySelector(".dce-scanguide-passport"),s=n.shadowRoot.querySelector(".dce-scanguide-td1"),a=n.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return r.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case t.EnumMRZScanMode.All:case t.EnumMRZScanMode.Passport:case t.EnumMRZScanMode.PassportAndTD1:case t.EnumMRZScanMode.PassportAndTD2:r.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.Passport);break;case t.EnumMRZScanMode.TD1:case t.EnumMRZScanMode.TD1AndTD2:r.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.TD1);break;case t.EnumMRZScanMode.TD2:r.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(t.EnumMRZDocumentType.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:t,cameraView:e}=this.resources,i=Ka(this.config.container);if(i.style.display="block",t.isOpen())t.isPaused()&&await t.resume();else{const n=e.getUIElement();n.parentElement||i.append(n),await t.open()}await t.setResolution({width:2560,height:1440}),!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");n.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",n.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(t=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:e,cameraView:i}=this.resources,n=Ka(this.config.container);n.style.display=t?"none":"block",(null==i?void 0:i.getUIElement().parentElement)&&n.removeChild(i.getUIElement()),e.close(),this.stopCapturing()}catch(t){let e=(null==t?void 0:t.message)||t;console.error(`Close Camera error: ${e}`)}}pauseCamera(){const{cameraEnhancer:t}=this.resources;t.pause()}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}async handleMRZResult(e){var i;if(this.capturedResultItems=e.items,!(e.items.length<=1))try{const{onResultUpdated:n}=this.resources,r=e.items.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData;r.toCanvas=()=>A(r),r.toBlob=async()=>await L("image/png",r),this.originalImageData=r;const s=null==e?void 0:e.textLineResultItems,a=null==e?void 0:e.parsedResultItems;if(s){this.isSoundFeedbackOn&&bs.beep();const e=(null===(i=null==s?void 0:s[0])||void 0===i?void 0:i.text)||"",r=ho(e,a[0]);this.closeCamera();const o={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:r,imageData:!0,_imageData:this.originalImageData};null==n||n(o),this.currentScanResolver(o)}}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(n)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((t=>{this.scanModeManager[t]=!1}));(Array.isArray(e)?e:[e]).forEach((t=>{this.scanModeManager[t]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([t,e])=>e)).map((([t])=>t)).sort().join(",");return{[t.EnumMRZDocumentType.Passport]:t.EnumMRZScanMode.Passport,[t.EnumMRZDocumentType.TD1]:t.EnumMRZScanMode.TD1,[t.EnumMRZDocumentType.TD2]:t.EnumMRZScanMode.TD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1}`]:t.EnumMRZScanMode.PassportAndTD1,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.PassportAndTD2,[`${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.TD1AndTD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.All,"":t.EnumMRZScanMode.All}[e]}DCEShowToast(t,e=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=t,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),e))}async startCapturing(){const{cvRouter:e,cameraEnhancer:i}=this.resources,n=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const t=await e.getSimplifiedSettings(n);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(n,t)}await e.startCapturing(n),i.setPixelFormat(l.IPF_ABGR_8888)}catch(e){let i=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",i),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([t,i])=>i&&t!==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[t.EnumMRZDocumentType.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.Passport])}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(n)}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise((async t=>{this.currentScanResolver=t,await this.openCamera(),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(n)}}}const fo={rescan:'\n\n\n \n \n \n\n \n \n \n \n',complete:'\n\n\n\n \n \n \n\n \n \n \n \n',failed:'\n \n \n \n \n',info:'\n\n \n \n \n \n'};class go{constructor(t,e,i){this.resources=t,this.config=e,this.scannerView=i,this.editedFields={}}async launch(){try{return Ka(this.config.container).textContent="",await this.initialize(),Ka(this.config.container).style.display="flex",new Promise((t=>{this.currentScanResultViewResolver=t}))}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const i=await this.scannerView.launch();if((null===(e=null==i?void 0:i.status)||void 0===e?void 0:e.code)===t.EnumResultStatus.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(i));this.resources.onResultUpdated&&((null==i?void 0:i.status.code)===t.EnumResultStatus.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==i?void 0:i.status.code)===t.EnumResultStatus.RS_SUCCESS&&this.resources.onResultUpdated(i)),this.dispose(!0),await this.initialize(),Ka(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,i;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!Qa(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===(i=this.config)||void 0===i?void 0:i.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:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var t,e,i,n,r,s,a,o;const{toolbarButtonsConfig:l}=this.config;return function(t){$a("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 e=document.createElement("div");return e.className="dynamsoft-mrz-controls",t.forEach((t=>{const i=document.createElement("div");i.className=`dynamsoft-mrz-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dynamsoft-mrz-control-icon-wrapper",(r=t.icon).trim().startsWith(""))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var r;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=t.label,t.isDisabled&&i.classList.add("disabled"),t.isHidden&&i.classList.add("hide"),i.appendChild(n),i.appendChild(s),t.onClick&&!t.isDisabled&&i.addEventListener("click",t.onClick),e.appendChild(i)})),e}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.icon)||fo.rescan,label:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.icon)||fo.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.className)||""}`,isHidden:(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,i){if(e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry)try{const[t,n,r]=i.split(/[\/\-\.]/);r&&n&&t&&(this.editedFields[e]={day:parseInt(r,10),month:parseInt(n,10),year:parseInt(t,10)})}catch(t){console.error("Error parsing date",t)}else this.editedFields[e]=i}createMRZDataDisplay(){var e;const i=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},n=!!this.config.allowResultEditing,r=i.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",Qa(i)){const t=document.createElement("div");return t.className="dynamsoft-mrz-data-row empty",t.innerText="No MRZ detected. Please try again.",s.appendChild(t),s}if(r.length>0){const t=document.createElement("div");t.className="dynamsoft-mrz-error-notification",t.innerHTML=`\n ${fo.failed}
\n \n ${n?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(t)}else if(0===r.length&&n){const t=document.createElement("div");t.className="dynamsoft-mrz-info-notification",t.innerHTML=`\n ${fo.info}
\n \n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(t)}return Object.entries(i).forEach((([e,i])=>{var a;if(e===t.EnumMRZData.InvalidFields||!i)return;if(e===t.EnumMRZData.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 l=r.includes(e);l&&o.classList.add("invalid-field");const h=[t.EnumMRZData.MRZText,t.EnumMRZData.DocumentType,t.EnumMRZData.IssuingStateRaw,t.EnumMRZData.NationalityRaw],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=so[e]||e,l){const t=document.createElement("span");if(t.className="dynamsoft-mrz-error-icon",t.innerHTML=fo.failed,c.appendChild(t),n){const t=document.createElement("span");t.className="dynamsoft-mrz-error-hint",t.textContent="Please correct this field",c.appendChild(t)}}const u=document.createElement("div");if(u.className="dynamsoft-mrz-data-value",n&&!h.includes(e)){const n=document.createElement("input");n.className="dynamsoft-mrz-data-input",l&&n.classList.add("invalid"),e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?(n.value=oo(i),n.setAttribute("placeholder","YYYY-MM-DD")):n.value=i,n.addEventListener("input",(t=>{if(this.handleFieldEdit(e,t.target.value),l){n.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...r]);const t=this.editedFields.invalidFields.indexOf(e);t>-1&&this.editedFields.invalidFields.splice(t,1)}})),u.appendChild(n)}else e===t.EnumMRZData.MRZText?(u.classList.add("code"),u.innerText=i):e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?u.innerText=oo(i):u.innerText=i,l&&u.classList.add("invalid-value");o.appendChild(c),o.appendChild(u),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");$a("dynamsoft-mrz-result-view-style",mo);const t=document.createElement("div");if(t.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const e=this.resources.result.originalImageResult,i=document.createElement("div");let n;i.className="dynamsoft-mrz-result-view-image-container",(null==e?void 0:e.toCanvas)&&(n=null==e?void 0:e.toCanvas()),Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),t.appendChild(i)}const e=this.createMRZDataDisplay();t.appendChild(e);const i=this.createControls();t.appendChild(i),Ka(this.config.container).appendChild(t)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){Ka(this.config.container).style.display="none"}dispose(t=!1){Ka(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const mo="\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",po={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class _o{showLoadingOverlay(t){var e,i;const n=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen=io(n,{message:t}),n.style.display="block",n.style.position="relative"}hideLoadingOverlay(t=!1){var e,i,n;const r=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,r.style.display="none",t&&(null===(n=this.config)||void 0===n?void 0:n.container)&&(Ka(this.config.container).style.display="none"))}constructor(t){this.config=t,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:{}};$a("dynamsoft-mrz-loading-screen-style",no),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=t=>{this.resources.result=t};const t={};return this.config.scannerViewConfig&&(this.scannerView=new uo(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new go(this.resources,this.config.resultViewConfig,this.scannerView),t.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;const e=`Initialization Failed: ${(null==t?void 0:t.message)||t}`;return console.error(e),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var t,e,i;try{return gt.engineResourcePaths=Qa(null===(t=this.config)||void 0===t?void 0:t.engineResourcePaths)?po:this.config.engineResourcePaths,Zt._onAuthMessage=t=>t.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await Zt.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",{executeNow:!0}),gt.loadWasm(["DLR","DCP"]),ta.loadSpec("MRTD_TD3_PASSPORT"),ta.loadSpec("MRTD_TD1_ID"),ta.loadSpec("MRTD_TD2_ID"),ca.loadRecognitionData("MRZ"),this.resources.cameraView=await An.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await Rs.createInstance(this.resources.cameraView),this.resources.cvRouter=await Ae.createInstance(),!0}catch(t){let e=(null==t?void 0:t.message)||t;if(null==e?void 0:e.toLowerCase().includes("license")){const t="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(t),console.error(t)}else{const t=`Resource Initialization Failed: ${e}`;alert(t),console.error(t)}return!1}}shouldCreateDefaultContainer(){var t,e;const i=!this.config.container,n=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container));return i&&n}createDefaultMRZScannerContainer(){const t=document.createElement("div");return t.className="mrz-scanner-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e,i,n,r,s,a,o;if(!this.config.container){if((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)){const t="MRZResultView container is required when showResultView is true";return alert(t),console.error(t),!1}if(!(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)&&(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)&&!this.resources.result){const t="Result is needed to create MRZResultView without a scanner view";return alert(t),console.error(t),!1}}try{if(this.config.container&&!Ka(this.config.container)){const t="Invalid main container reference";return alert(t),console.error(t),!1}if((null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.container)&&!Ka(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const t="Invalid scanner view container reference";return alert(t),console.error(t),!1}if((null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)&&!Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)){const t="Invalid result view container reference";return alert(t),console.error(t),!1}}catch(t){const e=`Error accessing container references: ${t.message}`;return alert(e),console.error(e),!1}return!0}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeMRZScannerConfig(){var e,i,n,r,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=Ka(this.config.container));const l=this.config.container?this.createViewContainers(Ka(this.config.container)):{},h={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(t.EnumMRZScanMode).map((t=>{var e;return[t,(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e[t])||qa[t]]}))),templateFilePath:(null===(i=this.config)||void 0===i?void 0:i.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:l[t.EnumMRZScannerViews.Scanner]||Ka(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:h.templateFilePath,utilizedTemplateNames:h.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),u=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:l[t.EnumMRZScannerViews.Result]||Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},h),{scannerViewConfig:c,resultViewConfig:u})),!0}createViewContainers(e){e.textContent="";const i=[t.EnumMRZScannerViews.Scanner];return this.showResultView()&&i.push(t.EnumMRZScannerViews.Result),i.reduce(((t,i)=>{const n=document.createElement("div");return n.className=`mrz-scanner-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(n),t[i]=n,t}),{})}dispose(){var t,e;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 i=t=>{const e=Ka(t);e&&(e.style.display="none",e.textContent="")};i(this.config.container),i(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container),i(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container),this.isInitialized=!1}async processUploadedFile(e){var i,n,r,s;try{this.showLoadingOverlay("Processing File...");const{cvRouter:a}=this.resources,o=null===(i=this.config.utilizedTemplateNames)||void 0===i?void 0:i.all,l=await a.getSimplifiedSettings(o);l.roiMeasuredInPercentage=!0,l.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await a.updateSettings(o,l);const h=await a.capture(e,o),c=h.items,u=c.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData;u.toCanvas=()=>A(u),u.toBlob=async()=>await L("image/png",u);const d=null==h?void 0:h.textLineResultItems,f=null==h?void 0:h.parsedResultItems;let g={};if(null==d?void 0:d.length){const t=(null===(n=d[0])||void 0===n?void 0:n.text)||"";g=ho(t,f[0])}const m={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:u,data:g,imageData:!0,_imageData:u};null===(s=(r=this.resources).onResultUpdated)||void 0===s||s.call(r,m)}catch(e){return console.error("Failed to process uploaded file:",e),{status:{code:t.EnumResultStatus.RS_FAILED,message:`Failed to process image: ${e.message||e}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(e){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:i}=await this.initialize();if(Qa(i))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(Ka(this.config.container).style.display="block"),e&&(i.scannerView=null,await this.processUploadedFile(e)),!i.scannerView&&this.resources.result&&i.resultView)return await i.resultView.launch();if(!i.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(i.scannerView){const e=await i.scannerView.launch();if((null==e?void 0:e.status.code)!==t.EnumResultStatus.RS_SUCCESS)return{status:{code:null==e?void 0:e.status.code,message:(null==e?void 0:e.status.message)||"Failed to capture image"}};if(i.resultView)return await i.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:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const vo={MRZScanner:_o,MRZScannerView:uo,MRZResultView:go};t.CVR=Ne,t.Core=xt,t.DCE=Us,t.DCP=ea,t.DEFAULT_TEMPLATE_NAMES=qa,t.DLR=fa,t.DynamsoftMRZScanner=vo,t.License=Jt,t.MRZDataLabel=so,t.MRZResultView=go,t.MRZScanner=_o,t.MRZScannerView=uo,t.Utility=Za,t.displayMRZDate=oo}));
diff --git a/dist/mrz-scanner.bundle.mjs b/dist/mrz-scanner.bundle.mjs
index 4165951..6816d26 100644
--- a/dist/mrz-scanner.bundle.mjs
+++ b/dist/mrz-scanner.bundle.mjs
@@ -1 +1 @@
-const t=t=>t&&"object"==typeof t&&"function"==typeof t.then,e=(async()=>{})().constructor;class i extends e{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(i){let n;this._task=i,t(i)?n=i:"function"==typeof i&&(n=new e(i)),n&&(async()=>{try{const t=await n;i===this._task&&this.resolve(t)}catch(t){i===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",i(e)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=e}}function n(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function r(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var s,a,o;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(a||(a={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(o||(o={}));const l="undefined"==typeof self,h="function"==typeof importScripts,c=(()=>{if(!h){if(!l&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),d=t=>{if(null==t&&(t="./"),l||h);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},u=t=>Object.prototype.toString.call(t),f=t=>Array.isArray?Array.isArray(t):"[object Array]"===u(t),g=t=>"[object Boolean]"===u(t),m=t=>"number"==typeof t&&!Number.isNaN(t),p=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),_=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.radius)||t.radius<0||!m(t.startAngle)||!m(t.endAngle)),v=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),y=t=>!(!p(t)||!m(t.width)||t.width<=0||!m(t.height)||t.height<=0||!m(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!S(t.tag)),w=t=>!(!y(t)||!m(t.bytes.length)&&!m(t.bytes.ptr)),C=t=>!!y(t)&&t.bytes instanceof Uint8Array,E=t=>!(!p(t)||!m(t.left)||t.left<0||!m(t.top)||t.top<0||!m(t.right)||t.right<0||!m(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!g(t.isMeasuredInPercentage)),S=t=>null===t||!!p(t)&&!!m(t.imageId)&&"type"in t,b=t=>!(!p(t)||!T(t.startPoint)||!T(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),T=t=>!!p(t)&&!!m(t.x)&&!!m(t.y),x=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),I=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!T(t))),O=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.width)||t.width<0||!m(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!g(t.isMeasuredInPercentage)),A=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),D=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],a=s&&"object"==typeof s&&s.path?s.path:s,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof s&&s.isInternal)o&&(a=t[r].version?`${o}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${o}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof a&&(a=a.replace(i,o||"")),"object"==typeof a&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[r]=d(a)}return e},M=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const a=await k(`image/${s}`,t);r.length<=1&&(s="png");const o=new File([a],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(o),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(o)}catch(t){return r()}})),F=t=>{C(t)&&(t=N(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},P=(t,e)=>{C(e)&&(e=N(e));const i=F(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},k=async(t,e)=>{C(e)&&(e=N(e));const i=F(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},N=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===o.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=(128&n)/128*255,e[a+3]=255,n<<=1}}}else if(Number(t.format)===o.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=128&n?0:255,e[a+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var B,j,V,U,G,W,Y,z;let H,X,Z,q,J,K=class t{get _isFetchingStarted(){return n(this,G,"f")}constructor(){B.add(this),j.set(this,[]),V.set(this,1),U.set(this,s.BOPM_BLOCK),G.set(this,!1),W.set(this,void 0),Y.set(this,a.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!C(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(n(this,j,"f").length>=n(this,V,"f"))switch(n(this,U,"f")){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:if(n(this,j,"f").push(t),p(n(this,W,"f"))&&m(n(this,W,"f").imageId)&&1==n(this,W,"f").keepInBuffer)for(;n(this,j,"f").length>n(this,V,"f");){const t=n(this,j,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==n(this,W,"f").imageId}));n(this,j,"f").splice(t,1)}else n(this,j,"f").splice(0,n(this,j,"f").length-n(this,V,"f"))}else n(this,j,"f").push(t)}getImage(){if(0===n(this,j,"f").length)return null;let e;if(n(this,W,"f")&&m(n(this,W,"f").imageId)){const t=n(this,B,"m",z).call(this,n(this,W,"f").imageId);if(t<0)throw new Error(`Image with id ${n(this,W,"f").imageId} doesn't exist.`);e=n(this,j,"f").slice(t,t+1)[0]}else e=n(this,j,"f").pop();if([o.IPF_RGB_565,o.IPF_RGB_555,o.IPF_RGB_888,o.IPF_ARGB_8888,o.IPF_RGB_161616,o.IPF_ARGB_16161616,o.IPF_ABGR_8888,o.IPF_ABGR_16161616,o.IPF_BGR_888].includes(e.format)){if(n(this,Y,"f")===a.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t