@scandit/web-datacapture-id
Version:
Scandit Data Capture SDK for the Web
1 lines • 182 kB
JavaScript
import {Brush,Color,CameraSettings,VideoResolution,FocusGestureStrategy,Logger,Feedback,Sound,Quadrilateral,DataCaptureError,Localization,DataCaptureContext,BrowserHelper,DataCaptureLoader,assertUnreachable,Point}from'@scandit/web-datacapture-core';import {isObject}from'@scandit/web-datacapture-core/build/js/private/utils/isObject.js';import {SafeStorage}from'@scandit/web-datacapture-core/build/js/private/utils/safeStorage.js';var l={"scandit-datacapture-sdk-id-simd-pthreads.wasm":{bytes:9618370},"scandit-datacapture-sdk-id-pthreads.wasm":{bytes:9701943},"scandit-datacapture-sdk-id-simd.wasm":{bytes:9515450},"scandit-datacapture-sdk-id.wasm":{bytes:9599478}};var Ge=(s=>(s.Undefined="Undefined",s.RecoveredAfterFailure="RecoveredAfterFailure",s.InvalidLicenseKeyForVIZProcessing="InvalidLicenseKeyForVIZProcessing",s.InvalidSettingsForVIZProcessing="InvalidSettingsForVIZProcessing",s.InvalidLicenseKeyForParser="InvalidLicenseKeyForParser",s))(Ge||{}),w=class a extends Error{constructor(){super(...arguments);this._type="Undefined";this._message="";}get type(){return this._type}get message(){return this._message}static create(t){let r=new a;return t&&(r.name=t.type,r._type=t.type,r._message=t.message),r}static fromJSON(t){let r=new a;return r._type=t.type,r._message=t.message,r}};var oe=class{constructor(e){this.idCaptureWorkerManager=e;}get workerCommand(){return this.idCaptureWorkerManager.workerCommand.bind(this.idCaptureWorkerManager)}async getLicenseText(){return (await this.workerCommand("getIdOpenSourceSoftwareLicenseInfo",{})).licenseText}};var St={"id.idCaptureOverlay.scanFrontSideHint":"","id.idCaptureOverlay.scanBackSideHint":"","id.idCaptureOverlay.moveCloseTextHint":"","id.idCaptureOverlay.moveFurtherAwayTextHint":"","id.idCaptureOverlay.tapShutterToScan":"","id.idCaptureOverlay.lookingForDocument":"","id.idCaptureOverlay.holdStill":""};function yt(a){let e=URL.createObjectURL(new Blob(['"use strict";(()=>{var ye=(t,e)=>()=>(t&&(e=t(t=0)),e);var h,u=ye(()=>{h={"scandit-datacapture-sdk-id-simd-pthreads.wasm":{bytes:9618370},"scandit-datacapture-sdk-id-pthreads.wasm":{bytes:9701943},"scandit-datacapture-sdk-id-simd.wasm":{bytes:9515450},"scandit-datacapture-sdk-id.wasm":{bytes:9599478}}});u();u();u();u();var o;(t=>{(c=>(c.Debug="debug",c.Info="info",c.Warn="warn",c.Error="error",c.Quiet="quiet"))(t.Level||(t.Level={}));let e=new Map([["debug",1],["info",2],["warn",3],["error",4],["quiet",5]]),r="debug";function a(c){r=c}t.setLevel=a;function s(c,...m){if(!(e.get(r)>e.get(c)))switch(c){case"debug":{console.debug(...m);break}case"info":{console.log(...m);break}case"warn":{console.warn(...m);break}case"error":{console.error(...m);break}}}t.log=s;function i(...c){s("warn",...c)}t.warn=i;function d(...c){s("debug",...c)}t.debug=d;function n(...c){s("info",...c)}t.info=n;function l(...c){s("error",...c)}t.error=l})(o||(o={}));u();u();var we=class{constructor(t){if(typeof t!="function")throw new TypeError("FinalizationRegistry callback must be a function")}register(t,e,r){}unregister(t){return!1}};function X(t){typeof t.FinalizationRegistry>"u"&&(t.FinalizationRegistry=we)}u();u();function Q(t,e,r){let a=e*r,s=new Uint8ClampedArray(a*4),i=new Uint32Array(s.buffer);for(let d=0;d<a;d++){let n=t[d];i[d]=4278190080|n<<16|n<<8|n}return s}u();u();var P=class Z extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,Z.prototype),this.name=e.name}toString(){return`${this.name}: ${this.message}`}};var R=Promise.resolve(),J=!1,z=!1,O=!1,M,U=1500,_="";async function ee(t){if(M==null)return;J=!0;let e;try{let r=new Promise((s,i)=>{e=setTimeout(()=>{o.debug(`IndexedDB database is blocked (timed out after ${U}ms). If you are running a Debug wasm build, things are slower and the timeout can be configured via IndexedDBBlockedTimeoutMs in localStorage (requires page reload).`),i(new P({name:"BlockedIndexedDB",message:"IndexedDB database is blocked"}))},U)}),a=new Promise((s,i)=>{M==null||M(t,d=>{d!=null?i(d):s()})});await Promise.race([a,r])}finally{e!==void 0&&clearTimeout(e),J=!1}}async function te(t){return z?(O=t,R):(J?(z=!0,O=t,R=R.then(async()=>(z=!1,ee(O)))):(O=t,R=ee(t)),R)}function be(){FS.syncfs=((t,e)=>{te(t).then(()=>e(),r=>e(r))})}async function ae(t){if(_=t.writableDataPath,U=t.indexedDBTimeoutMs,M=FS.syncfs,M==null)throw new Error("FS.syncfs is not available");be();try{FS.mkdir(_)}catch(e){if(e.code!=="EEXIST")throw M=void 0,e}try{FS.mount(IDBFS,{},_)}catch(e){throw M=void 0,e}return te(!0)}u();u();u();var re={};function De(t){return[...new Uint8Array(t)].map(e=>{let r=e.toString(16);return r.length===1?`0${r}`:r}).join("")}async function*ve(t){let e=t.getReader();try{for(;;){let{done:r,value:a}=await e.read();if(r)return;yield a}}finally{e.releaseLock()}}async function Me(t){let e=[],r=0,a=0;for await(let i of ve(t))e.push(i),r+=i.length;let s=new Uint8Array(r);for(let i of e)s.set(i,a),a+=i.length;return s.buffer}var xe=(t=>(t.VALID="VALID",t.INVALID="INVALID",t.NOT_VERIFIABLE="NOT_VERIFIABLE",t))(xe||{});async function Re(t,e,r){if(typeof crypto.subtle.digest!="function")return o.log(o.Level.Warn,`Insecure context (see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts): The hash of the Scandit Data Capture library WASM file found at ${r} could not be verified`),"NOT_VERIFIABLE";try{let a=t instanceof Promise?await t:t,s=await crypto.subtle.digest("SHA-256",a),i=De(s);return e==null?(o.log(o.Level.Warn,"The library hash is not defined or empty, cannot correctly verify integrity."),"NOT_VERIFIABLE"):i===e?(o.log(o.Level.Debug,`Data Capture library WASM integrity found at ${r} has been verified correctly.`),"VALID"):(o.log(o.Level.Warn,`The Scandit Data Capture library WASM file found at ${r} seems invalid: expected file hash doesn\'t match (received: ${i}, expected: ${e}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),"INVALID")}catch(a){return o.log(o.Level.Warn,"Wasm response could not be verified",a),"NOT_VERIFIABLE"}}var G=new Map([["br",4.4],["gzip",2.9],["none",1]]);function Fe(t){var e;let r="content-encoding";if(t==null||t.get(r)==null)return G.get("none");let a=new Set(((e=t.get(r))!=null?e:"").split(",").map(s=>s.trim()));for(let[s,i]of G)if(a.has(s))return i;return G.get("none")}function Ae(t){var e,r;if(t==null)return 0;let a=(e=Fe(t))!=null?e:1,s=Number.parseInt((r=t.get("content-length"))!=null?r:"0",10);return Number.isNaN(s)?0:Math.floor(s*a*100)/100}function ke(t){let{pathname:e}=new URL(t);for(let[r,a]of Object.entries(re))if(e.endsWith(r))return a.bytes;return 0}function se(t){re=t}var Ee=(t,e)=>{let r=Ae(e);return r===0?ke(t):r};function Le(t,e,r,{onProgress:a,onError:s,onComplete:i}){if(!e.body)return[e];let d=Ee(t,e.headers),n=0,l=0;if(typeof TransformStream>"u")return o.warn("TransformStream is not supported in this environment. Progress tracking will be disabled."),[e];let[c,m]=r?e.body.tee():[e.body],f=c.pipeThrough(new TransformStream({async transform(I,g){try{n+=I.length,l=Number((n/d*100).toFixed(2)),d>0&&I.length>0&&l<100?a==null||a({percentage:l,loadedBytes:n,privateUri:t}):d===0&&I.length>0&&(a==null||a({percentage:null,loadedBytes:n,privateUri:t})),g.enqueue(I)}catch(C){g.error(C),s==null||s({error:C})}},flush(I){a==null||a({percentage:100,loadedBytes:n,privateUri:t}),i==null||i({percentage:100,loadedBytes:n,privateUri:t}),I.terminate()}}));return[new Response(f,{headers:new Headers(e.headers),status:e.status,statusText:e.statusText}),m]}async function $({wasmURI:t,expectedHash:e,verifyResponseHash:r,onProgress:a,onComplete:s,onError:i,referredOrigin:d}){let n=await fetch(t,{referrerPolicy:"origin",referrer:d!=null?d:""});if(!n.ok)throw new Error(`HTTP status code is not ok: ${n.status}, ${n.statusText}`);let[l,c]=Le(t,n,r,{onProgress:a,onError:i,onComplete:s});return c!=null&&Re(Me(c),e,t),l}function ie({wasmURI:t,expectedHash:e,verifyResponseHash:r,progressCallback:a,successCallback:s,errorCallback:i,importObject:d,referredOrigin:n}){async function l(m){try{let f=await $({wasmURI:t,expectedHash:e,verifyResponseHash:r,onProgress:a,referredOrigin:n}),I=await(m!=null?m:f).arrayBuffer(),g=await self.WebAssembly.instantiate(I,d);s(g.instance,g.module)}catch(f){o.log(o.Level.Error,f),o.log(o.Level.Error,`Couldn\'t instantiate Scandit SDK DataCapture library at ${t}, did you configure the path for it correctly?`),i==null||i(f)}}async function c(){let m;try{m=await $({wasmURI:t,expectedHash:e,verifyResponseHash:r,onProgress:a,referredOrigin:n});let f=await self.WebAssembly.instantiateStreaming(m,d);s(f.instance,f.module)}catch(f){o.log(o.Level.Warn,f),o.log(o.Level.Warn,"WebAssembly streaming compile failed. Falling back to ArrayBuffer instantiation (this will make things slower)"),l((m==null?void 0:m.bodyUsed)===!0?void 0:m)}}typeof self.WebAssembly.instantiateStreaming=="function"?c():l()}async function j(t,e,r,a){return new Promise((s,i)=>{t().then(s).catch(d=>{let n=e*2;if(n>r){i(d);return}a(d),self.setTimeout(()=>{j(t,n,r,a).then(s).catch(i)},e)})})}function q(t){var e,r;let a="unknown";if((e=t.href)!=null&&e.startsWith("blob:null/"))a="localhost";else{let s=((r=t.pathname)==null?void 0:r.length)>1&&!t.pathname.startsWith("/");a=new URL(s?t.pathname:t.origin).hostname}return a.startsWith("[")&&a.endsWith("]")?(a=a.slice(1,-1),a):(/^(\\d{1,3}\\.){3}\\d{1,3}$/.test(a)&&(a=a.split(".").map(s=>Number.parseInt(s,10).toString()).join(".")),a)}async function ne(t,e){async function r(){return importScripts(t)}try{await j(r,250,4e3,s=>{o.log(o.Level.Warn,s),o.log(o.Level.Warn,`Couldn\'t retrieve Scandit Data Capture library at ${t}, retrying...`)}),self.Module.mainScriptUrlOrBlob=t;let a=self.SDC_WASM_JS_VERSION;return a!==e&&o.log(o.Level.Warn,`The Scandit Data Capture library JS file found at ${t} seems invalid: expected version doesn\'t match (received: ${a}, expected: ${e}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),!0}catch(a){return o.log(o.Level.Error,a),!1}}u();var oe=class{constructor(t){this.viewInfo=null,this.viewInfo=this.cloneViewInfo(t)}isSame(t){return this.viewInfo==null&&t==null?!0:this.viewInfo==null&&t!=null||this.viewInfo!=null&&t==null?!1:this.viewInfo.width===t.width&&this.viewInfo.height===t.height&&this.viewInfo.orientation===t.orientation&&this.viewInfo.viewFinderRect.origin.x===t.viewFinderRect.origin.x&&this.viewInfo.viewFinderRect.origin.y===t.viewFinderRect.origin.y&&this.viewInfo.viewFinderRect.size.width===t.viewFinderRect.size.width&&this.viewInfo.viewFinderRect.size.height===t.viewFinderRect.size.height}update(t){this.viewInfo=this.cloneViewInfo(t)}cloneViewInfo(t){return t?{...t,viewFinderRect:{origin:{...t.viewFinderRect.origin},size:{...t.viewFinderRect.size}}}:null}};u();u();var T=class{constructor(){this.promise=new Promise((t,e)=>{this.reject=e,this.resolve=t})}};var K=class{constructor(t,e){this.workerFunctions=t,this.options=e,this.imageIdCounter=0,this.conversions=new Map}convertToJpeg(t,e){let r=this.imageIdCounter++,a=new T;this.conversions.set(r,a);let s=t.toBitmap();return this.workerFunctions.postMessage({type:"convertToJPEG",imageId:r,width:t.getWidth(),height:t.getHeight(),data:s,planes:t.getPlanes(),orientation:e,quality:this.options.quality},Array.from(new Set([s.buffer]))),a.promise}convertToBitmap(t){return{data:t.toBitmap(),byteOrder:1}}onConvertToJPEGResult(t,e){let r=this.conversions.get(t);r?(r.resolve(e),this.conversions.delete(t)):o.warn(`ImageConverterForwarder: Conversion for imageId ${t} not found in Map`)}};u();u();var W=class{constructor(t){this.options=t}get quality(){return this.options.quality}async convertToJpeg(t,e){try{let{width:r,height:a,planes:s}=this.validateAndExtractImageData(t);this.prepareCanvas(r,a);let i=this.processImageData(t,s,r,a);return await this.convertToJpegBytes(i,e)}catch(r){throw o.warn(`Failed to convert image to JPEG: ${r}`),r instanceof Error?r:new Error("Failed to convert image to JPEG")}}convertToBitmap(t){return{data:t.toBitmap(),byteOrder:1}}validateAndExtractImageData(t){let e=t.getWidth(),r=t.getHeight(),a=t.getPlanes();if(e<=0||r<=0)throw o.warn(`Invalid image dimensions: ${e}x${r}`),new Error(`Invalid image dimensions: ${e}x${r}`);if(!a||a.length===0)throw o.warn("ImageBuffer has no planes"),new Error("ImageBuffer has no planes");return{width:e,height:r,planes:a}}prepareCanvas(t,e){if(!this.ensureCanvas(t,e))throw new Error("Failed to create OffscreenCanvas");if(!this.canvas||!this.context)throw new Error("Canvas or context not properly initialized")}processImageData(t,e,r,a){let s=this.createImageDataFromBuffer(t,e,r,a);if(s===null)throw new Error("Failed to create ImageData");return this.validateImageData(s,r,a),s}validateImageData(t,e,r){var a;if(t.width!==e||t.height!==r)throw o.warn(`ImageData dimensions mismatch: expected ${e}x${r}, got ${t.width}x${t.height}`),new Error("ImageData dimensions mismatch");if(!t.data||t.data.length!==e*r*4)throw o.warn(`ImageData has invalid data length: expected ${e*r*4}, got ${((a=t.data)==null?void 0:a.length)||0}`),new Error("ImageData has invalid data length")}async convertToJpegBytes(t,e){if(!this.context||!this.canvas)throw new Error("Canvas or context not available");try{this.context.putImageData(t,0,0)}catch(i){throw o.warn(`Failed to put image data on canvas: ${i}`),new Error(`Failed to put image data on canvas: ${i}`)}let r=e!==0?this.applyRotation(this.canvas,e):this.canvas,a;try{a=await this.canvasToBlob(r)}catch(i){throw o.warn(`Failed to convert canvas to blob: ${i}`),new Error(`Failed to convert canvas to blob: ${i}`)}if(!a||a.size===0)throw o.warn("Canvas convertToBlob returned empty or null blob"),new Error("Failed to create JPEG blob");let s;try{s=await a.arrayBuffer()}catch(i){throw o.warn(`Failed to get array buffer from blob: ${i}`),new Error(`Failed to get array buffer from blob: ${i}`)}if(!s||s.byteLength===0)throw o.warn("Blob arrayBuffer returned empty or null buffer"),new Error("Failed to get array buffer from blob");return new Uint8Array(s)}ensureCanvas(t,e){try{return(!this.canvas||this.canvas.width!==t||this.canvas.height!==e)&&(this.canvas=this.getNewCanvas(t,e),this.context=this.canvas.getContext("2d")),this.context!==null}catch(r){return o.warn("Failed to create HTMLCanvasElement",r),!1}}createImageDataFromBuffer(t,e,r,a){let s=new Set(e.map(i=>i.channel));try{if(this.isYUVFormat(s)){let n=t.toBitmap();return!n||n.length!==r*a*4?(o.warn(`Invalid bitmap data from toBitmap(): expected ${r*a*4} bytes, got ${(n==null?void 0:n.length)||0}`),null):new ImageData(new Uint8ClampedArray(n),r,a)}if(this.isRGBAFormat(s))return this.createImageDataFromRGBAPlanes(e,r,a);if(this.isRGBFormat(s))return this.createImageDataFromRGBPlanes(e,r,a);if(this.isGrayscaleFormat(s))return this.createImageDataFromGrayscalePlanes(e,r,a);o.warn(`Unknown image format with channels: ${Array.from(s).join(", ")}, falling back to toBitmap()`);let i=t.toBitmap();if(!i||i.length===0)return o.warn("toBitmap() returned empty or null data"),null;let d=i.length/(r*a);return d===4?new ImageData(new Uint8ClampedArray(i),r,a):(o.warn(`Unsupported format: ${d} bytes per pixel`),null)}catch(i){return o.warn(`Failed to create ImageData: ${i}`),null}}isYUVFormat(t){return t.has(0)&&t.has(1)&&t.has(2)}isRGBAFormat(t){return t.has(3)&&t.has(4)&&t.has(5)&&t.has(6)}isRGBFormat(t){return t.has(3)&&t.has(4)&&t.has(5)&&!t.has(6)}isGrayscaleFormat(t){return t.has(0)&&!t.has(1)&&!t.has(2)}createImageDataFromRGBAPlanes(t,e,r){let a=t.find(l=>l.channel===3),s=t.find(l=>l.channel===4),i=t.find(l=>l.channel===5),d=t.find(l=>l.channel===6);if(!a||!s||!i||!d)return o.warn("Missing RGBA planes"),null;let n=new Uint8ClampedArray(e*r*4);for(let l=0;l<r;l++)for(let c=0;c<e;c++){let m=(l*e+c)*4;n[m]=this.getPixelFromPlane(a,c,l),n[m+1]=this.getPixelFromPlane(s,c,l),n[m+2]=this.getPixelFromPlane(i,c,l),n[m+3]=this.getPixelFromPlane(d,c,l)}return new ImageData(n,e,r)}createImageDataFromRGBPlanes(t,e,r){let a=t.find(n=>n.channel===3),s=t.find(n=>n.channel===4),i=t.find(n=>n.channel===5);if(!a||!s||!i)return o.warn("Missing RGB planes"),null;let d=new Uint8ClampedArray(e*r*4);for(let n=0;n<r;n++)for(let l=0;l<e;l++){let c=(n*e+l)*4;d[c]=this.getPixelFromPlane(a,l,n),d[c+1]=this.getPixelFromPlane(s,l,n),d[c+2]=this.getPixelFromPlane(i,l,n),d[c+3]=255}return new ImageData(d,e,r)}createImageDataFromGrayscalePlanes(t,e,r){let a=t.find(i=>i.channel===0);if(!a)return o.warn("Missing Y plane for grayscale"),null;let s=new Uint8ClampedArray(e*r*4);for(let i=0;i<r;i++)for(let d=0;d<e;d++){let n=(i*e+d)*4,l=this.getPixelFromPlane(a,d,i);s[n]=l,s[n+1]=l,s[n+2]=l,s[n+3]=255}return new ImageData(s,e,r)}getPixelFromPlane(t,e,r){let a=Math.floor(e/(t.subsamplingX||1)),s=Math.floor(r/(t.subsamplingY||1)),i=t.rowStride,d=t.pixelStride,n=s*i+a*d,l=t.data;return n<l.length?l[n]:0}applyRotation(t,e){let r=e*Math.PI/180,a=e===90||e===270||e===-90||e===-270,s=a?t.height:t.width,i=a?t.width:t.height,d=this.getNewCanvas(s,i),n=d.getContext("2d");if(!n)throw new Error("Failed to get 2D context for rotated canvas");return n.translate(s/2,i/2),n.rotate(r),n.translate(-t.width/2,-t.height/2),n.drawImage(t,0,0),d}};W.JPEG_IMAGE_MIME_TYPE="image/jpeg";var de=class extends W{getNewCanvas(t,e){return new OffscreenCanvas(t,e)}canvasToBlob(t){return t.convertToBlob({type:W.JPEG_IMAGE_MIME_TYPE,quality:this.options.quality})}};u();var B;(t=>{function e(){return"8.2.1"}t.sdkVersion=e})(B||(B={}));u();function Pe(t){return/^https?:\\/\\/(?:[^./]*\\.)*cdn.jsdelivr.net\\//.test(t)?{result:!0,cdnBaseURL:"https://cdn.jsdelivr.net/npm/"}:/^https?:\\/\\/(?:[^./]*\\.)*unpkg.com\\//.test(t)?{result:!0,cdnBaseURL:"https://unpkg.com/"}:{result:!1,cdnBaseURL:""}}function Oe(t){let e=/@scandit\\/web-datacapture-[a-z]+/i.exec(t);return e?e[0]:null}function le(t,e,r){let a=e,s=Pe(a);if(s.result){let d=Oe(a);d!=null&&(a=`${s.cdnBaseURL}${d}@${t}/sdc-lib/`)}let i=r.replace(".wasm","");return s.result?{jsURI:`${a}${i}.js`,wasmURI:`${a}${i}.wasm`}:{jsURI:`${a}${i}.js?v=${t}`,wasmURI:`${a}${i}.wasm?v=${t}`}}var ue=class ce{constructor(e,r){this.hintPresenterV2=null,this.MAX_NUMBER_OF_IMAGES_IN_FRAME_DATA_POOL=5,this.redrawInterval=1e3/30,this.redrawRequests=[],this._isDrawLoopRunning=!1,this.frameDataPool=new Map,this.lastFrameColorType="RGBA",this.lastFrameId=null,this.poorMansBenchmarkLogs=!1,this.writableDataPathStandard="/scandit_sync_folder",this.resourceFilesSubfolder="resources",this.performanceMetricsReporterTimer=void 0,this.lastMetricsReportTime=0,this.metricsReportInterval=1e3,this.performanceMetrics={frameDataPoolSize:0,cameraOutputFrames:0,redrawRequestsCount:0,actualRedrawsCount:0,frameProcessingStartedCount:0,frameProcessedCount:0,frameSkippedCount:0},this.frameProcessingStartedCount=0,this.frameProcessingFinishedCount=0,this.gestureListener=null,this.webPlatformHintPresenter=null,this.lastViewInfo=new oe(null),this.lastFrameProcessingStartedCount=0,this.lastFrameProcessingFinishedCount=0,this.moduleHandler=e,this.workerFunctions=r,this._loadProgressCallback=this._loadProgressCallback.bind(this),se(this.getWasmMetadata())}get Module(){return this.moduleHandler.get()}set isDrawLoopRunning(e){this._isDrawLoopRunning=e,!e&&typeof this.loopTimeoutId=="number"&&(clearTimeout(this.loopTimeoutId),this.loopTimeoutId=void 0)}get isDrawLoopRunning(){return this._isDrawLoopRunning}prepareFrameForListener(e){let r=this.lastFrameId;if(this.frameDataPool.size>=this.MAX_NUMBER_OF_IMAGES_IN_FRAME_DATA_POOL){let d=this.frameDataPool.keys().next().value;d!=null&&this.frameDataPool.delete(d)}let a=e.getFrameData(),s=new Uint8ClampedArray(a);this.frameDataPool.set(r,{data:s,colorType:this.lastFrameColorType,frameId:r,width:e.getWidth(),height:e.getHeight()});let i=this.lastUsedModuleMirrorAxis==null?!1:this.lastUsedModuleMirrorAxis!==this.Module.Axis.None;return{frameId:r,width:e.getWidth(),height:e.getHeight(),isFrameSourceMirrored:i,colorType:this.lastFrameColorType}}createContext(e){var r,a,s,i,d;let n=this.getModeDeserializers(),l=q(location);(l==="localhost"||l==="127.0.0.1")&&navigator.userAgent.includes("Electron")&&e.appName!=null&&(l+=`-${e.appName}`),this.parentDomain=e.parentDomain,this.contextDeserializer=new this.Module.DataCaptureContextDeserializer(this.writableDataPath,e.deviceId,e.context.deviceModelName,l,this.parentDomain,n,e.delayedRegistration,e.highEndBlurryRecognition,this.resourcePath);let c=this.contextDeserializer.contextFromJson(JSON.stringify(e.context));if(c==null){let p=this.contextDeserializer.getLastError();throw new Error(`Could not create the context: ${p}`)}let m=c.getView();this.context=c.getContext(),c.delete();let f=this.Module.DataCaptureContextListener.extend("DataCaptureContextListener",{didChangeStatus:(p,y)=>{this.contextDidChangeStatus(JSON.parse(y.toJson())),p.delete()},didStartObservingContext:p=>{this.didStartObservingContext(),p.delete()},didStopObservingContext:p=>{p.delete()}}),I=this.Module.DataCaptureContextFrameListener.extend("DataCaptureContextFrameListener",{onObservationStarted:p=>{p.delete()},onObservationStopped:p=>{p.delete()},onFrameProcessingStarted:(p,y)=>{this.workerFunctions.postMessage({type:"onFrameProcessingStarted"}),y.delete(),p.delete()},onFrameProcessingFinished:(p,y)=>{this.workerFunctions.postMessage({type:"onFrameProcessingFinished"}),y.delete(),p.delete()},onFrameSkipped:(p,y)=>{this.workerFunctions.postMessage({type:"onFrameSkipped"}),y.delete(),p.delete()}}),g=this.Module.GestureRecognizer.extend("GestureRecognizer",{setGestureListener:(p,y)=>{var w;(w=this.gestureListener)==null||w.delete(),this.gestureListener=p.clone(),p.delete()}});(r=this.gestureRecognizer)==null||r.delete(),this.gestureRecognizer=new g;let C=new f;this.context.addListener(C),C.delete();let S=new I;this.context.addFrameListener(S),S.delete(),this.setView(m),(a=this.view)==null||a.setGestureRecognizer(this.gestureRecognizer);let D=this.Module.PlatformHintPresenter.extend("PlatformHintPresenter",{setHintPresenter:p=>{p.delete()},showToast:p=>{this.workerFunctions.postMessage({type:"showToast",payload:JSON.parse(p)})},hideToast:p=>{this.workerFunctions.postMessage({type:"hideToast",payload:JSON.parse(p)})},showGuidance:p=>{this.workerFunctions.postMessage({type:"showGuidance",payload:JSON.parse(p)})},hideGuidance:p=>{this.workerFunctions.postMessage({type:"hideGuidance",payload:JSON.parse(p)})},startUpdateTimer:p=>{this.workerFunctions.postMessage({type:"startUpdateTimer",payload:{duration:{unit:"ms",value:p}}})},stopUpdateTimer:()=>{this.workerFunctions.postMessage({type:"stopUpdateTimer"})}});(s=this.hintPresenterV2)==null||s.delete(),this.hintPresenterV2=null,(i=this.webPlatformHintPresenter)==null||i.delete(),this.webPlatformHintPresenter=null,this.webPlatformHintPresenter=new D,this.view&&(this.hintPresenterV2=new this.Module.HintPresenterV2(this.webPlatformHintPresenter),(d=this.view)==null||d.setHintPresenterV2(this.hintPresenterV2)),this.webImageConverterInstance=this.getImageConverterInstance({quality:1}),this.Module.ImageConverter.setInstance(this.webImageConverterInstance)}convertToJPEGResult(e,r){this.webImageConverterInstance instanceof K&&this.webImageConverterInstance.onConvertToJPEGResult(e,r)}getImageConverterInstance(e){return this.workerFunctions.getOffscreenCanvas()!=null?new de(e):new K(this.workerFunctions,e)}onTap(e){var r;(r=this.gestureListener)==null||r.onTap(JSON.stringify(e))}hintPresenterV2Update(){var e;(e=this.hintPresenterV2)==null||e.update()}startReportingPerformanceMetrics(){this.performanceMetricsReporterTimer==null&&(this.lastMetricsReportTime=performance.now(),this.scheduleMetricsReporting())}scheduleMetricsReporting(){this.performanceMetricsReporterTimer=setTimeout(()=>{this.checkAndReportMetrics()},100)}checkAndReportMetrics(){let e=performance.now();e-this.lastMetricsReportTime>=this.metricsReportInterval&&(this.reportPerformanceMetrics(),this.performanceMetrics.cameraOutputFrames=0,this.performanceMetrics.redrawRequestsCount=0,this.performanceMetrics.actualRedrawsCount=0,this.lastMetricsReportTime=e),this._isDrawLoopRunning&&this.scheduleMetricsReporting()}async reportPerformanceMetrics(){let e=this.frameProcessingStartedCount-this.lastFrameProcessingStartedCount,r=this.frameProcessingFinishedCount-this.lastFrameProcessingFinishedCount;this.lastFrameProcessingStartedCount=this.frameProcessingStartedCount,this.lastFrameProcessingFinishedCount=this.frameProcessingFinishedCount;let a={cameraOutputFrames:this.performanceMetrics.cameraOutputFrames,redrawRequestsCount:this.performanceMetrics.redrawRequestsCount,actualRedrawsCount:this.performanceMetrics.actualRedrawsCount,frameDataPoolSize:this.performanceMetrics.frameDataPoolSize,frameProcessingStartedCount:e,frameProcessedCount:r,frameSkippedCount:this.performanceMetrics.frameSkippedCount};this.workerFunctions.postMessage({type:"performanceMetricsReport",payload:a})}deleteFrameData(e){this.frameDataPool.delete(e)}dispose(){var e,r,a,s;this.context.dispose(),this.frameDataPool.clear(),this.isDrawLoopRunning=!1,this.cleanupMetricsReporting(),(e=this.gestureRecognizer)==null||e.delete(),this.gestureRecognizer=null,(r=this.gestureListener)==null||r.delete(),this.gestureListener=null,(a=this.hintPresenterV2)==null||a.delete(),this.hintPresenterV2=null,(s=this.webPlatformHintPresenter)==null||s.delete(),this.webPlatformHintPresenter=null}cleanupMetricsReporting(){this.performanceMetricsReporterTimer!=null&&(typeof this.performanceMetricsReporterTimer=="number"?cancelAnimationFrame(this.performanceMetricsReporterTimer):clearTimeout(this.performanceMetricsReporterTimer),this.performanceMetricsReporterTimer=void 0)}flushAnalytics(){this.context.flushAnalytics()}extractCentaurusLicense(e){return{payload:{centaurus:{licenseKey:this.Module.LicenseUtils[ce.get3dPartyLicenseKeyMethodName](e)}}}}getModeDeserializers(){return new this.Module.VectorDataCaptureModeDeserializer}loadLibrary(e){return this.libraryLoadingPromise!=null?this.libraryLoadingPromise:(this.libraryLoadingPromise=this.setup(e),this.libraryLoadingPromise)}processFrame(e){var r;if(this.context==null)return o.debug("[processFrame] Context is null, returning frame without processing"),{payload:e,transferables:[e.data.buffer]};this.lastFrameId=e.frameId;let a=e.data,s=e.colorType==="GRAYSCALE"?this.Module.ImageBufferFormat.Grayscale8:this.Module.ImageBufferFormat.Rgba8888;this.lastFrameColorType=e.colorType==="GRAYSCALE"?"GRAYSCALE":"RGBA";let i=this.Module.allocateUint8Array(a.byteLength);return this.Module.HEAPU8.set(a,i),(r=this.imageFrameSource)==null||r.outputFrame(i,e.width,e.height,s),{payload:e,transferables:[e.data.buffer]}}reportCameraProperties(e){this.context.setCameraProperties(e.deviceId,e.isFrontFacing,e.hasAutofocus)}requestFrameData(e){let r=this.frameDataPool.get(e);if(r==null)return{payload:{data:null,frameId:null,colorType:null}};if(r.data.buffer.byteLength===0)return this.frameDataPool.delete(e),{payload:{data:null,frameId:null,colorType:null}};let a=r.data;r.colorType==="GRAYSCALE"&&(a=Q(r.data,r.width,r.height));let s={payload:{data:a,frameId:r.frameId,colorType:r.colorType},transferables:[a.buffer]};return this.frameDataPool.delete(e),s}scheduleRedraw(e,r){this.addRedrawRequest(r),this.isDrawLoopRunning||this.startDrawLoop(e)}sendViewRefreshCommands(e){this.workerFunctions.postMessage({type:"draw",payload:e},[e.buffer])}setFrameSource(e,r){var a;this.lastUsedModuleMirrorAxis=this.mapMirrorAxisOnModule(e),(a=this.imageFrameSource)==null||a.delete(),this.imageFrameSource=new this.Module.ImageBufferFrameSource(this.lastUsedModuleMirrorAxis,r,0),this.context.setFrameSource(this.imageFrameSource)}startDrawLoop(e){this.isDrawLoopRunning=!0;let r=i=>this.redrawRequests.length>0&&this.redrawRequests[0]<=i,a=i=>{for(;this.redrawRequests.length>0&&this.redrawRequests[0]<=i;)this.redrawRequests.shift()},s=()=>{this.loopTimeoutId=setTimeout(()=>{if(!this.isDrawLoopRunning)return;let i=performance.now();if(r(i)){a(i),e.draw();let d=e.getDrawCommands();this.sendViewRefreshCommands(new Uint8Array(d))}s()},this.redrawInterval)};s()}updateContext(e){if(this.context!=null&&this.contextDeserializer!=null){e.view!=null&&!e.view.visible&&this.context.flushAnalytics();let r=this.onBeforeUpdateContextHook(e),a=this.contextDeserializer.updateContextFromJson(this.context,this.view,JSON.stringify(r.context));if(a==null){let i=this.contextDeserializer.getLastError();throw new Error(`Could not update the context: ${i}`)}this.context.delete(),this.context=a.getContext();let s=a.getView();a.delete(),s!=null&&r.view!=null&&(s.setViewSize(r.view.width,r.view.height,r.view.orientation),s.draw()),!this.hintPresenterV2&&this.webPlatformHintPresenter&&(this.hintPresenterV2=new this.Module.HintPresenterV2(this.webPlatformHintPresenter)),s!=null&&this.hintPresenterV2&&s.setHintPresenterV2(this.hintPresenterV2),this.gestureRecognizer!=null&&(s==null||s.setGestureRecognizer(this.gestureRecognizer)),this.setView(s),this.notifyMainThreadOnViewInfoChanged(s),o.debug("context updated",r)}}notifyMainThreadOnViewInfoChanged(e){let r=this.getViewInfo(e);this.lastViewInfo.isSame(r)||(this.lastViewInfo.update(r),this.workerFunctions.postMessage({type:"viewSizeChanged",payload:r}))}getViewInfo(e){if(e!=null)try{let r=JSON.parse(e.getViewInfo());if(r!=null){let a=this.getOrientationFromNumber(r.orientation);return{...r,orientation:a}}}catch(r){o.error("Failed to get view size",r)}return null}getOrientationFromNumber(e){switch(e){case 90:return"landscapeRight";case 180:return"portraitUpsideDown";case 270:return"landscapeLeft";default:return"portrait"}}onBeforeUpdateContextHook(e){return e}onDocumentVisibilityChange(e){e==="hidden"&&this.context.flushAnalytics()}isFeatureSupported(e){return{payload:{supported:this.context.isFeatureSupported(e)}}}getViewfinderInfo(){var e,r;return{payload:{isDisplayingViewfinder:(r=(e=this.view)==null?void 0:e.isDisplayingViewfinder())!=null?r:!1,rect:JSON.parse(this.view.getViewfinderRect())}}}getOpenSourceSoftwareLicenseInfo(){return{payload:{licenseText:this.Module.OpenSourceSoftwareLicenseInfo.getLicenseText()}}}getWasmDynamicLibraries(e){return this.getWasmSideModuleFileName()==null?[]:[`${e.replace(/\\/[^/]*$/,"/")}${this.getWasmSideModuleFileName()}`]}getWasmCoreExpectedHash(e,r){return r?e?"55d66e6ed468eee69c947f235479b9590f0fb63c82bd315696907818697274e5":"93543a37f8ed50a1a24ecf0ab9890106d02e2988b6ceebb7d04adb08fb283951":e?"a2b447fb1f1a1f5e8ece2497d731eadb116c241bab259dc4943c2df01e2cb660":""}getWasmCoreFileName(e,r){return r?e?"scandit-datacapture-sdk-id-simd-pthreads.wasm":"scandit-datacapture-sdk-id-pthreads.wasm":e?"scandit-datacapture-sdk-id-simd.wasm":""}getWasmMetadata(){return h}getWasmSideModuleFileName(){return""}_loadProgressCallback(e){this.workerFunctions.postMessage({type:"loadLibraryProgress",payload:e})}addRedrawRequest(e){this.redrawRequests.push(Math.round(performance.now())+e),this.redrawRequests.sort((r,a)=>r-a)}contextDidChangeStatus(e){e.code===260?e.message=e.message.replace("domain name",`domain name (${q(location)})`):e.code===265&&(e.message=e.message.replace("domain name",`domain name (${this.parentDomain})`)),this.workerFunctions.postMessage({type:"contextDidChangeStatus",payload:e})}didStartObservingContext(){this.workerFunctions.postMessage({type:"didStartObservingContext"})}mapMirrorAxisOnModule(e){switch(e){case"None":return this.Module.Axis.None;case"X":return this.Module.Axis.X;case"Y":return this.Module.Axis.Y;default:return this.Module.Axis.None}}setView(e){this.view=e,this.setViewRefreshHandler(e),e==null&&(this.isDrawLoopRunning=!1,this.sendViewRefreshCommands(new Uint8Array([])))}addNativeOverlay(e){o.warn("addNativeOverlay has not been implemented for this module",e)}removeNativeOverlay(e){o.warn("removeNativeOverlay has not been implemented for this module",e)}setViewRefreshHandler(e){if(e==null||e.isViewRefreshHandlerSet)return;let r=this.Module.NeedsRedrawDelegate.extend("NeedsRedrawDelegate",{setNeedsRedrawIn:this.scheduleRedraw.bind(this,e)}),a=new r;e.setNeedsRedrawDelegate(a),e.isViewRefreshHandlerSet=!0}setupDataDecoding(){let e=this.moduleHandler.get(),r=e.DataDecoding.extend("DataDecoding",{decode(a,s){try{let i=JSON.parse(s),d=[];for(let n of i){let l=new TextDecoder(n.ianaName,{fatal:!0});d.push(l.decode(a.slice(n.startIndex,n.endIndex)))}return d.join("")}catch{return""}}});e.setDataDecoding(new r)}start(e,r,a){e&&r&&(this.setupDataDecoding(),this.moduleHandler.get().callMain(),this.moduleHandler.get().__emscripten_proxy_main!==void 0||a())}getWritableDataPath(e){return e!=null?(o.debug(`IndexedDB database name override in use to recover from blocked standard database: ${e}`),e):this.writableDataPathStandard}numOfMBToPages(e){return Math.ceil(1024*e*1024/64/1024)}async setup({libraryLocation:e,locationPath:r,writableDataPathOverride:a,indexedDBTimeoutMs:s,verifyResponseHash:i,referredOrigin:d,fixedWasmMemory:n,simdSupport:l,threadsSupport:c}){var m;let f=!1,I=!1;this.writableDataPath=this.getWritableDataPath(a),this.resourcePath=`${e}${this.resourceFilesSubfolder}/`,self.path=r;let{resolve:g,reject:C,promise:S}=new T,D=B.sdkVersion();if(D==="")throw new P({name:"Invalid library version",message:"Library version is not defined or empty, cannot generate proper path to library files."});let p=this.getWasmCoreFileName(l,c),y=le(D,e,p),{jsURI:w,wasmURI:x}=y,E={instantiateWasm:(b,fe)=>(ie({importObject:b,wasmURI:x,expectedHash:this.getWasmCoreExpectedHash(l,c),verifyResponseHash:i,successCallback:fe,progressCallback:this._loadProgressCallback,errorCallback:Ie=>{C(Ie)},referredOrigin:d}),{})},L=n===null?null:new WebAssembly.Memory({initial:this.numOfMBToPages(n),maximum:this.numOfMBToPages(300),shared:c});return L!==null&&o.log(o.Level.Debug,"Fixed wasmMemory set",L),this.moduleHandler.set({...L?{wasmMemory:L}:{},mainScriptUrlOrBlob:w,canvas:(m=this.workerFunctions.getOffscreenCanvas())!=null?m:{getContext:()=>null},...E,dynamicLibraries:this.getWasmDynamicLibraries(x),locateFile:b=>e+b,noInitialRun:!0,preRun:[async()=>{try{await ae({writableDataPath:this.writableDataPath,indexedDBTimeoutMs:s})}catch(b){if(b.name==="BlockedIndexedDB"){C(b.toString());return}o.log(o.Level.Debug,"No IndexedDB support, some data will not be persisted:",b)}I=!0,this.start(I,f,g)}],onMainComplete:()=>{if([f,I].includes(!1)){o.log(o.Level.Warn,{runtimeLoaded:f,fileSystemSynced:I},"Both runtimeLoaded and fileSystemSynced should be true when calling onMainComplete"),C("onMainComplete has been called but runtime or file system was not ready.");return}g()},onRuntimeInitialized:()=>{f=!0,this.start(I,f,g)},print:b=>{o.info(b)}}),await ne(w,D)||C(`Couldn\'t retrieve Scandit Data Capture library at ${w}, did you configure the path for it correctly?`),S}};ue.get3dPartyLicenseKeyMethodName=atob("Z2V0QmxpbmtJZExpY2Vuc2VLZXk=");var F=ue;u();u();function A(t){return typeof t=="object"&&t!=null}function k(t){if(typeof t=="string")return t;if(A(t)){if(typeof t.message=="string")return t.message}else if(typeof(t==null?void 0:t.toString)=="function")return t.toString();return"unknown error"}u();function pe(t){return typeof t=="object"&&t!=null&&t.document==null&&"addEventListener"in t&&typeof t.importScripts=="function"}u();function me(t){console.warn("Reached unexpected case",t)}var Y=class{constructor(t,e){this.onMessageListener=this.onMessage.bind(this),this.workerSelf=t,this.dataCaptureInstance=new F(e,{postMessage:this.postMessage.bind(this),getOffscreenCanvas:this.getOffscreenCanvas.bind(this)}),pe(t)&&(X(t),this.listenToMessages())}listenToMessages(){this.workerSelf.addEventListener("message",this.onMessageListener),this.workerSelf.addEventListener("error",t=>{o.log(o.Level.Error,t)}),this.workerSelf.addEventListener("messageerror",t=>{o.log(o.Level.Error,t)})}postMessage(t,e){this.workerSelf.postMessage(t,e!=null?e:[])}getOffscreenCanvas(){if(this.isOffscreenCanvasSupported())return new this.workerSelf.OffscreenCanvas(32,32)}isOffscreenCanvasSupported(){return typeof this.workerSelf.OffscreenCanvas=="function"}hasPayload(t){return A(t)&&"payload"in t}hasTransferables(t){return A(t)&&Array.isArray(t.transferables)}async respondWith(t,e,r){let a=null,s;try{s=r(),s instanceof Promise&&(s=await s)}catch(d){s=void 0,a=k(d)}let i={type:"workerTaskId",command:t,id:e,payload:this.hasPayload(s)?s.payload:void 0};a!=null&&(i.error=a),this.postMessage(i,this.hasTransferables(s)?s.transferables:[])}onMessage(t){switch(t.data.command){case"loadLibrary":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.loadLibrary({libraryLocation:e.libraryLocation,locationPath:e.locationPath,referredOrigin:e.referredOrigin,writableDataPathOverride:e.writableDataPathOverride,threadsSupport:e.threadsSupport,simdSupport:e.simdSupport,verifyResponseHash:e.verifyResponseHash,fixedWasmMemory:e.fixedWasmMemory,indexedDBTimeoutMs:e.indexedDBTimeoutMs}))}break}case"onTap":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>{this.dataCaptureInstance.onTap(e.point)})}break}case"hintPresenterV2update":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>{this.dataCaptureInstance.hintPresenterV2Update()})}break}case"createContext":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.createContext({context:e.context,deviceId:e.deviceId,delayedRegistration:e.delayedRegistration,highEndBlurryRecognition:e.highEndBlurryRecognition,appName:e.appName,parentDomain:e.parentDomain}))}break}case"setFrameSource":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.setFrameSource(e.mirrorAxis,e.isCameraFrameSource))}break}case"processFrame":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.processFrame({data:e.data,frameId:e.frameId,width:e.width,height:e.height,colorType:e.colorType}))}break}case"requestFrameData":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.requestFrameData(e.frameId))}break}case"deleteFrameData":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{this.dataCaptureInstance.deleteFrameData(e.frameId)})}break}case"updateContext":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.updateContext(e))}break}case"dispose":{this.respondWith(t.data.command,t.data.id,()=>this.dataCaptureInstance.dispose());break}case"flushAnalytics":{this.respondWith(t.data.command,t.data.id,()=>{this.dataCaptureInstance.flushAnalytics()});break}case"reportCameraProperties":{{let{data:e}=t;this.respondWith(e.command,e.id,async()=>this.dataCaptureInstance.reportCameraProperties(e))}break}case"setLogLevel":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{o.setLevel(e.level)})}break}case"extractCentaurusLicense":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.extractCentaurusLicense(e.licenseKey))}break}case"documentVisibility":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>{this.dataCaptureInstance.onDocumentVisibilityChange(e.state)})}break}case"isFeatureSupported":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.isFeatureSupported(e.feature))}break}case"getViewfinderInfo":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.getViewfinderInfo())}break}case"getOpenSourceSoftwareLicenseInfo":{{let{data:e}=t;this.respondWith(e.command,e.id,()=>this.dataCaptureInstance.getOpenSourceSoftwareLicenseInfo())}break}case"addNativeOverlay":this.dataCaptureInstance.addNativeOverlay(t);break;case"removeNativeOverlay":this.dataCaptureInstance.removeNativeOverlay(t);break;case"convertToJPEGResult":{{let{data:e}=t;this.dataCaptureInstance.convertToJPEGResult(e.imageId,e.result)}break}default:return me(t.data),!1}return!0}};u();u();u();u();u();function he(t){return t.ok()}function ge(t,e){return he(t)?t.value():e}function Ce(t,e){return he(t)?e:t.error()}function v(t,e){return t===void 0?e:t}var N=class{constructor(e,r,a){this.SDCIdCaptureMode=null;this.lastResult="";this.lastError="";this.lastLocalizedId="";this.lastDetectionIssue="";this.lastDiagnostics="";this.coreEngine=e,this.Module=e.Module,this.workerFunctions=e.workerFunctions,this.start(r,a)}start(e,r){this.initHintPresenterIfNotInitialized();let a=this.Module.IdCaptureListener.extend("IdCaptureListener",{onSessionUpdated:(g,C)=>{g.delete(),C.delete()},onIdCaptured:(g,C)=>{this.onIdCapturedCallback(C),g.delete(),C.delete()},onIdPartiallyCaptured:(g,C)=>{this.onIdPartiallyCapturedCallback(C),g.delete(),C.delete()},onIdRejected:(g,C,S)=>{this.onIdRejectedCallback(C,S),g.delete(),C==null||C.delete()},onIdLocalized:(g,C)=>{this.onIdLocalizedCallback(C),g.delete()},onShutterButtonPositionChanged:g=>{this.onShutterButtonPositionChangedCallback(g)},onShutterButtonStateChanged:g=>{this.onShutterButtonStateChangedCallback(g)}}),s=this.Module.Feedback.extend("Feedback",{emit:()=>{this.workerFunctions.postMessage({type:"idCaptureIdCapturedFeedback"})}}),i=this.Module.Feedback.extend("Feedback",{emit:()=>{this.workerFunctions.postMessage({type:"idCaptureIdRejectedFeedback"})}}),d=this.Module.IdCaptureBackend.extend("IdCaptureBackend",{getLastError:()=>this.lastError,getLastResult:()=>this.backendGetLastResult(),getLocalizedOnlyId:()=>this.lastLocalizedId,getLastIssue:()=>this.lastDetectionIssue,getLastDiagnostics:()=>this.lastDiagnostics,processFrame:()=>{},reset:this.onResetFromSDC.bind(this),setDetectionOnlyMode:this.setDetectionOnlyMode.bind(this)}),n=this.Module.IdCaptureImageProcessor.extend("IdCaptureImageProcessor",{outlineRegions:g=>g,obscureRegions:g=>g}),l=new d,c=new n;this.SDCIdCaptureMode=new this.Module.IdCapture(e,l,r,c),l.delete(),c.delete();let m=new a;this.SDCIdCaptureMode.addListener(m),m.delete();let f=new s,I=new i;this.SDCIdCaptureMode.setFeedbacks(f,I),f.delete(),I.delete()}getSDCIdCaptureMode(){if(!this.SDCIdCaptureMode)throw new Error("IdCaptureMode not initialized");return this.SDCIdCaptureMode}backendGetLastResult(){return this.lastResult}setLastResult(e){this.lastResult=e}setLastError(e){this.lastError=e}setLastLocalizedId(e){this.lastLocalizedId=e}setLastDetectionIssue(e){this.lastDetectionIssue=e}setLastDiagnostics(e){this.lastDiagnostics=e}applySettings(e){var r;(r=this.SDCIdCaptureMode)==null||r.applySettings(JSON.stringify(e))}reset(){var e;(e=this.SDCIdCaptureMode)==null||e.reset()}setExternalTransactionId(e){var r;(r=this.SDCIdCaptureMode)==null||r.setExternalTransactionId(e)}getExternalTransactionId(){var e;return(e=this.SDCIdCaptureMode)==null?void 0:e.getExternalTransactionId()}parseCode(e){if(this.SDCIdCaptureMode){let r=this.SDCIdCaptureMode.parse(e);if(r.ok()){let a=ge(r,null);if(a!=null){let s=this.extractCaptureId(a);if(s!=null)return{status:"success",capturedId:s}}}else return{status:"error",error:Ce(r,"Undefined error")}}return null}getCentaurusSettings(){let e=this.getSDCIdCaptureMode().getCentaurusSettings();return JSON.parse(e)}async barcodeVerifyAamvaCapture(e,r){return new Promise(a=>{let s=this.Module.AamvaBarcodeVerifier.extend("AamvaBarcodeVerifier",{retriggerVerificationIn(d){setTimeout(()=>{i.startVerification(JSON.stringify(e))},d)},verificationEnded(){let d=i.getBarcodeVerificationResponse();a({isSuccess:d.isSuccess,error:d.error,allChecksPassed:d.allChecksPassed})}}),i=new s;i.initialize(this.coreEngine.context,r==null?"":r),i.startVerification(JSON.stringify(e))})}onResetFromSDC(e){this.workerFunctions.postMessage({type:"idCaptureBackendReset"}),this.lastError="",this.lastResult="",this.lastLocalizedId=""}setDetectionOnlyMode(e){this.workerFunctions.postMessage({type:"idCaptureDetectionOnlyMode",payload:{detectionOnlyMode:e}})}onIdCapturedCallback(e){let r=this.extractCaptureId(e);r&&this.workerFunctions.postMessage({type:"idCaptureDidCaptureId",payload:{capturedId:r}},this.extractImageTransferablesFromCapturedId(r))}onIdPartiallyCapturedCallback(e){let r=this.extractCaptureId(e);r&&this.workerFunctions.postMessage({type:"idCaptureDidPartiallyCaptureId",payload:{capturedId:r}},this.extractImageTransferablesFromCapturedId(r))}onIdRejectedCallback(e,r){let a=this.extractCaptureId(e);this.workerFunctions.postMessage({type:"idCaptureDidRejectId",payload:{capturedId:a,rejectionReason:r}},a?this.extractImageTransferablesFromCapturedId(a):[])}onIdLocalizedCallback(e){this.workerFunctions.postMessage({type:"idCaptureDidLocalizeId",payload:{localization:JSON.parse(e)}})}extractCaptureId(e){var C,S,D,p,y,w,x,E;if(e==null)return null;let r=e.getImages(),a=r.getFrameFront(),s=r.getFrameBack(),i=v(r.getFace(),null),d=v(r.getCroppedDocumentFront(),null),n=v(r.getCroppedDocumentBack(),null),l=v(r.getFrameObscuredRegionsFront(),null),c=v(r.getFrameObscuredRegionsBack(),null),m=v(r.getCroppedDocumentObscuredRegionsFront(),null),f=v(r.getCroppedDocumentObscuredRegionsBack(),null),I={front:{face:this.prefixImageWithDataUriIfNeeded(i),croppedDocument:{image:this.prefixImageWithDataUriIfNeeded(d),obscuredRegions:JSON.parse(m!=null?m:"[]")},frame:{image:{data:a?new Uint8ClampedArray(a.getFrameData()):null,width:(C=a==null?void 0:a.getWidth())!=null?C:0,height:(S=a==null?void 0:a.getHeight())!=null?S:0,mirrorAxis:(D=a==null?void 0:a.getMirrorAxis().value)!=null?D:0,orientation:(p=a==null?void 0:a.getOrientation())!=null?p:0},obscuredRegions:JSON.parse(l!=null?l:"[]")}},back:{face:null,croppedDocument:{image:this.prefixImageWithDataUriIfNeeded(n),obscuredRegions:JSON.parse(f!=null?f:"[]")},frame:{image:{data:s?new Uint8ClampedArray(s.getFrameData()):null,width:(y=s==null?void 0:s.getWidth())!=null?y:0,height:(w=s==null?void 0:s.getHeight())!=null?w:0,mirrorAxis:(x=s==null?void 0:s.getMirrorAxis().value)!=null?x:0,orientation:(E=s==null?void 0:s.getOrientation())!=null?E:0},obscuredRegions:JSON.parse(c!=null?c:"[]")}}};return a==null||a.delete(),s==null||s.delete(),r.delete(),{...JSON.parse(e.toJson()),rawImageInfo:I}}prefixImageWithDataUriIfNeeded(e){return e==null?null:e.includes("data:image/")?e:`data:image/jpeg;base64,${e}`}onShutterButtonPositionChangedCallback(e){this.workerFunctions.postMessage({type:"idCaptureDidShutterButtonPositionChanged",payload:{position:JSON.parse(e)}})}onShutterButtonStateChangedCallback(e){this.workerFunctions.postMessage({type:"idCaptureDidShutterButtonStateChanged",payload:{state:e}})}async reportSafariAbruptReload(e){let r=new this.Module.OutOfMemoryAnalyticsData(e.framesProcessedCount,e.didCaptureCount,e.didRejectCount,e.applySettingsCount,e.upTime,e.videoResolution,e.parentDomain,e.centaurusEnabled);this.Module.OutOfMemoryAnalyticsHelper.storeAnalyticsEvent(this.coreEngine.context,r),r.delete()}parseIdCaptureSession(e){return JSON.parse(e.toJson())}dispose(){var e;(e=this.SDCIdCaptureMode)==null||e.delete(),this.SDCIdCaptureMode=null,this.lastError="",this.lastLocalizedId="",this.lastResult=""}extractImageTransferablesFromCapturedId(e){let r=[],a=e.rawImageInfo.front.frame.image.data;a&&a.length>0&&r.push(a.buffer);let s=e.rawImageInfo.back.frame.image.data;return s&&s.length>0&&r.push(s.buffer),r}isReadyToDisplayHints(){return this.coreEngine.view?this.coreEngine.view.hintPresenterInitialized():!1}initHintPresenterIfNotInitialized(){var r;if(this.isReadyToDisplayHints())return;let e=this.Module.HintPresenter.extend("HintPresenter",{showHint:(a,s)=>{this.workerFunctions.postMessage({type:"showHint",payload:{text:a,style:JSON.parse(s)}})},updateHint:a=>{this.workerFunctions.postMessage({type:"updateHint",payload:{style:JSON.parse(a)}})},hideHint:()=>{this.workerFunctions.postMessage({type:"hideHint",payload:{}})}});(r=this.coreEngine.view)==null||r.setHintPresenter(new e)}};function Te(t,e,r){let a=e.IdCaptureDeserializerHelper.extend("IdCaptureDeserializerHelper",{createMode:(d,n)=>{let l=new N(t,d,n);return r(l),d.delete(),n.delete(),l.getSDCIdCaptureMode()}}),s=new a,i=new e.IdCaptureDeserializer(s);return s.delete(),i}var H=class extends F{constructor(){super(...arguments);this.idCaptureMode=null;this.lastIdCaptureModeSerializedSettings=""}getModeDeserializers(){let r=super.getModeDeserializers(),a=Te(this,this.Module,this.receiveNewCaptureMode.bind(this));return r.push_back(a),a.delete(),r}receiveNewCaptureMode(r){this.idCaptureMode=r}processFrame(r){return this.idCaptureMode?super.processFrame(r):{payload:r,transferables:[r.data.buffer]}}updateContext(r){super.updateContext(r)}idCaptureSetLastResult(r){var a;(a=this.idCaptureMode)==null||a.setLastResult(r)}idCaptureSetLastError(r){var a;(a=this.idCaptureMode)==null||a.setLastError(r)}idCaptureSetLastLocalizedId(r){var a;(a=this.idCaptureMode)==null||a.setLastLocalizedId(r)}idCaptureSetLastDetectionIssue(r){var a;(a=this.idCaptureMode)==null||a.setLastDetectionIssue(r)}idCaptureSetLastDiagnostics(r){var a;(a=this.idCaptureMode)==null||a.setLastDiagnostics(r)}idCaptureReset(){var r;(r=this.idCaptureMode)==null||r.reset()}idCaptureSetExternalTransactionId(r){var a;(a=this.idCaptureMode)==null||a.setExternalTransactionId(r)}idCaptureGetExternalTransactionId(){var r,a;return{payload:{transactionId:(a=(r=this.idCaptureMode)==null?void 0:r.getExternalTransactionId())!=null?a:null}}}idCaptureApplySettings(r){var a;(a=this.idCaptureMode)==null||a.applySettings(r)}idCaptureGetCentaurusSettings(){return{payload:{result:this.idCaptureMode.getCentaurusSettings()}}}idCaptureParse(r){var a,s;return{payload:{result:(s=(a=this.idCaptureMode)==null?void 0:a.parseCode(r))!=null?s:null}}}async idCaptureBarcodeVerifyAamvaCapture(r,a){var s,i;return{payload:{result:(i=await((s=this.idCaptureMode)==null?void 0:s.barcodeVerifyAamvaCapture(r,a)))!=null?i:null}}}idCaptureDrivingLicenseDetailsCreateWithCentaurusData(r,a,s){let i=this.Module.DrivingLicenseDetails.createWithCentaurusData(r,a,s);return{payload:{result:JSON.parse(i)}}}getIdOpenSourceSoftwareLicenseInfo(){return{payload:{licenseText:this.Module.IdOpenSourceSoftwareLicenseInfo.getLicenseText()}}}idCaptureReportSafariAbruptReload(r){var a;(a=this.idCaptureMode)==null||a.reportSafariAbruptReload(r)}idCaptureDispose(){var r;(r=this.idCaptureMode)==null||r.dispose(),this.idCaptureMode=null}getWasmSideModuleFileName(){return""}getWasmCoreFileName(r