@monitordog/detector 1.0.9 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{inference-worker-ekAaVxft.js → inference-worker-BTPzhc2n.js} +2 -2
- package/dist/assets/sdk/detector-320.onnx.enc +0 -0
- package/dist/assets/sdk/detector-416.onnx.enc +0 -0
- package/dist/assets/sdk/detector-640.onnx.enc +0 -0
- package/dist/index.d.ts +1 -0
- package/dist/monitordog-detector.js +120 -106
- package/dist/monitordog-detector.umd.cjs +1 -1
- package/dist/service/container.d.ts +3 -0
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
5
5
|
* Licensed under the MIT License.
|
|
6
6
|
*/
|
|
7
|
-
var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),a=(e,t)=>()=>(e&&(t=e(e=0)),t),o=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})},s=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))!r.call(i,c)&&c!==o&&e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},c=t=>s(e({},`__esModule`,{value:!0}),t),l,u,d,f,p,m=a(()=>{"use strict";l=new Map,u=[],d=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=l.get(e);if(r===void 0)l.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=u.indexOf(e);t!==-1&&u.splice(t,1);for(let t=0;t<u.length;t++)if(l.get(u[t]).priority<=n){u.splice(t,0,e);return}u.push(e)}return}throw TypeError(`not a valid backend`)},f=async e=>{let t=l.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},p=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?u:n,i,a=[],o=new Set;for(let e of r){let t=await f(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),h=a(()=>{"use strict";m()}),g,_=a(()=>{"use strict";g=`1.24.3`}),v,y,b=a(()=>{"use strict";_(),v=`warning`,y={wasm:{},webgl:{},webgpu:{},versions:{common:g},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);v=e}},get logLevel(){return v}},Object.defineProperty(y,"logLevel",{enumerable:!0})}),x,S=a(()=>{"use strict";b(),x=y}),ee,te,ne=a(()=>{"use strict";ee=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},te=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),C,re,ie,ae,oe,se,ce=a(()=>{"use strict";he(),C=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new E(`float32`,u,[1,4,n,r]):new E(`float32`,u,[1,3,n,r])},re=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,C(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(C(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return C(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},ie=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new E({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ae=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new E({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},oe=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new E({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},se=(e,t,n)=>new E({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),w,T,le,ue,de=a(()=>{"use strict";w=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),T=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),le=!1,ue=()=>{if(!le){le=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(w.set(`int64`,BigInt64Array),T.set(BigInt64Array,`int64`)),t&&(w.set(`uint64`,BigUint64Array),T.set(BigUint64Array,`uint64`)),r?(w.set(`float16`,n),T.set(n,`float16`)):w.set(`float16`,Uint16Array)}}}),fe,pe,me=a(()=>{"use strict";he(),fe=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},pe=(e,t)=>{switch(e.location){case`cpu`:return new E(e.type,e.data,t);case`cpu-pinned`:return new E({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new E({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new E({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new E({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),E,he=a(()=>{"use strict";ne(),ce(),de(),me(),E=class{constructor(e,t,n){ue();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=w.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=w.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=T.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=fe(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return re(e,t)}static fromTexture(e,t){return ie(e,t)}static fromGpuBuffer(e,t){return ae(e,t)}static fromMLTensor(e,t){return oe(e,t)}static fromPinnedBuffer(e,t,n){return se(e,t,n)}toDataURL(e){return ee(this,e)}toImageData(e){return te(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return pe(this,e)}}}),D,ge=a(()=>{"use strict";he(),D=E}),_e,ve,O,k,A,j,ye=a(()=>{"use strict";b(),_e=(e,t)=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.timeStamp(`${e}::ORT::${t}`)},ve=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),_e(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},O=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||ve(`BEGIN`,e)},k=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||ve(`END`,e)},A=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.time(`ORT::${e}`)},j=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.timeEnd(`ORT::${e}`)}}),be,xe=a(()=>{"use strict";m(),ge(),ye(),be=class e{constructor(e){this.handler=e}async run(e,t,n){O(),A(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof D||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof D)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof D)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof D?s[e]=t:s[e]=new D(t.type,t.data,t.dims)}return j(`InferenceSession.run`),k(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){O(),A(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await p(o),l=await s.createInferenceSessionHandler(a,c);return j(`InferenceSession.create`),k(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Se,Ce=a(()=>{"use strict";xe(),Se=be}),we=a(()=>{"use strict";}),Te=a(()=>{"use strict";}),Ee=a(()=>{"use strict";}),De=a(()=>{"use strict";});o({},{InferenceSession:()=>Se,TRACE:()=>_e,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>j,TRACE_FUNC_BEGIN:()=>O,TRACE_FUNC_END:()=>k,Tensor:()=>D,env:()=>x,registerBackend:()=>d});var M=a(()=>{"use strict";h(),S(),Ce(),ge(),we(),Te(),ye(),Ee(),De()}),Oe=a(()=>{"use strict";}),ke={};o(ke,{default:()=>Me});var Ae,je,Me,Ne=a(()=>{"use strict";Mt(),I(),qe(),Ae=`ort-wasm-proxy-worker`,je=globalThis.self?.name===Ae,je&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:et(n.wasm).then(()=>{xt(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;St(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Tt(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;Et(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Dt(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;kt(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},jt([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:At(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),Me=je?null:e=>new Worker(e??N,{type:`module`,name:Ae})}),Pe,Fe,Ie,N,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe=a(()=>{"use strict";Oe(),Pe=typeof location>`u`?void 0:location.origin,Fe=self.location.href>`file:`&&self.location.href<`file;`,Ie=()=>Fe?new URL(new URL(`ort.wasm.min.mjs`,self.location.href).href,Pe).href:self.location.href,N=Ie(),Le=()=>{if(N&&!N.startsWith(`blob:`))return N.substring(0,N.lastIndexOf(`/`)+1)},Re=(e,t)=>{try{let n=t??N;return(n?new URL(e,n):new URL(e)).origin===Pe}catch{return!1}},ze=(e,t)=>{let n=t??N;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Be=(e,t)=>`${t??`./`}${e}`,Ve=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},He=async e=>(await import(e)).default,Ue=(Ne(),c(ke)).default,We=async()=>{if(!N)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Re(N))return[void 0,Ue()];let e=await Ve(N);return[e,Ue(e)]},Ge=void 0,Ke=async(e,t,n,r)=>{let i=Ge&&!(e||t);if(i)if(N)i=Re(N)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,Ge];{let r=`ort-wasm-simd-threaded.mjs`,i=e??ze(r,t),a=n&&i&&!Re(i,t),o=a?await Ve(i):i??Be(r,t);return[a?o:void 0,await He(o)]}}}),Je,Ye,P,Xe,Ze,Qe,$e,et,F,I=a(()=>{"use strict";qe(),Ye=!1,P=!1,Xe=!1,Ze=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(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]))}catch{return!1}},Qe=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},$e=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},et=async e=>{if(Ye)return Promise.resolve();if(P)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Xe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);P=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!$e())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!Qe())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Ze();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Ke(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Le();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{P=!1,Ye=!0,Je=t,e(),d&&URL.revokeObjectURL(d)},e=>{P=!1,Xe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Ye&&Je)return Je;throw Error(`WebAssembly is not initialized yet.`)}}),L,tt,R,nt=a(()=>{"use strict";I(),L=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},tt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)tt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},R=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),rt,it=a(()=>{"use strict";I(),nt(),rt=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=L(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&R(`Can't create run options.`),e?.extra!==void 0&&tt(e.extra,``,new WeakSet,(e,i)=>{let a=L(e,r),o=L(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&R(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),at,ot,st,z,ct,lt,ut=a(()=>{"use strict";I(),nt(),at=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},ot=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},st=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},z=(e,t,n,r)=>{let i=L(t,r),a=L(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&R(`Can't set a session config entry: ${t} - ${n}.`)},ct=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof t!=`string`){let r=t?.deviceType;r&&z(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);z(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=L(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&R(`Can't append execution provider: ${r}.`)}},lt=async e=>{let t=F(),n=0,r=[],i=e||{};st(i);try{let e=at(i.graphOptimizationLevel??`all`),a=ot(i.executionMode??`sequential`),o=typeof i.logId==`string`?L(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?L(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&R(`Can't create session options.`),i.executionProviders&&await ct(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);z(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=L(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&R(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&tt(i.extra,``,new WeakSet,(e,t)=>{z(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&R(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),B,dt,V,ft,pt,mt,ht,gt,_t=a(()=>{"use strict";B=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},dt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},V=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ft=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},pt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},mt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,ht=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,gt=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),vt,yt=a(()=>{"use strict";Oe(),vt=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),bt,xt,St,H,Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt=a(()=>{"use strict";M(),it(),ut(),_t(),I(),nt(),yt(),bt=(e,t)=>{F()._OrtInit(e,t)!==0&&R(`Can't initialize onnxruntime.`)},xt=async e=>{bt(e.wasm.numThreads,pt(e.logLevel))},St=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`)},H=new Map,Ct=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&R(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},wt=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&R(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Tt=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Et=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Tt(e);let a=0,o=0,s=[],c=[],l=[];try{if([o,s]=await lt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(vt(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&R(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,u]=Ct(a),d=!!t?.enableGraphCapture,f=[],p=[],m=[],h=[];for(let t=0;t<e;t++){let[e,n,r]=wt(a,t);e===0&&R(`Can't get an input name.`),c.push(e);let o=i.UTF8ToString(e);f.push(o),m.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:dt(n),shape:r})}for(let t=0;t<u;t++){let[n,r,o]=wt(a,t+e);n===0&&R(`Can't get an output name.`),l.push(n);let s=i.UTF8ToString(n);p.push(s),h.push(r===0?{name:s,isTensor:!1}:{name:s,isTensor:!0,type:dt(r),shape:o})}return H.set(a,[a,c,l,null,d,!1]),[a,f,p,m,h]}catch(e){throw c.forEach(e=>i._OrtFree(e)),l.forEach(e=>i._OrtFree(e)),a!==0&&i._OrtReleaseSession(a)!==0&&R(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&R(`Can't release session options.`),s.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Dt=e=>{let t=F(),n=H.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&R(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&R(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&R(`Can't release session.`),H.delete(e)},Ot=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=V(B(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=V(B(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,B(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,L(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=B(l);m=V(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(B(l),p,m,g,u.length,gt(f));e===0&&R(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},kt=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=H.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];c[5];let m=t.length,h=r.length,g=0,_=[],v=[],y=[],b=[],x=[],S=o.stackSave(),ee=o.stackAlloc(m*s),te=o.stackAlloc(m*s),ne=o.stackAlloc(h*s),C=o.stackAlloc(h*s);try{[g,_]=rt(a),A(`wasm prepareInputOutputTensor`);for(let r=0;r<m;r++)await Ot(n[r],v,b,e,u[t[r]],t[r],p);for(let t=0;t<h;t++)await Ot(i[t],y,b,e,d[r[t]],m+r[t],p);j(`wasm prepareInputOutputTensor`);for(let e=0;e<m;e++)o.setValue(ee+e*s,v[e],`*`),o.setValue(te+e*s,u[t[e]],`*`);for(let e=0;e<h;e++)o.setValue(ne+e*s,y[e],`*`),o.setValue(C+e*s,d[r[e]],`*`);o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=await o._OrtRun(l,te,ee,m,C,h,ne,g),c!==0&&R(`failed to call OrtRun().`);let S=[],re=[];A(`wasm ProcessOutputTensor`);for(let t=0;t<h;t++){let n=Number(o.getValue(ne+t*s,`*`));if(n===y[t]||x.includes(y[t])){S.push(i[t]),n!==y[t]&&o._OrtReleaseTensor(n)!==0&&R(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&R(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&R(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=dt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}S.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=V(a,g);if(r===void 0||!mt(u))throw Error(`Unsupported data type: ${u}`);l=!0,S.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&R(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(V(a,g)===void 0||!ht(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,S.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=S.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(ft(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&R(`Can't clear bound outputs.`),H.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))S[e][2]=t;return j(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),v.forEach(e=>o._OrtReleaseTensor(e)),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._free(e)),g!==0&&o._OrtReleaseRunOptions(g),_.forEach(e=>o._free(e))}},At=e=>{let t=F(),n=H.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&R(`Can't get an profile file name.`),t._OrtFree(i)},jt=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),U,W,G,K,q,Nt,Pt,J,Y,X,Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut=a(()=>{"use strict";M(),Mt(),I(),qe(),U=()=>!!x.wasm.proxy&&typeof document<`u`,G=!1,K=!1,q=!1,J=new Map,Y=(e,t)=>{let n=J.get(e);n?n.push(t):J.set(e,[t])},X=()=>{if(G||!K||q||!W)throw Error(`worker not ready`)},Ft=e=>{switch(e.data.type){case`init-wasm`:G=!1,e.data.err?(q=!0,Pt[1](e.data.err)):(K=!0,Pt[0]()),Nt&&=(URL.revokeObjectURL(Nt),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=J.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},It=async()=>{if(!K){if(G)throw Error(`multiple calls to 'initWasm()' detected.`);if(q)throw Error(`previous call to 'initWasm()' failed.`);if(G=!0,U())return new Promise((e,t)=>{W?.terminate(),We().then(([n,r])=>{try{W=r,W.onerror=e=>t(e),W.onmessage=Ft,Pt=[e,t];let i={type:`init-wasm`,in:x};if(!i.in.wasm.wasmPaths&&n){let e=Le();e&&(i.in.wasm.wasmPaths=e)}W.postMessage(i),Nt=n}catch(e){t(e)}},t)});try{await et(x.wasm),await xt(x),K=!0}catch(e){throw q=!0,e}finally{G=!1}}},Lt=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:x}};W.postMessage(r)});await St(x,e)},Rt=async e=>U()?(X(),new Promise((t,n)=>{Y(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};W.postMessage(r,[e.buffer])})):Tt(e),zt=async(e,t)=>{if(U()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return X(),new Promise((n,r)=>{Y(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),W.postMessage(i,a)})}else return Et(e,t)},Bt=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`release`,[t,n]);let r={type:`release`,in:e};W.postMessage(r)});Dt(e)},Vt=async(e,t,n,r,i,a)=>{if(U()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return X(),new Promise((i,o)=>{Y(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};W.postMessage(c,jt(s))})}else return kt(e,t,n,r,i,a)},Ht=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};W.postMessage(r)});At(e)}}),Wt,Gt,Kt,qt=a(()=>{"use strict";M(),Ut(),_t(),Oe(),yt(),Wt=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Gt=e=>{switch(e[3]){case`cpu`:return new D(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!mt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return D.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!ht(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return D.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Kt=class{async fetchModelAndCopyToWasmMemory(e){return Rt(await vt(e))}async loadModel(e,t){O();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await zt(n,t),k()}async dispose(){return Bt(this.sessionId)}async run(e,t,n){O();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Wt(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Wt(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Vt(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Gt(l[e]);return k(),u}startProfiling(){}endProfiling(){Ht(this.sessionId)}}}),Jt={};o(Jt,{OnnxruntimeWebAssemblyBackend:()=>Xt,initializeFlags:()=>Yt,wasmBackend:()=>Zt});var Yt,Xt,Zt,Qt=a(()=>{"use strict";M(),Ut(),qt(),Yt=()=>{(typeof x.wasm.initTimeout!=`number`||x.wasm.initTimeout<0)&&(x.wasm.initTimeout=0);let e=x.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),x.wasm.simd=!1),typeof x.wasm.proxy!=`boolean`&&(x.wasm.proxy=!1),typeof x.wasm.trace!=`boolean`&&(x.wasm.trace=!1),typeof x.wasm.numThreads!=`number`||!Number.isInteger(x.wasm.numThreads)||x.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)x.wasm.numThreads=1;else{let e=typeof navigator>`u`?i(`node:os`).cpus().length:navigator.hardwareConcurrency;x.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Xt=class{async init(e){Yt(),await It(),await Lt(e)}async createInferenceSessionHandler(e,t){let n=new Kt;return await n.loadModel(e,t),n}},Zt=new Xt});M(),M(),M();var $t=`1.24.3`;{let e=(Qt(),c(Jt)).wasmBackend;d(`cpu`,e,10),d(`wasm`,e,10)}Object.defineProperty(x.versions,"web",{value:$t,enumerable:!0});function en(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw Error(`MonitorDog runtimeAssetBaseUrl must be a non-empty string when provided.`);let n=t.replace(/\/+$/,``);return n.length===0?`/`:n}function tn(e,t){let n=en(e),r=t.replace(/^\/+/,``);if(n===void 0)throw Error(`MonitorDog runtimeAssetBaseUrl must be provided to resolve runtime assets.`);return n===`/`?`/${r}`:`${n}/${r}`}function nn(e,t,n){return t===void 0?n:tn(t,`sdk/${e}`)}function rn(e,t){return e===void 0?t:tn(e,`ort/`)}let Z={environment:`prod`,bundleId:`prod-20260704T092019-46205c8d`,assetVersion:`0.0.1`,createdAt:`2026-07-04T09:20:19.192724+00:00`,assets:{detector:{320:{file:`assets/detector-320.onnx.enc`,version:`0.0.1`,encryptedSha256:`7c5c5945dc47c0aa35e9390ee5b08db1353d5077340f73f25f9b5ba5e96a4cad`},416:{file:`assets/detector-416.onnx.enc`,version:`0.0.1`,encryptedSha256:`ca95cd3eada515fbfc95705c7ed0b83902280ec73a9fa714da16fee27421f3bf`},640:{file:`assets/detector-640.onnx.enc`,version:`0.0.1`,encryptedSha256:`06f75db0ee622972fb3c1c240d7e7b0e0d95dabdd1982dbbd5dfd6a3f3474aef`}}}};async function an(e){bn();let t=on(e.inputSize),n=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`decrypt`]),r=pn(await dn(n.publicKey)),[i,a]=await Promise.all([cn(t.file,e.runtimeAssetBaseUrl),sn({apiBaseUrl:e.apiBaseUrl,accessToken:e.accessToken,inputSize:e.inputSize,assetEntry:t},r)]),o=new Uint8Array(await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,yn(mn(a.encrypted_dek)))),s=hn(o);try{return await un(i,s)}finally{i.fill(0),o.fill(0),s.fill(0)}}function on(e){if(e!==320&&e!==416&&e!==640)throw Error(`MonitorDog detector input size must be 320, 416, or 640.`);let t=Z.assets.detector[String(e)];if(!Z.environment||!Z.bundleId||!t?.file)throw Error(`MonitorDog SDK encrypted asset manifest is not configured. Run package:dev or package:prod before building a release package.`);if(!t.version||!t.encryptedSha256)throw Error(`MonitorDog SDK detector ${e} asset manifest is incomplete.`);return t}async function sn(e,t){let n=new URLSearchParams({environment:Z.environment,bundle_id:Z.bundleId,asset:`detector`,input_size:String(e.inputSize),version:e.assetEntry.version,encrypted_sha256:e.assetEntry.encryptedSha256,public_key:t}),r=await fetch(`${e.apiBaseUrl}/auth/sdk-asset-key?${n}`,{method:`GET`,headers:{accept:`application/json`,authorization:`Bearer ${e.accessToken}`,"Device-Access-Token":e.accessToken}});if(!r.ok)throw Error(`MonitorDog SDK model key request failed: ${r.status}`);let i=await r.json();if(!i.encrypted_dek)throw Error(`MonitorDog SDK model key response is incomplete.`);return{encrypted_dek:i.encrypted_dek,asset:i.asset??`detector`,input_size:i.input_size??e.inputSize,version:i.version??e.assetEntry.version}}async function cn(e,t){let n=await fetch(ln(e,t));if(!n.ok)throw Error(`Failed to download packaged MonitorDog model: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}function ln(e,t){let n=e.replace(/\\/g,`/`).split(`/`).pop();if(!n||!n.endsWith(`.onnx.enc`))throw Error(`Invalid MonitorDog SDK asset file path: ${e}`);return nn(n,t,new URL(`./sdk/${n}`,self.location.href).href)}async function un(e,t){if(e.byteLength<=12)throw Error(`MonitorDog encrypted model data is too short.`);let n=await crypto.subtle.importKey(`raw`,yn(t),{name:`AES-GCM`},!1,[`decrypt`]),r=e.slice(0,12),i=e.slice(12);return new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:yn(r)},n,yn(i)))}async function dn(e){let t=await crypto.subtle.exportKey(`spki`,e);return[`-----BEGIN PUBLIC KEY-----`,...fn(new Uint8Array(t)).match(/.{1,64}/g)??[],`-----END PUBLIC KEY-----`].join(`
|
|
8
|
-
`)}function fn(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function pn(e){return fn(new TextEncoder().encode(e))}function mn(e){let t=e.replace(/-----BEGIN [^-]+-----/g,``).replace(/-----END [^-]+-----/g,``).replace(/\s/g,``).replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t+`=`.repeat(n),i=atob(r),a=new Uint8Array(i.length);for(let e=0;e<i.length;e+=1)a[e]=i.charCodeAt(e);return a}function hn(e){if(vn(e.byteLength))return new Uint8Array(e);let t=new TextDecoder().decode(e).trim(),n=gn(t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t);if(n&&vn(n.byteLength))return n;throw Error(`MonitorDog SDK model DEK must decode to a 128-bit or 256-bit AES key. Received ${e.byteLength} bytes.`)}function gn(e){if(/^[0-9a-f]+$/i.test(e)&&e.length%2==0)return _n(e);try{return mn(e)}catch{return}}function _n(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function vn(e){return e===16||e===32}function yn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function bn(){if(!globalThis.crypto?.subtle)throw Error(`MonitorDog SDK model decryption requires Web Crypto API.`)}let xn=new Set([0,1]),Sn=[`phone_back`,`phone_front`,`phone_back_cam`,`cup`,`hand`,`face`];function Cn(e){if(e.output.type!==`float32`)throw Error(`Detector postprocessing requires float32 output.`);if(!(e.output.data instanceof Float32Array))throw Error(`Detector postprocessing expected Float32Array output.`);let t=e.output.data,n=[...e.output.dims];if(n.length!==3||n[0]!==1||n[1]<=0||n[2]<=0)throw Error(`Detector postprocessing received an unexpected output shape.`);let r=n[1]===10,i=r?n[2]:n[1];if((r?n[1]:n[2])<10||i===0)throw Error(`Detector postprocessing received an incomplete output tensor.`);let a=[];for(let n=0;n<i;n+=1){let o=Q(t,r,n,0,i),s=Q(t,r,n,1,i),c=Q(t,r,n,2,i),l=Q(t,r,n,3,i),u=0,d=0;for(let e=0;e<6;e+=1){let a=Q(t,r,n,e+4,i);a>d&&(d=a,u=e)}let f=u===5?e.faceConfidenceThreshold:e.confidenceThreshold,p={classId:u,score:d,cx:o,cy:s,width:c,height:l};d>=f&&wn(p,e.metadata)&&a.push(p)}let o=Tn(a,e.iouThreshold,e.maxDetections),s=[],c=[],l=[];for(let t of o){let n=En(t,e.metadata);xn.has(t.classId)?s.push(n):t.classId===4?c.push(n):t.classId===5&&l.push(n)}let u=s.filter(
|
|
7
|
+
var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),a=(e,t)=>()=>(e&&(t=e(e=0)),t),o=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})},s=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))!r.call(i,c)&&c!==o&&e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},c=t=>s(e({},`__esModule`,{value:!0}),t),l,u,d,f,p,m=a(()=>{"use strict";l=new Map,u=[],d=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=l.get(e);if(r===void 0)l.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=u.indexOf(e);t!==-1&&u.splice(t,1);for(let t=0;t<u.length;t++)if(l.get(u[t]).priority<=n){u.splice(t,0,e);return}u.push(e)}return}throw TypeError(`not a valid backend`)},f=async e=>{let t=l.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},p=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?u:n,i,a=[],o=new Set;for(let e of r){let t=await f(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),h=a(()=>{"use strict";m()}),g,_=a(()=>{"use strict";g=`1.24.3`}),v,y,b=a(()=>{"use strict";_(),v=`warning`,y={wasm:{},webgl:{},webgpu:{},versions:{common:g},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);v=e}},get logLevel(){return v}},Object.defineProperty(y,"logLevel",{enumerable:!0})}),x,S=a(()=>{"use strict";b(),x=y}),ee,te,ne=a(()=>{"use strict";ee=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}else throw Error(`Can not access image data`)},te=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),C,re,ie,ae,oe,se,ce=a(()=>{"use strict";he(),C=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new E(`float32`,u,[1,4,n,r]):new E(`float32`,u,[1,3,n,r])},re=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,C(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(C(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return C(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},ie=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new E({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ae=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new E({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},oe=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new E({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},se=(e,t,n)=>new E({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),w,T,le,ue,de=a(()=>{"use strict";w=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),T=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),le=!1,ue=()=>{if(!le){le=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(w.set(`int64`,BigInt64Array),T.set(BigInt64Array,`int64`)),t&&(w.set(`uint64`,BigUint64Array),T.set(BigUint64Array,`uint64`)),r?(w.set(`float16`,n),T.set(n,`float16`)):w.set(`float16`,Uint16Array)}}}),fe,pe,me=a(()=>{"use strict";he(),fe=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},pe=(e,t)=>{switch(e.location){case`cpu`:return new E(e.type,e.data,t);case`cpu-pinned`:return new E({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new E({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new E({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new E({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),E,he=a(()=>{"use strict";ne(),ce(),de(),me(),E=class{constructor(e,t,n){ue();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=w.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=w.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=T.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=fe(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return re(e,t)}static fromTexture(e,t){return ie(e,t)}static fromGpuBuffer(e,t){return ae(e,t)}static fromMLTensor(e,t){return oe(e,t)}static fromPinnedBuffer(e,t,n){return se(e,t,n)}toDataURL(e){return ee(this,e)}toImageData(e){return te(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return pe(this,e)}}}),D,ge=a(()=>{"use strict";he(),D=E}),_e,ve,O,k,A,j,ye=a(()=>{"use strict";b(),_e=(e,t)=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.timeStamp(`${e}::ORT::${t}`)},ve=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),_e(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},O=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||ve(`BEGIN`,e)},k=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||ve(`END`,e)},A=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.time(`ORT::${e}`)},j=e=>{(typeof y.trace>`u`?!y.wasm.trace:!y.trace)||console.timeEnd(`ORT::${e}`)}}),be,xe=a(()=>{"use strict";m(),ge(),ye(),be=class e{constructor(e){this.handler=e}async run(e,t,n){O(),A(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof D||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof D)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof D)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof D?s[e]=t:s[e]=new D(t.type,t.data,t.dims)}return j(`InferenceSession.run`),k(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){O(),A(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await p(o),l=await s.createInferenceSessionHandler(a,c);return j(`InferenceSession.create`),k(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Se,Ce=a(()=>{"use strict";xe(),Se=be}),we=a(()=>{"use strict";}),Te=a(()=>{"use strict";}),Ee=a(()=>{"use strict";}),De=a(()=>{"use strict";});o({},{InferenceSession:()=>Se,TRACE:()=>_e,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>j,TRACE_FUNC_BEGIN:()=>O,TRACE_FUNC_END:()=>k,Tensor:()=>D,env:()=>x,registerBackend:()=>d});var M=a(()=>{"use strict";h(),S(),Ce(),ge(),we(),Te(),ye(),Ee(),De()}),Oe=a(()=>{"use strict";}),ke={};o(ke,{default:()=>Me});var Ae,je,Me,Ne=a(()=>{"use strict";Mt(),I(),qe(),Ae=`ort-wasm-proxy-worker`,je=globalThis.self?.name===Ae,je&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:et(n.wasm).then(()=>{xt(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;St(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Tt(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;Et(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Dt(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;kt(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},jt([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:At(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),Me=je?null:e=>new Worker(e??N,{type:`module`,name:Ae})}),Pe,Fe,Ie,N,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe=a(()=>{"use strict";Oe(),Pe=typeof location>`u`?void 0:location.origin,Fe=self.location.href>`file:`&&self.location.href<`file;`,Ie=()=>Fe?new URL(new URL(`ort.wasm.min.mjs`,self.location.href).href,Pe).href:self.location.href,N=Ie(),Le=()=>{if(N&&!N.startsWith(`blob:`))return N.substring(0,N.lastIndexOf(`/`)+1)},Re=(e,t)=>{try{let n=t??N;return(n?new URL(e,n):new URL(e)).origin===Pe}catch{return!1}},ze=(e,t)=>{let n=t??N;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Be=(e,t)=>`${t??`./`}${e}`,Ve=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},He=async e=>(await import(e)).default,Ue=(Ne(),c(ke)).default,We=async()=>{if(!N)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Re(N))return[void 0,Ue()];let e=await Ve(N);return[e,Ue(e)]},Ge=void 0,Ke=async(e,t,n,r)=>{let i=Ge&&!(e||t);if(i)if(N)i=Re(N)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,Ge];{let r=`ort-wasm-simd-threaded.mjs`,i=e??ze(r,t),a=n&&i&&!Re(i,t),o=a?await Ve(i):i??Be(r,t);return[a?o:void 0,await He(o)]}}}),Je,Ye,P,Xe,Ze,Qe,$e,et,F,I=a(()=>{"use strict";qe(),Ye=!1,P=!1,Xe=!1,Ze=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(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]))}catch{return!1}},Qe=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},$e=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},et=async e=>{if(Ye)return Promise.resolve();if(P)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Xe)throw Error(`previous call to 'initializeWebAssembly()' failed.`);P=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!$e())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!Qe())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Ze();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Ke(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Le();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{P=!1,Ye=!0,Je=t,e(),d&&URL.revokeObjectURL(d)},e=>{P=!1,Xe=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},F=()=>{if(Ye&&Je)return Je;throw Error(`WebAssembly is not initialized yet.`)}}),L,tt,R,nt=a(()=>{"use strict";I(),L=(e,t)=>{let n=F(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},tt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)tt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},R=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),rt,it=a(()=>{"use strict";I(),nt(),rt=e=>{let t=F(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=L(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&R(`Can't create run options.`),e?.extra!==void 0&&tt(e.extra,``,new WeakSet,(e,i)=>{let a=L(e,r),o=L(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&R(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),at,ot,st,z,ct,lt,ut=a(()=>{"use strict";I(),nt(),at=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},ot=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},st=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},z=(e,t,n,r)=>{let i=L(t,r),a=L(n,r);F()._OrtAddSessionConfigEntry(e,i,a)!==0&&R(`Can't set a session config entry: ${t} - ${n}.`)},ct=async(e,t,n)=>{let r=t.executionProviders;for(let t of r){let r=typeof t==`string`?t:t.name,i=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof t!=`string`){let r=t?.deviceType;r&&z(e,`deviceType`,r,n)}break;case`webgpu`:if(r=`JS`,typeof t!=`string`){let r=t;if(r?.preferredLayout){if(r.preferredLayout!==`NCHW`&&r.preferredLayout!==`NHWC`)throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${r.preferredLayout}`);z(e,`preferredLayout`,r.preferredLayout,n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let a=L(r,n),o=i.length,s=0,c=0;if(o>0){s=F()._malloc(o*F().PTR_SIZE),n.push(s),c=F()._malloc(o*F().PTR_SIZE),n.push(c);for(let e=0;e<o;e++)F().setValue(s+e*F().PTR_SIZE,i[e][0],`*`),F().setValue(c+e*F().PTR_SIZE,i[e][1],`*`)}await F()._OrtAppendExecutionProvider(e,a,s,c,o)!==0&&R(`Can't append execution provider: ${r}.`)}},lt=async e=>{let t=F(),n=0,r=[],i=e||{};st(i);try{let e=at(i.graphOptimizationLevel??`all`),a=ot(i.executionMode??`sequential`),o=typeof i.logId==`string`?L(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?L(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&R(`Can't create session options.`),i.executionProviders&&await ct(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);z(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=L(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&R(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&tt(i.extra,``,new WeakSet,(e,t)=>{z(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&R(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),B,dt,V,ft,pt,mt,ht,gt,_t=a(()=>{"use strict";B=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},dt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},V=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ft=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},pt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},mt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,ht=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,gt=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),vt,yt=a(()=>{"use strict";Oe(),vt=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),bt,xt,St,H,Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt=a(()=>{"use strict";M(),it(),ut(),_t(),I(),nt(),yt(),bt=(e,t)=>{F()._OrtInit(e,t)!==0&&R(`Can't initialize onnxruntime.`)},xt=async e=>{bt(e.wasm.numThreads,pt(e.logLevel))},St=async(e,t)=>{F().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`)},H=new Map,Ct=e=>{let t=F(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&R(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},wt=(e,t)=>{let n=F(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&R(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Tt=e=>{let t=F(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Et=async(e,t)=>{let n,r,i=F();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Tt(e);let a=0,o=0,s=[],c=[],l=[];try{if([o,s]=await lt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(vt(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&R(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,u]=Ct(a),d=!!t?.enableGraphCapture,f=[],p=[],m=[],h=[];for(let t=0;t<e;t++){let[e,n,r]=wt(a,t);e===0&&R(`Can't get an input name.`),c.push(e);let o=i.UTF8ToString(e);f.push(o),m.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:dt(n),shape:r})}for(let t=0;t<u;t++){let[n,r,o]=wt(a,t+e);n===0&&R(`Can't get an output name.`),l.push(n);let s=i.UTF8ToString(n);p.push(s),h.push(r===0?{name:s,isTensor:!1}:{name:s,isTensor:!0,type:dt(r),shape:o})}return H.set(a,[a,c,l,null,d,!1]),[a,f,p,m,h]}catch(e){throw c.forEach(e=>i._OrtFree(e)),l.forEach(e=>i._OrtFree(e)),a!==0&&i._OrtReleaseSession(a)!==0&&R(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&R(`Can't release session options.`),s.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Dt=e=>{let t=F(),n=H.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&R(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&R(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&R(`Can't release session.`),H.delete(e)},Ot=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=F(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=V(B(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=V(B(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,B(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,L(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=B(l);m=V(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(B(l),p,m,g,u.length,gt(f));e===0&&R(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},kt=async(e,t,n,r,i,a)=>{let o=F(),s=o.PTR_SIZE,c=H.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4];c[5];let m=t.length,h=r.length,g=0,_=[],v=[],y=[],b=[],x=[],S=o.stackSave(),ee=o.stackAlloc(m*s),te=o.stackAlloc(m*s),ne=o.stackAlloc(h*s),C=o.stackAlloc(h*s);try{[g,_]=rt(a),A(`wasm prepareInputOutputTensor`);for(let r=0;r<m;r++)await Ot(n[r],v,b,e,u[t[r]],t[r],p);for(let t=0;t<h;t++)await Ot(i[t],y,b,e,d[r[t]],m+r[t],p);j(`wasm prepareInputOutputTensor`);for(let e=0;e<m;e++)o.setValue(ee+e*s,v[e],`*`),o.setValue(te+e*s,u[t[e]],`*`);for(let e=0;e<h;e++)o.setValue(ne+e*s,y[e],`*`),o.setValue(C+e*s,d[r[e]],`*`);o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=await o._OrtRun(l,te,ee,m,C,h,ne,g),c!==0&&R(`failed to call OrtRun().`);let S=[],re=[];A(`wasm ProcessOutputTensor`);for(let t=0;t<h;t++){let n=Number(o.getValue(ne+t*s,`*`));if(n===y[t]||x.includes(y[t])){S.push(i[t]),n!==y[t]&&o._OrtReleaseTensor(n)!==0&&R(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&R(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&R(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=dt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}S.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=V(a,g);if(r===void 0||!mt(u))throw Error(`Unsupported data type: ${u}`);l=!0,S.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&R(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(V(a,g)===void 0||!ht(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,S.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=S.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(ft(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&R(`Can't clear bound outputs.`),H.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))S[e][2]=t;return j(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),v.forEach(e=>o._OrtReleaseTensor(e)),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._free(e)),g!==0&&o._OrtReleaseRunOptions(g),_.forEach(e=>o._free(e))}},At=e=>{let t=F(),n=H.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&R(`Can't get an profile file name.`),t._OrtFree(i)},jt=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),U,W,G,K,q,Nt,Pt,J,Y,X,Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut=a(()=>{"use strict";M(),Mt(),I(),qe(),U=()=>!!x.wasm.proxy&&typeof document<`u`,G=!1,K=!1,q=!1,J=new Map,Y=(e,t)=>{let n=J.get(e);n?n.push(t):J.set(e,[t])},X=()=>{if(G||!K||q||!W)throw Error(`worker not ready`)},Ft=e=>{switch(e.data.type){case`init-wasm`:G=!1,e.data.err?(q=!0,Pt[1](e.data.err)):(K=!0,Pt[0]()),Nt&&=(URL.revokeObjectURL(Nt),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=J.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},It=async()=>{if(!K){if(G)throw Error(`multiple calls to 'initWasm()' detected.`);if(q)throw Error(`previous call to 'initWasm()' failed.`);if(G=!0,U())return new Promise((e,t)=>{W?.terminate(),We().then(([n,r])=>{try{W=r,W.onerror=e=>t(e),W.onmessage=Ft,Pt=[e,t];let i={type:`init-wasm`,in:x};if(!i.in.wasm.wasmPaths&&n){let e=Le();e&&(i.in.wasm.wasmPaths=e)}W.postMessage(i),Nt=n}catch(e){t(e)}},t)});try{await et(x.wasm),await xt(x),K=!0}catch(e){throw q=!0,e}finally{G=!1}}},Lt=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:x}};W.postMessage(r)});await St(x,e)},Rt=async e=>U()?(X(),new Promise((t,n)=>{Y(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};W.postMessage(r,[e.buffer])})):Tt(e),zt=async(e,t)=>{if(U()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return X(),new Promise((n,r)=>{Y(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),W.postMessage(i,a)})}else return Et(e,t)},Bt=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`release`,[t,n]);let r={type:`release`,in:e};W.postMessage(r)});Dt(e)},Vt=async(e,t,n,r,i,a)=>{if(U()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return X(),new Promise((i,o)=>{Y(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};W.postMessage(c,jt(s))})}else return kt(e,t,n,r,i,a)},Ht=async e=>{if(U())return X(),new Promise((t,n)=>{Y(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};W.postMessage(r)});At(e)}}),Wt,Gt,Kt,qt=a(()=>{"use strict";M(),Ut(),_t(),Oe(),yt(),Wt=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Gt=e=>{switch(e[3]){case`cpu`:return new D(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!mt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return D.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!ht(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return D.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Kt=class{async fetchModelAndCopyToWasmMemory(e){return Rt(await vt(e))}async loadModel(e,t){O();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await zt(n,t),k()}async dispose(){return Bt(this.sessionId)}async run(e,t,n){O();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Wt(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Wt(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Vt(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Gt(l[e]);return k(),u}startProfiling(){}endProfiling(){Ht(this.sessionId)}}}),Jt={};o(Jt,{OnnxruntimeWebAssemblyBackend:()=>Xt,initializeFlags:()=>Yt,wasmBackend:()=>Zt});var Yt,Xt,Zt,Qt=a(()=>{"use strict";M(),Ut(),qt(),Yt=()=>{(typeof x.wasm.initTimeout!=`number`||x.wasm.initTimeout<0)&&(x.wasm.initTimeout=0);let e=x.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),x.wasm.simd=!1),typeof x.wasm.proxy!=`boolean`&&(x.wasm.proxy=!1),typeof x.wasm.trace!=`boolean`&&(x.wasm.trace=!1),typeof x.wasm.numThreads!=`number`||!Number.isInteger(x.wasm.numThreads)||x.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)x.wasm.numThreads=1;else{let e=typeof navigator>`u`?i(`node:os`).cpus().length:navigator.hardwareConcurrency;x.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Xt=class{async init(e){Yt(),await It(),await Lt(e)}async createInferenceSessionHandler(e,t){let n=new Kt;return await n.loadModel(e,t),n}},Zt=new Xt});M(),M(),M();var $t=`1.24.3`;{let e=(Qt(),c(Jt)).wasmBackend;d(`cpu`,e,10),d(`wasm`,e,10)}Object.defineProperty(x.versions,"web",{value:$t,enumerable:!0});function en(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw Error(`MonitorDog runtimeAssetBaseUrl must be a non-empty string when provided.`);let n=t.replace(/\/+$/,``);return n.length===0?`/`:n}function tn(e,t){let n=en(e),r=t.replace(/^\/+/,``);if(n===void 0)throw Error(`MonitorDog runtimeAssetBaseUrl must be provided to resolve runtime assets.`);return n===`/`?`/${r}`:`${n}/${r}`}function nn(e,t,n){return t===void 0?n:tn(t,`sdk/${e}`)}function rn(e,t){return e===void 0?t:tn(e,`ort/`)}let Z={environment:`prod`,bundleId:`prod-20260705T192541-8e2ebd25`,assetVersion:`0.0.1`,createdAt:`2026-07-05T19:25:41.252382+00:00`,assets:{detector:{320:{file:`assets/detector-320.onnx.enc`,version:`0.0.1`,encryptedSha256:`d33f6351a47518ac8f3620b9ee01c278e9aa8d6965b142ff459fe69ef2f4459b`},416:{file:`assets/detector-416.onnx.enc`,version:`0.0.1`,encryptedSha256:`86c10df69cd3119760f67295954af2a61c595ce81f1ba3b7214e6b7631d41082`},640:{file:`assets/detector-640.onnx.enc`,version:`0.0.1`,encryptedSha256:`98ea0a44ed7216bb54da53c685a674063300840e2fb5624a7dee8f8e85f5076a`}}}};async function an(e){bn();let t=on(e.inputSize),n=await crypto.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`decrypt`]),r=pn(await dn(n.publicKey)),[i,a]=await Promise.all([cn(t.file,e.runtimeAssetBaseUrl),sn({apiBaseUrl:e.apiBaseUrl,accessToken:e.accessToken,inputSize:e.inputSize,assetEntry:t},r)]),o=new Uint8Array(await crypto.subtle.decrypt({name:`RSA-OAEP`},n.privateKey,yn(mn(a.encrypted_dek)))),s=hn(o);try{return await un(i,s)}finally{i.fill(0),o.fill(0),s.fill(0)}}function on(e){if(e!==320&&e!==416&&e!==640)throw Error(`MonitorDog detector input size must be 320, 416, or 640.`);let t=Z.assets.detector[String(e)];if(!Z.environment||!Z.bundleId||!t?.file)throw Error(`MonitorDog SDK encrypted asset manifest is not configured. Run package:dev or package:prod before building a release package.`);if(!t.version||!t.encryptedSha256)throw Error(`MonitorDog SDK detector ${e} asset manifest is incomplete.`);return t}async function sn(e,t){let n=new URLSearchParams({environment:Z.environment,bundle_id:Z.bundleId,asset:`detector`,input_size:String(e.inputSize),version:e.assetEntry.version,encrypted_sha256:e.assetEntry.encryptedSha256,public_key:t}),r=await fetch(`${e.apiBaseUrl}/auth/sdk-asset-key?${n}`,{method:`GET`,headers:{accept:`application/json`,authorization:`Bearer ${e.accessToken}`,"Device-Access-Token":e.accessToken}});if(!r.ok)throw Error(`MonitorDog SDK model key request failed: ${r.status}`);let i=await r.json();if(!i.encrypted_dek)throw Error(`MonitorDog SDK model key response is incomplete.`);return{encrypted_dek:i.encrypted_dek,asset:i.asset??`detector`,input_size:i.input_size??e.inputSize,version:i.version??e.assetEntry.version}}async function cn(e,t){let n=await fetch(ln(e,t));if(!n.ok)throw Error(`Failed to download packaged MonitorDog model: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}function ln(e,t){let n=e.replace(/\\/g,`/`).split(`/`).pop();if(!n||!n.endsWith(`.onnx.enc`))throw Error(`Invalid MonitorDog SDK asset file path: ${e}`);return nn(n,t,new URL(`./sdk/${n}`,self.location.href).href)}async function un(e,t){if(e.byteLength<=12)throw Error(`MonitorDog encrypted model data is too short.`);let n=await crypto.subtle.importKey(`raw`,yn(t),{name:`AES-GCM`},!1,[`decrypt`]),r=e.slice(0,12),i=e.slice(12);return new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:yn(r)},n,yn(i)))}async function dn(e){let t=await crypto.subtle.exportKey(`spki`,e);return[`-----BEGIN PUBLIC KEY-----`,...fn(new Uint8Array(t)).match(/.{1,64}/g)??[],`-----END PUBLIC KEY-----`].join(`
|
|
8
|
+
`)}function fn(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function pn(e){return fn(new TextEncoder().encode(e))}function mn(e){let t=e.replace(/-----BEGIN [^-]+-----/g,``).replace(/-----END [^-]+-----/g,``).replace(/\s/g,``).replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t+`=`.repeat(n),i=atob(r),a=new Uint8Array(i.length);for(let e=0;e<i.length;e+=1)a[e]=i.charCodeAt(e);return a}function hn(e){if(vn(e.byteLength))return new Uint8Array(e);let t=new TextDecoder().decode(e).trim(),n=gn(t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t);if(n&&vn(n.byteLength))return n;throw Error(`MonitorDog SDK model DEK must decode to a 128-bit or 256-bit AES key. Received ${e.byteLength} bytes.`)}function gn(e){if(/^[0-9a-f]+$/i.test(e)&&e.length%2==0)return _n(e);try{return mn(e)}catch{return}}function _n(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function vn(e){return e===16||e===32}function yn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function bn(){if(!globalThis.crypto?.subtle)throw Error(`MonitorDog SDK model decryption requires Web Crypto API.`)}let xn=new Set([0,1]),Sn=[`phone_back`,`phone_front`,`phone_back_cam`,`cup`,`hand`,`face`];function Cn(e){if(e.output.type!==`float32`)throw Error(`Detector postprocessing requires float32 output.`);if(!(e.output.data instanceof Float32Array))throw Error(`Detector postprocessing expected Float32Array output.`);let t=e.output.data,n=[...e.output.dims];if(n.length!==3||n[0]!==1||n[1]<=0||n[2]<=0)throw Error(`Detector postprocessing received an unexpected output shape.`);let r=n[1]===10,i=r?n[2]:n[1];if((r?n[1]:n[2])<10||i===0)throw Error(`Detector postprocessing received an incomplete output tensor.`);let a=[];for(let n=0;n<i;n+=1){let o=Q(t,r,n,0,i),s=Q(t,r,n,1,i),c=Q(t,r,n,2,i),l=Q(t,r,n,3,i),u=0,d=0;for(let e=0;e<6;e+=1){let a=Q(t,r,n,e+4,i);a>d&&(d=a,u=e)}let f=u===5?e.faceConfidenceThreshold:e.confidenceThreshold,p={classId:u,score:d,cx:o,cy:s,width:c,height:l};d>=f&&wn(p,e.metadata)&&a.push(p)}let o=Tn(a,e.iouThreshold,e.maxDetections),s=[],c=[],l=[];for(let t of o){let n=En(t,e.metadata);xn.has(t.classId)?s.push(n):t.classId===4?c.push(n):t.classId===5&&l.push(n)}let u=s.filter(t=>c.some(e=>On(t,e)>=.01)||t.score>=e.confidenceThreshold);return{faceDetected:l.length>0,phoneDetected:u.length>0,faceCount:l.length,phoneCount:u.length,faceDetections:l,phoneDetections:u}}function Q(e,t,n,r,i){return e[t?r*i+n:n*10+r]}function wn(e,t){let n=e.cx-e.width/2,r=e.cy-e.height/2,i=e.cx+e.width/2,a=e.cy+e.height/2;return i>=t.padX&&a>=t.padY&&n<=t.padX+t.sourceWidth*t.ratio&&r<=t.padY+t.sourceHeight*t.ratio}function Tn(e,t,n){let r=[...e].sort((e,t)=>t.score-e.score),i=[];for(let e of r)if(i.some(n=>n.classId===e.classId&&Dn(n,e)>t)||i.push(e),i.length>=n)break;return i}function En(e,t){let n=(e.cx-e.width/2-t.padX)/t.ratio,r=(e.cy-e.height/2-t.padY)/t.ratio,i=(e.cx+e.width/2-t.padX)/t.ratio,a=(e.cy+e.height/2-t.padY)/t.ratio,o=kn(n,0,t.sourceWidth),s=kn(r,0,t.sourceHeight);return{classId:e.classId,label:Sn[e.classId]??`unknown`,score:e.score,confidence:Math.round(e.score*1e4)/100,x:o,y:s,width:kn(i,0,t.sourceWidth)-o,height:kn(a,0,t.sourceHeight)-s}}function Dn(e,t){let n=e.cx-e.width/2,r=e.cy-e.height/2,i=e.cx+e.width/2,a=e.cy+e.height/2,o=t.cx-t.width/2,s=t.cy-t.height/2,c=t.cx+t.width/2,l=t.cy+t.height/2,u=Math.max(0,Math.min(i,c)-Math.max(n,o))*Math.max(0,Math.min(a,l)-Math.max(r,s)),d=e.width*e.height+t.width*t.height-u;return d<=0?0:u/d}function On(e,t){let n=e.x+e.width,r=e.y+e.height,i=t.x+t.width,a=t.y+t.height,o=Math.max(0,Math.min(n,i)-Math.max(e.x,t.x))*Math.max(0,Math.min(r,a)-Math.max(e.y,t.y)),s=e.width*e.height+t.width*t.height-o;return s<=0?0:o/s}function kn(e,t,n){return Math.min(Math.max(e,t),n)}function An(e,t,n){return e.map(e=>Mn(e,t,n))}function jn(e,t,n,r){if(e.phoneDetected||t.phoneDetections.length===0)return e;let i=An(t.phoneDetections,n,r);return{...e,phoneDetected:i.length>0,phoneCount:i.length,phoneDetections:i}}function Mn(e,t,n){return{...e,x:Nn(t-(e.x+e.width),0,t),y:Nn(n-(e.y+e.height),0,n)}}function Nn(e,t,n){return Math.min(Math.max(e,t),n)}let Pn=self,$,Fn=Promise.resolve(),In=-1/0,Ln=new URL(`./ort/`,self.location.href).href;x.wasm.numThreads=1,x.wasm.wasmPaths=Ln,Pn.addEventListener(`message`,e=>{Rn(e.data)});async function Rn(e){try{if(e.type===`load`){zn(e.model.runtimeAssetBaseUrl),$=void 0,In=-1/0;let t=await an(e.model);try{$=await Se.create($n(t),{executionProviders:[`wasm`]})}finally{t.fill(0)}Zn({id:e.id,ok:!0});return}let t=await Bn(e);Zn({id:e.id,ok:!0,result:t})}catch(t){Zn({id:e.id,ok:!1,error:t instanceof Error?t.message:String(t)})}}function zn(e){x.wasm.wasmPaths=rn(e,Ln)}function Bn(e){let t=Fn.then(()=>Vn(e));return Fn=t.then(()=>void 0,()=>void 0),t}async function Vn(e){if(!$)throw Error(`MonitorDog ONNX runtime session is not loaded.`);if(e.inputType!==`float32`)throw Error(`MonitorDog ONNX runtime only supports float32 input.`);let t=e.debug?performance.now():0,n=e.debug?performance.now():0,r=n,i=n,a=0,o;try{let{input:t,metadata:n}=Hn(e.source,e.inputSize,e.inputRotation);r=e.debug?performance.now():0;let s=await Gn(t,$);i=e.debug?performance.now():0;let c=Cn({output:s,metadata:n,confidenceThreshold:e.confidenceThreshold,faceConfidenceThreshold:e.faceConfidenceThreshold,iouThreshold:e.iouThreshold,maxDetections:e.maxDetections});if(o=c,Un(e,c)){let t=e.debug?performance.now():0,r=Hn(e.source,e.inputSize,`rotate180`);o=jn(c,Cn({output:await Gn(r.input,$),metadata:r.metadata,confidenceThreshold:e.confidenceThreshold,faceConfidenceThreshold:e.faceConfidenceThreshold,iouThreshold:e.iouThreshold,maxDetections:e.maxDetections}),n.sourceWidth,n.sourceHeight),e.debug&&(a=performance.now()-t)}}finally{Wn(e.source)}if(e.debug){let o=performance.now();console.info(`[MonitorDog] worker inference`,{source:e.source.kind,inputSize:e.inputSize,inputRotation:e.inputRotation,preprocessMs:Qn(r-n),ortMs:Qn(i-r),phoneRotationFallbackMs:Qn(a),totalMs:Qn(o-t)})}return o}function Hn(e,t,n){return e.kind===`bitmap`?Kn(e,t,n):qn(e,t,n)}function Un(e,t){if(!e.phoneRotationFallback||t.phoneDetected||e.inputRotation!==`none`)return!1;let n=performance.now();return n-In<e.phoneRotationFallbackMinIntervalMs?!1:(In=n,!0)}function Wn(e){e.kind===`bitmap`&&e.bitmap.close()}async function Gn(e,t){if(!(e.data instanceof Float32Array))throw Error(`MonitorDog ONNX runtime expected Float32Array input.`);let n=t.inputNames[0],r=t.outputNames[0],i=(await t.run({[n]:new D(`float32`,e.data,[...e.dims])}))[r];if(!i||i.type!==`float32`)throw Error(`MonitorDog ONNX runtime returned a non-float32 output.`);return{type:`float32`,data:i.data,dims:i.dims}}function Kn(e,t,n){if(typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not available.`);let r=Jn(e.sourceWidth,e.sourceHeight,t),i=Math.round(e.sourceWidth*r.ratio),a=Math.round(e.sourceHeight*r.ratio),o=new OffscreenCanvas(t,t).getContext(`2d`);if(!o)throw Error(`2D canvas context is not available.`);return o.fillStyle=`rgb(114, 114, 114)`,o.fillRect(0,0,t,t),n===`rotate180`?(o.save(),o.translate(r.padX+i,r.padY+a),o.rotate(Math.PI),o.drawImage(e.bitmap,0,0,i,a),o.restore()):o.drawImage(e.bitmap,r.padX,r.padY,i,a),{input:Xn(o.getImageData(0,0,t,t).data,t),metadata:r}}function qn(e,t,n){let r=Jn(e.sourceWidth,e.sourceHeight,t);return{input:Yn(e.data,e.sourceWidth,e.sourceHeight,r,t,n),metadata:r}}function Jn(e,t,n){let r=Math.min(n/e,n/t);return{sourceWidth:e,sourceHeight:t,ratio:r,padX:Math.floor((n-Math.round(e*r))/2),padY:Math.floor((n-Math.round(t*r))/2)}}function Yn(e,t,n,r,i,a){let o=i*i,s=[1,3,i,i],c=new Float32Array(o*3);for(let s=0;s<i;s+=1)for(let l=0;l<i;l+=1){let u=s*i+l,d=Math.floor((l-r.padX)/r.ratio),f=Math.floor((s-r.padY)/r.ratio),p=d>=0&&f>=0&&d<t&&f<n,m=a===`rotate180`?t-1-d:d,h=((a===`rotate180`?n-1-f:f)*t+m)*4,g=p?e[h]:114,_=p?e[h+1]:114,v=p?e[h+2]:114;c[u]=g/255,c[u+o]=_/255,c[u+o*2]=v/255}return{type:`float32`,data:c,dims:s}}function Xn(e,t){let n=t*t,r=[1,3,t,t],i=new Float32Array(n*3);for(let t=0;t<n;t+=1){let r=t*4;i[t]=e[r]/255,i[t+n]=e[r+1]/255,i[t+n*2]=e[r+2]/255}return{type:`float32`,data:i,dims:r}}function Zn(e,t){Pn.postMessage(e,t??[])}function Qn(e){return Math.round(e*10)/10}function $n(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}})();
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export declare class MonitorDogDetector {
|
|
|
10
10
|
stop(): void;
|
|
11
11
|
setRunInBackground(runInBackground: boolean): void;
|
|
12
12
|
setEventReportingEnabled(enabled: boolean): void;
|
|
13
|
+
setPhoneConfidenceThreshold(threshold?: number): void;
|
|
13
14
|
getUserPreferences(): Readonly<UserPreferences>;
|
|
14
15
|
getState(): MonitorDogDetectorState;
|
|
15
16
|
dispose(): void;
|
|
@@ -64,24 +64,24 @@ function h(e) {
|
|
|
64
64
|
}
|
|
65
65
|
//#endregion
|
|
66
66
|
//#region src/events.ts
|
|
67
|
-
function
|
|
68
|
-
if (e.faceCount === 0) return
|
|
69
|
-
if (e.faceCount >= 2) return
|
|
70
|
-
if (e.phoneCount >= 1) return
|
|
67
|
+
function ee(e) {
|
|
68
|
+
if (e.faceCount === 0) return _("noFaceDetected", e);
|
|
69
|
+
if (e.faceCount >= 2) return _("twoFacesDetected", e);
|
|
70
|
+
if (e.phoneCount >= 1) return _("mobileDevice", e);
|
|
71
71
|
}
|
|
72
|
-
function
|
|
72
|
+
function te(e) {
|
|
73
73
|
return {
|
|
74
|
-
...
|
|
74
|
+
...v(e, (/* @__PURE__ */ new Date()).toISOString()),
|
|
75
75
|
properties: {},
|
|
76
76
|
webcam_imgs: [],
|
|
77
77
|
monitor_imgs: []
|
|
78
78
|
};
|
|
79
79
|
}
|
|
80
|
-
function
|
|
80
|
+
function g(e) {
|
|
81
81
|
return e.phoneCount === 0 && e.faceCount === 1;
|
|
82
82
|
}
|
|
83
|
-
function
|
|
84
|
-
let n =
|
|
83
|
+
function _(e, t) {
|
|
84
|
+
let n = v(e, (/* @__PURE__ */ new Date()).toISOString());
|
|
85
85
|
switch (e) {
|
|
86
86
|
case "noFaceDetected": return {
|
|
87
87
|
type: e,
|
|
@@ -98,7 +98,7 @@ function y(e, t) {
|
|
|
98
98
|
payload: {
|
|
99
99
|
...n,
|
|
100
100
|
properties: {
|
|
101
|
-
confidence:
|
|
101
|
+
confidence: y(t.faceDetections),
|
|
102
102
|
spots: t.faceDetections
|
|
103
103
|
}
|
|
104
104
|
}
|
|
@@ -108,16 +108,16 @@ function y(e, t) {
|
|
|
108
108
|
payload: {
|
|
109
109
|
...n,
|
|
110
110
|
properties: {
|
|
111
|
-
confidence:
|
|
111
|
+
confidence: y(t.phoneDetections),
|
|
112
112
|
spots: t.phoneDetections
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
|
-
function
|
|
118
|
+
function v(e, t) {
|
|
119
119
|
return {
|
|
120
|
-
basic_event_uuid:
|
|
120
|
+
basic_event_uuid: b(e),
|
|
121
121
|
occured_at: t,
|
|
122
122
|
sended_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
123
123
|
device_type: l(),
|
|
@@ -125,10 +125,10 @@ function b(e, t) {
|
|
|
125
125
|
device_id: "browser"
|
|
126
126
|
};
|
|
127
127
|
}
|
|
128
|
-
function
|
|
128
|
+
function y(e) {
|
|
129
129
|
return e.reduce((e, t) => Math.max(e, t.score), 0);
|
|
130
130
|
}
|
|
131
|
-
function
|
|
131
|
+
function b(e) {
|
|
132
132
|
switch (e) {
|
|
133
133
|
case "logout": return "12ca646a-d832-4581-b03c-48f95627507f";
|
|
134
134
|
case "login": return "4c6f98ea-88d8-4215-9b6a-9b3ccb753465";
|
|
@@ -140,9 +140,9 @@ function S(e) {
|
|
|
140
140
|
}
|
|
141
141
|
//#endregion
|
|
142
142
|
//#region src/service/auth-service.ts
|
|
143
|
-
var
|
|
143
|
+
var x = "MonitorDog token refresh was superseded.", S = 300 * 1e3, C = class {
|
|
144
144
|
services;
|
|
145
|
-
refreshBeforeMs =
|
|
145
|
+
refreshBeforeMs = S;
|
|
146
146
|
periodicRefreshIntervalMs = r;
|
|
147
147
|
token;
|
|
148
148
|
tokenExpiresAt;
|
|
@@ -236,7 +236,7 @@ var C = "MonitorDog token refresh was superseded.", w = 300 * 1e3, T = class {
|
|
|
236
236
|
if (!t) throw Error("MonitorDog login email is required to refresh SDK token.");
|
|
237
237
|
let n = await this.fetchSessionToken(t), r = i(n);
|
|
238
238
|
if (!r || typeof r != "string") throw Error("MonitorDog SDK token response did not include a token.");
|
|
239
|
-
if (e !== this.authSessionId) throw Error(
|
|
239
|
+
if (e !== this.authSessionId) throw Error(x);
|
|
240
240
|
return this.setSessionTokenPayload(n), r;
|
|
241
241
|
}
|
|
242
242
|
startPeriodicRefresh() {
|
|
@@ -259,7 +259,7 @@ var C = "MonitorDog token refresh was superseded.", w = 300 * 1e3, T = class {
|
|
|
259
259
|
return !!(this.tokenExpiresAt && Date.now() >= this.tokenExpiresAt);
|
|
260
260
|
}
|
|
261
261
|
isRefreshSupersededError(e) {
|
|
262
|
-
return e instanceof Error && e.message ===
|
|
262
|
+
return e instanceof Error && e.message === x;
|
|
263
263
|
}
|
|
264
264
|
async fetchSessionToken(e) {
|
|
265
265
|
let t = this.services.options.sessionTokenProvider;
|
|
@@ -287,11 +287,11 @@ var C = "MonitorDog token refresh was superseded.", w = 300 * 1e3, T = class {
|
|
|
287
287
|
let t = await this.authorizedFetch("/event", {
|
|
288
288
|
method: "POST",
|
|
289
289
|
headers: { "content-type": "application/json" },
|
|
290
|
-
body: JSON.stringify(
|
|
290
|
+
body: JSON.stringify(te(e))
|
|
291
291
|
});
|
|
292
292
|
if (!t.ok) throw Error(`MonitorDog ${e} event failed: ${t.status}`);
|
|
293
293
|
} catch (t) {
|
|
294
|
-
let n = this.createSdkError(
|
|
294
|
+
let n = this.createSdkError(w(e), `MonitorDog ${e} event failed.`, t);
|
|
295
295
|
if (this.services.options.onAuthError?.(n), e === "logout") throw n;
|
|
296
296
|
}
|
|
297
297
|
}
|
|
@@ -299,12 +299,12 @@ var C = "MonitorDog token refresh was superseded.", w = 300 * 1e3, T = class {
|
|
|
299
299
|
return n instanceof m ? n : new m(e, t, n);
|
|
300
300
|
}
|
|
301
301
|
};
|
|
302
|
-
function
|
|
302
|
+
function w(e) {
|
|
303
303
|
return e === "logout" ? "LOGOUT_FAILED" : "SESSION_TOKEN_FAILED";
|
|
304
304
|
}
|
|
305
305
|
//#endregion
|
|
306
306
|
//#region src/service/camera-service.ts
|
|
307
|
-
var
|
|
307
|
+
var T = /(obs|virtual|xsplit|manycam|splitcam|webcammax|fake|loopback|camtwist|e2esoft|vcam|droidcam|iriun|epoccam|camo|mmhmm|nvidia broadcast|streamlabs|bandicam|wirecast|chromacam|youcam|cyberlink|altserver|logi capture|elgato|streamfx|screen capture|desktop capture)/i, E = class {
|
|
308
308
|
async createWebcamStream(e) {
|
|
309
309
|
if (!navigator.mediaDevices?.getUserMedia) throw Error("getUserMedia is not available in this browser.");
|
|
310
310
|
let t = this.getBaseWebcamConstraints(e), n = await this.createFirstCameraConstraints(t);
|
|
@@ -423,7 +423,7 @@ var D = /(obs|virtual|xsplit|manycam|splitcam|webcammax|fake|loopback|camtwist|e
|
|
|
423
423
|
}
|
|
424
424
|
isVirtualCamera(e) {
|
|
425
425
|
let t = e.label.toLowerCase();
|
|
426
|
-
return t ?
|
|
426
|
+
return t ? T.test(t) : !1;
|
|
427
427
|
}
|
|
428
428
|
isPermissionError(e) {
|
|
429
429
|
return e instanceof DOMException && (e.name === "NotAllowedError" || e.name === "SecurityError");
|
|
@@ -447,7 +447,7 @@ var D = /(obs|virtual|xsplit|manycam|splitcam|webcammax|fake|loopback|camtwist|e
|
|
|
447
447
|
};
|
|
448
448
|
//#endregion
|
|
449
449
|
//#region src/capture.ts
|
|
450
|
-
function
|
|
450
|
+
function D(e) {
|
|
451
451
|
if (e.videoWidth === 0 || e.videoHeight === 0) throw Error("Video frame is not ready for capture.");
|
|
452
452
|
let t = document.createElement("canvas"), n = t.getContext("2d");
|
|
453
453
|
if (!n) throw Error("2D canvas context is not available.");
|
|
@@ -461,7 +461,7 @@ function ee(e) {
|
|
|
461
461
|
}, "image/jpeg", .9);
|
|
462
462
|
});
|
|
463
463
|
}
|
|
464
|
-
async function
|
|
464
|
+
async function O() {
|
|
465
465
|
if (typeof document > "u" || !document.body) return null;
|
|
466
466
|
let t = await e(document.body, {
|
|
467
467
|
backgroundColor: "#ffffff",
|
|
@@ -473,7 +473,7 @@ async function te() {
|
|
|
473
473
|
}
|
|
474
474
|
//#endregion
|
|
475
475
|
//#region src/service/detection-event-service.ts
|
|
476
|
-
var
|
|
476
|
+
var ne = class e {
|
|
477
477
|
static NO_FACE_STARTUP_GRACE_MS = 1500;
|
|
478
478
|
services;
|
|
479
479
|
detectionEventLocked = !1;
|
|
@@ -489,12 +489,12 @@ var k = class e {
|
|
|
489
489
|
this.reset();
|
|
490
490
|
return;
|
|
491
491
|
}
|
|
492
|
-
if (
|
|
492
|
+
if (g(e)) {
|
|
493
493
|
this.noFaceStartedAt = void 0, this.clearLock();
|
|
494
494
|
return;
|
|
495
495
|
}
|
|
496
496
|
if (this.detectionEventLocked || this.detectionEventInFlight) return;
|
|
497
|
-
let n =
|
|
497
|
+
let n = ee(e);
|
|
498
498
|
if (!n) {
|
|
499
499
|
this.noFaceStartedAt = void 0;
|
|
500
500
|
return;
|
|
@@ -531,11 +531,11 @@ var k = class e {
|
|
|
531
531
|
}
|
|
532
532
|
async uploadWebcamImage(e) {
|
|
533
533
|
if (!(e instanceof HTMLVideoElement) || e.videoWidth === 0 || e.videoHeight === 0) return;
|
|
534
|
-
let t = await
|
|
534
|
+
let t = await D(e);
|
|
535
535
|
return this.uploadImage(t, "webcam.jpg");
|
|
536
536
|
}
|
|
537
537
|
async uploadMonitorImage() {
|
|
538
|
-
let e = this.services.options.captureMonitorImage ? await this.services.options.captureMonitorImage() : await
|
|
538
|
+
let e = this.services.options.captureMonitorImage ? await this.services.options.captureMonitorImage() : await O();
|
|
539
539
|
if (!e) return;
|
|
540
540
|
let t = typeof File < "u" && e instanceof File ? e.name : "monitor.jpg";
|
|
541
541
|
return this.uploadImage(e, t);
|
|
@@ -552,8 +552,8 @@ var k = class e {
|
|
|
552
552
|
}
|
|
553
553
|
shouldSendEvent(e, t) {
|
|
554
554
|
switch (e) {
|
|
555
|
-
case "mobileDevice": return this.services.userPreferences.mobileDetectionEnabled &&
|
|
556
|
-
case "twoFacesDetected": return this.services.userPreferences.multiPersonDetectionEnabled &&
|
|
555
|
+
case "mobileDevice": return this.services.userPreferences.mobileDetectionEnabled && k(t.phoneDetections) >= this.services.options.confidenceThreshold;
|
|
556
|
+
case "twoFacesDetected": return this.services.userPreferences.multiPersonDetectionEnabled && k(t.faceDetections) >= this.services.userPreferences.faceDetectionThreshold;
|
|
557
557
|
case "noFaceDetected": return this.services.userPreferences.noPersonDetectionEnabled;
|
|
558
558
|
}
|
|
559
559
|
}
|
|
@@ -585,12 +585,12 @@ var k = class e {
|
|
|
585
585
|
}
|
|
586
586
|
}
|
|
587
587
|
};
|
|
588
|
-
function
|
|
589
|
-
return e.reduce((e, t) => Math.max(e, t.
|
|
588
|
+
function k(e) {
|
|
589
|
+
return e.reduce((e, t) => Math.max(e, t.score), 0);
|
|
590
590
|
}
|
|
591
591
|
//#endregion
|
|
592
592
|
//#region src/detect/inference-worker.ts?worker&url
|
|
593
|
-
var
|
|
593
|
+
var A = "" + new URL("assets/inference-worker-BTPzhc2n.js", import.meta.url).href, j = class {
|
|
594
594
|
worker;
|
|
595
595
|
nextRequestId = 1;
|
|
596
596
|
pendingRequests = /* @__PURE__ */ new Map();
|
|
@@ -633,7 +633,7 @@ var j = "" + new URL("assets/inference-worker-ekAaVxft.js", import.meta.url).hre
|
|
|
633
633
|
});
|
|
634
634
|
}
|
|
635
635
|
getWorker() {
|
|
636
|
-
return this.worker || (this.worker = new Worker(
|
|
636
|
+
return this.worker || (this.worker = new Worker(A, {
|
|
637
637
|
name: "MonitorDogInference",
|
|
638
638
|
type: "module"
|
|
639
639
|
}), this.worker.addEventListener("message", this.handleMessage), this.worker.addEventListener("error", this.handleError), this.worker.addEventListener("messageerror", this.handleError)), this.worker;
|
|
@@ -659,15 +659,15 @@ var j = "" + new URL("assets/inference-worker-ekAaVxft.js", import.meta.url).hre
|
|
|
659
659
|
};
|
|
660
660
|
//#endregion
|
|
661
661
|
//#region src/detect/preprocess.ts
|
|
662
|
-
async function
|
|
663
|
-
let { sourceWidth: t, sourceHeight: n } =
|
|
662
|
+
async function M(e) {
|
|
663
|
+
let { sourceWidth: t, sourceHeight: n } = N(e);
|
|
664
664
|
if (e instanceof ImageData) return {
|
|
665
665
|
kind: "rgba",
|
|
666
666
|
data: new Uint8ClampedArray(e.data),
|
|
667
667
|
sourceWidth: t,
|
|
668
668
|
sourceHeight: n
|
|
669
669
|
};
|
|
670
|
-
if (
|
|
670
|
+
if (P() && F()) try {
|
|
671
671
|
return {
|
|
672
672
|
kind: "bitmap",
|
|
673
673
|
bitmap: await createImageBitmap(e),
|
|
@@ -675,9 +675,9 @@ async function N(e) {
|
|
|
675
675
|
sourceHeight: n
|
|
676
676
|
};
|
|
677
677
|
} catch {}
|
|
678
|
-
return
|
|
678
|
+
return I(e, t, n);
|
|
679
679
|
}
|
|
680
|
-
function
|
|
680
|
+
function N(e) {
|
|
681
681
|
return e instanceof ImageData ? {
|
|
682
682
|
sourceWidth: e.width,
|
|
683
683
|
sourceHeight: e.height
|
|
@@ -692,13 +692,13 @@ function P(e) {
|
|
|
692
692
|
sourceHeight: e.height
|
|
693
693
|
};
|
|
694
694
|
}
|
|
695
|
-
function
|
|
695
|
+
function P() {
|
|
696
696
|
return typeof createImageBitmap == "function";
|
|
697
697
|
}
|
|
698
|
-
function
|
|
698
|
+
function F() {
|
|
699
699
|
return typeof OffscreenCanvas == "function";
|
|
700
700
|
}
|
|
701
|
-
function
|
|
701
|
+
function I(e, t, n) {
|
|
702
702
|
let r = document.createElement("canvas"), i = r.getContext("2d");
|
|
703
703
|
if (!i) throw Error("2D canvas context is not available.");
|
|
704
704
|
return r.width = t, r.height = n, i.drawImage(e, 0, 0, t, n), {
|
|
@@ -710,12 +710,12 @@ function L(e, t, n) {
|
|
|
710
710
|
}
|
|
711
711
|
//#endregion
|
|
712
712
|
//#region src/detect/rotation-fallback.ts
|
|
713
|
-
function
|
|
714
|
-
return e.map((e) =>
|
|
713
|
+
function L(e, t, n) {
|
|
714
|
+
return e.map((e) => z(e, t, n));
|
|
715
715
|
}
|
|
716
|
-
function
|
|
716
|
+
function R(e, t, n, r) {
|
|
717
717
|
if (e.phoneDetected || t.phoneDetections.length === 0) return e;
|
|
718
|
-
let i =
|
|
718
|
+
let i = L(t.phoneDetections, n, r);
|
|
719
719
|
return {
|
|
720
720
|
...e,
|
|
721
721
|
phoneDetected: i.length > 0,
|
|
@@ -723,30 +723,30 @@ function z(e, t, n, r) {
|
|
|
723
723
|
phoneDetections: i
|
|
724
724
|
};
|
|
725
725
|
}
|
|
726
|
-
function
|
|
726
|
+
function z(e, t, n) {
|
|
727
727
|
return {
|
|
728
728
|
...e,
|
|
729
|
-
x:
|
|
730
|
-
y:
|
|
729
|
+
x: B(t - (e.x + e.width), 0, t),
|
|
730
|
+
y: B(n - (e.y + e.height), 0, n)
|
|
731
731
|
};
|
|
732
732
|
}
|
|
733
|
-
function
|
|
733
|
+
function B(e, t, n) {
|
|
734
734
|
return Math.min(Math.max(e, t), n);
|
|
735
735
|
}
|
|
736
736
|
//#endregion
|
|
737
737
|
//#region src/video.ts
|
|
738
|
-
function
|
|
738
|
+
function V(e) {
|
|
739
739
|
return e.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && e.videoWidth > 0 && e.videoHeight > 0 && !e.paused && !e.ended;
|
|
740
740
|
}
|
|
741
|
-
function
|
|
742
|
-
return
|
|
741
|
+
function H(e, t = 1e4) {
|
|
742
|
+
return U(e) ? Promise.resolve() : new Promise((n, r) => {
|
|
743
743
|
let i = window.setTimeout(() => {
|
|
744
744
|
o(), r(/* @__PURE__ */ Error("Timed out waiting for webcam video metadata."));
|
|
745
745
|
}, t), a = window.setInterval(s, 100), o = () => {
|
|
746
746
|
window.clearTimeout(i), window.clearInterval(a), e.removeEventListener("loadedmetadata", c), e.removeEventListener("loadeddata", c), e.removeEventListener("canplay", c), e.removeEventListener("playing", c), e.removeEventListener("resize", c), e.removeEventListener("error", l);
|
|
747
747
|
};
|
|
748
748
|
function s() {
|
|
749
|
-
|
|
749
|
+
U(e) && (o(), n());
|
|
750
750
|
}
|
|
751
751
|
let c = () => {
|
|
752
752
|
s();
|
|
@@ -756,12 +756,12 @@ function U(e, t = 1e4) {
|
|
|
756
756
|
e.addEventListener("loadedmetadata", c, { once: !0 }), e.addEventListener("loadeddata", c, { once: !0 }), e.addEventListener("canplay", c, { once: !0 }), e.addEventListener("playing", c, { once: !0 }), e.addEventListener("resize", c, { once: !0 }), e.addEventListener("error", l, { once: !0 });
|
|
757
757
|
});
|
|
758
758
|
}
|
|
759
|
-
function
|
|
759
|
+
function U(e) {
|
|
760
760
|
return e.readyState >= HTMLMediaElement.HAVE_METADATA && e.videoWidth > 0 && e.videoHeight > 0;
|
|
761
761
|
}
|
|
762
762
|
//#endregion
|
|
763
763
|
//#region src/service/detect-service.ts
|
|
764
|
-
var
|
|
764
|
+
var W = class {
|
|
765
765
|
services;
|
|
766
766
|
primaryInferenceWorker;
|
|
767
767
|
rotationInferenceWorker;
|
|
@@ -778,10 +778,10 @@ var G = class {
|
|
|
778
778
|
await this.load();
|
|
779
779
|
let t = this.services.options, n = t.debug ? performance.now() : 0, r = t.debug ? performance.now() : 0, i = r, a;
|
|
780
780
|
if (this.shouldUseParallelPhoneRotationFallback(t) && this.shouldRunParallelPhoneRotationFallback(t)) {
|
|
781
|
-
let [n, r] = await Promise.all([
|
|
781
|
+
let [n, r] = await Promise.all([M(e), M(e)]);
|
|
782
782
|
i = t.debug ? performance.now() : 0, a = await this.runParallelPhoneRotationFallback(n, r, t);
|
|
783
783
|
} else {
|
|
784
|
-
let n = await
|
|
784
|
+
let n = await M(e);
|
|
785
785
|
i = t.debug ? performance.now() : 0, a = await this.runWorkerInference(this.getInferenceWorker(), n, t, {
|
|
786
786
|
inputRotation: "none",
|
|
787
787
|
phoneRotationFallback: t.phoneRotationFallback && t.phoneRotationFallbackExecution === "sequential"
|
|
@@ -790,9 +790,9 @@ var G = class {
|
|
|
790
790
|
if (t.debug) {
|
|
791
791
|
let e = performance.now();
|
|
792
792
|
console.info("[MonitorDog] detect frame", {
|
|
793
|
-
sourceMs:
|
|
794
|
-
workerRoundtripMs:
|
|
795
|
-
totalMs:
|
|
793
|
+
sourceMs: G(i - r),
|
|
794
|
+
workerRoundtripMs: G(e - i),
|
|
795
|
+
totalMs: G(e - n)
|
|
796
796
|
});
|
|
797
797
|
}
|
|
798
798
|
return a;
|
|
@@ -811,7 +811,7 @@ var G = class {
|
|
|
811
811
|
let t = !1, n, r = this.services.options.detectionIntervalMs, i = async () => {
|
|
812
812
|
if (!t) {
|
|
813
813
|
try {
|
|
814
|
-
if (!this.services.shouldPauseDetection &&
|
|
814
|
+
if (!this.services.shouldPauseDetection && V(e)) {
|
|
815
815
|
let n = await this.detect(e);
|
|
816
816
|
if (t) return;
|
|
817
817
|
try {
|
|
@@ -826,7 +826,7 @@ var G = class {
|
|
|
826
826
|
if (t) return;
|
|
827
827
|
await this.services.detectionEvents.handleDetectionResult(n, e).catch((e) => {
|
|
828
828
|
this.services.options.onError?.(e);
|
|
829
|
-
}),
|
|
829
|
+
}), g(n) && this.services.detectionEvents.clearTransientState();
|
|
830
830
|
}
|
|
831
831
|
} catch (e) {
|
|
832
832
|
this.handleDetectionLoopError(e);
|
|
@@ -842,7 +842,7 @@ var G = class {
|
|
|
842
842
|
let e = this.services.options, t = await this.services.camera.createWebcamStream(e.constraints), n = this.services.camera, r = !e.video, i = e.video ?? document.createElement("video"), a = i.muted, o = i.playsInline, s = i.srcObject;
|
|
843
843
|
i.muted = !0, i.playsInline = !0, i.srcObject = t;
|
|
844
844
|
try {
|
|
845
|
-
await Promise.all([i.play(),
|
|
845
|
+
await Promise.all([i.play(), H(i)]);
|
|
846
846
|
} catch (e) {
|
|
847
847
|
throw n.stopStream(t), i.pause(), r ? i.srcObject = null : (i.muted = a, i.playsInline = o, i.srcObject = s), e;
|
|
848
848
|
}
|
|
@@ -869,7 +869,7 @@ var G = class {
|
|
|
869
869
|
inputRotation: "rotate180",
|
|
870
870
|
phoneRotationFallback: !1
|
|
871
871
|
})]);
|
|
872
|
-
return
|
|
872
|
+
return R(a, o, r, i);
|
|
873
873
|
}
|
|
874
874
|
runWorkerInference(e, t, n, r) {
|
|
875
875
|
return e.run({
|
|
@@ -905,10 +905,10 @@ var G = class {
|
|
|
905
905
|
return /out of memory|oom|memory access out of bounds|cannot enlarge memory|array buffer allocation|bad allocation|allocation failed/i.test(t);
|
|
906
906
|
}
|
|
907
907
|
getInferenceWorker() {
|
|
908
|
-
return this.primaryInferenceWorker ||= new
|
|
908
|
+
return this.primaryInferenceWorker ||= new j(), this.primaryInferenceWorker;
|
|
909
909
|
}
|
|
910
910
|
getRotationInferenceWorker() {
|
|
911
|
-
return this.rotationInferenceWorker ||= new
|
|
911
|
+
return this.rotationInferenceWorker ||= new j(), this.rotationInferenceWorker;
|
|
912
912
|
}
|
|
913
913
|
shouldUseParallelPhoneRotationFallback(e) {
|
|
914
914
|
return e.phoneRotationFallback && e.phoneRotationFallbackExecution === "parallel";
|
|
@@ -946,12 +946,12 @@ var G = class {
|
|
|
946
946
|
await this.getInferenceWorker().load(n);
|
|
947
947
|
}
|
|
948
948
|
};
|
|
949
|
-
function
|
|
949
|
+
function G(e) {
|
|
950
950
|
return Math.round(e * 10) / 10;
|
|
951
951
|
}
|
|
952
952
|
//#endregion
|
|
953
953
|
//#region src/service/webcam-service.ts
|
|
954
|
-
var
|
|
954
|
+
var K = class {
|
|
955
955
|
services;
|
|
956
956
|
isWebcamRunning = !1;
|
|
957
957
|
stopCurrentWebcam;
|
|
@@ -1043,7 +1043,7 @@ var q = class {
|
|
|
1043
1043
|
removeVisibilityListener() {
|
|
1044
1044
|
typeof document > "u" || document.removeEventListener("visibilitychange", this.handleVisibilityChange);
|
|
1045
1045
|
}
|
|
1046
|
-
},
|
|
1046
|
+
}, q = class {
|
|
1047
1047
|
auth;
|
|
1048
1048
|
camera;
|
|
1049
1049
|
detectionEvents;
|
|
@@ -1052,10 +1052,10 @@ var q = class {
|
|
|
1052
1052
|
onCameraDisconnect;
|
|
1053
1053
|
onLoginRequired;
|
|
1054
1054
|
#e = 0;
|
|
1055
|
-
#t =
|
|
1055
|
+
#t = J();
|
|
1056
1056
|
#n;
|
|
1057
1057
|
constructor(e) {
|
|
1058
|
-
this.#n = e, this.camera = new
|
|
1058
|
+
this.#n = e, this.camera = new E(), this.auth = new C(this), this.detectionEvents = new ne(this), this.detect = new W(this), this.webcam = new K(this);
|
|
1059
1059
|
}
|
|
1060
1060
|
get options() {
|
|
1061
1061
|
return Object.freeze({ ...this.#n() });
|
|
@@ -1072,6 +1072,9 @@ var q = class {
|
|
|
1072
1072
|
updateRequiredPasswordFromServer(e) {
|
|
1073
1073
|
this.#n().requiredPassword = e;
|
|
1074
1074
|
}
|
|
1075
|
+
setPhoneConfidenceThreshold(e) {
|
|
1076
|
+
this.#n().phoneConfidenceThreshold = e, this.syncEffectivePhoneConfidenceThreshold();
|
|
1077
|
+
}
|
|
1075
1078
|
degradeInferenceModelForMemoryPressure() {
|
|
1076
1079
|
let e = this.#n();
|
|
1077
1080
|
if (e.inputSize > 416) {
|
|
@@ -1088,14 +1091,18 @@ var q = class {
|
|
|
1088
1091
|
}
|
|
1089
1092
|
applyPolicyItems(e, t) {
|
|
1090
1093
|
let n = { ...this.#t };
|
|
1091
|
-
for (let t of e)
|
|
1092
|
-
this.#t = n, this
|
|
1094
|
+
for (let t of e) X(n, t);
|
|
1095
|
+
this.#t = n, this.syncEffectivePhoneConfidenceThreshold(), this.#n().faceConfidenceThreshold = n.faceDetectionThreshold, this.updateRequiredPasswordFromServer(!1);
|
|
1093
1096
|
}
|
|
1094
1097
|
resetAuthenticatedState() {
|
|
1095
|
-
this.#e = 0, this.#t =
|
|
1098
|
+
this.#e = 0, this.#t = J(), this.#n().requiredPassword = !1, this.syncEffectivePhoneConfidenceThreshold(), this.#n().faceConfidenceThreshold = this.#t.faceDetectionThreshold;
|
|
1099
|
+
}
|
|
1100
|
+
syncEffectivePhoneConfidenceThreshold() {
|
|
1101
|
+
let e = this.#n();
|
|
1102
|
+
e.confidenceThreshold = e.phoneConfidenceThreshold ?? this.#t.mobileDetectionThreshold;
|
|
1096
1103
|
}
|
|
1097
1104
|
};
|
|
1098
|
-
function
|
|
1105
|
+
function J() {
|
|
1099
1106
|
return {
|
|
1100
1107
|
mobileDetectionThreshold: .8,
|
|
1101
1108
|
faceDetectionThreshold: .8,
|
|
@@ -1111,19 +1118,19 @@ function Y() {
|
|
|
1111
1118
|
multiPersonDetectionMode: "auto_lock"
|
|
1112
1119
|
};
|
|
1113
1120
|
}
|
|
1114
|
-
function
|
|
1121
|
+
function Y(e) {
|
|
1115
1122
|
return e === "none";
|
|
1116
1123
|
}
|
|
1117
|
-
function
|
|
1118
|
-
let n = t.policy, r = !
|
|
1124
|
+
function X(e, t) {
|
|
1125
|
+
let n = t.policy, r = !Y(t.policy), i = t.seconds * 1e3, a = "sensitivity" in t ? 1 - t.sensitivity / 100 : void 0;
|
|
1119
1126
|
switch (t.basic_event_uuid) {
|
|
1120
|
-
case
|
|
1127
|
+
case b("mobileDevice"):
|
|
1121
1128
|
e.mobileDetectionEnabled = r, e.mobileDetectionLockDuration = i, e.mobileDetectionMode = n, a !== void 0 && (e.mobileDetectionThreshold = a);
|
|
1122
1129
|
break;
|
|
1123
|
-
case
|
|
1130
|
+
case b("twoFacesDetected"):
|
|
1124
1131
|
e.multiPersonDetectionEnabled = r, e.multiPersonLockDuration = i, e.multiPersonDetectionMode = n, a !== void 0 && (e.faceDetectionThreshold = a);
|
|
1125
1132
|
break;
|
|
1126
|
-
case
|
|
1133
|
+
case b("noFaceDetected"):
|
|
1127
1134
|
e.noPersonDetectionEnabled = r, e.noPersonLockDuration = i, e.noPersonDetectionMode = n;
|
|
1128
1135
|
break;
|
|
1129
1136
|
default: break;
|
|
@@ -1131,7 +1138,7 @@ function Z(e, t) {
|
|
|
1131
1138
|
}
|
|
1132
1139
|
//#endregion
|
|
1133
1140
|
//#region src/index.ts
|
|
1134
|
-
var
|
|
1141
|
+
var Z = class e {
|
|
1135
1142
|
#e;
|
|
1136
1143
|
#t;
|
|
1137
1144
|
#n = "anonymous";
|
|
@@ -1140,16 +1147,16 @@ var Q = class e {
|
|
|
1140
1147
|
#a;
|
|
1141
1148
|
#o;
|
|
1142
1149
|
static async init(t) {
|
|
1143
|
-
return
|
|
1150
|
+
return Q = new e(t), Q;
|
|
1144
1151
|
}
|
|
1145
1152
|
constructor(e) {
|
|
1146
|
-
|
|
1147
|
-
let r =
|
|
1153
|
+
ce(e);
|
|
1154
|
+
let r = se(), i = p(e.runtimeAssetBaseUrl);
|
|
1148
1155
|
this.#t = {
|
|
1149
1156
|
...e,
|
|
1150
1157
|
apiBaseUrl: c(e.apiBaseUrl),
|
|
1151
1158
|
runtimeAssetBaseUrl: i,
|
|
1152
|
-
confidenceThreshold:
|
|
1159
|
+
confidenceThreshold: e.phoneConfidenceThreshold ?? .8,
|
|
1153
1160
|
faceConfidenceThreshold: t,
|
|
1154
1161
|
iouThreshold: n,
|
|
1155
1162
|
maxDetections: 100,
|
|
@@ -1161,7 +1168,7 @@ var Q = class e {
|
|
|
1161
1168
|
phoneRotationFallback: e.phoneRotationFallback ?? !1,
|
|
1162
1169
|
phoneRotationFallbackMinIntervalMs: e.phoneRotationFallbackMinIntervalMs ?? 500,
|
|
1163
1170
|
phoneRotationFallbackExecution: e.phoneRotationFallbackExecution ?? "sequential"
|
|
1164
|
-
}, this.#e = new
|
|
1171
|
+
}, this.#e = new q(() => this.#t), this.#e.onLoginRequired = () => this.resetLoggedOutState(), Object.freeze(this);
|
|
1165
1172
|
}
|
|
1166
1173
|
async load() {
|
|
1167
1174
|
this.assertUsable(), this.assertAuthenticated("loading detection");
|
|
@@ -1233,6 +1240,9 @@ var Q = class e {
|
|
|
1233
1240
|
setEventReportingEnabled(e) {
|
|
1234
1241
|
this.assertUsable(), this.#t.eventReportingEnabled = e, e || this.#e.detectionEvents.reset();
|
|
1235
1242
|
}
|
|
1243
|
+
setPhoneConfidenceThreshold(e) {
|
|
1244
|
+
this.assertUsable(), $(e), this.#e.setPhoneConfidenceThreshold(e);
|
|
1245
|
+
}
|
|
1236
1246
|
getUserPreferences() {
|
|
1237
1247
|
return this.assertUsable(), this.#e.userPreferences;
|
|
1238
1248
|
}
|
|
@@ -1295,7 +1305,7 @@ var Q = class e {
|
|
|
1295
1305
|
});
|
|
1296
1306
|
} catch (e) {
|
|
1297
1307
|
let t = this.createSdkError(this.getStartErrorCode(e), this.getStartErrorMessage(e), e);
|
|
1298
|
-
throw this.transitionToError(t,
|
|
1308
|
+
throw this.transitionToError(t, re(t.code) ? "blocked" : "idle"), this.#t.onError?.(t), t;
|
|
1299
1309
|
}
|
|
1300
1310
|
}
|
|
1301
1311
|
clearSessionState() {
|
|
@@ -1367,36 +1377,40 @@ var Q = class e {
|
|
|
1367
1377
|
return typeof DOMException < "u" && e instanceof DOMException && e.name === "NotReadableError";
|
|
1368
1378
|
}
|
|
1369
1379
|
};
|
|
1370
|
-
function ne(e) {
|
|
1371
|
-
return e === "CAMERA_PERMISSION_DENIED" || e === "CAMERA_READ_FAILED";
|
|
1372
|
-
}
|
|
1373
|
-
var $;
|
|
1374
1380
|
function re(e) {
|
|
1375
|
-
return
|
|
1381
|
+
return e === "CAMERA_PERMISSION_DENIED" || e === "CAMERA_READ_FAILED";
|
|
1376
1382
|
}
|
|
1377
|
-
|
|
1378
|
-
|
|
1383
|
+
var Q;
|
|
1384
|
+
function ie(e) {
|
|
1385
|
+
return Q = new Z(e), Q;
|
|
1379
1386
|
}
|
|
1380
|
-
function ae() {
|
|
1381
|
-
|
|
1382
|
-
return $;
|
|
1387
|
+
async function ae(e) {
|
|
1388
|
+
return Z.init(e);
|
|
1383
1389
|
}
|
|
1384
1390
|
function oe() {
|
|
1391
|
+
if (!Q) throw Error("MonitorDog is not configured. Call MonitorDogDetector.init(), createMonitorDogDetector(), or configureMonitorDogDetector() before using getDetector().");
|
|
1392
|
+
return Q;
|
|
1393
|
+
}
|
|
1394
|
+
function se() {
|
|
1385
1395
|
if (typeof navigator > "u") return !1;
|
|
1386
1396
|
let e = l();
|
|
1387
1397
|
return e === "mobile" || e === "tablet";
|
|
1388
1398
|
}
|
|
1389
|
-
function
|
|
1399
|
+
function ce(e) {
|
|
1390
1400
|
if (!e || typeof e.apiBaseUrl != "string" || e.apiBaseUrl.length === 0) throw Error("MonitorDog apiBaseUrl is required.");
|
|
1391
1401
|
if (typeof e.sessionTokenProvider != "function") throw Error("MonitorDog sessionTokenProvider is required.");
|
|
1392
1402
|
if (typeof e.onDetect != "function") throw Error("MonitorDog onDetect callback is required.");
|
|
1393
1403
|
if (e.runtimeAssetBaseUrl !== void 0 && p(e.runtimeAssetBaseUrl), e.modelInputSize !== void 0 && !d(e.modelInputSize)) throw Error("MonitorDog modelInputSize must be \"auto\", 320, 416, or 640.");
|
|
1394
1404
|
if (e.phoneRotationFallback !== void 0 && typeof e.phoneRotationFallback != "boolean") throw Error("MonitorDog phoneRotationFallback must be a boolean when provided.");
|
|
1395
|
-
if (e.phoneRotationFallbackMinIntervalMs !== void 0 && !
|
|
1405
|
+
if (e.phoneRotationFallbackMinIntervalMs !== void 0 && !le(e.phoneRotationFallbackMinIntervalMs)) throw Error("MonitorDog phoneRotationFallbackMinIntervalMs must be a non-negative finite number when provided.");
|
|
1396
1406
|
if (e.phoneRotationFallbackExecution !== void 0 && e.phoneRotationFallbackExecution !== "sequential" && e.phoneRotationFallbackExecution !== "parallel") throw Error("MonitorDog phoneRotationFallbackExecution must be \"sequential\" or \"parallel\" when provided.");
|
|
1407
|
+
$(e.phoneConfidenceThreshold);
|
|
1397
1408
|
}
|
|
1398
|
-
function
|
|
1409
|
+
function le(e) {
|
|
1399
1410
|
return typeof e == "number" && Number.isFinite(e) && e >= 0;
|
|
1400
1411
|
}
|
|
1412
|
+
function $(e) {
|
|
1413
|
+
if (e !== void 0 && (typeof e != "number" || !Number.isFinite(e) || e < 0 || e > 1)) throw Error("MonitorDog phoneConfidenceThreshold must be a finite number between 0 and 1 when provided.");
|
|
1414
|
+
}
|
|
1401
1415
|
//#endregion
|
|
1402
|
-
export {
|
|
1416
|
+
export { Z as MonitorDogDetector, m as MonitorDogSdkError, ie as configureMonitorDogDetector, ae as createMonitorDogDetector, oe as getDetector, h as isMonitorDogSdkError };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("html2canvas")):typeof define==`function`&&define.amd?define([`exports`,`html2canvas`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.MonitorDogDetector={},e.html2canvas))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e};t=((e,t,i)=>(i=e==null?{}:n(o(e)),c(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)))(t,1);var l=.8,u=.7,d=3e4;function f(e){return typeof e==`string`?e:e.access_token}function p(e){if(typeof e!=`string`)return e.expires_in}function ee(e){if(typeof e!=`string`)return e.expires_at}function te(e){if(e.expiresAt){let t=Date.parse(e.expiresAt);if(!Number.isNaN(t))return t}if(e.expiresIn)return e.expiresIn>1e9?e.expiresIn*1e3:Date.now()+e.expiresIn*1e3}function m(e){return e.replace(/\/+$/,``)}function h(){if(typeof navigator>`u`)return`none`;let e=navigator.userAgent.toLowerCase();return/ipad|tablet/.test(e)?`tablet`:/mobile|iphone|ipod|android/.test(e)?`mobile`:/macintosh|windows|linux/.test(e)?`desktop`:`other`}function g(){if(typeof navigator>`u`)return`none`;let e=navigator.userAgent.toLowerCase(),t=navigator.platform.toLowerCase();return/win/.test(t)||/windows/.test(e)?`windows`:/mac/.test(t)||/mac os/.test(e)?`macos`:/android/.test(e)?`android`:/iphone|ipad|ipod/.test(e)?`ios`:/linux/.test(t)||/linux/.test(e)?`linux`:`other`}function ne(e){return e===`auto`||e===320||e===416||e===640}function re(e,t){let n=e??`auto`;return n===`auto`?t?416:640:n}function _(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw Error(`MonitorDog runtimeAssetBaseUrl must be a non-empty string when provided.`);let n=t.replace(/\/+$/,``);return n.length===0?`/`:n}var v=class extends Error{code;cause;constructor(e,t,n){super(t),this.name=`MonitorDogSdkError`,this.code=e,this.cause=n}};function y(e){return e instanceof v}function b(e){if(e.faceCount===0)return C(`noFaceDetected`,e);if(e.faceCount>=2)return C(`twoFacesDetected`,e);if(e.phoneCount>=1)return C(`mobileDevice`,e)}function x(e){return{...w(e,new Date().toISOString()),properties:{},webcam_imgs:[],monitor_imgs:[]}}function S(e){return e.phoneCount===0&&e.faceCount===1}function C(e,t){let n=w(e,new Date().toISOString());switch(e){case`noFaceDetected`:return{type:e,payload:{...n,properties:{confidence:0,spots:[]}}};case`twoFacesDetected`:return{type:e,payload:{...n,properties:{confidence:T(t.faceDetections),spots:t.faceDetections}}};case`mobileDevice`:return{type:e,payload:{...n,properties:{confidence:T(t.phoneDetections),spots:t.phoneDetections}}}}}function w(e,t){return{basic_event_uuid:E(e),occured_at:t,sended_at:new Date().toISOString(),device_type:h(),device_os:g(),device_id:`browser`}}function T(e){return e.reduce((e,t)=>Math.max(e,t.score),0)}function E(e){switch(e){case`logout`:return`12ca646a-d832-4581-b03c-48f95627507f`;case`login`:return`4c6f98ea-88d8-4215-9b6a-9b3ccb753465`;case`mobileDevice`:return`027af5c9-297d-4a64-983f-4199ca4b9dad`;case`twoFacesDetected`:return`d555efac-7465-4067-8056-611e95385807`;case`noFaceDetected`:return`e2c48c23-36e2-4253-82b1-7f6565fdcfc3`;default:return``}}var D=`MonitorDog token refresh was superseded.`,ie=300*1e3,O=class{services;refreshBeforeMs=ie;periodicRefreshIntervalMs=d;token;tokenExpiresAt;refreshPromise;refreshIntervalId;authSessionId=0;sessionEmail;constructor(e){this.services=e}async login(e){let t=await this.fetchSessionToken(e.email);return this.sessionEmail=e.email,this.setSessionTokenPayload(t),await this.sendUserActivityEvent(`login`),t}async logout(){if(this.token)try{await this.sendUserActivityEvent(`logout`)}finally{this.clearTokens()}}getToken(){return this.token}getTokenExpiresAt(){return this.tokenExpiresAt}getSessionEmail(){return this.sessionEmail}isAuthenticated(){return!!this.token}dispose(){this.clearTokens()}assertAuthenticated(){if(!this.token)throw Error(`MonitorDog login is required before detection.`)}async getValidAccessToken(){if(this.shouldRefreshCurrentToken())try{await this.handleAuthRefresh()}catch(e){if(this.token&&this.tokenExpiresAt&&Date.now()<this.tokenExpiresAt)return this.token;throw e}return this.token}async authorizedFetch(e,t={},n=!0){let r=await this.getValidAccessToken(),i=new Headers(t.headers);r&&(i.set(`authorization`,`Bearer ${r}`),i.set(`Device-Access-Token`,r));let a=await fetch(`${this.services.options.apiBaseUrl}${e}`,{...t,headers:i}),o=await this.getApiErrorCode(a);return a.status===400&&o===4221&&this.handleLoginRequired(),n&&this.shouldRefreshAfterAuthError(a,o)?(await this.handleAuthRefresh(),this.authorizedFetch(e,t,!1)):a}setSessionTokenPayload(e){let t=f(e);if(!t||typeof t!=`string`)throw Error(`MonitorDog SDK token response did not include a token.`);this.setTokens({accessToken:t,expiresIn:p(e),expiresAt:ee(e)})}setTokens(e){this.token=e.accessToken,this.tokenExpiresAt=te(e),this.tokenExpiresAt?this.startPeriodicRefresh():this.stopPeriodicRefresh()}clearTokens(){this.authSessionId+=1,this.token=void 0,this.tokenExpiresAt=void 0,this.refreshPromise=void 0,this.sessionEmail=void 0,this.stopPeriodicRefresh()}async refreshToken(){return this.refreshPromise||=this.refreshAccessToken().finally(()=>{this.refreshPromise=void 0}),this.refreshPromise}async handleAuthRefresh(){try{return await this.refreshToken()}catch(e){if(!this.isRefreshSupersededError(e)){let t=this.createSdkError(`SESSION_TOKEN_FAILED`,`MonitorDog SDK session token refresh failed.`,e);this.services.options.onAuthError?.(t),this.isCurrentTokenExpired()&&(this.clearTokens(),this.services.onLoginRequired?.())}throw e}}async refreshAccessToken(){let e=this.authSessionId,t=this.sessionEmail;if(!t)throw Error(`MonitorDog login email is required to refresh SDK token.`);let n=await this.fetchSessionToken(t),r=f(n);if(!r||typeof r!=`string`)throw Error(`MonitorDog SDK token response did not include a token.`);if(e!==this.authSessionId)throw Error(D);return this.setSessionTokenPayload(n),r}startPeriodicRefresh(){this.refreshIntervalId||=setInterval(()=>{this.refreshPeriodically()},this.periodicRefreshIntervalMs)}stopPeriodicRefresh(){this.refreshIntervalId&&=(clearInterval(this.refreshIntervalId),void 0)}async refreshPeriodically(){if(!(!this.token||!this.shouldRefreshCurrentToken()))try{await this.handleAuthRefresh()}catch{}}shouldRefreshCurrentToken(){return!!(this.token&&this.tokenExpiresAt&&Date.now()>=this.tokenExpiresAt-this.refreshBeforeMs)}isCurrentTokenExpired(){return!!(this.tokenExpiresAt&&Date.now()>=this.tokenExpiresAt)}isRefreshSupersededError(e){return e instanceof Error&&e.message===D}async fetchSessionToken(e){let t=this.services.options.sessionTokenProvider;if(!t)throw Error(`MonitorDog sessionTokenProvider is required for SDK login.`);return t({email:e})}async getApiErrorCode(e){if(e.status===400)try{let t=await e.clone().json();if(typeof t==`object`&&t&&`code`in t&&typeof t.code==`number`)return t.code}catch{return}}shouldRefreshAfterAuthError(e,t){return e.status===401?!0:e.status===400&&t===422}handleLoginRequired(){this.clearTokens(),this.services.onLoginRequired?.();let e=this.createSdkError(`NOT_LOGGED_IN`,`MonitorDog login is required.`);throw this.services.options.onAuthError?.(e),e}async sendUserActivityEvent(e){try{let t=await this.authorizedFetch(`/event`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(x(e))});if(!t.ok)throw Error(`MonitorDog ${e} event failed: ${t.status}`)}catch(t){let n=this.createSdkError(k(e),`MonitorDog ${e} event failed.`,t);if(this.services.options.onAuthError?.(n),e===`logout`)throw n}}createSdkError(e,t,n){return n instanceof v?n:new v(e,t,n)}};function k(e){return e===`logout`?`LOGOUT_FAILED`:`SESSION_TOKEN_FAILED`}var A=/(obs|virtual|xsplit|manycam|splitcam|webcammax|fake|loopback|camtwist|e2esoft|vcam|droidcam|iriun|epoccam|camo|mmhmm|nvidia broadcast|streamlabs|bandicam|wirecast|chromacam|youcam|cyberlink|altserver|logi capture|elgato|streamfx|screen capture|desktop capture)/i,j=class{async createWebcamStream(e){if(!navigator.mediaDevices?.getUserMedia)throw Error(`getUserMedia is not available in this browser.`);let t=this.getBaseWebcamConstraints(e),n=await this.createFirstCameraConstraints(t);try{return await this.getUserMedia(n)}catch(e){if(this.isPermissionError(e)||this.isCameraRequestTimeoutError(e))throw e;return this.createFallbackWebcamStream(n,e)}}stopStream(e){e.getTracks().forEach(e=>e.stop())}watchStreamDeviceDisconnect(e,t,n=1e3){let r=e.getVideoTracks()[0],i=r?.getSettings().deviceId;if(!r&&!i)return()=>{};let a=!1,o,s=()=>{a||(a=!0,t())},c=()=>{i&&(o&&clearTimeout(o),o=setTimeout(()=>{o=void 0,this.handleDeviceChange(i,s)},n))};return r?.addEventListener(`ended`,s),navigator.mediaDevices?.addEventListener?.(`devicechange`,c),()=>{o&&clearTimeout(o),r?.removeEventListener(`ended`,s),navigator.mediaDevices?.removeEventListener?.(`devicechange`,c)}}isCameraInUse(e){let t=e?.srcObject;return t instanceof MediaStream?t.getTracks().some(e=>e.readyState===`live`):!1}async getVideoInputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`):[]}async getRealVideoInputDevices(){let e=await this.getVideoInputDevices(),t=e.filter(e=>!this.isVirtualCamera(e));return t.length>0?t:e}async createFallbackWebcamStream(e,t){let n=await this.getRealVideoInputDevices();if(n.length===0)throw t;let r=n[0],i=t;if(!r?.deviceId)throw i;let a=await this.getWebcamNaturalAspectRatio(r.deviceId),o=this.generateResolutionList(a,720);for(let t of o)try{return await this.getUserMedia(this.createDeviceConstraints(e,r.deviceId,t))}catch(e){i=e}throw i}async handleDeviceChange(e,t){try{(await this.getVideoInputDevices()).some(t=>t.deviceId===e)||t()}catch{}}getBaseWebcamConstraints(e){return e??{audio:!1,video:{facingMode:`user`}}}async createFirstCameraConstraints(e){let t=typeof e.video==`object`?e.video:{};if(`deviceId`in t||`facingMode`in t)return e;let n=(await this.getRealVideoInputDevices())[0];return n?.deviceId?this.createDeviceConstraints(e,n.deviceId):e}async getWebcamNaturalAspectRatio(e){let t;try{t=await this.getUserMedia({audio:!1,video:{deviceId:{exact:e}}});let n=t.getVideoTracks()[0]?.getSettings();if(n?.width&&n.height)return n.width/n.height}catch{}finally{t?.getTracks().forEach(e=>e.stop())}return 16/9}generateResolutionList(e,t){return[t,640,600,480,320,240].map(t=>({width:t,height:Math.max(1,Math.round(t/e))})).filter(e=>e.width<=t&&e.height>=120&&e.height<=1080)}createDeviceConstraints(e,t,n){let r=typeof e.video==`object`?e.video:{};return{...e,audio:e.audio??!1,video:{...r,deviceId:{exact:t},...n?{width:{min:n.width,ideal:n.width},height:{min:n.height,ideal:n.height}}:{}}}}isVirtualCamera(e){let t=e.label.toLowerCase();return t?A.test(t):!1}isPermissionError(e){return e instanceof DOMException&&(e.name===`NotAllowedError`||e.name===`SecurityError`)}getUserMedia(e,t=15e3){let n=!1,r,i=navigator.mediaDevices.getUserMedia(e).then(e=>{if(n)throw this.stopStream(e),Error(`Camera permission request timed out.`);return e}),a=new Promise((e,i)=>{r=setTimeout(()=>{n=!0,i(Error(`Camera permission request timed out.`))},t)});return Promise.race([i,a]).finally(()=>{r&&clearTimeout(r)})}isCameraRequestTimeoutError(e){return e instanceof Error&&e.message===`Camera permission request timed out.`}};function M(e){if(e.videoWidth===0||e.videoHeight===0)throw Error(`Video frame is not ready for capture.`);let t=document.createElement(`canvas`),n=t.getContext(`2d`);if(!n)throw Error(`2D canvas context is not available.`);return t.width=e.videoWidth,t.height=e.videoHeight,n.drawImage(e,0,0,t.width,t.height),new Promise((e,n)=>{t.toBlob(t=>{if(!t){n(Error(`Failed to capture video frame.`));return}e(t)},`image/jpeg`,.9)})}async function N(){if(typeof document>`u`||!document.body)return null;let e=await(0,t.default)(document.body,{backgroundColor:`#ffffff`,useCORS:!0});return new Promise(t=>{e.toBlob(t,`image/jpeg`,.9)})}var P=class e{static NO_FACE_STARTUP_GRACE_MS=1500;services;detectionEventLocked=!1;detectionEventInFlight=!1;detectionEventLockTimeoutId;noFaceStartedAt;suppressNoFaceUntil=0;constructor(e){this.services=e}async handleDetectionResult(e,t){if(!this.services.options.eventReportingEnabled){this.reset();return}if(S(e)){this.noFaceStartedAt=void 0,this.clearLock();return}if(this.detectionEventLocked||this.detectionEventInFlight)return;let n=b(e);if(!n){this.noFaceStartedAt=void 0;return}if(!(n.type===`noFaceDetected`&&!this.hasNoFaceDelayElapsed())&&(n.type!==`noFaceDetected`&&(this.noFaceStartedAt=void 0),this.shouldSendEvent(n.type,e))){this.lock(n.type),this.detectionEventInFlight=!0;try{let e=await this.uploadWebcamImage(t);e&&(n.payload.webcam_imgs=e);let r=await this.uploadMonitorImage();if(r&&(n.payload.monitor_imgs=r),this.services.options.debug){console.log(n.payload);return}let i=await this.services.auth.authorizedFetch(`/event`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.payload)});if(!i.ok)throw Error(`MonitorDog event request failed: ${i.status}`)}finally{this.detectionEventInFlight=!1}}}reset(){this.clearLock(),this.noFaceStartedAt=void 0,this.suppressNoFaceUntil=0}resetForWebcamStartup(){this.clearLock(),this.noFaceStartedAt=void 0,this.suppressNoFaceUntil=Date.now()+e.NO_FACE_STARTUP_GRACE_MS}clearTransientState(){this.noFaceStartedAt=void 0}async uploadWebcamImage(e){if(!(e instanceof HTMLVideoElement)||e.videoWidth===0||e.videoHeight===0)return;let t=await M(e);return this.uploadImage(t,`webcam.jpg`)}async uploadMonitorImage(){let e=this.services.options.captureMonitorImage?await this.services.options.captureMonitorImage():await N();if(!e)return;let t=typeof File<`u`&&e instanceof File?e.name:`monitor.jpg`;return this.uploadImage(e,t)}async uploadImage(e,t){let n=new FormData;n.append(`files`,e,t);let r=await this.services.auth.authorizedFetch(`/file/image`,{method:`POST`,body:n});if(!r.ok)throw Error(`MonitorDog image upload failed: ${r.status}`);return r.json()}shouldSendEvent(e,t){switch(e){case`mobileDevice`:return this.services.userPreferences.mobileDetectionEnabled&&F(t.phoneDetections)>=this.services.userPreferences.mobileDetectionThreshold;case`twoFacesDetected`:return this.services.userPreferences.multiPersonDetectionEnabled&&F(t.faceDetections)>=this.services.userPreferences.faceDetectionThreshold;case`noFaceDetected`:return this.services.userPreferences.noPersonDetectionEnabled}}lock(e){this.clearLock(),this.detectionEventLocked=!0;let t=this.getLockDuration(e);if(t<=0){this.detectionEventLocked=!1;return}this.detectionEventLockTimeoutId=setTimeout(()=>{this.detectionEventLocked=!1,this.detectionEventLockTimeoutId=void 0},t)}clearLock(){this.detectionEventLockTimeoutId&&=(clearTimeout(this.detectionEventLockTimeoutId),void 0),this.detectionEventLocked=!1}hasNoFaceDelayElapsed(){if(Date.now()<this.suppressNoFaceUntil)return this.noFaceStartedAt=void 0,!1;if(this.services.noFaceEventDelayMs<=0)return!0;let e=Date.now();return this.noFaceStartedAt===void 0?(this.noFaceStartedAt=e,!1):e-this.noFaceStartedAt>=this.services.noFaceEventDelayMs}getLockDuration(e){switch(e){case`mobileDevice`:return this.services.userPreferences.mobileDetectionLockDuration;case`twoFacesDetected`:return this.services.userPreferences.multiPersonLockDuration;case`noFaceDetected`:return this.services.userPreferences.noPersonLockDuration}}};function F(e){return e.reduce((e,t)=>Math.max(e,t.confidence),0)}var I=``+(typeof document>`u`&&typeof location>`u`?require("url").pathToFileURL(__dirname+`/assets/inference-worker-ekAaVxft.js`).href:new URL(`assets/inference-worker-ekAaVxft.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),L=class{worker;nextRequestId=1;pendingRequests=new Map;async load(e){let t={id:this.nextRequestId,type:`load`,model:e};await this.request(t)}run(e){let t=e.source.kind===`bitmap`?[e.source.bitmap]:[e.source.data.buffer];return this.request({id:this.nextRequestId,type:`run`,source:e.source,inputSize:e.inputSize,inputType:e.inputType,confidenceThreshold:e.confidenceThreshold,faceConfidenceThreshold:e.faceConfidenceThreshold,iouThreshold:e.iouThreshold,maxDetections:e.maxDetections,debug:e.debug,inputRotation:e.inputRotation??`none`,phoneRotationFallback:e.phoneRotationFallback,phoneRotationFallbackMinIntervalMs:e.phoneRotationFallbackMinIntervalMs},t)}terminate(){this.rejectPendingRequests(Error(`Inference worker was terminated.`)),this.worker?.terminate(),this.worker=void 0}request(e,t=[]){let n=this.getWorker();return this.nextRequestId+=1,new Promise((r,i)=>{this.pendingRequests.set(e.id,{resolve:r,reject:i}),n.postMessage(e,t)})}getWorker(){return this.worker||(this.worker=new Worker(I,{name:`MonitorDogInference`,type:`module`}),this.worker.addEventListener(`message`,this.handleMessage),this.worker.addEventListener(`error`,this.handleError),this.worker.addEventListener(`messageerror`,this.handleError)),this.worker}handleMessage=e=>{let t=e.data,n=this.pendingRequests.get(t.id);if(n){if(this.pendingRequests.delete(t.id),!t.ok){n.reject(Error(t.error));return}n.resolve(t.result)}};handleError=e=>{let t=e instanceof ErrorEvent?e.message:`Inference worker message failed.`;this.rejectPendingRequests(Error(t)),this.worker?.terminate(),this.worker=void 0};rejectPendingRequests(e){for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};async function R(e){let{sourceWidth:t,sourceHeight:n}=z(e);if(e instanceof ImageData)return{kind:`rgba`,data:new Uint8ClampedArray(e.data),sourceWidth:t,sourceHeight:n};if(B()&&V())try{return{kind:`bitmap`,bitmap:await createImageBitmap(e),sourceWidth:t,sourceHeight:n}}catch{}return H(e,t,n)}function z(e){return e instanceof ImageData?{sourceWidth:e.width,sourceHeight:e.height}:e instanceof HTMLVideoElement?{sourceWidth:e.videoWidth,sourceHeight:e.videoHeight}:e instanceof HTMLImageElement?{sourceWidth:e.naturalWidth,sourceHeight:e.naturalHeight}:{sourceWidth:e.width,sourceHeight:e.height}}function B(){return typeof createImageBitmap==`function`}function V(){return typeof OffscreenCanvas==`function`}function H(e,t,n){let r=document.createElement(`canvas`),i=r.getContext(`2d`);if(!i)throw Error(`2D canvas context is not available.`);return r.width=t,r.height=n,i.drawImage(e,0,0,t,n),{kind:`rgba`,data:i.getImageData(0,0,t,n).data,sourceWidth:t,sourceHeight:n}}function U(e,t,n){return e.map(e=>W(e,t,n))}function ae(e,t,n,r){if(e.phoneDetected||t.phoneDetections.length===0)return e;let i=U(t.phoneDetections,n,r);return{...e,phoneDetected:i.length>0,phoneCount:i.length,phoneDetections:i}}function W(e,t,n){return{...e,x:G(t-(e.x+e.width),0,t),y:G(n-(e.y+e.height),0,n)}}function G(e,t,n){return Math.min(Math.max(e,t),n)}function K(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&e.videoWidth>0&&e.videoHeight>0&&!e.paused&&!e.ended}function q(e,t=1e4){return J(e)?Promise.resolve():new Promise((n,r)=>{let i=window.setTimeout(()=>{o(),r(Error(`Timed out waiting for webcam video metadata.`))},t),a=window.setInterval(s,100),o=()=>{window.clearTimeout(i),window.clearInterval(a),e.removeEventListener(`loadedmetadata`,c),e.removeEventListener(`loadeddata`,c),e.removeEventListener(`canplay`,c),e.removeEventListener(`playing`,c),e.removeEventListener(`resize`,c),e.removeEventListener(`error`,l)};function s(){J(e)&&(o(),n())}let c=()=>{s()},l=()=>{o(),r(Error(`Failed to load webcam video stream.`))};e.addEventListener(`loadedmetadata`,c,{once:!0}),e.addEventListener(`loadeddata`,c,{once:!0}),e.addEventListener(`canplay`,c,{once:!0}),e.addEventListener(`playing`,c,{once:!0}),e.addEventListener(`resize`,c,{once:!0}),e.addEventListener(`error`,l,{once:!0})})}function J(e){return e.readyState>=HTMLMediaElement.HAVE_METADATA&&e.videoWidth>0&&e.videoHeight>0}var oe=class{services;primaryInferenceWorker;rotationInferenceWorker;loadPromise;lastInferenceMemoryErrorAt=0;lastParallelPhoneRotationFallbackAt=-1/0;constructor(e){this.services=e}async load(){this.loadPromise||=this.loadInferenceWorker(),await this.loadPromise}async detect(e){await this.load();let t=this.services.options,n=t.debug?performance.now():0,r=t.debug?performance.now():0,i=r,a;if(this.shouldUseParallelPhoneRotationFallback(t)&&this.shouldRunParallelPhoneRotationFallback(t)){let[n,r]=await Promise.all([R(e),R(e)]);i=t.debug?performance.now():0,a=await this.runParallelPhoneRotationFallback(n,r,t)}else{let n=await R(e);i=t.debug?performance.now():0,a=await this.runWorkerInference(this.getInferenceWorker(),n,t,{inputRotation:`none`,phoneRotationFallback:t.phoneRotationFallback&&t.phoneRotationFallbackExecution===`sequential`})}if(t.debug){let e=performance.now();console.info(`[MonitorDog] detect frame`,{sourceMs:Y(i-r),workerRoundtripMs:Y(e-i),totalMs:Y(e-n)})}return a}toPublicResult(e){return{faceDetected:e.faceDetected,phoneDetected:e.phoneDetected,faceCount:e.faceCount,phoneCount:e.phoneCount,faceDetections:e.faceDetections,phoneDetections:e.phoneDetections}}detectVideo(e){let t=!1,n,r=this.services.options.detectionIntervalMs,i=async()=>{if(!t){try{if(!this.services.shouldPauseDetection&&K(e)){let n=await this.detect(e);if(t)return;try{await this.services.options.onDetect({...this.toPublicResult(n),video:e,timestamp:e.currentTime})}catch(e){this.services.options.onError?.(e)}if(t)return;await this.services.detectionEvents.handleDetectionResult(n,e).catch(e=>{this.services.options.onError?.(e)}),S(n)&&this.services.detectionEvents.clearTransientState()}}catch(e){this.handleDetectionLoopError(e)}t||(n=setTimeout(i,r))}};return i(),{stop(){t=!0,n&&clearTimeout(n)}}}async startWebcamDetection(){let e=this.services.options,t=await this.services.camera.createWebcamStream(e.constraints),n=this.services.camera,r=!e.video,i=e.video??document.createElement(`video`),a=i.muted,o=i.playsInline,s=i.srcObject;i.muted=!0,i.playsInline=!0,i.srcObject=t;try{await Promise.all([i.play(),q(i)])}catch(e){throw n.stopStream(t),i.pause(),r?i.srcObject=null:(i.muted=a,i.playsInline=o,i.srcObject=s),e}this.services.detectionEvents.resetForWebcamStartup();let c=this.detectVideo(i),l=!1,u=n.watchStreamDeviceDisconnect(t,()=>{d(),this.services.onCameraDisconnect?.()}),d=()=>{l||(l=!0,u(),c.stop(),this.services.detectionEvents.reset(),n.stopStream(t),i.pause(),r?i.srcObject=null:(i.muted=a,i.playsInline=o,i.srcObject=s))};return{stream:t,video:i,stop:d}}dispose(){this.primaryInferenceWorker?.terminate(),this.rotationInferenceWorker?.terminate(),this.primaryInferenceWorker=void 0,this.rotationInferenceWorker=void 0,this.loadPromise=void 0,this.lastParallelPhoneRotationFallbackAt=-1/0,this.services.detectionEvents.reset()}async runParallelPhoneRotationFallback(e,t,n){let r=e.sourceWidth,i=e.sourceHeight,[a,o]=await Promise.all([this.runWorkerInference(this.getInferenceWorker(),e,n,{inputRotation:`none`,phoneRotationFallback:!1}),this.runWorkerInference(this.getRotationInferenceWorker(),t,n,{inputRotation:`rotate180`,phoneRotationFallback:!1})]);return ae(a,o,r,i)}runWorkerInference(e,t,n,r){return e.run({source:t,inputSize:n.inputSize,inputType:n.inputType,confidenceThreshold:n.confidenceThreshold,faceConfidenceThreshold:n.faceConfidenceThreshold,iouThreshold:n.iouThreshold,maxDetections:n.maxDetections,debug:!!n.debug,inputRotation:r.inputRotation,phoneRotationFallback:r.phoneRotationFallback,phoneRotationFallbackMinIntervalMs:n.phoneRotationFallbackMinIntervalMs})}handleDetectionLoopError(e){this.isInferenceMemoryError(e)&&this.recoverFromInferenceMemoryError(),this.services.options.onError?.(e)}recoverFromInferenceMemoryError(){this.degradeModelForMemoryPressure(),this.resetInferenceWorker();let e=Date.now();e-this.lastInferenceMemoryErrorAt<1e4||(this.lastInferenceMemoryErrorAt=e)}resetInferenceWorker(){this.primaryInferenceWorker?.terminate(),this.rotationInferenceWorker?.terminate(),this.primaryInferenceWorker=void 0,this.rotationInferenceWorker=void 0,this.loadPromise=void 0,this.lastParallelPhoneRotationFallbackAt=-1/0}degradeModelForMemoryPressure(){this.services.degradeInferenceModelForMemoryPressure()}isInferenceMemoryError(e){let t=e instanceof Error?e.message:String(e);return/out of memory|oom|memory access out of bounds|cannot enlarge memory|array buffer allocation|bad allocation|allocation failed/i.test(t)}getInferenceWorker(){return this.primaryInferenceWorker||=new L,this.primaryInferenceWorker}getRotationInferenceWorker(){return this.rotationInferenceWorker||=new L,this.rotationInferenceWorker}shouldUseParallelPhoneRotationFallback(e){return e.phoneRotationFallback&&e.phoneRotationFallbackExecution===`parallel`}shouldRunParallelPhoneRotationFallback(e){let t=performance.now();return t-this.lastParallelPhoneRotationFallbackAt<e.phoneRotationFallbackMinIntervalMs?!1:(this.lastParallelPhoneRotationFallbackAt=t,!0)}async loadInferenceWorker(){try{await this.loadInferenceWorkerWithOptions()}catch(e){if(!this.isInferenceMemoryError(e))throw e;this.recoverFromInferenceMemoryError();try{await this.loadInferenceWorkerWithOptions()}catch(e){throw this.recoverFromInferenceMemoryError(),e}}}async loadInferenceWorkerWithOptions(){let e=await this.services.auth.getValidAccessToken();if(!e)throw Error(`MonitorDog login is required before loading detection.`);let t=this.services.options,n={apiBaseUrl:t.apiBaseUrl,accessToken:e,inputSize:t.inputSize,runtimeAssetBaseUrl:t.runtimeAssetBaseUrl};if(this.shouldUseParallelPhoneRotationFallback(t)){await Promise.all([this.getInferenceWorker().load(n),this.getRotationInferenceWorker().load(n)]);return}await this.getInferenceWorker().load(n)}};function Y(e){return Math.round(e*10)/10}var se=class{services;isWebcamRunning=!1;stopCurrentWebcam;startPromise;shouldRun=!1;resumeWhenUnpaused=!1;handleVisibilityChange=()=>{this.syncPauseState()};constructor(e){this.services=e,this.services.onCameraDisconnect=()=>this.handleCameraDisconnect()}get isRunning(){return this.isWebcamRunning}get isStarting(){return!!this.startPromise}async start(){if(this.services.auth.assertAuthenticated(),this.shouldRun=!0,this.addVisibilityListener(),!this.isWebcamRunning){if(this.services.shouldPauseDetection){this.resumeWhenUnpaused=!0;return}await this.ensureStarted()}}stop(){this.shouldRun=!1,this.resumeWhenUnpaused=!1,this.removeVisibilityListener(),this.services.detectionEvents.reset(),this.stopWebcam()}async retryConnection(){await this.start()}async syncPauseState(){if(this.shouldRun){if(this.services.shouldPauseDetection){this.isWebcamRunning&&(this.resumeWhenUnpaused=!0,this.stopWebcam());return}if(this.resumeWhenUnpaused&&!this.isWebcamRunning){this.resumeWhenUnpaused=!1;try{await this.ensureStarted()}catch{this.shouldRun=!1}}}}syncBackgroundPreference(){this.services.options.runInBackground?this.removeVisibilityListener():this.shouldRun&&this.addVisibilityListener(),this.syncPauseState()}async ensureStarted(){this.isWebcamRunning||(this.startPromise||=this.startWebcam().finally(()=>{this.startPromise=void 0}),await this.startPromise)}async startWebcam(){try{let e=await this.services.detect.startWebcamDetection();if(!this.shouldRun){e.stop();return}this.isWebcamRunning=!0,this.stopCurrentWebcam=e.stop}catch(e){throw this.services.options.onError?.(e),e}}stopWebcam(){this.stopCurrentWebcam?.(),this.stopCurrentWebcam=void 0,this.isWebcamRunning=!1}async handleCameraDisconnect(){if(this.isWebcamRunning&&(this.stopWebcam(),this.shouldRun)){if(this.services.shouldPauseDetection){this.resumeWhenUnpaused=!0;return}try{await this.ensureStarted()}catch(e){this.services.options.onError?.(e)}}}addVisibilityListener(){this.services.options.runInBackground||typeof document>`u`||document.addEventListener(`visibilitychange`,this.handleVisibilityChange)}removeVisibilityListener(){typeof document>`u`||document.removeEventListener(`visibilitychange`,this.handleVisibilityChange)}},ce=class{auth;camera;detectionEvents;detect;webcam;onCameraDisconnect;onLoginRequired;#e=0;#t=X();#n;constructor(e){this.#n=e,this.camera=new j,this.auth=new O(this),this.detectionEvents=new P(this),this.detect=new oe(this),this.webcam=new se(this)}get options(){return Object.freeze({...this.#n()})}get noFaceEventDelayMs(){return this.#e}get userPreferences(){return Object.freeze({...this.#t})}updateNoFaceEventDelayFromServer(e){this.#e=e}updateRequiredPasswordFromServer(e){this.#n().requiredPassword=e}degradeInferenceModelForMemoryPressure(){let e=this.#n();if(e.inputSize>416){e.inputSize=416;return}e.inputSize>320&&(e.inputSize=320)}get shouldPauseForHiddenPage(){return!this.options.runInBackground&&typeof document<`u`&&document.hidden}get shouldPauseDetection(){return this.shouldPauseForHiddenPage}applyPolicyItems(e,t){let n={...this.#t};for(let t of e)ue(n,t);this.#t=n,this.#n().confidenceThreshold=n.mobileDetectionThreshold,this.#n().faceConfidenceThreshold=n.faceDetectionThreshold,this.updateRequiredPasswordFromServer(!1)}resetAuthenticatedState(){this.#e=0,this.#t=X(),this.#n().requiredPassword=!1,this.#n().confidenceThreshold=this.#t.mobileDetectionThreshold,this.#n().faceConfidenceThreshold=this.#t.faceDetectionThreshold}};function X(){return{mobileDetectionThreshold:.8,faceDetectionThreshold:.8,language:`en`,mobileDetectionEnabled:!0,noPersonDetectionEnabled:!0,multiPersonDetectionEnabled:!0,noPersonLockDuration:0,multiPersonLockDuration:0,mobileDetectionLockDuration:0,mobileDetectionMode:`auto_lock`,noPersonDetectionMode:`auto_lock`,multiPersonDetectionMode:`auto_lock`}}function le(e){return e===`none`}function ue(e,t){let n=t.policy,r=!le(t.policy),i=t.seconds*1e3,a=`sensitivity`in t?1-t.sensitivity/100:void 0;switch(t.basic_event_uuid){case E(`mobileDevice`):e.mobileDetectionEnabled=r,e.mobileDetectionLockDuration=i,e.mobileDetectionMode=n,a!==void 0&&(e.mobileDetectionThreshold=a);break;case E(`twoFacesDetected`):e.multiPersonDetectionEnabled=r,e.multiPersonLockDuration=i,e.multiPersonDetectionMode=n,a!==void 0&&(e.faceDetectionThreshold=a);break;case E(`noFaceDetected`):e.noPersonDetectionEnabled=r,e.noPersonLockDuration=i,e.noPersonDetectionMode=n;break;default:break}}var Z=class e{#e;#t;#n=`anonymous`;#r=`idle`;#i=`idle`;#a;#o;static async init(t){return $=new e(t),$}constructor(e){he(e);let t=me(),n=_(e.runtimeAssetBaseUrl);this.#t={...e,apiBaseUrl:m(e.apiBaseUrl),runtimeAssetBaseUrl:n,confidenceThreshold:l,faceConfidenceThreshold:l,iouThreshold:u,maxDetections:100,inputSize:re(e.modelInputSize,t),inputType:`float32`,detectionIntervalMs:e.detectionIntervalMs??300,requiredPassword:!1,eventReportingEnabled:e.eventReportingEnabled??!0,phoneRotationFallback:e.phoneRotationFallback??!1,phoneRotationFallbackMinIntervalMs:e.phoneRotationFallbackMinIntervalMs??500,phoneRotationFallbackExecution:e.phoneRotationFallbackExecution??`sequential`},this.#e=new ce(()=>this.#t),this.#e.onLoginRequired=()=>this.resetLoggedOutState(),Object.freeze(this)}async load(){this.assertUsable(),this.assertAuthenticated(`loading detection`);try{this.updateState({runtime:`loading`,lastError:void 0}),await this.#e.detect.load(),this.updateState({runtime:`idle`,lastError:void 0})}catch(e){let t=this.createSdkError(`MODEL_LOAD_FAILED`,`MonitorDog detection model failed to load.`,e);throw this.transitionToError(t),this.#t.onError?.(t),t}}async login(e){this.assertUsable();let t;try{t=await this.#e.auth.login(e)}catch(e){let t=this.createSdkError(`SESSION_TOKEN_FAILED`,`MonitorDog SDK session token could not be created.`,e);throw this.transitionToError(t),this.#t.onAuthError?.(t),t}try{await this.completeAuthenticatedLogin()}catch(e){let t=this.createSdkError(`ACCOUNT_POLICY_FAILED`,`MonitorDog account or policy could not be loaded.`,e);throw this.rollbackAuthenticatedLogin(),this.transitionToError(t),this.#t.onAuthError?.(t),t}return this.updateState({session:`authenticated`,runtime:this.#r===`stopped`?`stopped`:`idle`,camera:this.#e.webcam.isRunning?`active`:`idle`,lastError:void 0}),t}async logout(){if(this.assertUsable(),this.isDetectorRunning())throw this.lifecycleError(`DETECTOR_RUNNING`,`MonitorDog detector is running. Call stop() before logout().`);if(!this.#e.auth.getToken()){this.clearSessionState();return}try{await this.#e.auth.logout(),this.clearSessionState()}catch(e){let t=this.createSdkError(`LOGOUT_FAILED`,`MonitorDog logout failed.`,e);throw this.transitionToError(t),this.#t.onAuthError?.(t),t}finally{this.#e.auth.getToken()||(this.#n=`anonymous`)}}async start(){this.assertUsable(),this.assertAuthenticated(`starting detection`),!this.isDetectorRunning()&&(this.#o||=this.startRuntime().finally(()=>{this.#o=void 0}),await this.#o)}stop(){this.assertUsable(),this.hasRuntimeToStop()&&(this.stopLocalRuntime(),this.updateState({runtime:this.#n===`authenticated`?`stopped`:`idle`,camera:`idle`,lastError:void 0}))}setRunInBackground(e){this.assertUsable(),this.#t.runInBackground=e,this.#e.webcam.syncBackgroundPreference()}setEventReportingEnabled(e){this.assertUsable(),this.#t.eventReportingEnabled=e,e||this.#e.detectionEvents.reset()}getUserPreferences(){return this.assertUsable(),this.#e.userPreferences}getState(){return Object.freeze({session:this.#n,runtime:this.#r,camera:this.#i,tokenExpiresAt:this.#e.auth.getTokenExpiresAt(),email:this.#e.auth.getSessionEmail(),lastError:this.#a})}dispose(){this.#r!==`disposed`&&(this.stopLocalRuntime(),this.#e.detect.dispose(),this.#e.auth.dispose(),this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`disposed`,camera:`idle`,lastError:void 0}))}async completeAuthenticatedLogin(){let e=await this.#e.auth.authorizedFetch(`/account/me`,{method:`GET`,headers:{"content-type":`application/json`}});if(!e.ok)throw Error(`MonitorDog account request failed: ${e.status}`);let t=await e.json(),n=await this.#e.auth.authorizedFetch(`/account/${t.uuid}/lock_policy`,{method:`GET`,headers:{"content-type":`application/json`}});if(!n.ok)throw Error(`MonitorDog lock policy request failed: ${n.status}`);let r=await n.json();this.#e.applyPolicyItems(r,t)}resetLoggedOutState(){this.stopLocalRuntime(),this.#e.detect.dispose(),this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`idle`,camera:`idle`,lastError:void 0})}rollbackAuthenticatedLogin(){this.#e.auth.dispose(),this.#e.resetAuthenticatedState()}async startRuntime(){try{this.updateState({runtime:`loading`,camera:`idle`,lastError:void 0}),await this.#e.detect.load(),this.updateState({runtime:`starting`,camera:`requesting`}),await this.#e.webcam.start(),this.updateState({runtime:`running`,camera:this.#e.shouldPauseDetection?`idle`:`active`,lastError:void 0})}catch(e){let t=this.createSdkError(this.getStartErrorCode(e),this.getStartErrorMessage(e),e);throw this.transitionToError(t,Q(t.code)?`blocked`:`idle`),this.#t.onError?.(t),t}}clearSessionState(){this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`idle`,camera:`idle`,lastError:void 0})}stopLocalRuntime(){this.#e.webcam.stop()}assertUsable(){if(this.#r===`disposed`)throw this.lifecycleError(`ALREADY_DISPOSED`,`MonitorDog detector instance has already been disposed.`,void 0,`disposed`)}assertAuthenticated(e){if(!this.#e.auth.isAuthenticated())throw this.lifecycleError(`NOT_LOGGED_IN`,`MonitorDog login is required before ${e}.`)}lifecycleError(e,t,n,r=`error`){let i=this.createSdkError(e,t,n);return r===`error`?this.transitionToError(i):this.updateState({runtime:r,lastError:i},!0),i}transitionToError(e,t=this.#i){this.updateState({runtime:`error`,camera:t,lastError:e},!0)}updateState(e,t=!1){let n=!1;e.session!==void 0&&e.session!==this.#n&&(this.#n=e.session,n=!0),e.runtime!==void 0&&e.runtime!==this.#r&&(this.#r=e.runtime,n=!0),e.camera!==void 0&&e.camera!==this.#i&&(this.#i=e.camera,n=!0),`lastError`in e&&e.lastError!==this.#a&&(this.#a=e.lastError,n=!0),(n||t)&&this.notifyStatusChange()}notifyStatusChange(){try{this.#t.onStatusChange?.(this.getState())}catch(e){this.#t.onError?.(e)}}createSdkError(e,t,n){return y(n)?n:new v(e,t,n)}isDetectorRunning(){return this.#r===`running`||this.#r===`starting`||!!this.#o||this.#e.webcam.isRunning||this.#e.webcam.isStarting}hasRuntimeToStop(){return this.#r===`running`||this.#r===`starting`||this.#i!==`idle`||!!this.#o||this.#e.webcam.isRunning||this.#e.webcam.isStarting}getStartErrorCode(e){return this.isCameraPermissionError(e)?`CAMERA_PERMISSION_DENIED`:this.isCameraReadError(e)?`CAMERA_READ_FAILED`:this.#r===`loading`?`MODEL_LOAD_FAILED`:`RUNTIME_START_FAILED`}getStartErrorMessage(e){switch(this.getStartErrorCode(e)){case`CAMERA_PERMISSION_DENIED`:return`MonitorDog camera permission was denied.`;case`CAMERA_READ_FAILED`:return`MonitorDog camera could not be read.`;case`MODEL_LOAD_FAILED`:return`MonitorDog detection model failed to load.`;default:return`MonitorDog detector runtime failed to start.`}}isCameraPermissionError(e){return typeof DOMException<`u`&&e instanceof DOMException&&(e.name===`NotAllowedError`||e.name===`SecurityError`)}isCameraReadError(e){return typeof DOMException<`u`&&e instanceof DOMException&&e.name===`NotReadableError`}};function Q(e){return e===`CAMERA_PERMISSION_DENIED`||e===`CAMERA_READ_FAILED`}var $;function de(e){return $=new Z(e),$}async function fe(e){return Z.init(e)}function pe(){if(!$)throw Error(`MonitorDog is not configured. Call MonitorDogDetector.init(), createMonitorDogDetector(), or configureMonitorDogDetector() before using getDetector().`);return $}function me(){if(typeof navigator>`u`)return!1;let e=h();return e===`mobile`||e===`tablet`}function he(e){if(!e||typeof e.apiBaseUrl!=`string`||e.apiBaseUrl.length===0)throw Error(`MonitorDog apiBaseUrl is required.`);if(typeof e.sessionTokenProvider!=`function`)throw Error(`MonitorDog sessionTokenProvider is required.`);if(typeof e.onDetect!=`function`)throw Error(`MonitorDog onDetect callback is required.`);if(e.runtimeAssetBaseUrl!==void 0&&_(e.runtimeAssetBaseUrl),e.modelInputSize!==void 0&&!ne(e.modelInputSize))throw Error(`MonitorDog modelInputSize must be "auto", 320, 416, or 640.`);if(e.phoneRotationFallback!==void 0&&typeof e.phoneRotationFallback!=`boolean`)throw Error(`MonitorDog phoneRotationFallback must be a boolean when provided.`);if(e.phoneRotationFallbackMinIntervalMs!==void 0&&!ge(e.phoneRotationFallbackMinIntervalMs))throw Error(`MonitorDog phoneRotationFallbackMinIntervalMs must be a non-negative finite number when provided.`);if(e.phoneRotationFallbackExecution!==void 0&&e.phoneRotationFallbackExecution!==`sequential`&&e.phoneRotationFallbackExecution!==`parallel`)throw Error(`MonitorDog phoneRotationFallbackExecution must be "sequential" or "parallel" when provided.`)}function ge(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}e.MonitorDogDetector=Z,e.MonitorDogSdkError=v,e.configureMonitorDogDetector=de,e.createMonitorDogDetector=fe,e.getDetector=pe,e.isMonitorDogSdkError=y});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("html2canvas")):typeof define==`function`&&define.amd?define([`exports`,`html2canvas`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.MonitorDogDetector={},e.html2canvas))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e};t=((e,t,i)=>(i=e==null?{}:n(o(e)),c(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)))(t,1);var l=.8,u=.7,d=3e4;function f(e){return typeof e==`string`?e:e.access_token}function ee(e){if(typeof e!=`string`)return e.expires_in}function p(e){if(typeof e!=`string`)return e.expires_at}function m(e){if(e.expiresAt){let t=Date.parse(e.expiresAt);if(!Number.isNaN(t))return t}if(e.expiresIn)return e.expiresIn>1e9?e.expiresIn*1e3:Date.now()+e.expiresIn*1e3}function h(e){return e.replace(/\/+$/,``)}function g(){if(typeof navigator>`u`)return`none`;let e=navigator.userAgent.toLowerCase();return/ipad|tablet/.test(e)?`tablet`:/mobile|iphone|ipod|android/.test(e)?`mobile`:/macintosh|windows|linux/.test(e)?`desktop`:`other`}function te(){if(typeof navigator>`u`)return`none`;let e=navigator.userAgent.toLowerCase(),t=navigator.platform.toLowerCase();return/win/.test(t)||/windows/.test(e)?`windows`:/mac/.test(t)||/mac os/.test(e)?`macos`:/android/.test(e)?`android`:/iphone|ipad|ipod/.test(e)?`ios`:/linux/.test(t)||/linux/.test(e)?`linux`:`other`}function ne(e){return e===`auto`||e===320||e===416||e===640}function _(e,t){let n=e??`auto`;return n===`auto`?t?416:640:n}function v(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw Error(`MonitorDog runtimeAssetBaseUrl must be a non-empty string when provided.`);let n=t.replace(/\/+$/,``);return n.length===0?`/`:n}var y=class extends Error{code;cause;constructor(e,t,n){super(t),this.name=`MonitorDogSdkError`,this.code=e,this.cause=n}};function b(e){return e instanceof y}function x(e){if(e.faceCount===0)return w(`noFaceDetected`,e);if(e.faceCount>=2)return w(`twoFacesDetected`,e);if(e.phoneCount>=1)return w(`mobileDevice`,e)}function S(e){return{...T(e,new Date().toISOString()),properties:{},webcam_imgs:[],monitor_imgs:[]}}function C(e){return e.phoneCount===0&&e.faceCount===1}function w(e,t){let n=T(e,new Date().toISOString());switch(e){case`noFaceDetected`:return{type:e,payload:{...n,properties:{confidence:0,spots:[]}}};case`twoFacesDetected`:return{type:e,payload:{...n,properties:{confidence:E(t.faceDetections),spots:t.faceDetections}}};case`mobileDevice`:return{type:e,payload:{...n,properties:{confidence:E(t.phoneDetections),spots:t.phoneDetections}}}}}function T(e,t){return{basic_event_uuid:D(e),occured_at:t,sended_at:new Date().toISOString(),device_type:g(),device_os:te(),device_id:`browser`}}function E(e){return e.reduce((e,t)=>Math.max(e,t.score),0)}function D(e){switch(e){case`logout`:return`12ca646a-d832-4581-b03c-48f95627507f`;case`login`:return`4c6f98ea-88d8-4215-9b6a-9b3ccb753465`;case`mobileDevice`:return`027af5c9-297d-4a64-983f-4199ca4b9dad`;case`twoFacesDetected`:return`d555efac-7465-4067-8056-611e95385807`;case`noFaceDetected`:return`e2c48c23-36e2-4253-82b1-7f6565fdcfc3`;default:return``}}var O=`MonitorDog token refresh was superseded.`,re=300*1e3,ie=class{services;refreshBeforeMs=re;periodicRefreshIntervalMs=d;token;tokenExpiresAt;refreshPromise;refreshIntervalId;authSessionId=0;sessionEmail;constructor(e){this.services=e}async login(e){let t=await this.fetchSessionToken(e.email);return this.sessionEmail=e.email,this.setSessionTokenPayload(t),await this.sendUserActivityEvent(`login`),t}async logout(){if(this.token)try{await this.sendUserActivityEvent(`logout`)}finally{this.clearTokens()}}getToken(){return this.token}getTokenExpiresAt(){return this.tokenExpiresAt}getSessionEmail(){return this.sessionEmail}isAuthenticated(){return!!this.token}dispose(){this.clearTokens()}assertAuthenticated(){if(!this.token)throw Error(`MonitorDog login is required before detection.`)}async getValidAccessToken(){if(this.shouldRefreshCurrentToken())try{await this.handleAuthRefresh()}catch(e){if(this.token&&this.tokenExpiresAt&&Date.now()<this.tokenExpiresAt)return this.token;throw e}return this.token}async authorizedFetch(e,t={},n=!0){let r=await this.getValidAccessToken(),i=new Headers(t.headers);r&&(i.set(`authorization`,`Bearer ${r}`),i.set(`Device-Access-Token`,r));let a=await fetch(`${this.services.options.apiBaseUrl}${e}`,{...t,headers:i}),o=await this.getApiErrorCode(a);return a.status===400&&o===4221&&this.handleLoginRequired(),n&&this.shouldRefreshAfterAuthError(a,o)?(await this.handleAuthRefresh(),this.authorizedFetch(e,t,!1)):a}setSessionTokenPayload(e){let t=f(e);if(!t||typeof t!=`string`)throw Error(`MonitorDog SDK token response did not include a token.`);this.setTokens({accessToken:t,expiresIn:ee(e),expiresAt:p(e)})}setTokens(e){this.token=e.accessToken,this.tokenExpiresAt=m(e),this.tokenExpiresAt?this.startPeriodicRefresh():this.stopPeriodicRefresh()}clearTokens(){this.authSessionId+=1,this.token=void 0,this.tokenExpiresAt=void 0,this.refreshPromise=void 0,this.sessionEmail=void 0,this.stopPeriodicRefresh()}async refreshToken(){return this.refreshPromise||=this.refreshAccessToken().finally(()=>{this.refreshPromise=void 0}),this.refreshPromise}async handleAuthRefresh(){try{return await this.refreshToken()}catch(e){if(!this.isRefreshSupersededError(e)){let t=this.createSdkError(`SESSION_TOKEN_FAILED`,`MonitorDog SDK session token refresh failed.`,e);this.services.options.onAuthError?.(t),this.isCurrentTokenExpired()&&(this.clearTokens(),this.services.onLoginRequired?.())}throw e}}async refreshAccessToken(){let e=this.authSessionId,t=this.sessionEmail;if(!t)throw Error(`MonitorDog login email is required to refresh SDK token.`);let n=await this.fetchSessionToken(t),r=f(n);if(!r||typeof r!=`string`)throw Error(`MonitorDog SDK token response did not include a token.`);if(e!==this.authSessionId)throw Error(O);return this.setSessionTokenPayload(n),r}startPeriodicRefresh(){this.refreshIntervalId||=setInterval(()=>{this.refreshPeriodically()},this.periodicRefreshIntervalMs)}stopPeriodicRefresh(){this.refreshIntervalId&&=(clearInterval(this.refreshIntervalId),void 0)}async refreshPeriodically(){if(!(!this.token||!this.shouldRefreshCurrentToken()))try{await this.handleAuthRefresh()}catch{}}shouldRefreshCurrentToken(){return!!(this.token&&this.tokenExpiresAt&&Date.now()>=this.tokenExpiresAt-this.refreshBeforeMs)}isCurrentTokenExpired(){return!!(this.tokenExpiresAt&&Date.now()>=this.tokenExpiresAt)}isRefreshSupersededError(e){return e instanceof Error&&e.message===O}async fetchSessionToken(e){let t=this.services.options.sessionTokenProvider;if(!t)throw Error(`MonitorDog sessionTokenProvider is required for SDK login.`);return t({email:e})}async getApiErrorCode(e){if(e.status===400)try{let t=await e.clone().json();if(typeof t==`object`&&t&&`code`in t&&typeof t.code==`number`)return t.code}catch{return}}shouldRefreshAfterAuthError(e,t){return e.status===401?!0:e.status===400&&t===422}handleLoginRequired(){this.clearTokens(),this.services.onLoginRequired?.();let e=this.createSdkError(`NOT_LOGGED_IN`,`MonitorDog login is required.`);throw this.services.options.onAuthError?.(e),e}async sendUserActivityEvent(e){try{let t=await this.authorizedFetch(`/event`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S(e))});if(!t.ok)throw Error(`MonitorDog ${e} event failed: ${t.status}`)}catch(t){let n=this.createSdkError(k(e),`MonitorDog ${e} event failed.`,t);if(this.services.options.onAuthError?.(n),e===`logout`)throw n}}createSdkError(e,t,n){return n instanceof y?n:new y(e,t,n)}};function k(e){return e===`logout`?`LOGOUT_FAILED`:`SESSION_TOKEN_FAILED`}var A=/(obs|virtual|xsplit|manycam|splitcam|webcammax|fake|loopback|camtwist|e2esoft|vcam|droidcam|iriun|epoccam|camo|mmhmm|nvidia broadcast|streamlabs|bandicam|wirecast|chromacam|youcam|cyberlink|altserver|logi capture|elgato|streamfx|screen capture|desktop capture)/i,j=class{async createWebcamStream(e){if(!navigator.mediaDevices?.getUserMedia)throw Error(`getUserMedia is not available in this browser.`);let t=this.getBaseWebcamConstraints(e),n=await this.createFirstCameraConstraints(t);try{return await this.getUserMedia(n)}catch(e){if(this.isPermissionError(e)||this.isCameraRequestTimeoutError(e))throw e;return this.createFallbackWebcamStream(n,e)}}stopStream(e){e.getTracks().forEach(e=>e.stop())}watchStreamDeviceDisconnect(e,t,n=1e3){let r=e.getVideoTracks()[0],i=r?.getSettings().deviceId;if(!r&&!i)return()=>{};let a=!1,o,s=()=>{a||(a=!0,t())},c=()=>{i&&(o&&clearTimeout(o),o=setTimeout(()=>{o=void 0,this.handleDeviceChange(i,s)},n))};return r?.addEventListener(`ended`,s),navigator.mediaDevices?.addEventListener?.(`devicechange`,c),()=>{o&&clearTimeout(o),r?.removeEventListener(`ended`,s),navigator.mediaDevices?.removeEventListener?.(`devicechange`,c)}}isCameraInUse(e){let t=e?.srcObject;return t instanceof MediaStream?t.getTracks().some(e=>e.readyState===`live`):!1}async getVideoInputDevices(){return navigator.mediaDevices?.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`):[]}async getRealVideoInputDevices(){let e=await this.getVideoInputDevices(),t=e.filter(e=>!this.isVirtualCamera(e));return t.length>0?t:e}async createFallbackWebcamStream(e,t){let n=await this.getRealVideoInputDevices();if(n.length===0)throw t;let r=n[0],i=t;if(!r?.deviceId)throw i;let a=await this.getWebcamNaturalAspectRatio(r.deviceId),o=this.generateResolutionList(a,720);for(let t of o)try{return await this.getUserMedia(this.createDeviceConstraints(e,r.deviceId,t))}catch(e){i=e}throw i}async handleDeviceChange(e,t){try{(await this.getVideoInputDevices()).some(t=>t.deviceId===e)||t()}catch{}}getBaseWebcamConstraints(e){return e??{audio:!1,video:{facingMode:`user`}}}async createFirstCameraConstraints(e){let t=typeof e.video==`object`?e.video:{};if(`deviceId`in t||`facingMode`in t)return e;let n=(await this.getRealVideoInputDevices())[0];return n?.deviceId?this.createDeviceConstraints(e,n.deviceId):e}async getWebcamNaturalAspectRatio(e){let t;try{t=await this.getUserMedia({audio:!1,video:{deviceId:{exact:e}}});let n=t.getVideoTracks()[0]?.getSettings();if(n?.width&&n.height)return n.width/n.height}catch{}finally{t?.getTracks().forEach(e=>e.stop())}return 16/9}generateResolutionList(e,t){return[t,640,600,480,320,240].map(t=>({width:t,height:Math.max(1,Math.round(t/e))})).filter(e=>e.width<=t&&e.height>=120&&e.height<=1080)}createDeviceConstraints(e,t,n){let r=typeof e.video==`object`?e.video:{};return{...e,audio:e.audio??!1,video:{...r,deviceId:{exact:t},...n?{width:{min:n.width,ideal:n.width},height:{min:n.height,ideal:n.height}}:{}}}}isVirtualCamera(e){let t=e.label.toLowerCase();return t?A.test(t):!1}isPermissionError(e){return e instanceof DOMException&&(e.name===`NotAllowedError`||e.name===`SecurityError`)}getUserMedia(e,t=15e3){let n=!1,r,i=navigator.mediaDevices.getUserMedia(e).then(e=>{if(n)throw this.stopStream(e),Error(`Camera permission request timed out.`);return e}),a=new Promise((e,i)=>{r=setTimeout(()=>{n=!0,i(Error(`Camera permission request timed out.`))},t)});return Promise.race([i,a]).finally(()=>{r&&clearTimeout(r)})}isCameraRequestTimeoutError(e){return e instanceof Error&&e.message===`Camera permission request timed out.`}};function M(e){if(e.videoWidth===0||e.videoHeight===0)throw Error(`Video frame is not ready for capture.`);let t=document.createElement(`canvas`),n=t.getContext(`2d`);if(!n)throw Error(`2D canvas context is not available.`);return t.width=e.videoWidth,t.height=e.videoHeight,n.drawImage(e,0,0,t.width,t.height),new Promise((e,n)=>{t.toBlob(t=>{if(!t){n(Error(`Failed to capture video frame.`));return}e(t)},`image/jpeg`,.9)})}async function N(){if(typeof document>`u`||!document.body)return null;let e=await(0,t.default)(document.body,{backgroundColor:`#ffffff`,useCORS:!0});return new Promise(t=>{e.toBlob(t,`image/jpeg`,.9)})}var P=class e{static NO_FACE_STARTUP_GRACE_MS=1500;services;detectionEventLocked=!1;detectionEventInFlight=!1;detectionEventLockTimeoutId;noFaceStartedAt;suppressNoFaceUntil=0;constructor(e){this.services=e}async handleDetectionResult(e,t){if(!this.services.options.eventReportingEnabled){this.reset();return}if(C(e)){this.noFaceStartedAt=void 0,this.clearLock();return}if(this.detectionEventLocked||this.detectionEventInFlight)return;let n=x(e);if(!n){this.noFaceStartedAt=void 0;return}if(!(n.type===`noFaceDetected`&&!this.hasNoFaceDelayElapsed())&&(n.type!==`noFaceDetected`&&(this.noFaceStartedAt=void 0),this.shouldSendEvent(n.type,e))){this.lock(n.type),this.detectionEventInFlight=!0;try{let e=await this.uploadWebcamImage(t);e&&(n.payload.webcam_imgs=e);let r=await this.uploadMonitorImage();if(r&&(n.payload.monitor_imgs=r),this.services.options.debug){console.log(n.payload);return}let i=await this.services.auth.authorizedFetch(`/event`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.payload)});if(!i.ok)throw Error(`MonitorDog event request failed: ${i.status}`)}finally{this.detectionEventInFlight=!1}}}reset(){this.clearLock(),this.noFaceStartedAt=void 0,this.suppressNoFaceUntil=0}resetForWebcamStartup(){this.clearLock(),this.noFaceStartedAt=void 0,this.suppressNoFaceUntil=Date.now()+e.NO_FACE_STARTUP_GRACE_MS}clearTransientState(){this.noFaceStartedAt=void 0}async uploadWebcamImage(e){if(!(e instanceof HTMLVideoElement)||e.videoWidth===0||e.videoHeight===0)return;let t=await M(e);return this.uploadImage(t,`webcam.jpg`)}async uploadMonitorImage(){let e=this.services.options.captureMonitorImage?await this.services.options.captureMonitorImage():await N();if(!e)return;let t=typeof File<`u`&&e instanceof File?e.name:`monitor.jpg`;return this.uploadImage(e,t)}async uploadImage(e,t){let n=new FormData;n.append(`files`,e,t);let r=await this.services.auth.authorizedFetch(`/file/image`,{method:`POST`,body:n});if(!r.ok)throw Error(`MonitorDog image upload failed: ${r.status}`);return r.json()}shouldSendEvent(e,t){switch(e){case`mobileDevice`:return this.services.userPreferences.mobileDetectionEnabled&&F(t.phoneDetections)>=this.services.options.confidenceThreshold;case`twoFacesDetected`:return this.services.userPreferences.multiPersonDetectionEnabled&&F(t.faceDetections)>=this.services.userPreferences.faceDetectionThreshold;case`noFaceDetected`:return this.services.userPreferences.noPersonDetectionEnabled}}lock(e){this.clearLock(),this.detectionEventLocked=!0;let t=this.getLockDuration(e);if(t<=0){this.detectionEventLocked=!1;return}this.detectionEventLockTimeoutId=setTimeout(()=>{this.detectionEventLocked=!1,this.detectionEventLockTimeoutId=void 0},t)}clearLock(){this.detectionEventLockTimeoutId&&=(clearTimeout(this.detectionEventLockTimeoutId),void 0),this.detectionEventLocked=!1}hasNoFaceDelayElapsed(){if(Date.now()<this.suppressNoFaceUntil)return this.noFaceStartedAt=void 0,!1;if(this.services.noFaceEventDelayMs<=0)return!0;let e=Date.now();return this.noFaceStartedAt===void 0?(this.noFaceStartedAt=e,!1):e-this.noFaceStartedAt>=this.services.noFaceEventDelayMs}getLockDuration(e){switch(e){case`mobileDevice`:return this.services.userPreferences.mobileDetectionLockDuration;case`twoFacesDetected`:return this.services.userPreferences.multiPersonLockDuration;case`noFaceDetected`:return this.services.userPreferences.noPersonLockDuration}}};function F(e){return e.reduce((e,t)=>Math.max(e,t.score),0)}var I=``+(typeof document>`u`&&typeof location>`u`?require("url").pathToFileURL(__dirname+`/assets/inference-worker-BTPzhc2n.js`).href:new URL(`assets/inference-worker-BTPzhc2n.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),L=class{worker;nextRequestId=1;pendingRequests=new Map;async load(e){let t={id:this.nextRequestId,type:`load`,model:e};await this.request(t)}run(e){let t=e.source.kind===`bitmap`?[e.source.bitmap]:[e.source.data.buffer];return this.request({id:this.nextRequestId,type:`run`,source:e.source,inputSize:e.inputSize,inputType:e.inputType,confidenceThreshold:e.confidenceThreshold,faceConfidenceThreshold:e.faceConfidenceThreshold,iouThreshold:e.iouThreshold,maxDetections:e.maxDetections,debug:e.debug,inputRotation:e.inputRotation??`none`,phoneRotationFallback:e.phoneRotationFallback,phoneRotationFallbackMinIntervalMs:e.phoneRotationFallbackMinIntervalMs},t)}terminate(){this.rejectPendingRequests(Error(`Inference worker was terminated.`)),this.worker?.terminate(),this.worker=void 0}request(e,t=[]){let n=this.getWorker();return this.nextRequestId+=1,new Promise((r,i)=>{this.pendingRequests.set(e.id,{resolve:r,reject:i}),n.postMessage(e,t)})}getWorker(){return this.worker||(this.worker=new Worker(I,{name:`MonitorDogInference`,type:`module`}),this.worker.addEventListener(`message`,this.handleMessage),this.worker.addEventListener(`error`,this.handleError),this.worker.addEventListener(`messageerror`,this.handleError)),this.worker}handleMessage=e=>{let t=e.data,n=this.pendingRequests.get(t.id);if(n){if(this.pendingRequests.delete(t.id),!t.ok){n.reject(Error(t.error));return}n.resolve(t.result)}};handleError=e=>{let t=e instanceof ErrorEvent?e.message:`Inference worker message failed.`;this.rejectPendingRequests(Error(t)),this.worker?.terminate(),this.worker=void 0};rejectPendingRequests(e){for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};async function R(e){let{sourceWidth:t,sourceHeight:n}=z(e);if(e instanceof ImageData)return{kind:`rgba`,data:new Uint8ClampedArray(e.data),sourceWidth:t,sourceHeight:n};if(B()&&V())try{return{kind:`bitmap`,bitmap:await createImageBitmap(e),sourceWidth:t,sourceHeight:n}}catch{}return H(e,t,n)}function z(e){return e instanceof ImageData?{sourceWidth:e.width,sourceHeight:e.height}:e instanceof HTMLVideoElement?{sourceWidth:e.videoWidth,sourceHeight:e.videoHeight}:e instanceof HTMLImageElement?{sourceWidth:e.naturalWidth,sourceHeight:e.naturalHeight}:{sourceWidth:e.width,sourceHeight:e.height}}function B(){return typeof createImageBitmap==`function`}function V(){return typeof OffscreenCanvas==`function`}function H(e,t,n){let r=document.createElement(`canvas`),i=r.getContext(`2d`);if(!i)throw Error(`2D canvas context is not available.`);return r.width=t,r.height=n,i.drawImage(e,0,0,t,n),{kind:`rgba`,data:i.getImageData(0,0,t,n).data,sourceWidth:t,sourceHeight:n}}function U(e,t,n){return e.map(e=>ae(e,t,n))}function W(e,t,n,r){if(e.phoneDetected||t.phoneDetections.length===0)return e;let i=U(t.phoneDetections,n,r);return{...e,phoneDetected:i.length>0,phoneCount:i.length,phoneDetections:i}}function ae(e,t,n){return{...e,x:G(t-(e.x+e.width),0,t),y:G(n-(e.y+e.height),0,n)}}function G(e,t,n){return Math.min(Math.max(e,t),n)}function K(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&e.videoWidth>0&&e.videoHeight>0&&!e.paused&&!e.ended}function q(e,t=1e4){return J(e)?Promise.resolve():new Promise((n,r)=>{let i=window.setTimeout(()=>{o(),r(Error(`Timed out waiting for webcam video metadata.`))},t),a=window.setInterval(s,100),o=()=>{window.clearTimeout(i),window.clearInterval(a),e.removeEventListener(`loadedmetadata`,c),e.removeEventListener(`loadeddata`,c),e.removeEventListener(`canplay`,c),e.removeEventListener(`playing`,c),e.removeEventListener(`resize`,c),e.removeEventListener(`error`,l)};function s(){J(e)&&(o(),n())}let c=()=>{s()},l=()=>{o(),r(Error(`Failed to load webcam video stream.`))};e.addEventListener(`loadedmetadata`,c,{once:!0}),e.addEventListener(`loadeddata`,c,{once:!0}),e.addEventListener(`canplay`,c,{once:!0}),e.addEventListener(`playing`,c,{once:!0}),e.addEventListener(`resize`,c,{once:!0}),e.addEventListener(`error`,l,{once:!0})})}function J(e){return e.readyState>=HTMLMediaElement.HAVE_METADATA&&e.videoWidth>0&&e.videoHeight>0}var oe=class{services;primaryInferenceWorker;rotationInferenceWorker;loadPromise;lastInferenceMemoryErrorAt=0;lastParallelPhoneRotationFallbackAt=-1/0;constructor(e){this.services=e}async load(){this.loadPromise||=this.loadInferenceWorker(),await this.loadPromise}async detect(e){await this.load();let t=this.services.options,n=t.debug?performance.now():0,r=t.debug?performance.now():0,i=r,a;if(this.shouldUseParallelPhoneRotationFallback(t)&&this.shouldRunParallelPhoneRotationFallback(t)){let[n,r]=await Promise.all([R(e),R(e)]);i=t.debug?performance.now():0,a=await this.runParallelPhoneRotationFallback(n,r,t)}else{let n=await R(e);i=t.debug?performance.now():0,a=await this.runWorkerInference(this.getInferenceWorker(),n,t,{inputRotation:`none`,phoneRotationFallback:t.phoneRotationFallback&&t.phoneRotationFallbackExecution===`sequential`})}if(t.debug){let e=performance.now();console.info(`[MonitorDog] detect frame`,{sourceMs:Y(i-r),workerRoundtripMs:Y(e-i),totalMs:Y(e-n)})}return a}toPublicResult(e){return{faceDetected:e.faceDetected,phoneDetected:e.phoneDetected,faceCount:e.faceCount,phoneCount:e.phoneCount,faceDetections:e.faceDetections,phoneDetections:e.phoneDetections}}detectVideo(e){let t=!1,n,r=this.services.options.detectionIntervalMs,i=async()=>{if(!t){try{if(!this.services.shouldPauseDetection&&K(e)){let n=await this.detect(e);if(t)return;try{await this.services.options.onDetect({...this.toPublicResult(n),video:e,timestamp:e.currentTime})}catch(e){this.services.options.onError?.(e)}if(t)return;await this.services.detectionEvents.handleDetectionResult(n,e).catch(e=>{this.services.options.onError?.(e)}),C(n)&&this.services.detectionEvents.clearTransientState()}}catch(e){this.handleDetectionLoopError(e)}t||(n=setTimeout(i,r))}};return i(),{stop(){t=!0,n&&clearTimeout(n)}}}async startWebcamDetection(){let e=this.services.options,t=await this.services.camera.createWebcamStream(e.constraints),n=this.services.camera,r=!e.video,i=e.video??document.createElement(`video`),a=i.muted,o=i.playsInline,s=i.srcObject;i.muted=!0,i.playsInline=!0,i.srcObject=t;try{await Promise.all([i.play(),q(i)])}catch(e){throw n.stopStream(t),i.pause(),r?i.srcObject=null:(i.muted=a,i.playsInline=o,i.srcObject=s),e}this.services.detectionEvents.resetForWebcamStartup();let c=this.detectVideo(i),l=!1,u=n.watchStreamDeviceDisconnect(t,()=>{d(),this.services.onCameraDisconnect?.()}),d=()=>{l||(l=!0,u(),c.stop(),this.services.detectionEvents.reset(),n.stopStream(t),i.pause(),r?i.srcObject=null:(i.muted=a,i.playsInline=o,i.srcObject=s))};return{stream:t,video:i,stop:d}}dispose(){this.primaryInferenceWorker?.terminate(),this.rotationInferenceWorker?.terminate(),this.primaryInferenceWorker=void 0,this.rotationInferenceWorker=void 0,this.loadPromise=void 0,this.lastParallelPhoneRotationFallbackAt=-1/0,this.services.detectionEvents.reset()}async runParallelPhoneRotationFallback(e,t,n){let r=e.sourceWidth,i=e.sourceHeight,[a,o]=await Promise.all([this.runWorkerInference(this.getInferenceWorker(),e,n,{inputRotation:`none`,phoneRotationFallback:!1}),this.runWorkerInference(this.getRotationInferenceWorker(),t,n,{inputRotation:`rotate180`,phoneRotationFallback:!1})]);return W(a,o,r,i)}runWorkerInference(e,t,n,r){return e.run({source:t,inputSize:n.inputSize,inputType:n.inputType,confidenceThreshold:n.confidenceThreshold,faceConfidenceThreshold:n.faceConfidenceThreshold,iouThreshold:n.iouThreshold,maxDetections:n.maxDetections,debug:!!n.debug,inputRotation:r.inputRotation,phoneRotationFallback:r.phoneRotationFallback,phoneRotationFallbackMinIntervalMs:n.phoneRotationFallbackMinIntervalMs})}handleDetectionLoopError(e){this.isInferenceMemoryError(e)&&this.recoverFromInferenceMemoryError(),this.services.options.onError?.(e)}recoverFromInferenceMemoryError(){this.degradeModelForMemoryPressure(),this.resetInferenceWorker();let e=Date.now();e-this.lastInferenceMemoryErrorAt<1e4||(this.lastInferenceMemoryErrorAt=e)}resetInferenceWorker(){this.primaryInferenceWorker?.terminate(),this.rotationInferenceWorker?.terminate(),this.primaryInferenceWorker=void 0,this.rotationInferenceWorker=void 0,this.loadPromise=void 0,this.lastParallelPhoneRotationFallbackAt=-1/0}degradeModelForMemoryPressure(){this.services.degradeInferenceModelForMemoryPressure()}isInferenceMemoryError(e){let t=e instanceof Error?e.message:String(e);return/out of memory|oom|memory access out of bounds|cannot enlarge memory|array buffer allocation|bad allocation|allocation failed/i.test(t)}getInferenceWorker(){return this.primaryInferenceWorker||=new L,this.primaryInferenceWorker}getRotationInferenceWorker(){return this.rotationInferenceWorker||=new L,this.rotationInferenceWorker}shouldUseParallelPhoneRotationFallback(e){return e.phoneRotationFallback&&e.phoneRotationFallbackExecution===`parallel`}shouldRunParallelPhoneRotationFallback(e){let t=performance.now();return t-this.lastParallelPhoneRotationFallbackAt<e.phoneRotationFallbackMinIntervalMs?!1:(this.lastParallelPhoneRotationFallbackAt=t,!0)}async loadInferenceWorker(){try{await this.loadInferenceWorkerWithOptions()}catch(e){if(!this.isInferenceMemoryError(e))throw e;this.recoverFromInferenceMemoryError();try{await this.loadInferenceWorkerWithOptions()}catch(e){throw this.recoverFromInferenceMemoryError(),e}}}async loadInferenceWorkerWithOptions(){let e=await this.services.auth.getValidAccessToken();if(!e)throw Error(`MonitorDog login is required before loading detection.`);let t=this.services.options,n={apiBaseUrl:t.apiBaseUrl,accessToken:e,inputSize:t.inputSize,runtimeAssetBaseUrl:t.runtimeAssetBaseUrl};if(this.shouldUseParallelPhoneRotationFallback(t)){await Promise.all([this.getInferenceWorker().load(n),this.getRotationInferenceWorker().load(n)]);return}await this.getInferenceWorker().load(n)}};function Y(e){return Math.round(e*10)/10}var se=class{services;isWebcamRunning=!1;stopCurrentWebcam;startPromise;shouldRun=!1;resumeWhenUnpaused=!1;handleVisibilityChange=()=>{this.syncPauseState()};constructor(e){this.services=e,this.services.onCameraDisconnect=()=>this.handleCameraDisconnect()}get isRunning(){return this.isWebcamRunning}get isStarting(){return!!this.startPromise}async start(){if(this.services.auth.assertAuthenticated(),this.shouldRun=!0,this.addVisibilityListener(),!this.isWebcamRunning){if(this.services.shouldPauseDetection){this.resumeWhenUnpaused=!0;return}await this.ensureStarted()}}stop(){this.shouldRun=!1,this.resumeWhenUnpaused=!1,this.removeVisibilityListener(),this.services.detectionEvents.reset(),this.stopWebcam()}async retryConnection(){await this.start()}async syncPauseState(){if(this.shouldRun){if(this.services.shouldPauseDetection){this.isWebcamRunning&&(this.resumeWhenUnpaused=!0,this.stopWebcam());return}if(this.resumeWhenUnpaused&&!this.isWebcamRunning){this.resumeWhenUnpaused=!1;try{await this.ensureStarted()}catch{this.shouldRun=!1}}}}syncBackgroundPreference(){this.services.options.runInBackground?this.removeVisibilityListener():this.shouldRun&&this.addVisibilityListener(),this.syncPauseState()}async ensureStarted(){this.isWebcamRunning||(this.startPromise||=this.startWebcam().finally(()=>{this.startPromise=void 0}),await this.startPromise)}async startWebcam(){try{let e=await this.services.detect.startWebcamDetection();if(!this.shouldRun){e.stop();return}this.isWebcamRunning=!0,this.stopCurrentWebcam=e.stop}catch(e){throw this.services.options.onError?.(e),e}}stopWebcam(){this.stopCurrentWebcam?.(),this.stopCurrentWebcam=void 0,this.isWebcamRunning=!1}async handleCameraDisconnect(){if(this.isWebcamRunning&&(this.stopWebcam(),this.shouldRun)){if(this.services.shouldPauseDetection){this.resumeWhenUnpaused=!0;return}try{await this.ensureStarted()}catch(e){this.services.options.onError?.(e)}}}addVisibilityListener(){this.services.options.runInBackground||typeof document>`u`||document.addEventListener(`visibilitychange`,this.handleVisibilityChange)}removeVisibilityListener(){typeof document>`u`||document.removeEventListener(`visibilitychange`,this.handleVisibilityChange)}},ce=class{auth;camera;detectionEvents;detect;webcam;onCameraDisconnect;onLoginRequired;#e=0;#t=X();#n;constructor(e){this.#n=e,this.camera=new j,this.auth=new ie(this),this.detectionEvents=new P(this),this.detect=new oe(this),this.webcam=new se(this)}get options(){return Object.freeze({...this.#n()})}get noFaceEventDelayMs(){return this.#e}get userPreferences(){return Object.freeze({...this.#t})}updateNoFaceEventDelayFromServer(e){this.#e=e}updateRequiredPasswordFromServer(e){this.#n().requiredPassword=e}setPhoneConfidenceThreshold(e){this.#n().phoneConfidenceThreshold=e,this.syncEffectivePhoneConfidenceThreshold()}degradeInferenceModelForMemoryPressure(){let e=this.#n();if(e.inputSize>416){e.inputSize=416;return}e.inputSize>320&&(e.inputSize=320)}get shouldPauseForHiddenPage(){return!this.options.runInBackground&&typeof document<`u`&&document.hidden}get shouldPauseDetection(){return this.shouldPauseForHiddenPage}applyPolicyItems(e,t){let n={...this.#t};for(let t of e)ue(n,t);this.#t=n,this.syncEffectivePhoneConfidenceThreshold(),this.#n().faceConfidenceThreshold=n.faceDetectionThreshold,this.updateRequiredPasswordFromServer(!1)}resetAuthenticatedState(){this.#e=0,this.#t=X(),this.#n().requiredPassword=!1,this.syncEffectivePhoneConfidenceThreshold(),this.#n().faceConfidenceThreshold=this.#t.faceDetectionThreshold}syncEffectivePhoneConfidenceThreshold(){let e=this.#n();e.confidenceThreshold=e.phoneConfidenceThreshold??this.#t.mobileDetectionThreshold}};function X(){return{mobileDetectionThreshold:.8,faceDetectionThreshold:.8,language:`en`,mobileDetectionEnabled:!0,noPersonDetectionEnabled:!0,multiPersonDetectionEnabled:!0,noPersonLockDuration:0,multiPersonLockDuration:0,mobileDetectionLockDuration:0,mobileDetectionMode:`auto_lock`,noPersonDetectionMode:`auto_lock`,multiPersonDetectionMode:`auto_lock`}}function le(e){return e===`none`}function ue(e,t){let n=t.policy,r=!le(t.policy),i=t.seconds*1e3,a=`sensitivity`in t?1-t.sensitivity/100:void 0;switch(t.basic_event_uuid){case D(`mobileDevice`):e.mobileDetectionEnabled=r,e.mobileDetectionLockDuration=i,e.mobileDetectionMode=n,a!==void 0&&(e.mobileDetectionThreshold=a);break;case D(`twoFacesDetected`):e.multiPersonDetectionEnabled=r,e.multiPersonLockDuration=i,e.multiPersonDetectionMode=n,a!==void 0&&(e.faceDetectionThreshold=a);break;case D(`noFaceDetected`):e.noPersonDetectionEnabled=r,e.noPersonLockDuration=i,e.noPersonDetectionMode=n;break;default:break}}var Z=class e{#e;#t;#n=`anonymous`;#r=`idle`;#i=`idle`;#a;#o;static async init(t){return Q=new e(t),Q}constructor(e){ge(e);let t=he(),n=v(e.runtimeAssetBaseUrl);this.#t={...e,apiBaseUrl:h(e.apiBaseUrl),runtimeAssetBaseUrl:n,confidenceThreshold:e.phoneConfidenceThreshold??.8,faceConfidenceThreshold:l,iouThreshold:u,maxDetections:100,inputSize:_(e.modelInputSize,t),inputType:`float32`,detectionIntervalMs:e.detectionIntervalMs??300,requiredPassword:!1,eventReportingEnabled:e.eventReportingEnabled??!0,phoneRotationFallback:e.phoneRotationFallback??!1,phoneRotationFallbackMinIntervalMs:e.phoneRotationFallbackMinIntervalMs??500,phoneRotationFallbackExecution:e.phoneRotationFallbackExecution??`sequential`},this.#e=new ce(()=>this.#t),this.#e.onLoginRequired=()=>this.resetLoggedOutState(),Object.freeze(this)}async load(){this.assertUsable(),this.assertAuthenticated(`loading detection`);try{this.updateState({runtime:`loading`,lastError:void 0}),await this.#e.detect.load(),this.updateState({runtime:`idle`,lastError:void 0})}catch(e){let t=this.createSdkError(`MODEL_LOAD_FAILED`,`MonitorDog detection model failed to load.`,e);throw this.transitionToError(t),this.#t.onError?.(t),t}}async login(e){this.assertUsable();let t;try{t=await this.#e.auth.login(e)}catch(e){let t=this.createSdkError(`SESSION_TOKEN_FAILED`,`MonitorDog SDK session token could not be created.`,e);throw this.transitionToError(t),this.#t.onAuthError?.(t),t}try{await this.completeAuthenticatedLogin()}catch(e){let t=this.createSdkError(`ACCOUNT_POLICY_FAILED`,`MonitorDog account or policy could not be loaded.`,e);throw this.rollbackAuthenticatedLogin(),this.transitionToError(t),this.#t.onAuthError?.(t),t}return this.updateState({session:`authenticated`,runtime:this.#r===`stopped`?`stopped`:`idle`,camera:this.#e.webcam.isRunning?`active`:`idle`,lastError:void 0}),t}async logout(){if(this.assertUsable(),this.isDetectorRunning())throw this.lifecycleError(`DETECTOR_RUNNING`,`MonitorDog detector is running. Call stop() before logout().`);if(!this.#e.auth.getToken()){this.clearSessionState();return}try{await this.#e.auth.logout(),this.clearSessionState()}catch(e){let t=this.createSdkError(`LOGOUT_FAILED`,`MonitorDog logout failed.`,e);throw this.transitionToError(t),this.#t.onAuthError?.(t),t}finally{this.#e.auth.getToken()||(this.#n=`anonymous`)}}async start(){this.assertUsable(),this.assertAuthenticated(`starting detection`),!this.isDetectorRunning()&&(this.#o||=this.startRuntime().finally(()=>{this.#o=void 0}),await this.#o)}stop(){this.assertUsable(),this.hasRuntimeToStop()&&(this.stopLocalRuntime(),this.updateState({runtime:this.#n===`authenticated`?`stopped`:`idle`,camera:`idle`,lastError:void 0}))}setRunInBackground(e){this.assertUsable(),this.#t.runInBackground=e,this.#e.webcam.syncBackgroundPreference()}setEventReportingEnabled(e){this.assertUsable(),this.#t.eventReportingEnabled=e,e||this.#e.detectionEvents.reset()}setPhoneConfidenceThreshold(e){this.assertUsable(),$(e),this.#e.setPhoneConfidenceThreshold(e)}getUserPreferences(){return this.assertUsable(),this.#e.userPreferences}getState(){return Object.freeze({session:this.#n,runtime:this.#r,camera:this.#i,tokenExpiresAt:this.#e.auth.getTokenExpiresAt(),email:this.#e.auth.getSessionEmail(),lastError:this.#a})}dispose(){this.#r!==`disposed`&&(this.stopLocalRuntime(),this.#e.detect.dispose(),this.#e.auth.dispose(),this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`disposed`,camera:`idle`,lastError:void 0}))}async completeAuthenticatedLogin(){let e=await this.#e.auth.authorizedFetch(`/account/me`,{method:`GET`,headers:{"content-type":`application/json`}});if(!e.ok)throw Error(`MonitorDog account request failed: ${e.status}`);let t=await e.json(),n=await this.#e.auth.authorizedFetch(`/account/${t.uuid}/lock_policy`,{method:`GET`,headers:{"content-type":`application/json`}});if(!n.ok)throw Error(`MonitorDog lock policy request failed: ${n.status}`);let r=await n.json();this.#e.applyPolicyItems(r,t)}resetLoggedOutState(){this.stopLocalRuntime(),this.#e.detect.dispose(),this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`idle`,camera:`idle`,lastError:void 0})}rollbackAuthenticatedLogin(){this.#e.auth.dispose(),this.#e.resetAuthenticatedState()}async startRuntime(){try{this.updateState({runtime:`loading`,camera:`idle`,lastError:void 0}),await this.#e.detect.load(),this.updateState({runtime:`starting`,camera:`requesting`}),await this.#e.webcam.start(),this.updateState({runtime:`running`,camera:this.#e.shouldPauseDetection?`idle`:`active`,lastError:void 0})}catch(e){let t=this.createSdkError(this.getStartErrorCode(e),this.getStartErrorMessage(e),e);throw this.transitionToError(t,de(t.code)?`blocked`:`idle`),this.#t.onError?.(t),t}}clearSessionState(){this.#e.resetAuthenticatedState(),this.updateState({session:`anonymous`,runtime:`idle`,camera:`idle`,lastError:void 0})}stopLocalRuntime(){this.#e.webcam.stop()}assertUsable(){if(this.#r===`disposed`)throw this.lifecycleError(`ALREADY_DISPOSED`,`MonitorDog detector instance has already been disposed.`,void 0,`disposed`)}assertAuthenticated(e){if(!this.#e.auth.isAuthenticated())throw this.lifecycleError(`NOT_LOGGED_IN`,`MonitorDog login is required before ${e}.`)}lifecycleError(e,t,n,r=`error`){let i=this.createSdkError(e,t,n);return r===`error`?this.transitionToError(i):this.updateState({runtime:r,lastError:i},!0),i}transitionToError(e,t=this.#i){this.updateState({runtime:`error`,camera:t,lastError:e},!0)}updateState(e,t=!1){let n=!1;e.session!==void 0&&e.session!==this.#n&&(this.#n=e.session,n=!0),e.runtime!==void 0&&e.runtime!==this.#r&&(this.#r=e.runtime,n=!0),e.camera!==void 0&&e.camera!==this.#i&&(this.#i=e.camera,n=!0),`lastError`in e&&e.lastError!==this.#a&&(this.#a=e.lastError,n=!0),(n||t)&&this.notifyStatusChange()}notifyStatusChange(){try{this.#t.onStatusChange?.(this.getState())}catch(e){this.#t.onError?.(e)}}createSdkError(e,t,n){return b(n)?n:new y(e,t,n)}isDetectorRunning(){return this.#r===`running`||this.#r===`starting`||!!this.#o||this.#e.webcam.isRunning||this.#e.webcam.isStarting}hasRuntimeToStop(){return this.#r===`running`||this.#r===`starting`||this.#i!==`idle`||!!this.#o||this.#e.webcam.isRunning||this.#e.webcam.isStarting}getStartErrorCode(e){return this.isCameraPermissionError(e)?`CAMERA_PERMISSION_DENIED`:this.isCameraReadError(e)?`CAMERA_READ_FAILED`:this.#r===`loading`?`MODEL_LOAD_FAILED`:`RUNTIME_START_FAILED`}getStartErrorMessage(e){switch(this.getStartErrorCode(e)){case`CAMERA_PERMISSION_DENIED`:return`MonitorDog camera permission was denied.`;case`CAMERA_READ_FAILED`:return`MonitorDog camera could not be read.`;case`MODEL_LOAD_FAILED`:return`MonitorDog detection model failed to load.`;default:return`MonitorDog detector runtime failed to start.`}}isCameraPermissionError(e){return typeof DOMException<`u`&&e instanceof DOMException&&(e.name===`NotAllowedError`||e.name===`SecurityError`)}isCameraReadError(e){return typeof DOMException<`u`&&e instanceof DOMException&&e.name===`NotReadableError`}};function de(e){return e===`CAMERA_PERMISSION_DENIED`||e===`CAMERA_READ_FAILED`}var Q;function fe(e){return Q=new Z(e),Q}async function pe(e){return Z.init(e)}function me(){if(!Q)throw Error(`MonitorDog is not configured. Call MonitorDogDetector.init(), createMonitorDogDetector(), or configureMonitorDogDetector() before using getDetector().`);return Q}function he(){if(typeof navigator>`u`)return!1;let e=g();return e===`mobile`||e===`tablet`}function ge(e){if(!e||typeof e.apiBaseUrl!=`string`||e.apiBaseUrl.length===0)throw Error(`MonitorDog apiBaseUrl is required.`);if(typeof e.sessionTokenProvider!=`function`)throw Error(`MonitorDog sessionTokenProvider is required.`);if(typeof e.onDetect!=`function`)throw Error(`MonitorDog onDetect callback is required.`);if(e.runtimeAssetBaseUrl!==void 0&&v(e.runtimeAssetBaseUrl),e.modelInputSize!==void 0&&!ne(e.modelInputSize))throw Error(`MonitorDog modelInputSize must be "auto", 320, 416, or 640.`);if(e.phoneRotationFallback!==void 0&&typeof e.phoneRotationFallback!=`boolean`)throw Error(`MonitorDog phoneRotationFallback must be a boolean when provided.`);if(e.phoneRotationFallbackMinIntervalMs!==void 0&&!_e(e.phoneRotationFallbackMinIntervalMs))throw Error(`MonitorDog phoneRotationFallbackMinIntervalMs must be a non-negative finite number when provided.`);if(e.phoneRotationFallbackExecution!==void 0&&e.phoneRotationFallbackExecution!==`sequential`&&e.phoneRotationFallbackExecution!==`parallel`)throw Error(`MonitorDog phoneRotationFallbackExecution must be "sequential" or "parallel" when provided.`);$(e.phoneConfidenceThreshold)}function _e(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function $(e){if(e!==void 0&&(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1))throw Error(`MonitorDog phoneConfidenceThreshold must be a finite number between 0 and 1 when provided.`)}e.MonitorDogDetector=Z,e.MonitorDogSdkError=y,e.configureMonitorDogDetector=fe,e.createMonitorDogDetector=pe,e.getDetector=me,e.isMonitorDogSdkError=b});
|
|
@@ -7,6 +7,7 @@ import { WebcamService } from "./webcam-service";
|
|
|
7
7
|
export type DetectorOptions = Required<Pick<MonitorDogDetectorOptions, "apiBaseUrl">> & MonitorDogDetectorOptions & {
|
|
8
8
|
confidenceThreshold: number;
|
|
9
9
|
faceConfidenceThreshold: number;
|
|
10
|
+
phoneConfidenceThreshold?: number;
|
|
10
11
|
requiredPassword: boolean;
|
|
11
12
|
iouThreshold: number;
|
|
12
13
|
maxDetections: number;
|
|
@@ -33,9 +34,11 @@ export declare class ServiceContainer {
|
|
|
33
34
|
get userPreferences(): Readonly<UserPreferences>;
|
|
34
35
|
updateNoFaceEventDelayFromServer(delayMs: number): void;
|
|
35
36
|
updateRequiredPasswordFromServer(requiredPassword: boolean): void;
|
|
37
|
+
setPhoneConfidenceThreshold(threshold: number | undefined): void;
|
|
36
38
|
degradeInferenceModelForMemoryPressure(): void;
|
|
37
39
|
get shouldPauseForHiddenPage(): boolean;
|
|
38
40
|
get shouldPauseDetection(): boolean;
|
|
39
41
|
applyPolicyItems(items: LockPolicyResponse[], _account: AccountResponse): void;
|
|
40
42
|
resetAuthenticatedState(): void;
|
|
43
|
+
private syncEffectivePhoneConfidenceThreshold;
|
|
41
44
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -70,6 +70,7 @@ export interface MonitorDogDetectorOptions {
|
|
|
70
70
|
detectionIntervalMs?: number;
|
|
71
71
|
runtimeAssetBaseUrl?: string;
|
|
72
72
|
modelInputSize?: MonitorDogModelInputSize;
|
|
73
|
+
phoneConfidenceThreshold?: number;
|
|
73
74
|
phoneRotationFallback?: boolean;
|
|
74
75
|
phoneRotationFallbackMinIntervalMs?: number;
|
|
75
76
|
phoneRotationFallbackExecution?: MonitorDogPhoneRotationFallbackExecution;
|