@scandit/web-datacapture-core
Version:
Scandit Data Capture SDK for the Web
6 lines (5 loc) • 19.2 kB
JavaScript
import {a as a$6}from'./chunk-C3EY6I75.js';import {a as a$9,c as c$2,b as b$3}from'./chunk-X2ZGBI4S.js';import {a as a$g}from'./chunk-BA3RP6L2.js';import {a as a$7}from'./chunk-AIC4H5KG.js';import {a as a$e}from'./chunk-4F5JUHOJ.js';import {a as a$c}from'./chunk-JS3T7K2Z.js';import {b as b$2}from'./chunk-6H6FKGVE.js';import {a as a$b}from'./chunk-N5YZEC56.js';import {a as a$5}from'./chunk-VJB527QZ.js';import {a as a$4}from'./chunk-GHTCNOQN.js';import {a as a$1}from'./chunk-LXOZUOZU.js';import {a as a$d}from'./chunk-FGO2SSRS.js';import {d}from'./chunk-ADFFBLII.js';import {a as a$8}from'./chunk-GPJEB376.js';import {b as b$1}from'./chunk-VBUDN72N.js';import {c as c$1,e}from'./chunk-SBC5K7IT.js';import {a as a$3}from'./chunk-XR65N6EG.js';import {f as f$1}from'./chunk-3D2HNEVH.js';import {a as a$f}from'./chunk-WUHKODFA.js';import {a as a$2}from'./chunk-7SW2PEHB.js';import {a as a$a}from'./chunk-QCZSSQAQ.js';import {c}from'./chunk-TR3NGINC.js';var $=[{from:"unconfigured",to:"configuring"},{from:"configuring",to:"configured"},{from:"configuring",to:"unconfigured"},{from:"configured",to:"creating-context"},{from:"creating-context",to:"ready"},{from:"creating-context",to:"unconfigured"},{from:"ready",to:"unconfigured"},{from:"configured",to:"unconfigured"}];function f(C,e,t){let r=t.value;return t.value=function(...n){let i=g.stateMachine;return i.currentState==="ready"&&g.mainDataCaptureLoader!=null?r.apply(this,n):i.isInitializing||i.currentState==="configured"?i.waitForState("ready").then(()=>r.apply(this,n)):Promise.reject(new Error(`Please call DataCaptureContext.forLicenseKey() before calling ${String(e)}`))},t}function j(C){return C[a$g]!=null}function P(C){return "skipSerialization"in C||C[a$g]!=null}var z,B,U,a=class a{constructor(){this._asyncImageConverterInstance=void 0;this.framework="web";this.runtimeEnvironment={deviceOS:(z=b$1.getUserAgentInfo().getOS().name)!=null?z:"",browser:(B=b$1.getUserAgentInfo().getBrowser().name)!=null?B:"",browserVersion:(U=b$1.getUserAgentInfo().getBrowser().version)!=null?U:"",get deviceModelName(){let{model:e,vendor:t}=b$1.getUserAgentInfo().getDevice();return (t==null||t==="")&&(t="Unknown"),(e==null||e==="")&&(e="Unknown"),[t,e].join(" ")}};this.settings=new a$2;this._frameSource=null;this._view=null;this.modes=new Set;this.components=[];this.listeners=[];this.updateListeners=new Set;this.cameraPropertiesReportListener=this.reportCameraProperties.bind(this);this.cameraAccessErrorListener=this.onCameraAccessError.bind(this);this.onWorkerMessageListener=this.onWorkerMessage.bind(this);this.onVisibilityChangeListener=this.onVisibilityChange.bind(this);this.pendingWorkerMessageListeners=new Set;this.delayedRegistration=false;this.highEndBlurryRecognition=false;this._frameHandlers=[];this._useSynchronousFrameFlow=false;}static get moduleLicenseTextProviders(){return [new b]}static get sharedInstance(){return a._sharedInstance==null&&(a._sharedInstance=new a),a._sharedInstance}static get currentState(){return a.stateMachine.currentState}static get isReady(){return a.stateMachine.currentState==="ready"}static get isInitializing(){return a.stateMachine.isInitializing}static addStateListener(e){a.stateMachine.addListener(e);}static removeStateListener(e){a.stateMachine.removeListener(e);}async initializeWithOptions(e){var t,r,n,i,o,s,u,p,c;this.licenseKey=(r=(t=e.licenseKey)!=null?t:a.userLicenseKey)!=null?r:"",this.deviceName=(n=e.deviceName)!=null?n:"",this.dataCaptureInstance=(i=e.dataCaptureInstance)!=null?i:a.mainDataCaptureLoader,this.delayedRegistration=(o=e.delayedRegistration)!=null?o:false,e.settings!=null&&(this.settings=e.settings),this.highEndBlurryRecognition=(c=(p=(s=e.dataCaptureInstance)==null?void 0:s.highEndBlurryRecognition)!=null?p:(u=a.mainDataCaptureLoader)==null?void 0:u.highEndBlurryRecognition)!=null?c:false;for(let S of this.pendingWorkerMessageListeners)this.dataCaptureInstance.addWorkerListener(S);this.pendingWorkerMessageListeners.clear(),this.settings!=null&&await this.applySettings(this.settings),await this.createContext();}get frameSource(){return this._frameSource}get workerCommand(){if(this.dataCaptureInstance==null)throw new Error("Cannot call workerCommand before dataCaptureInstance is set");return this.dataCaptureInstance.workerCommand.bind(this.dataCaptureInstance)}static async forLicenseKey(e,t){return a$3.debug(`forLicenseKey called, current state: ${a.stateMachine.currentState}`),a.stateMachine.currentState==="ready"?(a$3.debug("DataCaptureContext is already ready, returning existing instance"),a.sharedInstance):a.stateMachine.isInitializing?(a$3.debug("DataCaptureContext is already initializing, waiting for completion"),await a.stateMachine.waitForState("ready"),a.sharedInstance):(a.stateMachine.currentState==="unconfigured"&&(a$3.debug("Starting initialization from unconfigured state"),await a.stateMachine.executeAsyncTransition({targetState:"configuring",action:async()=>{await a.internalConfigure(e,t);},onSuccess:"configured",onError:"unconfigured"}),await a.stateMachine.executeAsyncTransition({targetState:"creating-context",action:async()=>{await a.sharedInstance.initializeWithOptions({licenseKey:e,deviceName:t.deviceName,settings:t.settings});},onSuccess:"ready",onError:"unconfigured"})),a.sharedInstance)}static async internalConfigure(e$1,t){var S;a$4.getInstance().updateIfMissing(a$5);let{forceAllPolyfills:r,overrideThreadsSupport:n,overrideSimdSupport:i}=a.getOverridesFromQueryString(),[o,s,u]=await Promise.all([a$6({forceAllPolyfills:r}),c$1(),e()]);n!=="auto"&&(a$3.warn(`Threads support override: was ${u} is now ${n==="on"}`),u=n==="on"),i!=="auto"&&(a$3.warn(`SIMD support override: was ${s} is now ${i==="on"}`),s=i==="on"),a.capabilityInfo={simdSupport:s,threadsSupport:u},a$3.debug(`Capability info detected - SIMD: ${s}, Threads: ${u}`),await a.validateOptions({...t,licenseKey:e$1});let p={licenseKey:e$1,libraryLocation:a$7(t.libraryLocation),moduleLoaders:t.moduleLoaders,logLevel:(S=t.logLevel)!=null?S:a$3.Level.Debug,verifyResponseHash:true,loadProgressNotifier:b$2.notify.bind(b$2),simdSupport:s,threadsSupport:u};a$3.setLevel(p.logLevel),a.userLicenseKey=p.licenseKey,a.libraryLocation=p.libraryLocation,b$2.subscribe(a.updateViewsWithProgress);let c=b$1.checkBrowserCompatibility();if(!c.fullSupport&&!c.scannerSupport)throw new a$8(c);b$1.isSupportedIOSVersion()||a$3.warn(`Warning: Minimum supported iOS version is 14.6.
Please check the minimum system requirements here:
https://docs.scandit.com/system-requirements#browser-compatibility`),a.dataCaptureLoaders=await a.loadModules(p.moduleLoaders,p),a.mainDataCaptureLoader=[...a.dataCaptureLoaders.entries()][0][1],b$2.unsubscribe(a.updateViewsWithProgress);}static async forLicenseKeyInElectronPath(e,t){if(!a$9())throw new a$a({name:"MisconfigurationError",message:"forLicenseKeyInElectronPath can only be used in Electron applications"});let r=await c$2({licenseDataPath:e});if(r==null)throw new a$a({name:"NoLicenseKeyError",message:`Cannot retrieve license key for Electron app at ${e}`});return a.forLicenseKey(r.licenseKey,{...t})}static updateViewsWithProgress({percentage:e}){for(let t of a$b.values())t.setProgressBarPercentage(e);}static getOverridesFromQueryString(){var o,s,u;function e(p){return ["auto","off","on"].includes(p)}let t=new URLSearchParams(window.location.search),[r="auto",n="auto",i=false]=[(o=t.get("pthreads"))==null?void 0:o.toLowerCase(),(s=t.get("simd"))==null?void 0:s.toLowerCase(),((u=t.get("forceAllPolyfills"))==null?void 0:u.toLowerCase())==="true"];return {overrideThreadsSupport:e(r)?r:"auto",overrideSimdSupport:e(n)?n:"auto",forceAllPolyfills:i}}static async validateOptions(e){if(e.licenseKey==null||e.licenseKey.trim().length<64)throw new a$a({name:"NoLicenseKeyError",message:"No license key provided"});if(typeof e.libraryLocation!="string")throw new a$a({name:"MisconfigurationError",message:'Option "libraryLocation" was not provided'});if(!Array.isArray(e.moduleLoaders)||e.moduleLoaders.length===0)throw new a$a({name:"MisconfigurationError",message:'Option "moduleLoaders" is missing or empty'});let t=e.moduleLoaders.map(r=>r.moduleName);if(!["BarcodeCapture","IdCapture","LabelCapture"].includes(t[0]))throw new a$a({name:"MisconfigurationError",message:'Main modules must be loaded before side modules. For example "BarcodeCapture" must be loaded before "Parser".'})}static async loadModules(e,t){let r=new Map,n=new Map;for(let i of e)n.set(i.moduleName,i.load(t));await Promise.all(n.values());for(let[i,o]of n)r.set(i,await o);return r}static async getOpenSourceSoftwareLicenseInfo(){let e=[];for(let r of a.moduleLicenseTextProviders){let n=await r.getLicenseText();e.push(n);}let t=e.join(`
`);return new a$c(t)}async setFrameSource(e){let t=e!==this._frameSource;if(this._frameSource!==null&&(this._frameSource.context=null),this._frameSource=e!=null?e:null,e&&(e.context=this,await this.workerCommand("setFrameSource",{mirrorAxis:this.getMirrorAxisForFrameSource(e),isCameraFrameSource:f$1(e)})),await this.update([{type:"frameSourceState",newValue:this.frameSource}]),t)for(let r of this.listeners)r.didChangeFrameSource&&r.didChangeFrameSource(this,this._frameSource);}addListener(e){this.listeners.includes(e)||this.listeners.push(e);}async flushAnalytics(){await this.workerCommand("flushAnalytics",{});}removeListener(e){this.listeners.includes(e)&&this.listeners.splice(this.listeners.indexOf(e),1);}async addMode(e){this.modes.add(e),await e.attachedToContext(this),this.updateCameraFrameFlow(),await this.update([],{updateContext:!P(e)});}async removeMode(e){this.modes.delete(e),await e.detachedFromContext(),this.updateCameraFrameFlow(),await this.update([],{updateContext:!P(e)});}async setMode(e){this.modes.has(e)||(this.modes.clear(),this.modes.add(e),await e.attachedToContext(this),this.updateCameraFrameFlow(),await this.update());}async removeCurrentMode(){for(let e of this.modes)await e.detachedFromContext();this.modes.clear(),await this.update();}async removeAllModes(){let e=Array.from(this.modes);for(let t of e)await this.removeMode(t);}async dispose(){if(a.stateMachine.currentState!=="unconfigured")try{await a.stateMachine.executeAsyncTransition({targetState:"unconfigured",action:async()=>{d.instance().removeListener("cameraProperties",this.cameraPropertiesReportListener),d.instance().removeListener("cameraAccessError",this.cameraAccessErrorListener),this.unsubscribeToVisibilityChange(this.onVisibilityChangeListener);for(let e of this.modes)await e.detachedFromContext();this._view&&(await this._view.setContext(null),this._view=null),this.dataCaptureInstance&&(await this.dataCaptureInstance.terminateDataCaptureWorker(true).catch(()=>{}),this.dataCaptureInstance=void 0);},onSuccess:"unconfigured",onError:"unconfigured"});}catch(e){if(a.stateMachine.currentState==="unconfigured")return;throw e}finally{this.modes.clear(),this.listeners=[],this.components.length=0,this.updateListeners.clear(),this.pendingWorkerMessageListeners.clear(),this.delayedRegistration=false,this.highEndBlurryRecognition=false,this._frameHandlers.length=0,this.frameSource&&(this.frameSource.context=null,this._frameSource=null),this.licenseKey="",this.deviceName="";}}async applySettings(e){this.settings=e,await this.update();}toJSONObject(){var e,t;return {licenseKey:this.licenseKey,framework:this.framework,deviceName:this.deviceName,...this.runtimeEnvironment,modes:[...this.modes].filter(r=>!P(r)).map(r=>r.toJSONObject()),components:this.components.map(r=>r.toJSONObject()),frameSource:this.frameSource?this.frameSource.toJSONObject():null,settings:this.settings.toJSONObject(),view:(t=(e=this._view)==null?void 0:e.toJSONObject())!=null?t:null}}getView(){return this._view}async setView(e){return this._view=e,this.update([{type:"viewSet",newValue:e}])}async getAppName(){let e=null;if(a$9()){let t=await b$3();if((t==null?void 0:t.appName)==null||t.appName==="")throw new Error("Cannot retrieve electron appName. Did you set it up in package.json? https://www.electronjs.org/docs/latest/api/app#appgetname");e=t.appName;}return e}urlToHostname(e){try{return new URL(e!=null?e:"").hostname}catch{return ""}}getParentDomain(){var t;let e="";return parent!==window&&(e||(e=this.urlToHostname((t=location.ancestorOrigins)==null?void 0:t[0])),e||(e=this.urlToHostname(document.referrer)),e||(e="")),e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1)),e}async createContext(){await this.workerCommand("createContext",{context:this.toJSONObject(),deviceId:a.deviceID,delayedRegistration:this.delayedRegistration,highEndBlurryRecognition:this.highEndBlurryRecognition,appName:await this.getAppName(),parentDomain:this.getParentDomain()}),this.subscribeToWorkerMessages(this.onWorkerMessageListener),this.subscribeToCameraManagerEvents(),this.subscribeToVisibilityChange(this.onVisibilityChangeListener),this._view!=null&&await this.setView(this._view),this.frameSource!=null&&await this.setFrameSource(this.frameSource);}subscribeToVisibilityChange(e){document.addEventListener("visibilitychange",e);}unsubscribeToVisibilityChange(e){document.removeEventListener("visibilitychange",e);}async requestFrameData(e){return this.workerCommand("requestFrameData",{frameId:e})}performanceMark(e){a$d(globalThis.performance)&&typeof globalThis.performance.mark=="function"&&performance.mark(e);}async sendFrameToProcessor(e){let t=e instanceof ImageData?{data:e.data,width:e.width,height:e.height}:e,r=await this.sendFrameToHandlers(t);return t.data=r.capture.data,r.skip?r.capture:(this.performanceMark("processFrameBeforeSDC"),this.sendFrameToSDC(t))}async sendFrameToHandlers(e){for(let t of this._frameHandlers)if((await t(e)).action==="skip")return {skip:true,capture:e};return {skip:false,capture:e}}async sendFrameToSDC(e){return this.workerCommand("processFrame",e,[e.data.buffer])}registerFrameHandler(e){this._frameHandlers.includes(e)||this._frameHandlers.push(e);}unregisterFrameHandler(e){this._frameHandlers.includes(e)&&this._frameHandlers.splice(this._frameHandlers.indexOf(e),1);}onVisibilityChange(){this.workerCommand("documentVisibility",{state:document.visibilityState});}getImageConverterInstance(e){return this._asyncImageConverterInstance==null&&(this._asyncImageConverterInstance=new a$e(e)),this._asyncImageConverterInstance}onWorkerMessage(e){if(e.type==="contextDidChangeStatus"){e.payload.isValid||a$3.error(e.payload);for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$f.fromJSON(e.payload));}if(e.type==="didStartObservingContext")for(let t of this.listeners)t.didStartObservingContext&&t.didStartObservingContext(this);e.type==="onFrameProcessingFinished"&&this.performanceMark("processFrameAfterSDC"),e.type==="convertToJPEG"&&this.convertImageToJPEG(e);}async convertImageToJPEG(e){let{imageId:t,width:r,height:n,data:i,planes:o,orientation:s,quality:u}=e,p={getWidth:()=>r,getHeight:()=>n,getPlanes:()=>o,toBitmap:()=>i,getBitmapRepresentationFromYUV:()=>{throw new Error("Not implemented")},deepCopy:()=>{throw new Error("Not implemented")}},c=await this.getImageConverterInstance({quality:u}).convertToJpeg(p,s);return this.workerCommand("convertToJPEGResult",{imageId:t,result:c})}subscribeToCameraManagerEvents(){d.instance().addListener("cameraProperties",this.cameraPropertiesReportListener),d.instance().addListener("cameraAccessError",this.cameraAccessErrorListener);}async reportCameraProperties(e){return this.workerCommand("reportCameraProperties",e)}onCameraAccessError(e){for(let t of this.listeners)t.didChangeStatus&&t.didChangeStatus(this,a$f.fromJSON({code:33794,isValid:true,message:typeof(e==null?void 0:e.toString)=="function"?e.toString():"Unknown error"}));}async update(e=[],{updateContext:t=true}={}){var r,n;t&&await this.updateContext();for(let i of e){switch(i.type){case "frameSourceState":{await((r=this._view)==null?void 0:r.onFrameSourceChange(this.frameSource));break}case "singleImageModeUploaderSettings":{(n=this._view)==null||n.onSingleImageUploaderSettingsChange(i.newValue);break}case "addOverlay":{await this.addNativeOverlay(i.newValue);break}case "removeOverlay":{await this.removeNativeOverlay(i.newValue);break}}for(let o of this.updateListeners)o(i);}}async updateContext(){await this.workerCommand("updateContext",{context:this.toJSONObject(),...this.getViewInfo()}).catch(e=>a$3.warn("Error while updating context:",e,this.toJSONObject()));}getViewInfo(){return this._view!=null?{view:{width:this._view.width,height:this._view.height,visible:this._view.width>0&&this._view.height>0,orientation:this._view.orientation}}:{view:null}}getMirrorAxisForFrameSource(e){let t="None";return f$1(e)&&e.getMirrorImageEnabled()&&(t="Y"),t}async addComponent(e){if(!this.components.includes(e))return this.components.push(e),e._context=this,this.update()}async addNativeOverlay(e){if(j(e))return this.workerCommand("addNativeOverlay",{overlayHandle:e[a$g]})}async removeNativeOverlay(e){if(j(e))return this.workerCommand("removeNativeOverlay",{overlayHandle:e[a$g]})}subscribeToWorkerMessages(e){this.dataCaptureInstance?this.dataCaptureInstance.addWorkerListener(e):this.pendingWorkerMessageListeners.add(e);}unsubscribeToWorkerMessages(e){this.dataCaptureInstance&&this.dataCaptureInstance.removeWorkerListener(e),this.pendingWorkerMessageListeners.delete(e);}hasEnabledMode(){return [...this.modes].some(e=>e.isEnabled())}updateCameraFrameFlow(){let e=[...this.modes].some(t=>t._synchronousFrameFlow===true);d.instance().setFrameHandling(e);}async isFeatureSupported(e){return (await this.workerCommand("isFeatureSupported",{feature:e})).supported}};a.deviceID=b$1.getDeviceId(),a.stateMachine=new a$1("unconfigured",$),a.mainDataCaptureLoader=void 0,a.dataCaptureLoaders=new Map,a.libraryLocation=void 0,a.userLicenseKey=null,a.capabilityInfo=void 0,c([f],a.prototype,"setFrameSource",1),c([f],a.prototype,"addMode",1),c([f],a.prototype,"removeMode",1),c([f],a.prototype,"setMode",1),c([f],a.prototype,"removeCurrentMode",1),c([f],a.prototype,"isFeatureSupported",1);var g=a;var b=class{constructor(e=g,t=a$3,r=globalThis.fetch.bind(globalThis)){this.staticContext=g;this.staticContext=e,this.logger=t,this.fetch=r;}get workerCommand(){var e;return (e=this.staticContext.mainDataCaptureLoader)==null?void 0:e.workerCommand.bind(this.staticContext.mainDataCaptureLoader)}async getLicenseText(){var i,o;let e=this.staticContext.stateMachine.currentState;if(e==="unconfigured"||e==="configuring")return this.logger.warn('You must call "DataCaptureContext.forLicenseKey" before retrieving open source license text info.'),"";let t=new URL(`${((i=this.staticContext.libraryLocation)!=null?i:"").replace(/\/$/,"")}/license/web-core-license.txt`),[r,n]=await Promise.all([(o=this.workerCommand)==null?void 0:o.call(this,"getOpenSourceSoftwareLicenseInfo",{}),this.fetchWebLicenseText(t.toString())]);return [r==null?void 0:r.licenseText,n].filter(s=>s!=null).join(`
`)}async fetchWebLicenseText(e){return this.fetch(e,{mode:"cors",credentials:"include",headers:{"Content-Type":"text/plain"}}).then(async t=>{if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.text()}).catch(t=>(this.logger.warn(`Failed to fetch license from ${e}: ${t.toString()}`),null))}};export{b as a,g as b};