UNPKG

@scandit/web-datacapture-id

Version:

Scandit Data Capture SDK for the Web

6 lines 25.7 kB
var __defProp=Object.defineProperty;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value:value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value);var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value);var __privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method) /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */;var _wasmModule,_defaultSessionSettings,_showDemoOverlay,_showProductionOverlay,_proxyUrls,_CentaurusWorker_instances,loadWasm_fn,configureProxyUrls_fn,validateProxyPermissions_fn,sanitizeProxyUrls_fn,buildServiceUrl_fn;const proxyMarker=Symbol("Comlink.proxy");const createEndpoint=Symbol("Comlink.endpoint");const releaseProxy=Symbol("Comlink.releaseProxy");const finalizer=Symbol("Comlink.finalizer");const throwMarker=Symbol("Comlink.thrown");const isObject=val=>typeof val==="object"&&val!==null||typeof val==="function";const proxyTransferHandler={canHandle:val=>isObject(val)&&val[proxyMarker],serialize(obj){const{port1:port1,port2:port2}=new MessageChannel;expose(obj,port1);return[port2,[port2]]},deserialize(port){port.start();return wrap(port)}};const throwTransferHandler={canHandle:value=>isObject(value)&&throwMarker in value,serialize({value:value}){let serialized;if(value instanceof Error)serialized={isError:true,value:{message:value.message,name:value.name,stack:value.stack}};else serialized={isError:false,value:value};return[serialized,[]]},deserialize(serialized){if(serialized.isError)throw Object.assign(new Error(serialized.value.message),serialized.value);throw serialized.value}};const transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler]]);function isAllowedOrigin(allowedOrigins,origin){for(const allowedOrigin of allowedOrigins){if(origin===allowedOrigin||allowedOrigin==="*")return true;if(allowedOrigin instanceof RegExp&&allowedOrigin.test(origin))return true}return false}function expose(obj,ep=globalThis,allowedOrigins=["*"]){ep.addEventListener("message",(function callback(ev){if(!ev||!ev.data)return;if(!isAllowedOrigin(allowedOrigins,ev.origin)){console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);return}const{id:id,type:type,path:path}=Object.assign({path:[]},ev.data);const argumentList=(ev.data.argumentList||[]).map(fromWireValue);let returnValue;try{const parent=path.slice(0,-1).reduce(((obj2,prop)=>obj2[prop]),obj);const rawValue=path.reduce(((obj2,prop)=>obj2[prop]),obj);switch(type){case"GET":returnValue=rawValue;break;case"SET":parent[path.slice(-1)[0]]=fromWireValue(ev.data.value);returnValue=true;break;case"APPLY":returnValue=rawValue.apply(parent,argumentList);break;case"CONSTRUCT":{const value=new rawValue(...argumentList);returnValue=proxy(value)}break;case"ENDPOINT":{const{port1:port1,port2:port2}=new MessageChannel;expose(obj,port2);returnValue=transfer(port1,[port1])}break;case"RELEASE":returnValue=void 0;break;default:return}}catch(value){returnValue={value:value,[throwMarker]:0}}Promise.resolve(returnValue).catch((value=>({value:value,[throwMarker]:0}))).then((returnValue2=>{const[wireValue,transferables]=toWireValue(returnValue2);ep.postMessage(Object.assign(Object.assign({},wireValue),{id:id}),transferables);if(type==="RELEASE"){ep.removeEventListener("message",callback);closeEndPoint(ep);if(finalizer in obj&&typeof obj[finalizer]==="function")obj[finalizer]()}})).catch((error=>{const[wireValue,transferables]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});ep.postMessage(Object.assign(Object.assign({},wireValue),{id:id}),transferables)}))}));if(ep.start)ep.start()}function isMessagePort(endpoint){return endpoint.constructor.name==="MessagePort"}function closeEndPoint(endpoint){if(isMessagePort(endpoint))endpoint.close()}function wrap(ep,target){const pendingListeners=new Map;ep.addEventListener("message",(function handleMessage(ev){const{data:data}=ev;if(!data||!data.id)return;const resolver=pendingListeners.get(data.id);if(!resolver)return;try{resolver(data)}finally{pendingListeners.delete(data.id)}}));return createProxy(ep,pendingListeners,[],target)}function throwIfProxyReleased(isReleased){if(isReleased)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(ep){return requestResponseMessage(ep,new Map,{type:"RELEASE"}).then((()=>{closeEndPoint(ep)}))}const proxyCounter=new WeakMap;const proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry((ep=>{const newCount=(proxyCounter.get(ep)||0)-1;proxyCounter.set(ep,newCount);if(newCount===0)releaseEndpoint(ep)}));function registerProxy(proxy2,ep){const newCount=(proxyCounter.get(ep)||0)+1;proxyCounter.set(ep,newCount);if(proxyFinalizers)proxyFinalizers.register(proxy2,ep,proxy2)}function unregisterProxy(proxy2){if(proxyFinalizers)proxyFinalizers.unregister(proxy2)}function createProxy(ep,pendingListeners,path=[],target=function(){}){let isProxyReleased=false;const proxy2=new Proxy(target,{get(_target,prop){throwIfProxyReleased(isProxyReleased);if(prop===releaseProxy)return()=>{unregisterProxy(proxy2);releaseEndpoint(ep);pendingListeners.clear();isProxyReleased=true};if(prop==="then"){if(path.length===0)return{then:()=>proxy2};const r=requestResponseMessage(ep,pendingListeners,{type:"GET",path:path.map((p=>p.toString()))}).then(fromWireValue);return r.then.bind(r)}return createProxy(ep,pendingListeners,[...path,prop])},set(_target,prop,rawValue){throwIfProxyReleased(isProxyReleased);const[value,transferables]=toWireValue(rawValue);return requestResponseMessage(ep,pendingListeners,{type:"SET",path:[...path,prop].map((p=>p.toString())),value:value},transferables).then(fromWireValue)},apply(_target,_thisArg,rawArgumentList){throwIfProxyReleased(isProxyReleased);const last=path[path.length-1];if(last===createEndpoint)return requestResponseMessage(ep,pendingListeners,{type:"ENDPOINT"}).then(fromWireValue);if(last==="bind")return createProxy(ep,pendingListeners,path.slice(0,-1));const[argumentList,transferables]=processArguments(rawArgumentList);return requestResponseMessage(ep,pendingListeners,{type:"APPLY",path:path.map((p=>p.toString())),argumentList:argumentList},transferables).then(fromWireValue)},construct(_target,rawArgumentList){throwIfProxyReleased(isProxyReleased);const[argumentList,transferables]=processArguments(rawArgumentList);return requestResponseMessage(ep,pendingListeners,{type:"CONSTRUCT",path:path.map((p=>p.toString())),argumentList:argumentList},transferables).then(fromWireValue)}});registerProxy(proxy2,ep);return proxy2}function myFlat(arr){return Array.prototype.concat.apply([],arr)}function processArguments(argumentList){const processed=argumentList.map(toWireValue);return[processed.map((v=>v[0])),myFlat(processed.map((v=>v[1])))]}const transferCache=new WeakMap;function transfer(obj,transfers){transferCache.set(obj,transfers);return obj}function proxy(obj){return Object.assign(obj,{[proxyMarker]:true})}function toWireValue(value){for(const[name,handler]of transferHandlers)if(handler.canHandle(value)){const[serializedValue,transferables]=handler.serialize(value);return[{type:"HANDLER",name:name,value:serializedValue},transferables]}return[{type:"RAW",value:value},transferCache.get(value)||[]]}function fromWireValue(value){switch(value.type){case"HANDLER":return transferHandlers.get(value.name).deserialize(value.value);case"RAW":return value.value}}function requestResponseMessage(ep,pendingListeners,msg,transfers){return new Promise((resolve=>{const id=generateUUID();pendingListeners.set(id,resolve);if(ep.start)ep.start();ep.postMessage(Object.assign({id:id},msg),transfers)}))}function generateUUID(){return new Array(4).fill(0).map((()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16))).join("-")}const bulkMemory=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),mutableGlobals=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,2,8,1,1,97,1,98,3,127,1,6,6,1,127,1,65,0,11,7,5,1,1,97,3,1])),referenceTypes=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,208,112,26,11])),saturatedFloatToInt=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])),signExtensions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])),simd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),threads=()=>(async e=>{try{return"undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e2){return false}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]));function isSafari(){const userAgent=navigator.userAgent.toLowerCase();return userAgent.includes("safari")&&!userAgent.includes("chrome")}async function checkThreadsSupport(){const supportsWasmThreads=await threads();if(!supportsWasmThreads)return false;if(!("importScripts"in self))throw Error("Not implemented");if(isSafari())return false;return"Worker"in self}async function detectWasmFeatures(){const basicSet=[mutableGlobals(),referenceTypes(),bulkMemory(),saturatedFloatToInt(),signExtensions()];const supportsBasic=(await Promise.all(basicSet)).every(Boolean);if(!supportsBasic)throw new Error("Browser doesn't meet minimum requirements!");const supportsAdvanced=await simd();if(!supportsAdvanced)return"basic";const supportsAdvancedThreads=await checkThreadsSupport();if(!supportsAdvancedThreads)return"advanced";return"advanced-threads"}const workerType="application/javascript";const getCrossOriginWorkerURL=(originalWorkerUrl,_options={})=>{const options={skipSameOrigin:true,useBlob:true,..._options};if(options.skipSameOrigin&&new URL(originalWorkerUrl).origin===self.location.origin)return Promise.resolve(originalWorkerUrl);return new Promise(((resolve,reject)=>void fetch(originalWorkerUrl).then((res=>res.text())).then((codeString=>{const workerPath=new URL(originalWorkerUrl).href.split("/");workerPath.pop();let finalURL="";if(options.useBlob){const blob=new Blob([codeString],{type:workerType});finalURL=URL.createObjectURL(blob)}else finalURL=`data:${workerType},`+encodeURIComponent(codeString);resolve(finalURL)})).catch(reject)))};function isIOS(){const userAgent=self.navigator.userAgent.toLowerCase();return/iphone|ipad|ipod/.test(userAgent)}function constructLicenseRequest(unlockResult){return{licenseId:unlockResult.licenseId,licensee:unlockResult.licensee,applicationIds:unlockResult.applicationIds,packageName:unlockResult.packageName,platform:"Browser",sdkName:unlockResult.sdkName,sdkVersion:unlockResult.sdkVersion}}async function obtainNewServerPermission(unlockResult,baltazarUrl="https://www.scandit.com"){if(!baltazarUrl||typeof baltazarUrl!=="string")throw new Error("Invalid baltazarUrl: must be a non-empty string");try{new URL(baltazarUrl)}catch(error){throw new Error(`Invalid baltazarUrl format: ${baltazarUrl}`)}try{const response=await fetch(baltazarUrl,{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-cache",body:JSON.stringify(constructLicenseRequest(unlockResult))});if(!response.ok)throw new Error(`Server returned error: ${response.status} ${response.statusText}`);const serverPermission=await response.json();return serverPermission}catch(error){console.error("Server permission request failed:",error);throw error}}function mbToWasmPages(mb){return Math.ceil(mb*1024*1024/64/1024)}async function downloadArrayBuffer(url,progressCallback){const response=await fetch(url);if(!response.body||!response.headers.has("Content-Length"))return response.arrayBuffer();const contentLength=parseInt(response.headers.get("Content-Length"),10);let loaded=0;const reader=response.body.getReader();const chunks=[];let result=await reader.read();while(!result.done){const value=result.value;if(value){chunks.push(value);loaded+=value.length;if(progressCallback){const progress=Math.min(Math.round(loaded/contentLength*100),100);progressCallback({loaded:loaded,contentLength:contentLength,progress:progress})}}result=await reader.read()}const allChunks=new Uint8Array(loaded);let position=0;for(const chunk of chunks){allChunks.set(chunk,position);position+=chunk.length}return allChunks.buffer}function buildResourcePath(...segments){const path=segments.filter((segment=>segment)).join("/").replace(/([^:]\/)\/+/g,"$1");try{new URL(path,"http://example.com")}catch{throw new Error(`Invalid URL: ${path}`)}return path}function getType(payload){return Object.prototype.toString.call(payload).slice(8,-1)}function isPlainObject(payload){if(getType(payload)!=="Object")return false;const prototype=Object.getPrototypeOf(payload);return!!prototype&&prototype.constructor===Object&&prototype===Object.prototype}function isSymbol(payload){return getType(payload)==="Symbol"}function assignProp(carry,key,newVal,originalObject){const propType={}.propertyIsEnumerable.call(originalObject,key)?"enumerable":"nonenumerable";if(propType==="enumerable")carry[key]=newVal;if(propType==="nonenumerable")Object.defineProperty(carry,key,{value:newVal,enumerable:false,writable:true,configurable:true})}function mergeRecursively(origin,newComer,compareFn){if(!isPlainObject(newComer))return newComer;let newObject={};if(isPlainObject(origin)){const props2=Object.getOwnPropertyNames(origin);const symbols2=Object.getOwnPropertySymbols(origin);newObject=[...props2,...symbols2].reduce(((carry,key)=>{const targetVal=origin[key];if(!isSymbol(key)&&!Object.getOwnPropertyNames(newComer).includes(key)||isSymbol(key)&&!Object.getOwnPropertySymbols(newComer).includes(key))assignProp(carry,key,targetVal,origin);return carry}),{})}const props=Object.getOwnPropertyNames(newComer);const symbols=Object.getOwnPropertySymbols(newComer);const result=[...props,...symbols].reduce(((carry,key)=>{let newVal=newComer[key];const targetVal=isPlainObject(origin)?origin[key]:void 0;if(targetVal!==void 0&&isPlainObject(newVal))newVal=mergeRecursively(targetVal,newVal);const propToAssign=newVal;assignProp(carry,key,propToAssign,newComer);return carry}),newObject);return result}function merge(object,...otherObjects){return otherObjects.reduce(((result,newComer)=>mergeRecursively(result,newComer)),object)}function normalizeDocumentFilter(filter){return{country:(filter==null?void 0:filter.country)??void 0,region:(filter==null?void 0:filter.region)??void 0,type:(filter==null?void 0:filter.type)??void 0}}const normalizeDocumentRule=rule=>({documentFilter:normalizeDocumentFilter(rule.documentFilter),fields:rule.fields??[]});const normalizeDocumentAnonymizationSettings=settings=>({documentFilter:normalizeDocumentFilter(settings.documentFilter),fields:settings.fields||[],documentNumberAnonymizationSettings:settings.documentNumberAnonymizationSettings?{prefixDigitsVisible:settings.documentNumberAnonymizationSettings.prefixDigitsVisible,suffixDigitsVisible:settings.documentNumberAnonymizationSettings.suffixDigitsVisible}:void 0});function buildSessionSettings(options={},defaultSessionSettings){var _a,_b,_c,_d;if(options)options=Object.fromEntries(Object.entries(options).filter((([_,value])=>value!==void 0)));const customDocumentRules=((_b=(_a=options==null?void 0:options.scanningSettings)==null?void 0:_a.customDocumentRules)==null?void 0:_b.map(normalizeDocumentRule))??[];const customDocumentAnonymizationSettings=((_d=(_c=options==null?void 0:options.scanningSettings)==null?void 0:_c.customDocumentAnonymizationSettings)==null?void 0:_d.map(normalizeDocumentAnonymizationSettings))??[];const scanningSettings={...options==null?void 0:options.scanningSettings,customDocumentRules:customDocumentRules,customDocumentAnonymizationSettings:customDocumentAnonymizationSettings};const sessionSettings=merge(defaultSessionSettings,{...options,scanningSettings:scanningSettings});return sessionSettings}class ProxyUrlValidationError extends Error{constructor(message,url){super(`Proxy URL validation failed for "${url}": ${message}`);this.url=url;this.name="ProxyUrlValidationError"}}class LicenseError extends Error{constructor(message,code){super(message);__publicField(this,"code");this.name="LicenseError";this.code=code}}class CentaurusWorker{constructor(){__privateAdd(this,_CentaurusWorker_instances);__privateAdd(this,_wasmModule);__privateAdd(this,_defaultSessionSettings);__publicField(this,"progressStatusCallback");__privateAdd(this,_showDemoOverlay,true);__privateAdd(this,_showProductionOverlay,true);__privateAdd(this,_proxyUrls)}async[atob("aW5pdEJsaW5rSWQ=")](settings,defaultSessionSettings,progressCallback){var _a;const resourcesPath=new URL("resources/",settings.resourcesLocation).toString();__privateSet(this,_defaultSessionSettings,defaultSessionSettings);this.progressStatusCallback=progressCallback;await __privateMethod(this,_CentaurusWorker_instances,loadWasm_fn).call(this,{resourceUrl:resourcesPath,variant:settings.wasmVariant,initialMemory:settings.initialMemory,useLightweightBuild:settings.useLightweightBuild});if(!__privateGet(this,_wasmModule))throw new Error("Wasm module not loaded");const licenceUnlockResult=__privateGet(this,_wasmModule).initializeWithLicenseKey(settings.licenseKey,settings.userId,false);if(licenceUnlockResult.licenseError)throw new LicenseError("License unlock error: "+licenceUnlockResult.licenseError,"LICENSE_ERROR");if(settings[atob("bWljcm9ibGlua1Byb3h5VXJs")])__privateMethod(this,_CentaurusWorker_instances,configureProxyUrls_fn).call(this,settings[atob("bWljcm9ibGlua1Byb3h5VXJs")],licenceUnlockResult);if(licenceUnlockResult.unlockResult==="requires-server-permission"){const baltazarUrl=(_a=__privateGet(this,_proxyUrls))==null?void 0:_a.baltazar;const serverPermissionResponse=baltazarUrl&&licenceUnlockResult.allowBaltazarProxy?await obtainNewServerPermission(licenceUnlockResult,baltazarUrl):await obtainNewServerPermission(licenceUnlockResult);const serverPermissionResult=__privateGet(this,_wasmModule).submitServerPermission(JSON.stringify(serverPermissionResponse));if(serverPermissionResult.error)throw new Error("Server unlock error: "+serverPermissionResult.error)}__privateSet(this,_showDemoOverlay,licenceUnlockResult.showDemoOverlay);__privateSet(this,_showProductionOverlay,licenceUnlockResult.showProductionOverlay)}[atob("Y3JlYXRlQmxpbmtJZFNjYW5uaW5nU2Vzc2lvbg==")](options){if(!__privateGet(this,_wasmModule))throw new Error("Wasm module not loaded");const sessionSettings=buildSessionSettings(options,__privateGet(this,_defaultSessionSettings));const session=__privateGet(this,_wasmModule)[atob("Y3JlYXRlQmxpbmtJZFNjYW5uaW5nU2Vzc2lvbg==")](sessionSettings);const proxySession=this.createProxySession(session,sessionSettings);return proxySession}createProxySession(session,sessionSettings){const customSession={getResult:()=>session.getResult(),process:image=>{const processResult=session.process(image);if("error"in processResult)throw new Error(`Error processing frame: ${processResult.error}`);const transferPackage=transfer({...processResult,arrayBuffer:image.data.buffer},[image.data.buffer]);return transferPackage},getSettings:()=>sessionSettings,reset:()=>session.reset(),delete:()=>session.delete(),deleteLater:()=>session.deleteLater(),isDeleted:()=>session.isDeleted(),isAliasOf:other=>session.isAliasOf(other),showDemoOverlay:()=>__privateGet(this,_showDemoOverlay),showProductionOverlay:()=>__privateGet(this,_showProductionOverlay)};return proxy(customSession)}[finalizer](){}terminate(){self.close()}ping(){return 1}}_wasmModule=new WeakMap;_defaultSessionSettings=new WeakMap;_showDemoOverlay=new WeakMap;_showProductionOverlay=new WeakMap;_proxyUrls=new WeakMap;_CentaurusWorker_instances=new WeakSet;loadWasm_fn=async function({resourceUrl:resourceUrl,variant:variant,useLightweightBuild:useLightweightBuild,initialMemory:initialMemory}){if(__privateGet(this,_wasmModule)){console.log("Wasm already loaded");return}const wasmVariant=variant??await detectWasmFeatures();const featureVariant=useLightweightBuild?"lightweight":"full";const MODULE_NAME="Centaurus";const variantUrl=buildResourcePath(resourceUrl,featureVariant,wasmVariant);const workerUrl=buildResourcePath(variantUrl,`${MODULE_NAME}.js`);const wasmUrl=buildResourcePath(variantUrl,`${MODULE_NAME}.wasm`);const dataUrl=buildResourcePath(variantUrl,`${MODULE_NAME}.data`);const crossOriginWorkerUrl=await getCrossOriginWorkerURL(workerUrl);const imported=await import(crossOriginWorkerUrl);const createModule=imported.default;if(!initialMemory)initialMemory=isIOS()?700:200;const wasmMemory=new WebAssembly.Memory({initial:mbToWasmPages(initialMemory),maximum:mbToWasmPages(2048),shared:wasmVariant==="advanced-threads"});let wasmProgress;let dataProgress;let lastProgressUpdate=0;const progressUpdateInterval=32;const throttledCombinedProgress=()=>{if(!this.progressStatusCallback)return;if(!wasmProgress||!dataProgress)return;const totalLoaded=wasmProgress.loaded+dataProgress.loaded;const totalLength=wasmProgress.contentLength+dataProgress.contentLength;const combinedPercent=Math.min(Math.round(totalLoaded/totalLength*100),100);const combinedProgress={loaded:totalLoaded,contentLength:totalLength,progress:combinedPercent};const currentTime=performance.now();if(currentTime-lastProgressUpdate<progressUpdateInterval)return;lastProgressUpdate=currentTime;this.progressStatusCallback(combinedProgress)};const wasmProgressCallback=progress=>{wasmProgress=progress;void throttledCombinedProgress()};const dataProgressCallback=progress=>{dataProgress=progress;void throttledCombinedProgress()};const[preloadedWasm,preloadedData]=await Promise.all([downloadArrayBuffer(wasmUrl,wasmProgressCallback),downloadArrayBuffer(dataUrl,dataProgressCallback)]);if(this.progressStatusCallback&&wasmProgress&&dataProgress){const totalLength=wasmProgress.contentLength+dataProgress.contentLength;this.progressStatusCallback({loaded:totalLength,contentLength:totalLength,progress:100})}__privateSet(this,_wasmModule,await createModule({locateFile:path=>`${variantUrl}/${wasmVariant}/${path}`,mainScriptUrlOrBlob:crossOriginWorkerUrl,wasmBinary:preloadedWasm,getPreloadedPackage(){return preloadedData},wasmMemory:wasmMemory,noExitRuntime:true}));if(!__privateGet(this,_wasmModule))throw new Error("Failed to load Wasm module")};configureProxyUrls_fn=function(proxyUrl,licenceUnlockResult){if(!proxyUrl){console.debug("No proxy URL configured, using default Centaurus servers");return}__privateMethod(this,_CentaurusWorker_instances,validateProxyPermissions_fn).call(this,licenceUnlockResult,proxyUrl);try{__privateSet(this,_proxyUrls,__privateMethod(this,_CentaurusWorker_instances,sanitizeProxyUrls_fn).call(this,proxyUrl));if(licenceUnlockResult.allowPingProxy)__privateGet(this,_wasmModule).setPingProxyUrl(__privateGet(this,_proxyUrls).ping);console.debug("Proxy URLs configured successfully:",{ping:__privateGet(this,_proxyUrls).ping,baltazar:__privateGet(this,_proxyUrls).baltazar})}catch(error){const enhancedError=error instanceof ProxyUrlValidationError?new Error(`${error.message}\n\nTroubleshooting:\n- Ensure the URL is accessible\n- Check HTTPS requirements\n- Verify proxy server implementation`):error;throw enhancedError}};validateProxyPermissions_fn=function(licenceUnlockResult,proxyUrl){if(!licenceUnlockResult.allowPingProxy&&!licenceUnlockResult.allowBaltazarProxy)throw new Error(`Proxy URL "${proxyUrl}" was provided, but your license does not permit proxy usage.\nLicense permissions: pingProxy=${licenceUnlockResult.allowPingProxy}, baltazarProxy=${licenceUnlockResult.allowBaltazarProxy}\nCheck your license.`);else if(!licenceUnlockResult.hasPing&&licenceUnlockResult.unlockResult!=="requires-server-permission")throw new Error(`Centaurus proxy URL is set but cannot be used because ping and online license check are disabled in your license.\nCheck your license.`)};sanitizeProxyUrls_fn=function(baseUrl){let parsedUrl;try{parsedUrl=new URL(baseUrl)}catch(error){throw new ProxyUrlValidationError(`Failed to create URL instance for provided Centaurus proxy URL "${baseUrl}". Expected format: https://your-proxy.com or https://your-proxy.com/`,baseUrl)}if(parsedUrl.protocol!=="https:")throw new ProxyUrlValidationError(`Proxy URL validation failed for "${baseUrl}": HTTPS protocol must be used. Expected format: https://your-proxy.com or https://your-proxy.com/`,baseUrl);const baseUrlStr=parsedUrl.origin;const baltazarUrl=__privateMethod(this,_CentaurusWorker_instances,buildServiceUrl_fn).call(this,baseUrlStr,"/api/v2/status/check");return{ping:baseUrlStr,baltazar:baltazarUrl}};buildServiceUrl_fn=function(baseUrl,servicePath){try{const url=new URL(servicePath,baseUrl);return url.toString()}catch(error){throw new ProxyUrlValidationError(`Failed to build service URL for path "${servicePath}"`,baseUrl)}};const centaurusWorker=new CentaurusWorker;expose(centaurusWorker);