UNPKG

@scandit/web-datacapture-id

Version:

Scandit Data Capture SDK for the Web

1 lines 55.1 kB
(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t;(function(e){e.Level=function(e){return e.Debug=`debug`,e.Info=`info`,e.Warn=`warn`,e.Error=`error`,e.Quiet=`quiet`,e}({});let t=new Map([[`debug`,1],[`info`,2],[`warn`,3],[`error`,4],[`quiet`,5]]),n=`debug`;function r(e){n=e}e.setLevel=r;function i(e,...r){if(!(t.get(n)>t.get(e)))switch(e){case`debug`:console.debug(...r);break;case`info`:console.log(...r);break;case`warn`:console.warn(...r);break;case`error`:console.error(...r);break;default:break}}e.log=i;function a(...e){i(`warn`,...e)}e.warn=a;function o(...e){i(`debug`,...e)}e.debug=o;function s(...e){i(`info`,...e)}e.info=s;function c(...e){i(`error`,...e)}e.error=c})(t||={});var n=class e extends Error{constructor(t){super(t.message),Object.setPrototypeOf(this,e.prototype),this.name=t.name}toString(){return`${this.name}: ${this.message}`}};function r(e){console.warn(`Reached unexpected case`,e)}function i(e){return/^https?:\/\/(?:[^./]*\.)*cdn.jsdelivr.net\//.test(e)?{result:!0,cdnBaseURL:`https://cdn.jsdelivr.net/npm/`}:/^https?:\/\/(?:[^./]*\.)*unpkg.com\//.test(e)?{result:!0,cdnBaseURL:`https://unpkg.com/`}:{result:!1,cdnBaseURL:``}}function a(e){let t=/@scandit\/web-datacapture-[a-z]+/i.exec(e);return t?t[0]:null}function o(e,t,n){let r=t,o=i(r);if(o.result){let t=a(r);t!=null&&(r=`${o.cdnBaseURL}${t}@${e}/sdc-lib/`)}let s=n.replace(`.wasm`,``);return o.result?{jsURI:`${r}${s}.js`,wasmURI:`${r}${s}.wasm`}:{jsURI:`${r}${s}.js?v=${e}`,wasmURI:`${r}${s}.wasm?v=${e}`}}var s=class{constructor(e){this.options=e}get quality(){return this.options.quality}async convertToJpeg(e,n){try{let{width:t,height:r,planes:i}=this.validateAndExtractImageData(e);this.prepareCanvas(t,r);let a=this.processImageData(e,i,t,r);return await this.convertToJpegBytes(a,n)}catch(e){throw t.warn(`Failed to convert image to JPEG: ${e}`),e instanceof Error?e:Error(`Failed to convert image to JPEG`)}}convertToBitmap(e){return{data:e.toBitmap(),byteOrder:1}}validateAndExtractImageData(e){let n=e.getWidth(),r=e.getHeight(),i=e.getPlanes();if(n<=0||r<=0)throw t.warn(`Invalid image dimensions: ${n}x${r}`),Error(`Invalid image dimensions: ${n}x${r}`);if(!i||i.length===0)throw t.warn(`ImageBuffer has no planes`),Error(`ImageBuffer has no planes`);return{width:n,height:r,planes:i}}prepareCanvas(e,t){if(!this.ensureCanvas(e,t))throw Error(`Failed to create OffscreenCanvas`);if(!this.canvas||!this.context)throw Error(`Canvas or context not properly initialized`)}processImageData(e,t,n,r){let i=this.createImageDataFromBuffer(e,t,n,r);if(i===null)throw Error(`Failed to create ImageData`);return this.validateImageData(i,n,r),i}validateImageData(e,n,r){if(e.width!==n||e.height!==r)throw t.warn(`ImageData dimensions mismatch: expected ${n}x${r}, got ${e.width}x${e.height}`),Error(`ImageData dimensions mismatch`);if(!e.data||e.data.length!==n*r*4)throw t.warn(`ImageData has invalid data length: expected ${n*r*4}, got ${e.data?.length||0}`),Error(`ImageData has invalid data length`)}async convertToJpegBytes(e,n){if(!this.context||!this.canvas)throw Error(`Canvas or context not available`);try{this.context.putImageData(e,0,0)}catch(e){throw t.warn(`Failed to put image data on canvas: ${e}`),Error(`Failed to put image data on canvas: ${e}`)}let r=n===0?this.canvas:this.applyRotation(this.canvas,n),i;try{i=await this.canvasToBlob(r)}catch(e){throw t.warn(`Failed to convert canvas to blob: ${e}`),Error(`Failed to convert canvas to blob: ${e}`)}if(!i||i.size===0)throw t.warn(`Canvas convertToBlob returned empty or null blob`),Error(`Failed to create JPEG blob`);let a;try{a=await i.arrayBuffer()}catch(e){throw t.warn(`Failed to get array buffer from blob: ${e}`),Error(`Failed to get array buffer from blob: ${e}`)}if(!a||a.byteLength===0)throw t.warn(`Blob arrayBuffer returned empty or null buffer`),Error(`Failed to get array buffer from blob`);return new Uint8Array(a)}ensureCanvas(e,n){try{return(!this.canvas||this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas=this.getNewCanvas(e,n),this.context=this.canvas.getContext(`2d`)),this.context!==null}catch(e){return t.warn(`Failed to create HTMLCanvasElement`,e),!1}}createImageDataFromBuffer(e,n,r,i){let a=new Set(n.map(e=>e.channel));try{if(this.isYUVFormat(a)){let n=e.toBitmap();return!n||n.length!==r*i*4?(t.warn(`Invalid bitmap data from toBitmap(): expected ${r*i*4} bytes, got ${n?.length||0}`),null):new ImageData(new Uint8ClampedArray(n),r,i)}if(this.isRGBAFormat(a))return this.createImageDataFromRGBAPlanes(n,r,i);if(this.isRGBFormat(a))return this.createImageDataFromRGBPlanes(n,r,i);if(this.isGrayscaleFormat(a))return this.createImageDataFromGrayscalePlanes(n,r,i);t.warn(`Unknown image format with channels: ${Array.from(a).join(`, `)}, falling back to toBitmap()`);let o=e.toBitmap();if(!o||o.length===0)return t.warn(`toBitmap() returned empty or null data`),null;let s=o.length/(r*i);return s===4?new ImageData(new Uint8ClampedArray(o),r,i):(t.warn(`Unsupported format: ${s} bytes per pixel`),null)}catch(e){return t.warn(`Failed to create ImageData: ${e}`),null}}isYUVFormat(e){return e.has(0)&&e.has(1)&&e.has(2)}isRGBAFormat(e){return e.has(3)&&e.has(4)&&e.has(5)&&e.has(6)}isRGBFormat(e){return e.has(3)&&e.has(4)&&e.has(5)&&!e.has(6)}isGrayscaleFormat(e){return e.has(0)&&!e.has(1)&&!e.has(2)}createImageDataFromRGBAPlanes(e,n,r){let i=e.find(e=>e.channel===3),a=e.find(e=>e.channel===4),o=e.find(e=>e.channel===5),s=e.find(e=>e.channel===6);if(!i||!a||!o||!s)return t.warn(`Missing RGBA planes`),null;let c=new Uint8ClampedArray(n*r*4);for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;c[r]=this.getPixelFromPlane(i,t,e),c[r+1]=this.getPixelFromPlane(a,t,e),c[r+2]=this.getPixelFromPlane(o,t,e),c[r+3]=this.getPixelFromPlane(s,t,e)}return new ImageData(c,n,r)}createImageDataFromRGBPlanes(e,n,r){let i=e.find(e=>e.channel===3),a=e.find(e=>e.channel===4),o=e.find(e=>e.channel===5);if(!i||!a||!o)return t.warn(`Missing RGB planes`),null;let s=new Uint8ClampedArray(n*r*4);for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;s[r]=this.getPixelFromPlane(i,t,e),s[r+1]=this.getPixelFromPlane(a,t,e),s[r+2]=this.getPixelFromPlane(o,t,e),s[r+3]=255}return new ImageData(s,n,r)}createImageDataFromGrayscalePlanes(e,n,r){let i=e.find(e=>e.channel===0);if(!i)return t.warn(`Missing Y plane for grayscale`),null;let a=new Uint8ClampedArray(n*r*4);for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4,o=this.getPixelFromPlane(i,t,e);a[r]=o,a[r+1]=o,a[r+2]=o,a[r+3]=255}return new ImageData(a,n,r)}getPixelFromPlane(e,t,n){let r=Math.floor(t/(e.subsamplingX||1)),i=Math.floor(n/(e.subsamplingY||1)),a=e.rowStride,o=e.pixelStride,s=i*a+r*o,c=e.data;return s<c.length?c[s]:0}applyRotation(e,t){let n=t*Math.PI/180,r=t===90||t===270||t===-90||t===-270,i=r?e.height:e.width,a=r?e.width:e.height,o=this.getNewCanvas(i,a),s=o.getContext(`2d`);if(!s)throw Error(`Failed to get 2D context for rotated canvas`);return s.translate(i/2,a/2),s.rotate(n),s.translate(-e.width/2,-e.height/2),s.drawImage(e,0,0),o}};s.JPEG_IMAGE_MIME_TYPE=`image/jpeg`;function c(e){return typeof e==`object`&&!!e}let l;(function(e){function t(){let e=`8.5.0`;if(e==null)throw new n({name:`Invalid library version`,message:`Library version is not defined or empty.`});return e}e.sdkVersion=t})(l||={});function u(e){if(typeof e==`string`)return e;if(c(e)){if(typeof e.message==`string`)return e.message}else if(typeof e?.toString==`function`)return e.toString();return`unknown error`}function d(e){return typeof e==`object`&&!!e&&e.document==null&&`addEventListener`in e&&typeof e.importScripts==`function`}var f=class{constructor(e){if(typeof e!=`function`)throw TypeError(`FinalizationRegistry callback must be a function`)}register(e,t,n){}unregister(e){return!1}};function p(e){e.FinalizationRegistry===void 0&&(e.FinalizationRegistry=f)}var m=class{constructor(){this.promise=new Promise((e,t)=>{this.reject=t,this.resolve=e})}};let h={};function g(e){return[...new Uint8Array(e)].map(e=>{let t=e.toString(16);return t.length===1?`0${t}`:t}).join(``)}async function*_(e){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}}async function v(e){let t=[],n=0,r=0;for await(let r of _(e))t.push(r),n+=r.length;let i=new Uint8Array(n);for(let e of t)i.set(e,r),r+=e.length;return i.buffer}(function(e){return e.VALID=`VALID`,e.INVALID=`INVALID`,e.NOT_VERIFIABLE=`NOT_VERIFIABLE`,e})({});async function y(e,n,r){if(typeof crypto.subtle.digest!=`function`)return t.log(t.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 i=e instanceof Promise?await e:e,a=g(await crypto.subtle.digest(`SHA-256`,i));return n==null?(t.log(t.Level.Warn,`The library hash is not defined or empty, cannot correctly verify integrity.`),`NOT_VERIFIABLE`):a===n?(t.log(t.Level.Debug,`Data Capture library WASM integrity found at ${r} has been verified correctly.`),`VALID`):(t.log(t.Level.Warn,`The Scandit Data Capture library WASM file found at ${r} seems invalid: expected file hash doesn't match (received: ${a}, expected: ${n}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),`INVALID`)}catch(e){return t.log(t.Level.Warn,`Wasm response could not be verified`,e),`NOT_VERIFIABLE`}}let b=new Map([[`br`,4.4],[`gzip`,2.9],[`none`,1]]);function x(e){let t=`content-encoding`;if(e==null||e.get(t)==null)return b.get(`none`);let n=new Set((e.get(t)??``).split(`,`).map(e=>e.trim()));for(let[e,t]of b)if(n.has(e))return t;return b.get(`none`)}function S(e){if(e==null)return 0;let t=x(e)??1,n=Number.parseInt(e.get(`content-length`)??`0`,10);return Number.isNaN(n)?0:Math.floor(n*t*100)/100}function C(e){let{pathname:t}=new URL(e);for(let[e,n]of Object.entries(h))if(t.endsWith(e))return n.bytes;return 0}function w(e){h=e}let T=(e,t)=>{let n=S(t);return n===0?C(e):n};function E(e,n,r,{onProgress:i,onError:a,onComplete:o}){if(!n.body)return[n];let s=T(e,n.headers),c=0,l=0;if(typeof TransformStream>`u`)return t.warn(`TransformStream is not supported in this environment. Progress tracking will be disabled.`),[n];let[u,d]=r?n.body.tee():[n.body],f=u.pipeThrough(new TransformStream({async transform(t,n){try{c+=t.length,l=Number((c/s*100).toFixed(2)),s>0&&t.length>0&&l<100?i?.({percentage:l,loadedBytes:c,privateUri:e}):s===0&&t.length>0&&i?.({percentage:null,loadedBytes:c,privateUri:e}),n.enqueue(t)}catch(e){n.error(e),a?.({error:e})}},flush(t){i?.({percentage:100,loadedBytes:c,privateUri:e}),o?.({percentage:100,loadedBytes:c,privateUri:e}),t.terminate()}}));return[new Response(f,{headers:new Headers(n.headers),status:n.status,statusText:n.statusText}),d]}async function D({wasmURI:e,expectedHash:t,verifyResponseHash:n,onProgress:r,onComplete:i,onError:a,referredOrigin:o}){let s=await fetch(e,{referrerPolicy:`origin`,referrer:o??``});if(!s.ok)throw Error(`HTTP status code is not ok: ${s.status}, ${s.statusText}`);let[c,l]=E(e,s,n,{onProgress:r,onError:a,onComplete:i});return l!=null&&y(v(l),t,e),c}function O({wasmURI:e,expectedHash:n,verifyResponseHash:r,progressCallback:i,successCallback:a,errorCallback:o,importObject:s,referredOrigin:c}){async function l(l){try{let t=await D({wasmURI:e,expectedHash:n,verifyResponseHash:r,onProgress:i,referredOrigin:c}),o=await(l??t).arrayBuffer(),u=await globalThis.WebAssembly.instantiate(o,s);a(u.instance,u.module)}catch(n){t.log(t.Level.Error,n),t.log(t.Level.Error,`Couldn't instantiate Scandit SDK DataCapture library at ${e}, did you configure the path for it correctly?`),o?.(n)}}async function u(){let o;try{o=await D({wasmURI:e,expectedHash:n,verifyResponseHash:r,onProgress:i,referredOrigin:c});let t=await globalThis.WebAssembly.instantiateStreaming(o,s);a(t.instance,t.module)}catch(e){t.log(t.Level.Warn,e),t.log(t.Level.Warn,`WebAssembly streaming compile failed. Falling back to ArrayBuffer instantiation (this will make things slower)`),l(o?.bodyUsed===!0?void 0:o)}}typeof globalThis.WebAssembly.instantiateStreaming==`function`?u():l()}async function k(e,t,n,r){return new Promise((i,a)=>{e().then(i).catch(o=>{let s=t*2;if(s>n){a(o);return}r(o),globalThis.setTimeout(()=>{k(e,s,n,r).then(i).catch(a)},t)})})}function A(e){var t;let n=`unknown`;if((t=e.href)!=null&&t.startsWith(`blob:null/`))n=`localhost`;else{let t=e.pathname?.length>1&&!e.pathname.startsWith(`/`);n=new URL(t?e.pathname:e.origin).hostname}return n.startsWith(`[`)&&n.endsWith(`]`)?(n=n.slice(1,-1),n):(/^(\d{1,3}\.){3}\d{1,3}$/.test(n)&&(n=n.split(`.`).map(e=>Number.parseInt(e,10).toString()).join(`.`)),n)}async function j(e){let r;try{let i=new Promise((i,a)=>{r=setTimeout(()=>{t.debug(`IndexedDB database is blocked (timed out after ${e}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).`),a(new n({name:`BlockedIndexedDB`,message:`IndexedDB database is blocked`}))},e)}),a=new Promise((e,t)=>{FS.syncfs(!0,n=>{n==null?e():t(n)})});await Promise.race([a,i])}finally{r!==void 0&&clearTimeout(r)}}async function M(e){try{FS.mkdir(e.writableDataPath)}catch(e){if(e.code!==`EEXIST`)throw e}return FS.mount(IDBFS,{autoPersist:!0},e.writableDataPath),j(e.indexedDBTimeoutMs)}async function N(e,n){function r(e){try{return new URL(e,self.location.href).origin!==self.location.origin}catch(n){return t.log(t.Level.Warn,`Could not determine origin for WASM JS URL "${e}": ${n instanceof Error?n.message:String(n)}. Defaulting to same-origin path.`),!1}}function i(n){t.log(t.Level.Warn,n),t.log(t.Level.Warn,`Couldn't retrieve Scandit Data Capture library at ${e}, retrying...`)}try{if(r(e)){let t=await k(async()=>{let t=await fetch(e,{mode:`cors`,credentials:`omit`});if(!t.ok)throw Error(`Failed to load WASM JS script: ${e} (status ${t.status})`);let n=await t.blob();return/javascript|ecmascript/i.test(n.type)?n:new Blob([n],{type:`application/javascript`})},250,4e3,i),n=URL.createObjectURL(t);try{await importScripts(n)}finally{URL.revokeObjectURL(n)}self.Module.mainScriptUrlOrBlob=t}else await k(async()=>importScripts(e),250,4e3,i),self.Module.mainScriptUrlOrBlob=e;let a=globalThis.SDC_WASM_JS_VERSION;return a!==n&&t.log(t.Level.Warn,`The Scandit Data Capture library JS file found at ${e} seems invalid: expected version doesn't match (received: ${a}, expected: ${n}). Please ensure the correct Scandit Data Capture file (with correct version) is retrieved.`),!0}catch(e){return t.log(t.Level.Error,e),!1}}function P(e,t,n){let r=t*n,i=new Uint8ClampedArray(r*4),a=new Uint32Array(i.buffer);for(let t=0;t<r;t++){let n=e[t];a[t]=4278190080|n<<16|n<<8|n}return i}var F=class{constructor(e,t){this.workerFunctions=e,this.options=t,this.imageIdCounter=0,this.conversions=new Map}convertToJpeg(e,t){let n=this.imageIdCounter++,r=new m;this.conversions.set(n,r);let i=e.toBitmap();return this.workerFunctions.postMessage({type:`convertToJPEG`,imageId:n,width:e.getWidth(),height:e.getHeight(),data:i,planes:e.getPlanes(),orientation:t,quality:this.options.quality},Array.from(new Set([i.buffer]))),r.promise}convertToBitmap(e){return{data:e.toBitmap(),byteOrder:1}}onConvertToJPEGResult(e,n){let r=this.conversions.get(e);r?(r.resolve(n),this.conversions.delete(e)):t.warn(`ImageConverterForwarder: Conversion for imageId ${e} not found in Map`)}},I=class extends s{getNewCanvas(e,t){return new OffscreenCanvas(e,t)}canvasToBlob(e){return e.convertToBlob({type:s.JPEG_IMAGE_MIME_TYPE,quality:this.options.quality})}},L=class{constructor(e){this.viewInfo=null,this.viewInfo=this.cloneViewInfo(e)}isSame(e){return this.viewInfo==null&&e==null?!0:this.viewInfo==null&&e!=null||this.viewInfo!=null&&e==null?!1:this.viewInfo.width===e.width&&this.viewInfo.height===e.height&&this.viewInfo.orientation===e.orientation&&this.viewInfo.viewFinderRect.origin.x===e.viewFinderRect.origin.x&&this.viewInfo.viewFinderRect.origin.y===e.viewFinderRect.origin.y&&this.viewInfo.viewFinderRect.size.width===e.viewFinderRect.size.width&&this.viewInfo.viewFinderRect.size.height===e.viewFinderRect.size.height}update(e){this.viewInfo=this.cloneViewInfo(e)}cloneViewInfo(e){return e?{...e,viewFinderRect:{origin:{...e.viewFinderRect.origin},size:{...e.viewFinderRect.size}}}:null}},R=class e{constructor(e,t){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.deviceInstance=null,this.deviceInfo=null,this.lastViewInfo=new L(null),this.lastFrameProcessingStartedCount=0,this.lastFrameProcessingFinishedCount=0,this.moduleHandler=e,this.workerFunctions=t,this._loadProgressCallback=this._loadProgressCallback.bind(this),w(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 t=this.lastFrameId;if(this.frameDataPool.size>=this.MAX_NUMBER_OF_IMAGES_IN_FRAME_DATA_POOL){let e=this.frameDataPool.keys().next().value;e!=null&&this.frameDataPool.delete(e)}let n=e.getFrameData(),r=new Uint8ClampedArray(n);this.frameDataPool.set(t,{data:r,colorType:this.lastFrameColorType,frameId:t,width:e.getWidth(),height:e.getHeight()});let i=this.lastUsedModuleMirrorAxis==null?!1:this.lastUsedModuleMirrorAxis!==this.Module.Axis.None;return{frameId:t,width:e.getWidth(),height:e.getHeight(),isFrameSourceMirrored:i,colorType:this.lastFrameColorType}}createContext(e){var t,n,r,i;let a=this.getModeDeserializers(),o=A(location);(o===`localhost`||o===`127.0.0.1`)&&navigator.userAgent.includes(`Electron`)&&e.appName!=null&&(o+=`-${e.appName}`),this.parentDomain=e.parentDomain,this.contextDeserializer=new this.Module.DataCaptureContextDeserializer(this.writableDataPath,e.deviceId,e.context.deviceModelName,o,this.parentDomain,a,e.delayedRegistration,e.highEndBlurryRecognition,this.resourcePath);let s=this.contextDeserializer.contextFromJson(JSON.stringify(e.context));if(s==null){let e=this.contextDeserializer.getLastError();throw Error(`Could not create the context: ${e}`)}let c=s.getView();this.context=s.getContext(),s.delete(),this.setupDeviceInterface(e.isTablet,e.batteryInfo);let l=this.Module.DataCaptureContextListener.extend(`DataCaptureContextListener`,{didChangeStatus:(e,t)=>{this.contextDidChangeStatus(JSON.parse(t.toJson())),e.delete()},didStartObservingContext:e=>{this.didStartObservingContext(),e.delete()},didStopObservingContext:e=>{e.delete()}}),u=this.Module.DataCaptureContextFrameListener.extend(`DataCaptureContextFrameListener`,{onObservationStarted:e=>{e.delete()},onObservationStopped:e=>{e.delete()},onFrameProcessingStarted:(e,t)=>{this.workerFunctions.postMessage({type:`onFrameProcessingStarted`}),t.delete(),e.delete()},onFrameProcessingFinished:(e,t)=>{this.workerFunctions.postMessage({type:`onFrameProcessingFinished`}),t.delete(),e.delete()},onFrameSkipped:(e,t)=>{this.workerFunctions.postMessage({type:`onFrameSkipped`}),t.delete(),e.delete()}}),d=this.Module.GestureRecognizer.extend(`GestureRecognizer`,{setGestureListener:(e,t)=>{var n;(n=this.gestureListener)==null||n.delete(),this.gestureListener=e.clone(),e.delete()}});(t=this.gestureRecognizer)==null||t.delete(),this.gestureRecognizer=new d;let f=new l;this.context.addListener(f),f.delete();let p=new u;this.context.addFrameListener(p),p.delete(),this.setView(c),(n=this.view)==null||n.setGestureRecognizer(this.gestureRecognizer);let m=this.Module.PlatformHintPresenter.extend(`PlatformHintPresenter`,{setHintPresenter:e=>{e.delete()},showToast:e=>{this.workerFunctions.postMessage({type:`showToast`,payload:JSON.parse(e)})},hideToast:e=>{this.workerFunctions.postMessage({type:`hideToast`,payload:JSON.parse(e)})},showGuidance:e=>{this.workerFunctions.postMessage({type:`showGuidance`,payload:JSON.parse(e)})},hideGuidance:e=>{this.workerFunctions.postMessage({type:`hideGuidance`,payload:JSON.parse(e)})},startUpdateTimer:e=>{this.workerFunctions.postMessage({type:`startUpdateTimer`,payload:{duration:{unit:`ms`,value:e}}})},stopUpdateTimer:()=>{this.workerFunctions.postMessage({type:`stopUpdateTimer`})}});if((r=this.hintPresenterV2)==null||r.delete(),this.hintPresenterV2=null,(i=this.webPlatformHintPresenter)==null||i.delete(),this.webPlatformHintPresenter=null,this.webPlatformHintPresenter=new m,this.view){var h;this.hintPresenterV2=new this.Module.HintPresenterV2(this.webPlatformHintPresenter),(h=this.view)==null||h.setHintPresenterV2(this.hintPresenterV2)}this.webImageConverterInstance=this.getImageConverterInstance({quality:1}),this.Module.ImageConverter.setInstance(this.webImageConverterInstance)}convertToJPEGResult(e,t){this.webImageConverterInstance instanceof F&&this.webImageConverterInstance.onConvertToJPEGResult(e,t)}getImageConverterInstance(e){return this.workerFunctions.getOffscreenCanvas()==null?new F(this.workerFunctions,e):new I(e)}onTap(e){var t;(t=this.gestureListener)==null||t.onTap(JSON.stringify(e))}hintPresenterV2Update(){var e;(e=this.hintPresenterV2)==null||e.update()}startReportingPerformanceMetrics(){this.performanceMetricsReporterTimer??(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,t=this.frameProcessingFinishedCount-this.lastFrameProcessingFinishedCount;this.lastFrameProcessingStartedCount=this.frameProcessingStartedCount,this.lastFrameProcessingFinishedCount=this.frameProcessingFinishedCount;let n={cameraOutputFrames:this.performanceMetrics.cameraOutputFrames,redrawRequestsCount:this.performanceMetrics.redrawRequestsCount,actualRedrawsCount:this.performanceMetrics.actualRedrawsCount,frameDataPoolSize:this.performanceMetrics.frameDataPoolSize,frameProcessingStartedCount:e,frameProcessedCount:t,frameSkippedCount:this.performanceMetrics.frameSkippedCount};this.workerFunctions.postMessage({type:`performanceMetricsReport`,payload:n})}deleteFrameData(e){this.frameDataPool.delete(e)}dispose(){var e,t,n,r,i;this.context.dispose(),this.frameDataPool.clear(),this.isDrawLoopRunning=!1,this.cleanupMetricsReporting(),(e=this.gestureRecognizer)==null||e.delete(),this.gestureRecognizer=null,(t=this.gestureListener)==null||t.delete(),this.gestureListener=null,(n=this.hintPresenterV2)==null||n.delete(),this.hintPresenterV2=null,(r=this.webPlatformHintPresenter)==null||r.delete(),this.webPlatformHintPresenter=null,(i=this.deviceInstance)==null||i.delete(),this.deviceInstance=null,this.deviceInfo=null}cleanupMetricsReporting(){this.performanceMetricsReporterTimer!=null&&(typeof this.performanceMetricsReporterTimer==`number`?cancelAnimationFrame(this.performanceMetricsReporterTimer):clearTimeout(this.performanceMetricsReporterTimer),this.performanceMetricsReporterTimer=void 0)}flushAnalytics(){this.context.flushAnalytics()}extractCentaurusLicense(t){return{payload:{centaurus:{licenseKey:this.Module.LicenseUtils[e.get3dPartyLicenseKeyMethodName](t)}}}}getModeDeserializers(){return new this.Module.VectorDataCaptureModeDeserializer}loadLibrary(e){return this.libraryLoadingPromise??=this.setup(e),this.libraryLoadingPromise}processFrame(e){var n;if(this.context==null)return t.debug(`[processFrame] Context is null, returning frame without processing`),{payload:e,transferables:[e.data.buffer]};this.lastFrameId=e.frameId;let r=e.data,i=e.colorType===`GRAYSCALE`?this.Module.ImageBufferFormat.Grayscale8:this.Module.ImageBufferFormat.Rgba8888;this.lastFrameColorType=e.colorType===`GRAYSCALE`?`GRAYSCALE`:`RGBA`;let a=this.Module.allocateUint8Array(r.byteLength);return this.Module.HEAPU8.set(r,a),(n=this.imageFrameSource)==null||n.outputFrame(a,e.width,e.height,i),{payload:e,transferables:[e.data.buffer]}}reportCameraProperties(e){this.context.setCameraProperties(e.deviceId,e.isFrontFacing,e.hasAutofocus)}requestFrameData(e){let t=this.frameDataPool.get(e);if(t==null)return{payload:{data:null,frameId:null,colorType:null}};if(t.data.buffer.byteLength===0)return this.frameDataPool.delete(e),{payload:{data:null,frameId:null,colorType:null}};let n=t.data;t.colorType===`GRAYSCALE`&&(n=P(t.data,t.width,t.height));let r={payload:{data:n,frameId:t.frameId,colorType:t.colorType},transferables:[n.buffer]};return this.frameDataPool.delete(e),r}scheduleRedraw(e,t){this.addRedrawRequest(t),this.isDrawLoopRunning||this.startDrawLoop(e)}sendViewRefreshCommands(e){this.workerFunctions.postMessage({type:`draw`,payload:e},[e.buffer])}setFrameSource(e,t){var n;this.lastUsedModuleMirrorAxis=this.mapMirrorAxisOnModule(e),(n=this.imageFrameSource)==null||n.delete(),this.imageFrameSource=new this.Module.ImageBufferFrameSource(this.lastUsedModuleMirrorAxis,t,0),this.context.setFrameSource(this.imageFrameSource)}startDrawLoop(e){this.isDrawLoopRunning=!0;let t=e=>this.redrawRequests.length>0&&this.redrawRequests[0]<=e,n=e=>{for(;this.redrawRequests.length>0&&this.redrawRequests[0]<=e;)this.redrawRequests.shift()},r=()=>{this.loopTimeoutId=setTimeout(()=>{if(!this.isDrawLoopRunning)return;let i=performance.now();if(t(i)){n(i),e.draw();let t=e.getDrawCommands();this.sendViewRefreshCommands(new Uint8Array(t))}r()},this.redrawInterval)};r()}updateContext(e){if(this.context!=null&&this.contextDeserializer!=null){e.view!=null&&!e.view.visible&&this.context.flushAnalytics();let n=this.onBeforeUpdateContextHook(e),r=this.contextDeserializer.updateContextFromJson(this.context,this.view,JSON.stringify(n.context));if(r==null){let e=this.contextDeserializer.getLastError();throw Error(`Could not update the context: ${e}`)}this.context.delete(),this.context=r.getContext();let i=r.getView();r.delete(),i!=null&&n.view!=null&&(i.setViewSize(n.view.width,n.view.height,n.view.orientation),i.draw()),!this.hintPresenterV2&&this.webPlatformHintPresenter&&(this.hintPresenterV2=new this.Module.HintPresenterV2(this.webPlatformHintPresenter)),i!=null&&this.hintPresenterV2&&i.setHintPresenterV2(this.hintPresenterV2),this.gestureRecognizer!=null&&i?.setGestureRecognizer(this.gestureRecognizer),this.setView(i),this.notifyMainThreadOnViewInfoChanged(i),t.debug(`context updated`,n)}}notifyMainThreadOnViewInfoChanged(e){let t=this.getViewInfo(e);this.lastViewInfo.isSame(t)||(this.lastViewInfo.update(t),this.workerFunctions.postMessage({type:`viewSizeChanged`,payload:t}))}getViewInfo(e){if(e!=null)try{let t=JSON.parse(e.getViewInfo());if(t!=null){let e=this.getOrientationFromNumber(t.orientation);return{...t,orientation:e}}}catch(e){t.error(`Failed to get view size`,e)}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(){return{payload:{isDisplayingViewfinder:this.view?.isDisplayingViewfinder()??!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,t){return t?e?`08e72d09da01cd9d2fc3b7466f25e8d339c1c1cfac72402b522740eae76e6fe6`:`b92d83e367dfec4e0f4edc6b32abdb6987c7542818702badaa1528a2132d181e`:e?`201ec6aa2bfa9233d89ee4501a745cade93030d57e271ca8aeacdc7f819883e1`:``}getWasmCoreFileName(e,t){return t?e?`scandit-datacapture-sdk-id-simd-pthreads.wasm`:`scandit-datacapture-sdk-id-pthreads.wasm`:e?`scandit-datacapture-sdk-id-simd.wasm`:``}getWasmMetadata(){return{"scandit-datacapture-sdk-id-simd-pthreads.wasm":{bytes:9133200},"scandit-datacapture-sdk-id-pthreads.wasm":{bytes:9177107},"scandit-datacapture-sdk-id.wasm":{bytes:9300918},"scandit-datacapture-sdk-id-simd.wasm":{bytes:9243489}}}getWasmSideModuleFileName(){return``}_loadProgressCallback(e){this.workerFunctions.postMessage({type:`loadLibraryProgress`,payload:e})}addRedrawRequest(e){this.redrawRequests.push(Math.round(performance.now())+e),this.redrawRequests.sort((e,t)=>e-t)}contextDidChangeStatus(e){e.code===260?e.message=e.message.replace(`domain name`,`domain name (${A(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??(this.isDrawLoopRunning=!1,this.sendViewRefreshCommands(new Uint8Array([])))}addNativeOverlay(e){t.warn(`addNativeOverlay has not been implemented for this module`,e)}removeNativeOverlay(e){t.warn(`removeNativeOverlay has not been implemented for this module`,e)}setViewRefreshHandler(e){if(e==null||e.isViewRefreshHandlerSet)return;let t=new(this.Module.NeedsRedrawDelegate.extend(`NeedsRedrawDelegate`,{setNeedsRedrawIn:this.scheduleRedraw.bind(this,e)}));e.setNeedsRedrawDelegate(t),e.isViewRefreshHandlerSet=!0}setupDataDecoding(){let e=this.moduleHandler.get(),t=e.DataDecoding.extend(`DataDecoding`,{decode(e,t){try{let n=JSON.parse(t),r=[];for(let t of n){let n=new TextDecoder(t.ianaName,{fatal:!0});r.push(n.decode(e.slice(t.startIndex,t.endIndex)))}return r.join(``)}catch{return``}}});e.setDataDecoding(new t)}getBatteryData(){var e;let t=(e=this.deviceInfo)==null||(e=e.batteryInfo)==null?void 0:e.percentage;if(t!=null)return{percentage:t}}isTablet(){return this.deviceInfo?.isTablet??!1}setupDeviceInterface(e,t){this.deviceInfo={isTablet:e,batteryInfo:t};let n=this.moduleHandler.get(),r=n.DeviceInterface.extend(`DeviceInterface`,{getBatteryData:this.getBatteryData.bind(this),isTablet:this.isTablet.bind(this)});this.deviceInstance=new r,n.DeviceHolder.setCurrentDevice(this.deviceInstance)}updateBatteryInfo(e){this.deviceInfo&&(this.deviceInfo.batteryInfo=e)}start(e,t,n){e&&t&&(this.setupDataDecoding(),this.moduleHandler.get().callMain(),this.moduleHandler.get().__emscripten_proxy_main===void 0&&n())}getWritableDataPath(e){return e==null?this.writableDataPathStandard:(t.debug(`IndexedDB database name override in use to recover from blocked standard database: ${e}`),e)}numOfMBToPages(e){return Math.ceil(1024*e*1024/64/1024)}async setup({libraryLocation:e,locationPath:r,writableDataPathOverride:i,indexedDBTimeoutMs:a,verifyResponseHash:s,referredOrigin:c,fixedWasmMemory:u,simdSupport:d,threadsSupport:f}){let p=!1,h=!1;this.writableDataPath=this.getWritableDataPath(i),this.resourcePath=`${e}${this.resourceFilesSubfolder}/`,globalThis.path=r;let{resolve:g,reject:_,promise:v}=new m,y=l.sdkVersion();if(y===``)throw new n({name:`Invalid library version`,message:`Library version is not defined or empty, cannot generate proper path to library files.`});let{jsURI:b,wasmURI:x}=o(y,e,this.getWasmCoreFileName(d,f)),S={instantiateWasm:(e,t)=>(O({importObject:e,wasmURI:x,expectedHash:this.getWasmCoreExpectedHash(d,f),verifyResponseHash:s,successCallback:t,progressCallback:this._loadProgressCallback,errorCallback:e=>{_(e)},referredOrigin:c}),{})},C=u===null?null:new WebAssembly.Memory({initial:this.numOfMBToPages(u),maximum:this.numOfMBToPages(300),shared:f});return C!==null&&t.log(t.Level.Debug,`Fixed wasmMemory set`,C),this.moduleHandler.set({...C?{wasmMemory:C}:{},mainScriptUrlOrBlob:b,canvas:this.workerFunctions.getOffscreenCanvas()??{getContext:()=>null},...S,dynamicLibraries:this.getWasmDynamicLibraries(x),locateFile:t=>e+t,noInitialRun:!0,preRun:[async()=>{try{await M({writableDataPath:this.writableDataPath,indexedDBTimeoutMs:a})}catch(e){if(e.name===`BlockedIndexedDB`){_(e.toString());return}t.log(t.Level.Debug,`No IndexedDB support, some data will not be persisted:`,e)}h=!0,this.start(h,p,g)}],onMainComplete:()=>{if([p,h].includes(!1)){t.log(t.Level.Warn,{runtimeLoaded:p,fileSystemSynced:h},`Both runtimeLoaded and fileSystemSynced should be true when calling onMainComplete`),_(`onMainComplete has been called but runtime or file system was not ready.`);return}g()},onRuntimeInitialized:()=>{p=!0,this.start(h,p,g)},print:e=>{t.info(e)}}),await N(b,y)||_(`Couldn't retrieve Scandit Data Capture library at ${b}, did you configure the path for it correctly?`),v}};R.get3dPartyLicenseKeyMethodName=atob(`Z2V0QmxpbmtJZExpY2Vuc2VLZXk=`);var z=class{constructor(e,t){this.onMessageListener=this.onMessage.bind(this),this.workerSelf=e,this.dataCaptureInstance=new R(t,{postMessage:this.postMessage.bind(this),getOffscreenCanvas:this.getOffscreenCanvas.bind(this)}),d(e)&&(p(e),this.listenToMessages())}listenToMessages(){this.workerSelf.addEventListener(`message`,this.onMessageListener),this.workerSelf.addEventListener(`error`,e=>{t.log(t.Level.Error,e)}),this.workerSelf.addEventListener(`messageerror`,e=>{t.log(t.Level.Error,e)})}postMessage(e,t){this.workerSelf.postMessage(e,t??[])}getOffscreenCanvas(){if(this.isOffscreenCanvasSupported())return new this.workerSelf.OffscreenCanvas(32,32)}isOffscreenCanvasSupported(){return typeof this.workerSelf.OffscreenCanvas==`function`}hasPayload(e){return c(e)&&`payload`in e}hasTransferables(e){return c(e)&&Array.isArray(e.transferables)}async respondWith(e,t,n){let r=null,i;try{i=n(),i instanceof Promise&&(i=await i)}catch(e){i=void 0,r=u(e)}let a={type:`workerTaskId`,command:e,id:t,payload:this.hasPayload(i)?i.payload:void 0};r!=null&&(a.error=r),this.postMessage(a,this.hasTransferables(i)?i.transferables:[])}onMessage(e){switch(e.data.command){case`loadLibrary`:{let{data:t}=e;this.respondWith(t.command,t.id,async()=>this.dataCaptureInstance.loadLibrary({libraryLocation:t.libraryLocation,locationPath:t.locationPath,referredOrigin:t.referredOrigin,writableDataPathOverride:t.writableDataPathOverride,threadsSupport:t.threadsSupport,simdSupport:t.simdSupport,verifyResponseHash:t.verifyResponseHash,fixedWasmMemory:t.fixedWasmMemory,indexedDBTimeoutMs:t.indexedDBTimeoutMs}))}break;case`onTap`:{let{data:t}=e;this.respondWith(t.command,t.id,async()=>{this.dataCaptureInstance.onTap(t.point)})}break;case`hintPresenterV2update`:{let{data:t}=e;this.respondWith(t.command,t.id,async()=>{this.dataCaptureInstance.hintPresenterV2Update()})}break;case`createContext`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.createContext({context:t.context,deviceId:t.deviceId,delayedRegistration:t.delayedRegistration,highEndBlurryRecognition:t.highEndBlurryRecognition,appName:t.appName,parentDomain:t.parentDomain,isTablet:t.isTablet,batteryInfo:t.batteryInfo}))}break;case`setFrameSource`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.setFrameSource(t.mirrorAxis,t.isCameraFrameSource))}break;case`processFrame`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.processFrame({data:t.data,frameId:t.frameId,width:t.width,height:t.height,colorType:t.colorType}))}break;case`requestFrameData`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.requestFrameData(t.frameId))}break;case`deleteFrameData`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>{this.dataCaptureInstance.deleteFrameData(t.frameId)})}break;case`updateContext`:{let{data:t}=e;this.respondWith(t.command,t.id,async()=>this.dataCaptureInstance.updateContext(t))}break;case`dispose`:this.respondWith(e.data.command,e.data.id,()=>this.dataCaptureInstance.dispose());break;case`flushAnalytics`:this.respondWith(e.data.command,e.data.id,()=>{this.dataCaptureInstance.flushAnalytics()});break;case`reportCameraProperties`:{let{data:t}=e;this.respondWith(t.command,t.id,async()=>this.dataCaptureInstance.reportCameraProperties(t))}break;case`setLogLevel`:{let{data:n}=e;this.respondWith(n.command,n.id,()=>{t.setLevel(n.level)})}break;case`updateBatteryInfo`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>{this.dataCaptureInstance.updateBatteryInfo(t.batteryInfo)})}break;case`extractCentaurusLicense`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.extractCentaurusLicense(t.licenseKey))}break;case`documentVisibility`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>{this.dataCaptureInstance.onDocumentVisibilityChange(t.state)})}break;case`isFeatureSupported`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.isFeatureSupported(t.feature))}break;case`getViewfinderInfo`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.getViewfinderInfo())}break;case`getOpenSourceSoftwareLicenseInfo`:{let{data:t}=e;this.respondWith(t.command,t.id,()=>this.dataCaptureInstance.getOpenSourceSoftwareLicenseInfo())}break;case`addNativeOverlay`:this.dataCaptureInstance.addNativeOverlay(e);break;case`removeNativeOverlay`:this.dataCaptureInstance.removeNativeOverlay(e);break;case`convertToJPEGResult`:{let{data:t}=e;this.dataCaptureInstance.convertToJPEGResult(t.imageId,t.result)}break;default:return r(e.data),!1}return!0}};function B(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.command==`string`&&typeof t.id==`number`}function V(e){return e.ok()}function H(e,t){return V(e)?e.value():t}function U(e,t){return V(e)?t:e.error()}function W(e,t){return e===void 0?t:e}let G=(...e)=>void 0,K=G,q=G;var J=class{constructor(e,t,n){this.SDCIdCaptureMode=null,this.lastResult=``,this.lastError=``,this.lastLocalizedId=``,this.lastDetectionIssue=``,this.lastDiagnostics=``,this.privateFrameSignalsEnabled=!1,this.coreEngine=e,this.Module=e.Module,this.workerFunctions=e.workerFunctions,this.start(t,n)}start(e,t){this.initHintPresenterIfNotInitialized();let n=this.Module.IdCaptureListener.extend(`IdCaptureListener`,{onSessionUpdated:(e,t)=>{this.onIdOutlineUpdatedCallback(t),e.delete(),t.delete()},onIdCaptured:(e,t)=>{this.onIdCapturedCallback(t),e.delete(),t.delete()},onIdPartiallyCaptured:(e,t)=>{this.onIdPartiallyCapturedCallback(t),e.delete(),t.delete()},onIdRejected:(e,t,n)=>{this.onIdRejectedCallback(t,n),e.delete(),t?.delete()},onIdLocalized:(e,t)=>{this.onIdLocalizedCallback(t),e.delete()},onShutterButtonPositionChanged:e=>{this.onShutterButtonPositionChangedCallback(e)},onShutterButtonStateChanged:e=>{this.onShutterButtonStateChangedCallback(e)},onCloudProcessingStarted:()=>{this.onCloudProcessingStartedCallback()},onCloudProcessingFinished:()=>{this.onCloudProcessingFinishedCallback()},onCaptureIssueEncountered:e=>{this.onCaptureIssueEncounteredCallback(e??null)},onViewfinderHintChanged:e=>{this.onViewfinderHintChangedCallback(e??null)}}),r=this.Module.Feedback.extend(`Feedback`,{emit:()=>{this.workerFunctions.postMessage({type:`idCaptureIdCapturedFeedback`})}}),i=this.Module.Feedback.extend(`Feedback`,{emit:()=>{this.workerFunctions.postMessage({type:`idCaptureIdRejectedFeedback`})}}),a=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)}),o=this.Module.IdCaptureImageProcessor.extend(`IdCaptureImageProcessor`,{outlineRegions:e=>e,obscureRegions:e=>e}),s=new a,c=new o;this.SDCIdCaptureMode=new this.Module.IdCapture(e,s,t,c),s.delete(),c.delete();let l=new n;this.SDCIdCaptureMode.addListener(l),l.delete();let u=new r,d=new i;this.SDCIdCaptureMode.setFeedbacks(u,d),u.delete(),d.delete()}getSDCIdCaptureMode(){if(!this.SDCIdCaptureMode)throw Error(`IdCaptureMode not initialized`);return this.SDCIdCaptureMode}backendGetLastResult(){return q(()=>{let e=null,t=!1;try{e=JSON.parse(this.lastResult),t=!0}catch{e=this.lastResult}t&&e&&typeof e==`object`?K(`DataCaptureEngine: getting last result`,{...e,imageInfo:{front:{frame:null,croppedDocument:e.imageInfo?.front.croppedDocument?`<redacted>`:null,face:e.imageInfo?.front.face?`<redacted>`:null},back:{frame:null,croppedDocument:e.imageInfo?.back.croppedDocument?`<redacted>`:null,face:null}}}):K(`DataCaptureEngine: getting last result`,this.lastResult)}),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){this.privateFrameSignalsEnabled=e.properties.enablePrivateFrameSignals===!0,this.SDCIdCaptureMode?.applySettings(JSON.stringify(e))}enablePrivateFrameSignals(e){this.privateFrameSignalsEnabled=e}reset(){this.SDCIdCaptureMode?.reset()}setExternalTransactionId(e){this.SDCIdCaptureMode?.setExternalTransactionId(e)}getExternalTransactionId(){return this.SDCIdCaptureMode?.getExternalTransactionId()}parseCode(e){if(this.SDCIdCaptureMode){let t=this.SDCIdCaptureMode.parse(e);if(t.ok()){let e=H(t,null);if(e!=null){let t=this.extractCaptureId(e);if(t!=null)return{status:`success`,capturedId:t}}}else return{status:`error`,error:U(t,`Undefined error`)}}return null}getCentaurusSettings(){let e=this.getSDCIdCaptureMode().getCentaurusSettings();return JSON.parse(e)}async barcodeVerifyAamvaCapture(e,t){return new Promise(n=>{let r=new(this.Module.AamvaBarcodeVerifier.extend(`AamvaBarcodeVerifier`,{retriggerVerificationIn(t){setTimeout(()=>{r.startVerification(JSON.stringify(e))},t)},verificationEnded:()=>{let e=r.getBarcodeVerificationResponse();if(e.status===void 0){n({status:null,error:e.error});return}let t=this.Module.AamvaBarcodeVerificationStatus,i;switch(e.status){case t.Authentic:i=`authentic`;break;case t.LikelyForged:i=`likelyForged`;break;case t.Forged:i=`forged`;break;default:i=`authentic`}n({status:i,error:null})}}));r.initialize(this.coreEngine.context,t),r.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}})}onIdOutlineUpdatedCallback(e){let t=e.getIdOutline(),n=t?JSON.parse(t):null;if(this.privateFrameSignalsEnabled){let t=e.getDiagnosticFromBackend(),r=t?JSON.parse(t):null;this.workerFunctions.postMessage({type:`idCaptureDidUpdateIdOutline`,payload:{idOutline:n,isGoodFrame:e.isGoodFrame(),diagnostics:r}})}else this.workerFunctions.postMessage({type:`idCaptureDidUpdateIdOutline`,payload:{idOutline:n}})}onCaptureIssueEncounteredCallback(e){this.privateFrameSignalsEnabled&&this.workerFunctions.postMessage({type:`idCaptureCaptureIssueEncountered`,payload:{issue:e}})}onViewfinderHintChangedCallback(e){this.privateFrameSignalsEnabled&&this.workerFunctions.postMessage({type:`idCaptureViewfinderHintChanged`,payload:{hint:e}})}onIdCapturedCallback(e){let t=this.extractCaptureId(e);t&&this.workerFunctions.postMessage({type:`idCaptureDidCaptureId`,payload:{capturedId:t}},this.extractImageTransferablesFromCapturedId(t))}onIdPartiallyCapturedCallback(e){let t=this.extractCaptureId(e);t&&this.workerFunctions.postMessage({type:`idCaptureDidPartiallyCaptureId`,payload:{capturedId:t}},this.extractImageTransferablesFromCapturedId(t))}onIdRejectedCallback(e,t){let n=this.extractCaptureId(e);this.workerFunctions.postMessage({type:`idCaptureDidRejectId`,payload:{capturedId:n,rejectionReason:t}},n?this.extractImageTransferablesFromCapturedId(n):[])}onIdLocalizedCallback(e){this.workerFunctions.postMessage({type:`idCaptureDidLocalizeId`,payload:{localization:JSON.parse(e)}})}extractCaptureId(e){if(e==null)return null;let t=e.getImages(),n=t.getFrameFront(),r=t.getFrameBack(),i=W(t.getFace(),null),a=W(t.getCroppedDocumentFront(),null),o=W(t.getCroppedDocumentBack(),null),s=W(t.getFrameObscuredRegionsFront(),null),c=W(t.getFrameObscuredRegionsBack(),null),l=W(t.getCroppedDocumentObscuredRegionsFront(),null),u=W(t.getCroppedDocumentObscuredRegionsBack(),null),d={front:{face:this.prefixImageWithDataUriIfNeeded(i),croppedDocument:{image:this.prefixImageWithDataUriIfNeeded(a),obscuredRegions:JSON.parse(l??`[]`)},frame:{image:{data:n?new Uint8ClampedArray(n.getFrameData()):null,width:n?.getWidth()??0,height:n?.getHeight()??0,mirrorAxis:n?.getMirrorAxis().value??0,orientation:n?.getOrientation()??0},obscuredRegions:JSON.parse(s??`[]`)}},back:{face:null,croppedDocument:{image:this.prefixImageWithDataUriIfNeeded(o),obscuredRegions:JSON.parse(u??`[]`)},frame:{image:{data:r?new Uint8ClampedArray(r.getFrameData()):null,width:r?.getWidth()??0,height:r?.getHeight()??0,mirrorAxis:r?.getMirrorAxis().value??0,orientation:r?.getOrientation()??0},obscuredRegions:JSON.parse(c??`[]`)}}};return n?.delete(),r?.delete(),t.delete(),{...JSON.parse(e.toJson()),rawImageInfo:d}}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}})}onCloudProcessingStartedCallback(){this.workerFunctions.postMessage({type:`idCaptureCloudProcessingStarted`})}onCloudProcessingFinishedCallback(){this.workerFunctions.postMessage({type:`idCaptureCloudProcessingFinished`})}async reportSafariAbruptReload(e){let t=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,t),t.delete()}parseIdCaptureSession(e){return JSON.parse(e.toJson())}dispose(){this.SDCIdCaptureMode?.delete(),this.SDCIdCaptureMode=null,this.lastError=``,this.lastLocalizedId=``,this.lastResult=``}extractImageTransferablesFromCapturedId(e){let t=[],n=e.rawImageInfo.front.frame.image.data;n&&n.length>0&&t.push(n.buffer);let r=e.rawImageInfo.back.frame.image.data;return r&&r.length>0&&t.push(r.buffer),t}isReadyToDisplayHints(){return this.coreEngine.view?this.coreEngine.view.hintPresenterInitialized():!1}initHintPresenterIfNotInitialized(){if(this.isReadyToDisplayHints())return;let e=this.Module.HintPresenter.extend(`HintPresenter`,{showHint:(e,t)=>{this.workerFunctions.postMessage({type:`showHint`,payload:{text:e,style:JSON.parse(t)}})},updateHint:e=>{this.workerFunctions.postMessage({type:`updateHint`,payload:{style:JSON.parse(e)}})},hideHint:()=>{this.workerFunctions.postMessage({type:`hideHint`,payload:{}})}});this.coreEngine.view?.setHintPresenter(new e)}};function Y(e,t,n){let r=new(t.IdCaptureDeserializerHelper.extend(`IdCaptureDeserializerHelper`,{createMode:(t,r)=>{let i=new J(e,t,r);return n(i),t.delete(),r.delete(),i.getSDCIdCaptureMode()}})),i=new t.IdCaptureDeserializer(r);return r.delete(),i}var X=class extends R{constructor(...e){super(...e),this.idCaptureMode=null,this.lastIdCaptureModeSerializedSettings=``}getModeDeserializers(){let e=super.getModeDeserializers(),t=Y(this,this.Module,this.receiveNewCaptureMode.bind(this));return e.push_back(t),t.delete(),e}receiveNewCaptureMode(e){this.idCaptureMode=e}processFrame(e){return this.idCaptureMode?super.processFrame(e):{payload:e,transferables:[e.data.buffer]}}updateContext(e){super.updateContext(e)}idCaptureSetLastResult(e){this.idCaptureMode?.setLastResult(e)}idCaptureSetLastError(e){this.idCaptureMode?.setLastError(e)}idCaptureSetLastLocalizedId(e){this.idCaptureMode?.setLastLocalizedId(e)}idCaptureSetLastDetectionIssue(e){this.idCaptureMode?.setLastDetectionIssue(e)}idCaptureSetLastDiagnostics(e){this.idCaptureMode?.setLastDiagnostics(e)}idCaptureReset(){this.idCaptureMode?.reset()}idCaptureSetExternalTransactionId(e){this.idCaptureMode?.setExternalTransactionId(e)}idCaptureGetExternalTransactionId(){return{payload:{transactionId:this.idCaptureMode?.getExternalTransactionId()??null}}}idCaptureApplySettings(e){this.idCaptureMode?.applySettings(e)}idCaptureEnablePrivateFrameSignals(e){this.idCaptureMode?.enablePrivateFrameSignals(e)}idCaptureGetCentaurusSettings(){return{payload:{result:this.idCaptureMode.getCentaurusSettings()}}}idCaptureParse(e){return{payload:{result:this.idCaptureMode?.parseCode(e)??null}}}async idCaptureBarcodeVerifyAamvaCapture(e,t){return{payload:{result:await this.idCaptureMode?.barcodeVerifyAamvaCapture(e,t)??null}}}idCaptureDrivingLicenseD