@jaak.ai/stamps 2.2.0-dev.5 → 2.2.0-dev.9

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.
@@ -0,0 +1,7 @@
1
+ import{r as t,c as e,g as i,h as r}from"./p-BCfAsrzL.js";class n{events=new Map;on(t,e){if(!this.events.has(t)){this.events.set(t,[])}this.events.get(t).push(e)}off(t,e){const i=this.events.get(t);if(i){const t=i.indexOf(e);if(t>-1){i.splice(t,1)}}}emit(t,e){const i=this.events.get(t);if(i){i.forEach((t=>{try{t(e)}catch(t){}}))}}once(t,e){const i=r=>{e(r);this.off(t,i)};this.on(t,i)}clear(){this.events.clear()}}class s{eventBus;captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};constructor(t){this.eventBus=t}getCaptureState(){return{...this.captureState}}updateCaptureState(t){const e={...this.captureState};this.captureState={...this.captureState,...t};this.eventBus.emit("state-changed",{previous:e,current:this.captureState,changes:t})}getCapturedImages(){return JSON.parse(JSON.stringify(this.capturedImages))}setCapturedImages(t){this.capturedImages={...this.capturedImages,...t,metadata:{...this.capturedImages.metadata,...t.metadata}};let e=0;if(this.capturedImages.front.fullFrame&&this.capturedImages.front.cropped){e+=2}if(this.capturedImages.back.fullFrame&&this.capturedImages.back.cropped){e+=2}this.capturedImages.metadata.totalImages=e}reset(){this.captureState={step:"front",isCapturing:false,isDetectionPaused:false,isVideoActive:false,isLoading:false,showFlipAnimation:false,showSuccessAnimation:false,bestScore:0,hasScreenshotTaken:false};this.capturedImages={front:{fullFrame:null,cropped:null},back:{fullFrame:null,cropped:null},metadata:{totalImages:0,processCompleted:false,backCaptureSkipped:false}};this.eventBus.emit("state-changed",{previous:null,current:this.captureState,changes:{reset:true}})}isProcessCompleted(){return this.captureState.step==="completed"}canProceedToBack(){return this.captureState.step==="front"&&this.capturedImages.front.fullFrame!==null&&this.capturedImages.front.cropped!==null}}class o{eventBus;availableCameras=[];selectedCameraId=null;deviceType="desktop";preferredCameraFacing=null;preferredCamera="auto";static cameraCapabilitiesCache=new Map;static deviceEnumerationCache=null;static CACHE_DURATION=3e4;currentStreamPromise;lastStreamConstraints;constructor(t,e="auto"){this.eventBus=t;this.preferredCamera=e}async detectDeviceType(){const t=navigator.userAgent;const e=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t);const i=/iPad|Android/i.test(t)&&window.innerWidth>=768;if(i){this.deviceType="tablet"}else if(e){this.deviceType="mobile"}else{this.deviceType="desktop"}return this.deviceType}async enumerateDevices(){try{const t=Date.now();if(o.deviceEnumerationCache&&t-o.deviceEnumerationCache.timestamp<o.CACHE_DURATION){this.availableCameras=o.deviceEnumerationCache.devices;await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}const e=await this.checkCameraPermission();if(e==="denied"){return[]}if(e==="prompt"){const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()))}const i=await navigator.mediaDevices.enumerateDevices();const r=i.filter((t=>t.kind==="videoinput"));this.availableCameras=r.filter((t=>{const e=this.isVirtualCamera(t);if(e){console.log(`Virtual camera detected and filtered: ${t.label}`)}return!e}));if(this.availableCameras.length===0){console.log("No physical cameras available");this.eventBus.emit("error",new Error("Cámaras virtuales no están permitidas. Use una cámara física."));return[]}o.deviceEnumerationCache={devices:this.availableCameras,timestamp:t};await this.setInitialCameraPreference();this.eventBus.emit("camera-changed",this.selectedCameraId);return this.availableCameras}catch(t){this.handleCameraPermissionError(t);return[]}}getAvailableCameras(){return[...this.availableCameras]}isMultipleCamerasAvailable(){return this.availableCameras.length>1}getSelectedCameraId(){return this.selectedCameraId}async setSelectedCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){throw new Error(`Camera with ID ${t} not found`)}this.selectedCameraId=t;this.updatePreferredFacing(e);this.eventBus.emit("camera-changed",t)}getPreferredFacing(){return this.preferredCameraFacing}async setupCamera(t){try{const e=t||await this.getMaxResolution();if(this.currentStreamPromise&&this.constraintsEqual(e,this.lastStreamConstraints)){return await this.currentStreamPromise}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;const i=await this.currentStreamPromise;const r=i.getVideoTracks()[0];if(r){const t=r.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const r=t.find((t=>t.deviceId===e));if(r&&this.isVirtualCamera(r)){console.log(`Virtual camera detected in active stream: ${r.label}`);i.getTracks().forEach((t=>t.stop()));throw new Error("Cámaras virtuales no están permitidas. Use una cámara física.")}}}return i}catch(t){const e={width:{ideal:1280},height:{ideal:720}};if(this.deviceType!=="desktop"&&this.preferredCameraFacing){e.facingMode=this.preferredCameraFacing}this.currentStreamPromise=navigator.mediaDevices.getUserMedia({video:e,audio:false});this.lastStreamConstraints=e;const i=await this.currentStreamPromise;const r=i.getVideoTracks()[0];if(r){const t=r.getSettings();const e=t.deviceId;if(e){const t=await navigator.mediaDevices.enumerateDevices();const r=t.find((t=>t.deviceId===e));if(r&&this.isVirtualCamera(r)){console.log(`Virtual camera detected in fallback stream: ${r.label}`);i.getTracks().forEach((t=>t.stop()));throw new Error("Cámaras virtuales no están permitidas. Use una cámara física.")}}}return i}}async switchCamera(t){const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){await this.enumerateDevices();return}if(this.isVirtualCamera(e)){console.log(`Attempted to switch to virtual camera: ${e.label}`);this.eventBus.emit("error",new Error("No se puede cambiar a cámara virtual"));return}await this.setSelectedCamera(t)}isRearCamera(t){const e=t.getVideoTracks()[0];if(!e)return false;const i=e.getSettings();return i.facingMode==="environment"}async getCameraInfo(){const t=await Promise.all(this.availableCameras.map((async t=>{const e=await this.checkCameraAutofocus(t.deviceId);return{id:t.deviceId,label:t.label||"Unknown Camera",selected:t.deviceId===this.selectedCameraId,hasAutofocus:e}})));return{availableCameras:t,selectedCameraId:this.selectedCameraId,deviceType:this.deviceType,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable(),preferredFacing:this.preferredCameraFacing}}async checkCameraPermission(){try{if(!navigator.permissions){return"prompt"}const t=await navigator.permissions.query({name:"camera"});return t.state}catch(t){return"prompt"}}handleCameraPermissionError(t){this.availableCameras=[];this.eventBus.emit("error",new Error(`Camera permission error: ${t.message}`))}async setInitialCameraPreference(){if(this.availableCameras.length===0)return;if(this.preferredCamera==="front"){await this.selectFrontCamera()}else if(this.preferredCamera==="back"){await this.selectBackCamera()}else{await this.selectAutoCamera()}}async checkCameraAutofocus(t){try{if(o.cameraCapabilitiesCache.has(t)){const e=o.cameraCapabilitiesCache.get(t);return typeof e==="boolean"?e:false}const e=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:t}}});const i=e.getVideoTracks()[0];const r=i.getCapabilities();e.getTracks().forEach((t=>t.stop()));const n=r.focusMode&&Array.isArray(r.focusMode)&&r.focusMode.length>0;const s=n&&(r.focusMode.includes("continuous")||r.focusMode.includes("auto"));o.cameraCapabilitiesCache.set(t,s);return s}catch(e){o.cameraCapabilitiesCache.set(t,false);return false}}async selectFrontCamera(){this.preferredCameraFacing="user";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("front")||e.includes("user")||e.includes("selfie")||e.includes("frontal")||!e.includes("back")&&!e.includes("rear")&&!e.includes("environment")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectBackCamera(){this.preferredCameraFacing="environment";const t=this.availableCameras.filter((t=>{const e=t.label.toLowerCase();return e.includes("back")||e.includes("rear")||e.includes("environment")||e.includes("trasera")||e.includes("posterior")}));let e=null;if(t.length>0){for(const i of t){const t=await this.checkCameraAutofocus(i.deviceId);if(t){e=i;break}}if(!e){e=t[0]}}else if(this.availableCameras.length>1){const t=this.availableCameras[this.availableCameras.length-1];const i=await this.checkCameraAutofocus(t.deviceId);e=i?t:this.availableCameras[this.availableCameras.length-1]}this.selectedCameraId=e?e.deviceId:this.availableCameras[0].deviceId}async selectAutoCamera(){if(this.deviceType==="mobile"||this.deviceType==="tablet"){await this.selectBackCamera()}else{await this.selectFrontCamera()}}updatePreferredFacing(t){const e=t.label.toLowerCase().includes("back")||t.label.toLowerCase().includes("rear")||t.label.toLowerCase().includes("environment");this.preferredCameraFacing=e?"environment":"user"}async getMaxResolution(){try{if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const t={};if(this.selectedCameraId){t.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const e=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};t.facingMode=e}else{if(this.preferredCamera==="front"){t.facingMode="user"}else if(this.preferredCamera==="back"){t.facingMode="environment"}else{t.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}let e;if(this.selectedCameraId&&o.cameraCapabilitiesCache.has(this.selectedCameraId+"_caps")){e=JSON.parse(o.cameraCapabilitiesCache.get(this.selectedCameraId+"_caps"))}else{const i=await navigator.mediaDevices.getUserMedia({video:t});const r=i.getVideoTracks()[0];e=r.getCapabilities();i.getTracks().forEach((t=>t.stop()));if(this.selectedCameraId){o.cameraCapabilitiesCache.set(this.selectedCameraId+"_caps",JSON.stringify(e))}}const i={...t};if(e.width&&e.height){const t=Math.min(e.width.max,1920);const r=Math.min(e.height.max,1080);const n=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;if(n){i.width={ideal:Math.min(t,1280)};i.height={ideal:Math.min(r,720)}}else{i.width={ideal:t};i.height={ideal:r}}}const r=e;if(r.focusMode&&Array.isArray(r.focusMode)){if(r.focusMode.includes("continuous")){i.focusMode="continuous"}else if(r.focusMode.includes("auto")){i.focusMode="auto"}}return i}catch(t){if(!this.deviceType||this.deviceType==="desktop"){await this.detectDeviceType()}const e=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;const i={width:{ideal:e?1280:1920},height:{ideal:e?720:1080}};if(this.selectedCameraId){i.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){const t=this.deviceType==="desktop"?{ideal:this.preferredCameraFacing}:{exact:this.preferredCameraFacing};i.facingMode=t}else{if(this.preferredCamera==="front"){i.facingMode="user"}else if(this.preferredCamera==="back"){i.facingMode="environment"}else{i.facingMode=this.deviceType==="mobile"||this.deviceType==="tablet"?"environment":"user"}}return i}}constraintsEqual(t,e){if(!t||!e)return false;return JSON.stringify(t)===JSON.stringify(e)}static clearCaches(){o.cameraCapabilitiesCache.clear();o.deviceEnumerationCache=null}invalidateDeviceCache(){o.deviceEnumerationCache=null}isVirtualCamera(t){const e=t.label.toLowerCase();const i=["obs","virtual","snap camera","manycam","xsplit","camtwist","ecamm","nvidia broadcast","droidcam","iriun","elgato","streamlabs","wirecast","zoom virtual","teams virtual","mmhmm","camo","reincubate camo","webcamoid","splitcam","cheese","guvcview","yawcam","webcam 7","altserver"];return i.some((t=>e.includes(t)))}}class a{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const r=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:true,isSlowConnection:r}}getSessionOptions(t){return{executionProviders:["wasm"],graphOptimizationLevel:"basic",logSeverityLevel:4,logVerbosityLevel:0,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1}}shouldUseSequentialLoading(){return true}}class c{getDeviceInfo(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=t.connection||t.mozConnection||t.webkitConnection;const r=i&&(i.effectiveType==="slow-2g"||i.effectiveType==="2g");return{estimatedRAM:e,isLowMemory:false,isSlowConnection:r}}getSessionOptions(t){return{executionProviders:["webgl","wasm"],graphOptimizationLevel:"all",logSeverityLevel:t?2:4,logVerbosityLevel:0,enableCpuMemArena:true,enableMemPattern:true,executionMode:"parallel",interOpNumThreads:2,intraOpNumThreads:2}}shouldUseSequentialLoading(){return false}}class u{static createStrategy(){const t=navigator;const e=t.deviceMemory||t.hardwareConcurrency||4;const i=e<=4;if(i){return new a}else{return new c}}}class f{debug;useDocumentClassification;useDocumentDetector;session;mobileNetSession;mobileNetClassMap;modelLoaded=false;deviceStrategy;MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";MOBILENET_MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/squeezenet_new_fp32.onnx";MOBILENET_CLASSES_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;preprocessCanvas;preprocessCtx;captureCanvas;static canvasPool=new Map;static MAX_POOL_SIZE=5;constructor(t=false,e=false,i=true){this.debug=t;this.useDocumentClassification=e;this.useDocumentDetector=i;this.deviceStrategy=u.createStrategy();this.initializeCanvasPool()}async loadModel(){if(this.modelLoaded||this.session){return}if(!this.useDocumentDetector){this.modelLoaded=true;return}try{const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.session=await window.ort.InferenceSession.create(this.MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}this.modelLoaded=true}catch(t){throw t}}async loadClassificationModel(){if(!this.useDocumentClassification){return}try{try{const t=await fetch(this.MOBILENET_CLASSES_PATH);if(t.ok){this.mobileNetClassMap=await t.json()}}catch(t){this.mobileNetClassMap={0:"document",1:"id_card",2:"passport",3:"license",4:"other"}}const t=this.deviceStrategy.getSessionOptions(this.debug);try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){const e=t.message.includes("failed to allocate a buffer")||t.message.includes("Out of memory")||t.message.includes("RangeError: Out of memory")||t.message.includes("no available backend found");if(e){const t={executionProviders:["wasm"],graphOptimizationLevel:"disabled",logSeverityLevel:4,enableCpuMemArena:false,enableMemPattern:false,executionMode:"sequential",interOpNumThreads:1,intraOpNumThreads:1,enableProfiling:false,sessionLogSeverityLevel:4,sessionLogVerbosityLevel:0};try{this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,t)}catch(t){throw new Error(`no available backend found. ERR: [wasm] RangeError: Out of memory`)}}else{throw t}}}catch(t){throw t}}isModelLoaded(){if(!this.useDocumentDetector){return this.modelLoaded}return this.modelLoaded&&!!this.session}preprocess(t){if(!this.preprocessCanvas||!this.preprocessCtx){this.initializeCanvasPool()}this.preprocessCtx.clearRect(0,0,this.INPUT_SIZE,this.INPUT_SIZE);this.preprocessCtx.drawImage(t,0,0,this.INPUT_SIZE,this.INPUT_SIZE);const e=this.preprocessCtx.getImageData(0,0,this.INPUT_SIZE,this.INPUT_SIZE);const[i,r,n]=[[],[],[]];const{data:s}=e;for(let t=0;t<s.length;t+=4){i.push(s[t]/255);r.push(s[t+1]/255);n.push(s[t+2]/255)}const o=new Float32Array(i.concat(r,n));const a=new Uint16Array(o.length);for(let t=0;t<o.length;t++){a[t]=this.float32ToFloat16(o[t])}return new window.ort.Tensor("float16",a,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}async runInference(t){if(!this.useDocumentDetector){return[]}if(!this.session){throw new Error("Detection model not loaded")}const e={[this.session.inputNames[0]]:t};const i=await this.session.run(e);const r=i[this.session.outputNames[0]].data;const n=[];for(let t=0;t<r.length;t+=6){const[e,i,s,o,a,c]=r.slice(t,t+6);if(a>this.CONFIDENCE_THRESHOLD){n.push({x:e,y:i,w:s-e,h:o-i,score:a,classId:c})}}return n}async classifyDocument(t){if(!this.mobileNetSession||!this.mobileNetClassMap){return null}try{const e=this.preprocessMobileNet(t);const i={[this.mobileNetSession.inputNames[0]]:e};const r=await this.mobileNetSession.run(i);const n=r[Object.keys(r)[0]].data;const s=n.reduce(((t,e,i,r)=>e>r[t]?i:t),0);const o=n[s];const a=this.mobileNetClassMap[s.toString()]||"unknown";return{class:a,confidence:o,classIndex:s}}catch(t){return null}}checkSideAlignment(t,e){const{INPUT_SIZE:i,ID1_ASPECT_RATIO:r,shouldMirrorVideo:n,alignmentTolerance:s,maskSize:o,videoRef:a}=e;if(!a){return{top:false,right:false,bottom:false,left:false}}const c=a.videoWidth;const u=a.videoHeight;if(c===0||u===0){return{top:false,right:false,bottom:false,left:false}}const f=c/u;const l=1;let h,d;if(f>l){h=i;d=i/f}else{d=i;h=i*f}const p=d*r;let m,b;const v=o/100;if(p<=h){b=d*v;m=b*r}else{m=h*v;b=m/r}const w=m*(i/h);const g=b*(i/d);const y=i/2;const x=i/2;const k=y-w/2;const S=y+w/2;const _=x-g/2;const T=x+g/2;let E=t.x;let C=t.x+t.w;const M=t.y;const A=t.y+t.h;if(n){const t=E;const e=C;E=i-e;C=i-t}const P=s;const I=Math.abs(M-_)<=P;const O=Math.abs(C-S)<=P;const L=Math.abs(A-T)<=P;const j=Math.abs(E-k)<=P;return{top:I&&j,right:I&&O,bottom:L&&j,left:L&&O}}isCardInFrame(t){const e=t.x+t.w/2;const i=t.y+t.h/2;const r=this.INPUT_SIZE/2;const n=this.INPUT_SIZE/2;const s=40;const o=30;const a=Math.abs(e-r)<s&&Math.abs(i-n)<o;const c=t.w>150&&t.w<300&&t.h>90&&t.h<200;return a&&c}areAllSidesAligned(t){return t.top&&t.right&&t.bottom&&t.left}cleanup(){this.cleanupCanvasPool();if(this.session){this.session.release?.();this.session=undefined}if(this.mobileNetSession){this.mobileNetSession.release?.();this.mobileNetSession=undefined}this.mobileNetClassMap=undefined;this.modelLoaded=false}initializeCanvasPool(){this.preprocessCanvas=document.createElement("canvas");this.preprocessCanvas.width=this.INPUT_SIZE;this.preprocessCanvas.height=this.INPUT_SIZE;this.preprocessCtx=this.preprocessCanvas.getContext("2d",{alpha:false,willReadFrequently:true});this.captureCanvas=document.createElement("canvas")}cleanupCanvasPool(){if(this.preprocessCanvas){this.preprocessCtx=undefined;this.preprocessCanvas=undefined}if(this.captureCanvas){this.captureCanvas=undefined}}float32ToFloat16(t){const e=new ArrayBuffer(4);const i=new DataView(e);i.setFloat32(0,t,true);const r=i.getUint32(0,true);const n=r>>31&1;const s=r>>23&255;const o=r&8388607;let a=s-127+15;if(s===0){a=0}else if(s===255){a=31}else if(a>=31){a=31;return n<<15|a<<10}else if(a<=0){return n<<15}return n<<15|a<<10|o>>13}preprocessMobileNet(t){const e=this.getCanvas(224,224);const i=e.getContext("2d");i.clearRect(0,0,224,224);i.drawImage(t,0,0,224,224);const r=i.getImageData(0,0,224,224);const n=r.data;const s=224*224;const o=new Float32Array(3*s);for(let t=0;t<s;t++){o[t]=n[t*4+0]/255;o[s+t]=n[t*4+1]/255;o[2*s+t]=n[t*4+2]/255}this.returnCanvas(e);return new window.ort.Tensor("float32",o,[1,3,224,224])}getCanvas(t,e){const i=`${t}x${e}`;if(!f.canvasPool.has(i)){f.canvasPool.set(i,[])}const r=f.canvasPool.get(i);let n=r.pop();if(!n){n=document.createElement("canvas");n.width=t;n.height=e}else{const i=n.getContext("2d");i.clearRect(0,0,t,e)}return n}returnCanvas(t){const e=`${t.width}x${t.height}`;if(!f.canvasPool.has(e)){f.canvasPool.set(e,[])}const i=f.canvasPool.get(e);if(i.length<f.MAX_POOL_SIZE){i.push(t)}}static clearCanvasPools(){f.canvasPool.clear()}getPoolStats(){const t={};f.canvasPool.forEach(((e,i)=>{t[i]=e.length}));return t}}var l=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};var h="1.9.0";var d=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function p(t){var e=new Set([t]);var i=new Set;var r=t.match(d);if(!r){return function(){return false}}var n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null){return function e(i){return i===t}}function s(t){i.add(t);return false}function o(t){e.add(t);return true}return function t(r){if(e.has(r)){return true}if(i.has(r)){return false}var a=r.match(d);if(!a){return s(r)}var c={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(c.prerelease!=null){return s(r)}if(n.major!==c.major){return s(r)}if(n.major===0){if(n.minor===c.minor&&n.patch<=c.patch){return o(r)}return s(r)}if(n.minor<=c.minor){return o(r)}return s(r)}}var m=p(h);var b=h.split(".")[0];var v=Symbol.for("opentelemetry.js.api."+b);var w=l;function g(t,e,i,r){var n;if(r===void 0){r=false}var s=w[v]=(n=w[v])!==null&&n!==void 0?n:{version:h};if(!r&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);i.error(o.stack||o.message);return false}if(s.version!==h){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+h);i.error(o.stack||o.message);return false}s[t]=e;i.debug("@opentelemetry/api: Registered a global for "+t+" v"+h+".");return true}function y(t){var e,i;var r=(e=w[v])===null||e===void 0?void 0:e.version;if(!r||!m(r)){return}return(i=w[v])===null||i===void 0?void 0:i[t]}function x(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+h+".");var i=w[v];if(i){delete i[t]}}var k=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var S=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var _=function(){function t(t){this._namespace=t.namespace||"DiagComponentLogger"}t.prototype.debug=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("debug",this._namespace,t)};t.prototype.error=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("error",this._namespace,t)};t.prototype.info=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("info",this._namespace,t)};t.prototype.warn=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("warn",this._namespace,t)};t.prototype.verbose=function(){var t=[];for(var e=0;e<arguments.length;e++){t[e]=arguments[e]}return T("verbose",this._namespace,t)};return t}();function T(t,e,i){var r=y("diag");if(!r){return}i.unshift(e);return r[t].apply(r,S([],k(i),false))}var E;(function(t){t[t["NONE"]=0]="NONE";t[t["ERROR"]=30]="ERROR";t[t["WARN"]=50]="WARN";t[t["INFO"]=60]="INFO";t[t["DEBUG"]=70]="DEBUG";t[t["VERBOSE"]=80]="VERBOSE";t[t["ALL"]=9999]="ALL"})(E||(E={}));function C(t,e){if(t<E.NONE){t=E.NONE}else if(t>E.ALL){t=E.ALL}e=e||{};function i(i,r){var n=e[i];if(typeof n==="function"&&t>=r){return n.bind(e)}return function(){}}return{error:i("error",E.ERROR),warn:i("warn",E.WARN),info:i("info",E.INFO),debug:i("debug",E.DEBUG),verbose:i("verbose",E.VERBOSE)}}var M=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var A=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var P="diag";var I=function(){function t(){function t(t){return function(){var e=[];for(var i=0;i<arguments.length;i++){e[i]=arguments[i]}var r=y("diag");if(!r)return;return r[t].apply(r,A([],M(e),false))}}var e=this;var i=function(t,i){var r,n,s;if(i===void 0){i={logLevel:E.INFO}}if(t===e){var o=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");e.error((r=o.stack)!==null&&r!==void 0?r:o.message);return false}if(typeof i==="number"){i={logLevel:i}}var a=y("diag");var c=C((n=i.logLevel)!==null&&n!==void 0?n:E.INFO,t);if(a&&!i.suppressOverrideMessage){var u=(s=(new Error).stack)!==null&&s!==void 0?s:"<failed to generate stacktrace>";a.warn("Current logger will be overwritten from "+u);c.warn("Current logger will overwrite one already registered from "+u)}return g("diag",c,e,true)};e.setLogger=i;e.disable=function(){x(P,e)};e.createComponentLogger=function(t){return new _(t)};e.verbose=t("verbose");e.debug=t("debug");e.info=t("info");e.warn=t("warn");e.error=t("error")}t.instance=function(){if(!this._instance){this._instance=new t}return this._instance};return t}();var O=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var L=undefined&&undefined.__values||function(t){var e=typeof Symbol==="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length==="number")return{next:function(){if(t&&r>=t.length)t=void 0;return{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};var j=function(){function t(t){this._entries=t?new Map(t):new Map}t.prototype.getEntry=function(t){var e=this._entries.get(t);if(!e){return undefined}return Object.assign({},e)};t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map((function(t){var e=O(t,2),i=e[0],r=e[1];return[i,r]}))};t.prototype.setEntry=function(e,i){var r=new t(this._entries);r._entries.set(e,i);return r};t.prototype.removeEntry=function(e){var i=new t(this._entries);i._entries.delete(e);return i};t.prototype.removeEntries=function(){var e,i;var r=[];for(var n=0;n<arguments.length;n++){r[n]=arguments[n]}var s=new t(this._entries);try{for(var o=L(r),a=o.next();!a.done;a=o.next()){var c=a.value;s._entries.delete(c)}}catch(t){e={error:t}}finally{try{if(a&&!a.done&&(i=o.return))i.call(o)}finally{if(e)throw e.error}}return s};t.prototype.clear=function(){return new t};return t}();var R=Symbol("BaggageEntryMetadata");var N=I.instance();function z(t){if(t===void 0){t={}}return new j(new Map(Object.entries(t)))}function $(t){if(typeof t!=="string"){N.error("Cannot create baggage metadata from unknown type: "+typeof t);t=""}return{__TYPE__:R,toString:function(){return t}}}function D(t){return Symbol.for(t)}var F=function(){function t(e){var i=this;i._currentContext=e?new Map(e):new Map;i.getValue=function(t){return i._currentContext.get(t)};i.setValue=function(e,r){var n=new t(i._currentContext);n._currentContext.set(e,r);return n};i.deleteValue=function(e){var r=new t(i._currentContext);r._currentContext.delete(e);return r}}return t}();var U=new F;var B=undefined&&undefined.__extends||function(){var t=function(e,i){t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i))t[i]=e[i]};return t(e,i)};return function(e,i){if(typeof i!=="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(e,i);function r(){this.constructor=e}e.prototype=i===null?Object.create(i):(r.prototype=i.prototype,new r)}}();var q=function(){function t(){}t.prototype.createGauge=function(t,e){return et};t.prototype.createHistogram=function(t,e){return it};t.prototype.createCounter=function(t,e){return tt};t.prototype.createUpDownCounter=function(t,e){return rt};t.prototype.createObservableGauge=function(t,e){return st};t.prototype.createObservableCounter=function(t,e){return nt};t.prototype.createObservableUpDownCounter=function(t,e){return ot};t.prototype.addBatchObservableCallback=function(t,e){};t.prototype.removeBatchObservableCallback=function(t){};return t}();var V=function(){function t(){}return t}();var H=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(V);var G=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.add=function(t,e){};return e}(V);var Z=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(V);var W=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}e.prototype.record=function(t,e){};return e}(V);var X=function(){function t(){}t.prototype.addCallback=function(t){};t.prototype.removeCallback=function(t){};return t}();var Y=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var J=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var K=function(t){B(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(X);var Q=new q;var tt=new H;var et=new Z;var it=new W;var rt=new G;var nt=new Y;var st=new J;var ot=new K;function at(){return Q}var ct;(function(t){t[t["INT"]=0]="INT";t[t["DOUBLE"]=1]="DOUBLE"})(ct||(ct={}));var ut={get:function(t,e){if(t==null){return undefined}return t[e]},keys:function(t){if(t==null){return[]}return Object.keys(t)}};var ft={set:function(t,e,i){if(t==null){return}t[e]=i}};var lt=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var ht=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var dt=function(){function t(){}t.prototype.active=function(){return U};t.prototype.with=function(t,e,i){var r=[];for(var n=3;n<arguments.length;n++){r[n-3]=arguments[n]}return e.call.apply(e,ht([i],lt(r),false))};t.prototype.bind=function(t,e){return e};t.prototype.enable=function(){return this};t.prototype.disable=function(){return this};return t}();var pt=undefined&&undefined.__read||function(t,e){var i=typeof Symbol==="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{while((e===void 0||e-- >0)&&!(n=r.next()).done)s.push(n.value)}catch(t){o={error:t}}finally{try{if(n&&!n.done&&(i=r["return"]))i.call(r)}finally{if(o)throw o.error}}return s};var mt=undefined&&undefined.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++){if(s||!(r in e)){if(!s)s=Array.prototype.slice.call(e,0,r);s[r]=e[r]}}return t.concat(s||Array.prototype.slice.call(e))};var bt="context";var vt=new dt;var wt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalContextManager=function(t){return g(bt,t,I.instance())};t.prototype.active=function(){return this._getContextManager().active()};t.prototype.with=function(t,e,i){var r;var n=[];for(var s=3;s<arguments.length;s++){n[s-3]=arguments[s]}return(r=this._getContextManager()).with.apply(r,mt([t,e,i],pt(n),false))};t.prototype.bind=function(t,e){return this._getContextManager().bind(t,e)};t.prototype._getContextManager=function(){return y(bt)||vt};t.prototype.disable=function(){this._getContextManager().disable();x(bt,I.instance())};return t}();var gt;(function(t){t[t["NONE"]=0]="NONE";t[t["SAMPLED"]=1]="SAMPLED"})(gt||(gt={}));var yt="0000000000000000";var xt="00000000000000000000000000000000";var kt={traceId:xt,spanId:yt,traceFlags:gt.NONE};var St=function(){function t(t){if(t===void 0){t=kt}this._spanContext=t}t.prototype.spanContext=function(){return this._spanContext};t.prototype.setAttribute=function(t,e){return this};t.prototype.setAttributes=function(t){return this};t.prototype.addEvent=function(t,e){return this};t.prototype.addLink=function(t){return this};t.prototype.addLinks=function(t){return this};t.prototype.setStatus=function(t){return this};t.prototype.updateName=function(t){return this};t.prototype.end=function(t){};t.prototype.isRecording=function(){return false};t.prototype.recordException=function(t,e){};return t}();var _t=D("OpenTelemetry Context Key SPAN");function Tt(t){return t.getValue(_t)||undefined}function Et(){return Tt(wt.getInstance().active())}function Ct(t,e){return t.setValue(_t,e)}function Mt(t){return t.deleteValue(_t)}function At(t,e){return Ct(t,new St(e))}function Pt(t){var e;return(e=Tt(t))===null||e===void 0?void 0:e.spanContext()}var It=/^([0-9a-f]{32})$/i;var Ot=/^[0-9a-f]{16}$/i;function Lt(t){return It.test(t)&&t!==xt}function jt(t){return Ot.test(t)&&t!==yt}function Rt(t){return Lt(t.traceId)&&jt(t.spanId)}function Nt(t){return new St(t)}var zt=wt.getInstance();var $t=function(){function t(){}t.prototype.startSpan=function(t,e,i){if(i===void 0){i=zt.active()}var r=Boolean(e===null||e===void 0?void 0:e.root);if(r){return new St}var n=i&&Pt(i);if(Dt(n)&&Rt(n)){return new St(n)}else{return new St}};t.prototype.startActiveSpan=function(t,e,i,r){var n;var s;var o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){n=e;o=i}else{n=e;s=i;o=r}var a=s!==null&&s!==void 0?s:zt.active();var c=this.startSpan(t,n,a);var u=Ct(a,c);return zt.with(u,o,undefined,c)};return t}();function Dt(t){return typeof t==="object"&&typeof t["spanId"]==="string"&&typeof t["traceId"]==="string"&&typeof t["traceFlags"]==="number"}var Ft=new $t;var Ut=function(){function t(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}t.prototype.startSpan=function(t,e,i){return this._getTracer().startSpan(t,e,i)};t.prototype.startActiveSpan=function(t,e,i,r){var n=this._getTracer();return Reflect.apply(n.startActiveSpan,n,arguments)};t.prototype._getTracer=function(){if(this._delegate){return this._delegate}var t=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!t){return Ft}this._delegate=t;return this._delegate};return t}();var Bt=function(){function t(){}t.prototype.getTracer=function(t,e,i){return new $t};return t}();var qt=new Bt;var Vt=function(){function t(){}t.prototype.getTracer=function(t,e,i){var r;return(r=this.getDelegateTracer(t,e,i))!==null&&r!==void 0?r:new Ut(this,t,e,i)};t.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:qt};t.prototype.setDelegate=function(t){this._delegate=t};t.prototype.getDelegateTracer=function(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(t,e,i)};return t}();var Ht;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(Ht||(Ht={}));var Gt;(function(t){t[t["INTERNAL"]=0]="INTERNAL";t[t["SERVER"]=1]="SERVER";t[t["CLIENT"]=2]="CLIENT";t[t["PRODUCER"]=3]="PRODUCER";t[t["CONSUMER"]=4]="CONSUMER"})(Gt||(Gt={}));var Zt;(function(t){t[t["UNSET"]=0]="UNSET";t[t["OK"]=1]="OK";t[t["ERROR"]=2]="ERROR"})(Zt||(Zt={}));var Wt=wt.getInstance();var Xt=I.instance();var Yt=function(){function t(){}t.prototype.getMeter=function(t,e,i){return Q};return t}();var Jt=new Yt;var Kt="metrics";var Qt=function(){function t(){}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalMeterProvider=function(t){return g(Kt,t,I.instance())};t.prototype.getMeterProvider=function(){return y(Kt)||Jt};t.prototype.getMeter=function(t,e,i){return this.getMeterProvider().getMeter(t,e,i)};t.prototype.disable=function(){x(Kt,I.instance())};return t}();var te=Qt.getInstance();var ee=function(){function t(){}t.prototype.inject=function(t,e){};t.prototype.extract=function(t,e){return t};t.prototype.fields=function(){return[]};return t}();var ie=D("OpenTelemetry Baggage Key");function re(t){return t.getValue(ie)||undefined}function ne(){return re(wt.getInstance().active())}function se(t,e){return t.setValue(ie,e)}function oe(t){return t.deleteValue(ie)}var ae="propagation";var ce=new ee;var ue=function(){function t(){this.createBaggage=z;this.getBaggage=re;this.getActiveBaggage=ne;this.setBaggage=se;this.deleteBaggage=oe}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalPropagator=function(t){return g(ae,t,I.instance())};t.prototype.inject=function(t,e,i){if(i===void 0){i=ft}return this._getGlobalPropagator().inject(t,e,i)};t.prototype.extract=function(t,e,i){if(i===void 0){i=ut}return this._getGlobalPropagator().extract(t,e,i)};t.prototype.fields=function(){return this._getGlobalPropagator().fields()};t.prototype.disable=function(){x(ae,I.instance())};t.prototype._getGlobalPropagator=function(){return y(ae)||ce};return t}();var fe=ue.getInstance();var le="trace";var he=function(){function t(){this._proxyTracerProvider=new Vt;this.wrapSpanContext=Nt;this.isSpanContextValid=Rt;this.deleteSpan=Mt;this.getSpan=Tt;this.getActiveSpan=Et;this.getSpanContext=Pt;this.setSpan=Ct;this.setSpanContext=At}t.getInstance=function(){if(!this._instance){this._instance=new t}return this._instance};t.prototype.setGlobalTracerProvider=function(t){var e=g(le,this._proxyTracerProvider,I.instance());if(e){this._proxyTracerProvider.setDelegate(t)}return e};t.prototype.getTracerProvider=function(){return y(le)||this._proxyTracerProvider};t.prototype.getTracer=function(t,e){return this.getTracerProvider().getTracer(t,e)};t.prototype.disable=function(){x(le,I.instance());this._proxyTracerProvider=new Vt};return t}();var de=he.getInstance();const pe=D("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function me(t){return t.setValue(pe,true)}function be(t){return t.getValue(pe)===true}const ve="=";const we=";";const ge=",";const ye="baggage";const xe=180;const ke=4096;const Se=8192;function _e(t){return t.reduce(((t,e)=>{const i=`${t}${t!==""?ge:""}${e}`;return i.length>Se?t:i}),"")}function Te(t){return t.getAllEntries().map((([t,e])=>{let i=`${encodeURIComponent(t)}=${encodeURIComponent(e.value)}`;if(e.metadata!==undefined){i+=we+e.metadata.toString()}return i}))}function Ee(t){const e=t.split(we);if(e.length<=0)return;const i=e.shift();if(!i)return;const r=i.indexOf(ve);if(r<=0)return;const n=decodeURIComponent(i.substring(0,r).trim());const s=decodeURIComponent(i.substring(r+1).trim());let o;if(e.length>0){o=$(e.join(we))}return{key:n,value:s,metadata:o}}class Ce{inject(t,e,i){const r=fe.getBaggage(t);if(!r||be(t))return;const n=Te(r).filter((t=>t.length<=ke)).slice(0,xe);const s=_e(n);if(s.length>0){i.set(e,ye,s)}}extract(t,e,i){const r=i.get(e,ye);const n=Array.isArray(r)?r.join(ge):r;if(!n)return t;const s={};if(n.length===0){return t}const o=n.split(ge);o.forEach((t=>{const e=Ee(t);if(e){const t={value:e.value};if(e.metadata){t.metadata=e.metadata}s[e.key]=t}}));if(Object.entries(s).length===0){return t}return fe.setBaggage(t,fe.createBaggage(s))}fields(){return[ye]}}function Me(t){const e={};if(typeof t!=="object"||t==null){return e}for(const i in t){if(!Object.prototype.hasOwnProperty.call(t,i)){continue}if(!Ae(i)){Xt.warn(`Invalid attribute key: ${i}`);continue}const r=t[i];if(!Pe(r)){Xt.warn(`Invalid attribute value set for key: ${i}`);continue}if(Array.isArray(r)){e[i]=r.slice()}else{e[i]=r}}return e}function Ae(t){return typeof t==="string"&&t!==""}function Pe(t){if(t==null){return true}if(Array.isArray(t)){return Ie(t)}return Oe(typeof t)}function Ie(t){let e;for(const i of t){if(i==null)continue;const t=typeof i;if(t===e){continue}if(!e){if(Oe(t)){e=t;continue}return false}return false}return true}function Oe(t){switch(t){case"number":case"boolean":case"string":return true}return false}function Le(){return t=>{Xt.error(je(t))}}function je(t){if(typeof t==="string"){return t}else{return JSON.stringify(Re(t))}}function Re(t){const e={};let i=t;while(i!==null){Object.getOwnPropertyNames(i).forEach((t=>{if(e[t])return;const r=i[t];if(r){e[t]=String(r)}}));i=Object.getPrototypeOf(i)}return e}let Ne=Le();function ze(t){try{Ne(t)}catch{}}function $e(t){return undefined}const De=performance;const Fe="2.2.0";const Ue="exception.message";const Be="exception.stacktrace";const qe="exception.type";const Ve="service.name";const He="telemetry.sdk.language";const Ge="webjs";const Ze="telemetry.sdk.name";const We="telemetry.sdk.version";const Xe="process.runtime.name";const Ye={[Ze]:"opentelemetry",[Xe]:"browser",[He]:Ge,[We]:Fe};const Je=9;const Ke=6;const Qe=Math.pow(10,Ke);const ti=Math.pow(10,Je);function ei(t){const e=t/1e3;const i=Math.trunc(e);const r=Math.round(t%1e3*Qe);return[i,r]}function ii(){let t=De.timeOrigin;if(typeof t!=="number"){const e=De;t=e.timing&&e.timing.fetchStart}return t}function ri(t){const e=ei(ii());const i=ei(typeof t==="number"?t:De.now());return ui(e,i)}function ni(t,e){let i=e[0]-t[0];let r=e[1]-t[1];if(r<0){i-=1;r+=ti}return[i,r]}function si(t){return t[0]*ti+t[1]}function oi(t){return t[0]*1e6+t[1]/1e3}function ai(t){return Array.isArray(t)&&t.length===2&&typeof t[0]==="number"&&typeof t[1]==="number"}function ci(t){return ai(t)||typeof t==="number"||t instanceof Date}function ui(t,e){const i=[t[0]+e[0],t[1]+e[1]];if(i[1]>=ti){i[1]-=ti;i[0]+=1}return i}var fi;(function(t){t[t["SUCCESS"]=0]="SUCCESS";t[t["FAILED"]=1]="FAILED"})(fi||(fi={}));class li{_propagators;_fields;constructor(t={}){this._propagators=t.propagators??[];this._fields=Array.from(new Set(this._propagators.map((t=>typeof t.fields==="function"?t.fields():[])).reduce(((t,e)=>t.concat(e)),[])))}inject(t,e,i){for(const r of this._propagators){try{r.inject(t,e,i)}catch(t){Xt.warn(`Failed to inject with ${r.constructor.name}. Err: ${t.message}`)}}}extract(t,e,i){return this._propagators.reduce(((t,r)=>{try{return r.extract(t,e,i)}catch(t){Xt.warn(`Failed to extract with ${r.constructor.name}. Err: ${t.message}`)}return t}),t)}fields(){return this._fields.slice()}}const hi="[_0-9a-z-*/]";const di=`[a-z]${hi}{0,255}`;const pi=`[a-z0-9]${hi}{0,240}@[a-z]${hi}{0,13}`;const mi=new RegExp(`^(?:${di}|${pi})$`);const bi=/^[ -~]{0,255}[!-~]$/;const vi=/,|=/;function wi(t){return mi.test(t)}function gi(t){return bi.test(t)&&!vi.test(t)}const yi=32;const xi=512;const ki=",";const Si="=";class _i{_internalState=new Map;constructor(t){if(t)this._parse(t)}set(t,e){const i=this._clone();if(i._internalState.has(t)){i._internalState.delete(t)}i._internalState.set(t,e);return i}unset(t){const e=this._clone();e._internalState.delete(t);return e}get(t){return this._internalState.get(t)}serialize(){return this._keys().reduce(((t,e)=>{t.push(e+Si+this.get(e));return t}),[]).join(ki)}_parse(t){if(t.length>xi)return;this._internalState=t.split(ki).reverse().reduce(((t,e)=>{const i=e.trim();const r=i.indexOf(Si);if(r!==-1){const n=i.slice(0,r);const s=i.slice(r+1,e.length);if(wi(n)&&gi(s)){t.set(n,s)}}return t}),new Map);if(this._internalState.size>yi){this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,yi))}}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const t=new _i;t._internalState=new Map(this._internalState);return t}}const Ti="traceparent";const Ei="tracestate";const Ci="00";const Mi="(?!ff)[\\da-f]{2}";const Ai="(?![0]{32})[\\da-f]{32}";const Pi="(?![0]{16})[\\da-f]{16}";const Ii="[\\da-f]{2}";const Oi=new RegExp(`^\\s?(${Mi})-(${Ai})-(${Pi})-(${Ii})(-.*)?\\s?$`);function Li(t){const e=Oi.exec(t);if(!e)return null;if(e[1]==="00"&&e[5])return null;return{traceId:e[2],spanId:e[3],traceFlags:parseInt(e[4],16)}}class ji{inject(t,e,i){const r=de.getSpanContext(t);if(!r||be(t)||!Rt(r))return;const n=`${Ci}-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||gt.NONE).toString(16)}`;i.set(e,Ti,n);if(r.traceState){i.set(e,Ei,r.traceState.serialize())}}extract(t,e,i){const r=i.get(e,Ti);if(!r)return t;const n=Array.isArray(r)?r[0]:r;if(typeof n!=="string")return t;const s=Li(n);if(!s)return t;s.isRemote=true;const o=i.get(e,Ei);if(o){const t=Array.isArray(o)?o.join(","):o;s.traceState=new _i(typeof t==="string"?t:undefined)}return de.setSpanContext(t,s)}fields(){return[Ti,Ei]}}const Ri="[object Object]";const Ni="[object Null]";const zi="[object Undefined]";const $i=Function.prototype;const Di=$i.toString;const Fi=Di.call(Object);const Ui=Object.getPrototypeOf;const Bi=Object.prototype;const qi=Bi.hasOwnProperty;const Vi=Symbol?Symbol.toStringTag:undefined;const Hi=Bi.toString;function Gi(t){if(!Zi(t)||Wi(t)!==Ri){return false}const e=Ui(t);if(e===null){return true}const i=qi.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&Di.call(i)===Fi}function Zi(t){return t!=null&&typeof t=="object"}function Wi(t){if(t==null){return t===undefined?zi:Ni}return Vi&&Vi in Object(t)?Xi(t):Yi(t)}function Xi(t){const e=qi.call(t,Vi),i=t[Vi];let r=false;try{t[Vi]=undefined;r=true}catch{}const n=Hi.call(t);if(r){if(e){t[Vi]=i}else{delete t[Vi]}}return n}function Yi(t){return Hi.call(t)}const Ji=20;function Ki(...t){let e=t.shift();const i=new WeakMap;while(t.length>0){e=tr(e,t.shift(),0,i)}return e}function Qi(t){if(ir(t)){return t.slice()}return t}function tr(t,e,i=0,r){let n;if(i>Ji){return undefined}i++;if(sr(t)||sr(e)||rr(e)){n=Qi(e)}else if(ir(t)){n=t.slice();if(ir(e)){for(let t=0,i=e.length;t<i;t++){n.push(Qi(e[t]))}}else if(nr(e)){const t=Object.keys(e);for(let i=0,r=t.length;i<r;i++){const r=t[i];n[r]=Qi(e[r])}}}else if(nr(t)){if(nr(e)){if(!or(t,e)){return e}n=Object.assign({},t);const s=Object.keys(e);for(let o=0,a=s.length;o<a;o++){const a=s[o];const c=e[a];if(sr(c)){if(typeof c==="undefined"){delete n[a]}else{n[a]=c}}else{const s=n[a];const o=c;if(er(t,a,r)||er(e,a,r)){delete n[a]}else{if(nr(s)&&nr(o)){const i=r.get(s)||[];const n=r.get(o)||[];i.push({obj:t,key:a});n.push({obj:e,key:a});r.set(s,i);r.set(o,n)}n[a]=tr(n[a],c,i,r)}}}}else{n=e}}return n}function er(t,e,i){const r=i.get(t[e])||[];for(let i=0,n=r.length;i<n;i++){const n=r[i];if(n.key===e&&n.obj===t){return true}}return false}function ir(t){return Array.isArray(t)}function rr(t){return typeof t==="function"}function nr(t){return!sr(t)&&!ir(t)&&!rr(t)&&typeof t==="object"}function sr(t){return typeof t==="string"||typeof t==="number"||typeof t==="boolean"||typeof t==="undefined"||t instanceof Date||t instanceof RegExp||t===null}function or(t,e){if(!Gi(t)||!Gi(e)){return false}return true}class ar{_promise;_resolve;_reject;constructor(){this._promise=new Promise(((t,e)=>{this._resolve=t;this._reject=e}))}get promise(){return this._promise}resolve(t){this._resolve(t)}reject(t){this._reject(t)}}class cr{_callback;_that;_isCalled=false;_deferred=new ar;constructor(t,e){this._callback=t;this._that=e}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...t){if(!this._isCalled){this._isCalled=true;try{Promise.resolve(this._callback.call(this._that,...t)).then((t=>this._deferred.resolve(t)),(t=>this._deferred.reject(t)))}catch(t){this._deferred.reject(t)}}return this._deferred.promise}}function ur(t,e){return new Promise((i=>{Wt.with(me(Wt.active()),(()=>{t.export(e,(t=>{i(t)}))}))}))}const fr={_export:ur};function lr(){return"unknown_service"}const hr=t=>t!==null&&typeof t==="object"&&typeof t.then==="function";class dr{_rawAttributes;_asyncAttributesPending=false;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,e){const i=new dr({},e);i._rawAttributes=br(t);i._asyncAttributesPending=t.filter((([t,e])=>hr(e))).length>0;return i}constructor(t,e){const i=t.attributes??{};this._rawAttributes=Object.entries(i).map((([t,e])=>{if(hr(e)){this._asyncAttributesPending=true}return[t,e]}));this._rawAttributes=br(this._rawAttributes);this._schemaUrl=vr(e?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(!this.asyncAttributesPending){return}for(let t=0;t<this._rawAttributes.length;t++){const[e,i]=this._rawAttributes[t];this._rawAttributes[t]=[e,hr(i)?await i:i]}this._asyncAttributesPending=false}get attributes(){if(this.asyncAttributesPending){Xt.error("Accessing resource attributes before async attributes settled")}if(this._memoizedAttributes){return this._memoizedAttributes}const t={};for(const[e,i]of this._rawAttributes){if(hr(i)){Xt.debug(`Unsettled resource attribute ${e} skipped`);continue}if(i!=null){t[e]??=i}}if(!this._asyncAttributesPending){this._memoizedAttributes=t}return t}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;const e=wr(this,t);const i=e?{schemaUrl:e}:undefined;return dr.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],i)}}function pr(t,e){return dr.FromAttributeList(Object.entries(t),e)}function mr(){return pr({[Ve]:lr(),[He]:Ye[He],[Ze]:Ye[Ze],[We]:Ye[We]})}function br(t){return t.map((([t,e])=>{if(hr(e)){return[t,e.catch((e=>{Xt.debug("promise rejection for resource attribute: %s - %s",t,e);return undefined}))]}return[t,e]}))}function vr(t){if(typeof t==="string"||t===undefined){return t}Xt.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",t);return undefined}function wr(t,e){const i=t?.schemaUrl;const r=e?.schemaUrl;const n=i===undefined||i==="";const s=r===undefined||r==="";if(n){return r}if(s){return i}if(i===r){return i}Xt.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.',i,r);return undefined}const gr="exception";class yr{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:Zt.UNSET};endTime=[0,0];_ended=false;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(t){const e=Date.now();this._spanContext=t.spanContext;this._performanceStartTime=De.now();this._performanceOffset=e-(this._performanceStartTime+ii());this._startTimeProvided=t.startTime!=null;this._spanLimits=t.spanLimits;this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0;this._spanProcessor=t.spanProcessor;this.name=t.name;this.parentSpanContext=t.parentSpanContext;this.kind=t.kind;this.links=t.links||[];this.startTime=this._getTime(t.startTime??e);this.resource=t.resource;this.instrumentationScope=t.scope;if(t.attributes!=null){this.setAttributes(t.attributes)}this._spanProcessor.onStart(this,t.context)}spanContext(){return this._spanContext}setAttribute(t,e){if(e==null||this._isSpanEnded())return this;if(t.length===0){Xt.warn(`Invalid attribute key: ${t}`);return this}if(!Pe(e)){Xt.warn(`Invalid attribute value set for key: ${t}`);return this}const{attributeCountLimit:i}=this._spanLimits;if(i!==undefined&&Object.keys(this.attributes).length>=i&&!Object.prototype.hasOwnProperty.call(this.attributes,t)){this._droppedAttributesCount++;return this}this.attributes[t]=this._truncateToSize(e);return this}setAttributes(t){for(const[e,i]of Object.entries(t)){this.setAttribute(e,i)}return this}addEvent(t,e,i){if(this._isSpanEnded())return this;const{eventCountLimit:r}=this._spanLimits;if(r===0){Xt.warn("No events allowed.");this._droppedEventsCount++;return this}if(r!==undefined&&this.events.length>=r){if(this._droppedEventsCount===0){Xt.debug("Dropping extra events.")}this.events.shift();this._droppedEventsCount++}if(ci(e)){if(!ci(i)){i=e}e=undefined}const n=Me(e);this.events.push({name:t,attributes:n,time:this._getTime(i),droppedAttributesCount:0});return this}addLink(t){this.links.push(t);return this}addLinks(t){this.links.push(...t);return this}setStatus(t){if(this._isSpanEnded())return this;this.status={...t};if(this.status.message!=null&&typeof t.message!=="string"){Xt.warn(`Dropping invalid status.message of type '${typeof t.message}', expected 'string'`);delete this.status.message}return this}updateName(t){if(this._isSpanEnded())return this;this.name=t;return this}end(t){if(this._isSpanEnded()){Xt.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this._ended=true;this.endTime=this._getTime(t);this._duration=ni(this.startTime,this.endTime);if(this._duration[0]<0){Xt.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime);this.endTime=this.startTime.slice();this._duration=[0,0]}if(this._droppedEventsCount>0){Xt.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`)}this._spanProcessor.onEnd(this)}_getTime(t){if(typeof t==="number"&&t<=De.now()){return ri(t+this._performanceOffset)}if(typeof t==="number"){return ei(t)}if(t instanceof Date){return ei(t.getTime())}if(ai(t)){return t}if(this._startTimeProvided){return ei(Date.now())}const e=De.now()-this._performanceStartTime;return ui(this.startTime,ei(e))}isRecording(){return this._ended===false}recordException(t,e){const i={};if(typeof t==="string"){i[Ue]=t}else if(t){if(t.code){i[qe]=t.code.toString()}else if(t.name){i[qe]=t.name}if(t.message){i[Ue]=t.message}if(t.stack){i[Be]=t.stack}}if(i[qe]||i[Ue]){this.addEvent(gr,i,e)}else{Xt.warn(`Failed to record an exception ${t}`)}}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const t=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);Xt.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,t)}return this._ended}_truncateToLimitUtil(t,e){if(t.length<=e){return t}return t.substring(0,e)}_truncateToSize(t){const e=this._attributeValueLengthLimit;if(e<=0){Xt.warn(`Attribute value limit must be positive, got ${e}`);return t}if(typeof t==="string"){return this._truncateToLimitUtil(t,e)}if(Array.isArray(t)){return t.map((t=>typeof t==="string"?this._truncateToLimitUtil(t,e):t))}return t}}var xr;(function(t){t[t["NOT_RECORD"]=0]="NOT_RECORD";t[t["RECORD"]=1]="RECORD";t[t["RECORD_AND_SAMPLED"]=2]="RECORD_AND_SAMPLED"})(xr||(xr={}));class kr{shouldSample(){return{decision:xr.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class Sr{shouldSample(){return{decision:xr.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class _r{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(t){this._root=t.root;if(!this._root){ze(new Error("ParentBasedSampler must have a root sampler configured"));this._root=new Sr}this._remoteParentSampled=t.remoteParentSampled??new Sr;this._remoteParentNotSampled=t.remoteParentNotSampled??new kr;this._localParentSampled=t.localParentSampled??new Sr;this._localParentNotSampled=t.localParentNotSampled??new kr}shouldSample(t,e,i,r,n,s){const o=de.getSpanContext(t);if(!o||!Rt(o)){return this._root.shouldSample(t,e,i,r,n,s)}if(o.isRemote){if(o.traceFlags&gt.SAMPLED){return this._remoteParentSampled.shouldSample(t,e,i,r,n,s)}return this._remoteParentNotSampled.shouldSample(t,e,i,r,n,s)}if(o.traceFlags&gt.SAMPLED){return this._localParentSampled.shouldSample(t,e,i,r,n,s)}return this._localParentNotSampled.shouldSample(t,e,i,r,n,s)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class Tr{_ratio;_upperBound;constructor(t=0){this._ratio=t;this._ratio=this._normalize(t);this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(t,e){return{decision:Lt(e)&&this._accumulate(e)<this._upperBound?xr.RECORD_AND_SAMPLED:xr.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(t){if(typeof t!=="number"||isNaN(t))return 0;return t>=1?1:t<=0?0:t}_accumulate(t){let e=0;for(let i=0;i<t.length/8;i++){const r=i*8;const n=parseInt(t.slice(r,r+8),16);e=(e^n)>>>0}return e}}var Er;(function(t){t["AlwaysOff"]="always_off";t["AlwaysOn"]="always_on";t["ParentBasedAlwaysOff"]="parentbased_always_off";t["ParentBasedAlwaysOn"]="parentbased_always_on";t["ParentBasedTraceIdRatio"]="parentbased_traceidratio";t["TraceIdRatio"]="traceidratio"})(Er||(Er={}));const Cr=1;function Mr(){return{sampler:Ar(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:Infinity,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Ar(){const t=Er.ParentBasedAlwaysOn;switch(t){case Er.AlwaysOn:return new Sr;case Er.AlwaysOff:return new kr;case Er.ParentBasedAlwaysOn:return new _r({root:new Sr});case Er.ParentBasedAlwaysOff:return new _r({root:new kr});case Er.TraceIdRatio:return new Tr(Pr());case Er.ParentBasedTraceIdRatio:return new _r({root:new Tr(Pr())});default:Xt.error(`OTEL_TRACES_SAMPLER value "${t}" invalid, defaulting to "${Er.ParentBasedAlwaysOn}".`);return new _r({root:new Sr})}}function Pr(){{Xt.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Cr}.`);return Cr}}const Ir=128;const Or=Infinity;function Lr(t){const e={sampler:Ar()};const i=Mr();const r=Object.assign({},i,e,t);r.generalLimits=Object.assign({},i.generalLimits,t.generalLimits||{});r.spanLimits=Object.assign({},i.spanLimits,t.spanLimits||{});return r}function jr(t){const e=Object.assign({},t.spanLimits);e.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??$e()??$e()??Ir;e.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??$e()??$e()??Or;return Object.assign({},t,{spanLimits:e})}class Rr{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=false;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(t,e){this._exporter=t;this._maxExportBatchSize=typeof e?.maxExportBatchSize==="number"?e.maxExportBatchSize:512;this._maxQueueSize=typeof e?.maxQueueSize==="number"?e.maxQueueSize:2048;this._scheduledDelayMillis=typeof e?.scheduledDelayMillis==="number"?e.scheduledDelayMillis:5e3;this._exportTimeoutMillis=typeof e?.exportTimeoutMillis==="number"?e.exportTimeoutMillis:3e4;this._shutdownOnce=new cr(this._shutdown,this);if(this._maxExportBatchSize>this._maxQueueSize){Xt.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize");this._maxExportBatchSize=this._maxQueueSize}}forceFlush(){if(this._shutdownOnce.isCalled){return this._shutdownOnce.promise}return this._flushAll()}onStart(t,e){}onEnd(t){if(this._shutdownOnce.isCalled){return}if((t.spanContext().traceFlags&gt.SAMPLED)===0){return}this._addToBuffer(t)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then((()=>this.onShutdown())).then((()=>this._flushAll())).then((()=>this._exporter.shutdown()))}_addToBuffer(t){if(this._finishedSpans.length>=this._maxQueueSize){if(this._droppedSpansCount===0){Xt.debug("maxQueueSize reached, dropping spans")}this._droppedSpansCount++;return}if(this._droppedSpansCount>0){Xt.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`);this._droppedSpansCount=0}this._finishedSpans.push(t);this._maybeStartTimer()}_flushAll(){return new Promise(((t,e)=>{const i=[];const r=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let t=0,e=r;t<e;t++){i.push(this._flushOneBatch())}Promise.all(i).then((()=>{t()})).catch(e)}))}_flushOneBatch(){this._clearTimer();if(this._finishedSpans.length===0){return Promise.resolve()}return new Promise(((t,e)=>{const i=setTimeout((()=>{e(new Error("Timeout"))}),this._exportTimeoutMillis);Wt.with(me(Wt.active()),(()=>{let r;if(this._finishedSpans.length<=this._maxExportBatchSize){r=this._finishedSpans;this._finishedSpans=[]}else{r=this._finishedSpans.splice(0,this._maxExportBatchSize)}const n=()=>this._exporter.export(r,(r=>{clearTimeout(i);if(r.code===fi.SUCCESS){t()}else{e(r.error??new Error("BatchSpanProcessor: span export failed"))}}));let s=null;for(let t=0,e=r.length;t<e;t++){const e=r[t];if(e.resource.asyncAttributesPending&&e.resource.waitForAsyncAttributes){s??=[];s.push(e.resource.waitForAsyncAttributes())}}if(s===null){n()}else{Promise.all(s).then(n,(t=>{ze(t);e(t)}))}}))}))}_maybeStartTimer(){if(this._isExporting)return;const t=()=>{this._isExporting=true;this._flushOneBatch().finally((()=>{this._isExporting=false;if(this._finishedSpans.length>0){this._clearTimer();this._maybeStartTimer()}})).catch((t=>{this._isExporting=false;ze(t)}))};if(this._finishedSpans.length>=this._maxExportBatchSize){return t()}if(this._timer!==undefined)return;this._timer=setTimeout((()=>t()),this._scheduledDelayMillis);if(typeof this._timer!=="number"){this._timer.unref()}}_clearTimer(){if(this._timer!==undefined){clearTimeout(this._timer);this._timer=undefined}}}class Nr extends Rr{_visibilityChangeListener;_pageHideListener;constructor(t,e){super(t,e);this.onInit(e)}onInit(t){if(t?.disableAutoFlushOnDocumentHide!==true&&typeof document!=="undefined"){this._visibilityChangeListener=()=>{if(document.visibilityState==="hidden"){this.forceFlush().catch((t=>{ze(t)}))}};this._pageHideListener=()=>{this.forceFlush().catch((t=>{ze(t)}))};document.addEventListener("visibilitychange",this._visibilityChangeListener);document.addEventListener("pagehide",this._pageHideListener)}}onShutdown(){if(typeof document!=="undefined"){if(this._visibilityChangeListener){document.removeEventListener("visibilitychange",this._visibilityChangeListener)}if(this._pageHideListener){document.removeEventListener("pagehide",this._pageHideListener)}}}}const zr=8;const $r=16;class Dr{generateTraceId=Ur($r);generateSpanId=Ur(zr)}const Fr=Array(32);function Ur(t){return function e(){for(let e=0;e<t*2;e++){Fr[e]=Math.floor(Math.random()*16)+48;if(Fr[e]>=58){Fr[e]+=39}}return String.fromCharCode.apply(null,Fr.slice(0,t*2))}}class Br{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(t,e,i,r){const n=Lr(e);this._sampler=n.sampler;this._generalLimits=n.generalLimits;this._spanLimits=n.spanLimits;this._idGenerator=e.idGenerator||new Dr;this._resource=i;this._spanProcessor=r;this.instrumentationScope=t}startSpan(t,e={},i=Wt.active()){if(e.root){i=de.deleteSpan(i)}const r=de.getSpan(i);if(be(i)){Xt.debug("Instrumentation suppressed, returning Noop Span");const t=de.wrapSpanContext(kt);return t}const n=r?.spanContext();const s=this._idGenerator.generateSpanId();let o;let a;let c;if(!n||!de.isSpanContextValid(n)){a=this._idGenerator.generateTraceId()}else{a=n.traceId;c=n.traceState;o=n}const u=e.kind??Gt.INTERNAL;const f=(e.links??[]).map((t=>({context:t.context,attributes:Me(t.attributes)})));const l=Me(e.attributes);const h=this._sampler.shouldSample(i,a,t,u,l,f);c=h.traceState??c;const d=h.decision===Ht.RECORD_AND_SAMPLED?gt.SAMPLED:gt.NONE;const p={traceId:a,spanId:s,traceFlags:d,traceState:c};if(h.decision===Ht.NOT_RECORD){Xt.debug("Recording is off, propagating context in a non-recording span");const t=de.wrapSpanContext(p);return t}const m=Me(Object.assign(l,h.attributes));const b=new yr({resource:this._resource,scope:this.instrumentationScope,context:i,spanContext:p,name:t,kind:u,links:f,parentSpanContext:o,attributes:m,startTime:e.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits});return b}startActiveSpan(t,e,i,r){let n;let s;let o;if(arguments.length<2){return}else if(arguments.length===2){o=e}else if(arguments.length===3){n=e;o=i}else{n=e;s=i;o=r}const a=s??Wt.active();const c=this.startSpan(t,n,a);const u=de.setSpan(a,c);return Wt.with(u,o,undefined,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class qr{_spanProcessors;constructor(t){this._spanProcessors=t}forceFlush(){const t=[];for(const e of this._spanProcessors){t.push(e.forceFlush())}return new Promise((e=>{Promise.all(t).then((()=>{e()})).catch((t=>{ze(t||new Error("MultiSpanProcessor: forceFlush failed"));e()}))}))}onStart(t,e){for(const i of this._spanProcessors){i.onStart(t,e)}}onEnd(t){for(const e of this._spanProcessors){e.onEnd(t)}}shutdown(){const t=[];for(const e of this._spanProcessors){t.push(e.shutdown())}return new Promise(((e,i)=>{Promise.all(t).then((()=>{e()}),i)}))}}var Vr;(function(t){t[t["resolved"]=0]="resolved";t[t["timeout"]=1]="timeout";t[t["error"]=2]="error";t[t["unresolved"]=3]="unresolved"})(Vr||(Vr={}));class Hr{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(t={}){const e=Ki({},Mr(),jr(t));this._resource=e.resource??mr();this._config=Object.assign({},e,{resource:this._resource});const i=[];if(t.spanProcessors?.length){i.push(...t.spanProcessors)}this._activeSpanProcessor=new qr(i)}getTracer(t,e,i){const r=`${t}@${e||""}:${i?.schemaUrl||""}`;if(!this._tracers.has(r)){this._tracers.set(r,new Br({name:t,version:e,schemaUrl:i?.schemaUrl},this._config,this._resource,this._activeSpanProcessor))}return this._tracers.get(r)}forceFlush(){const t=this._config.forceFlushTimeoutMillis;const e=this._activeSpanProcessor["_spanProcessors"].map((e=>new Promise((i=>{let r;const n=setTimeout((()=>{i(new Error(`Span processor did not completed within timeout period of ${t} ms`));r=Vr.timeout}),t);e.forceFlush().then((()=>{clearTimeout(n);if(r!==Vr.timeout){r=Vr.resolved;i(r)}})).catch((t=>{clearTimeout(n);r=Vr.error;i(t)}))}))));return new Promise(((t,i)=>{Promise.all(e).then((e=>{const r=e.filter((t=>t!==Vr.resolved));if(r.length>0){i(r)}else{t()}})).catch((t=>i([t])))}))}shutdown(){return this._activeSpanProcessor.shutdown()}}class Gr{_enabled=false;_currentContext=U;_bindFunction(t=U,e){const i=this;const r=function(...r){return i.with(t,(()=>e.apply(this,r)))};Object.defineProperty(r,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return r}active(){return this._currentContext}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}return e}disable(){this._currentContext=U;this._enabled=false;return this}enable(){if(this._enabled){return this}this._enabled=true;this._currentContext=U;return this}with(t,e,i,...r){const n=this._currentContext;this._currentContext=t||U;try{return e.call(i,...r)}finally{this._currentContext=n}}}function Zr(t){if(t===null){return}if(t===undefined){const t=new Gr;t.enable();Wt.setGlobalContextManager(t);return}t.enable();Wt.setGlobalContextManager(t)}function Wr(t){if(t===null){return}if(t===undefined){fe.setGlobalPropagator(new li({propagators:[new ji,new Ce]}));return}fe.setGlobalPropagator(t)}class Xr extends Hr{constructor(t={}){super(t)}register(t={}){de.setGlobalTracerProvider(this);Wr(t.propagator);Zr(t.contextManager)}}function Yr(t,e){if(t.nodeType===Node.DOCUMENT_NODE){return"/"}const i=Kr(t,e);if(e&&i.indexOf("@id")>0){return i}let r="";if(t.parentNode){r+=Yr(t.parentNode,false)}r+=i;return r}function Jr(t){if(!t.parentNode){return 0}const e=[t.nodeType];if(t.nodeType===Node.CDATA_SECTION_NODE){e.push(Node.TEXT_NODE)}let i=Array.from(t.parentNode.childNodes);i=i.filter((i=>{const r=i.localName;return e.indexOf(i.nodeType)>=0&&r===t.localName}));if(i.length>=1){return i.indexOf(t)+1}return 0}function Kr(t,e){const i=t.nodeType;const r=Jr(t);let n="";if(i===Node.ELEMENT_NODE){const i=t.getAttribute("id");if(e&&i){return`//*[@id="${i}"]`}n=t.localName}else if(i===Node.TEXT_NODE||i===Node.CDATA_SECTION_NODE){n="text()"}else if(i===Node.COMMENT_NODE){n="comment()"}else{return""}if(n&&r>1){return`/${n}[${r}]`}return`/${n}`}class Qr{_delegate;constructor(t){this._delegate=t}export(t,e){this._delegate.export(t,e)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class tn extends Error{code;name="OTLPExporterError";data;constructor(t,e,i){super(t);this.data=i;this.code=e}}function en(t){if(Number.isFinite(t)&&t>0){return t}throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${t}')`)}function rn(t){if(t==null){return undefined}return async()=>t}function nn(t,e,i){return{timeoutMillis:en(t.timeoutMillis??e.timeoutMillis??i.timeoutMillis),concurrencyLimit:t.concurrencyLimit??e.concurrencyLimit??i.concurrencyLimit,compression:t.compression??e.compression??i.compression}}function sn(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class on{_concurrencyLimit;_sendingPromises=[];constructor(t){this._concurrencyLimit=t}pushPromise(t){if(this.hasReachedLimit()){throw new Error("Concurrency Limit reached")}this._sendingPromises.push(t);const e=()=>{const e=this._sendingPromises.indexOf(t);void this._sendingPromises.splice(e,1)};t.then(e,e)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function an(t){return new on(t.concurrencyLimit)}function cn(t){return Object.prototype.hasOwnProperty.call(t,"partialSuccess")}function un(){return{handleResponse(t){if(t==null||!cn(t)||t.partialSuccess==null||Object.keys(t.partialSuccess).length===0){return}Xt.warn("Received Partial Success response:",JSON.stringify(t.partialSuccess))}}}class fn{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(t,e,i,r,n){this._transport=t;this._serializer=e;this._responseHandler=i;this._promiseQueue=r;this._timeout=n;this._diagLogger=Xt.createComponentLogger({namespace:"OTLPExportDelegate"})}export(t,e){this._diagLogger.debug("items to be sent",t);if(this._promiseQueue.hasReachedLimit()){e({code:fi.FAILED,error:new Error("Concurrent export limit reached")});return}const i=this._serializer.serializeRequest(t);if(i==null){e({code:fi.FAILED,error:new Error("Nothing to send")});return}this._promiseQueue.pushPromise(this._transport.send(i,this._timeout).then((t=>{if(t.status==="success"){if(t.data!=null){try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(t.data))}catch(e){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",e,t.data)}}e({code:fi.SUCCESS});return}else if(t.status==="failure"&&t.error){e({code:fi.FAILED,error:t.error});return}else if(t.status==="retryable"){e({code:fi.FAILED,error:new tn("Export failed with retryable status")})}else{e({code:fi.FAILED,error:new tn("Export failed with unknown error")})}}),(t=>e({code:fi.FAILED,error:t}))))}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started");await this.forceFlush();this._transport.shutdown()}}function ln(t,e){return new fn(t.transport,t.serializer,un(),t.promiseHandler,e.timeout)}function hn(t,e,i){return ln({transport:i,serializer:e,promiseHandler:an(t)},{timeout:t.timeoutMillis})}function dn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t["default"]:t}function pn(t){if(t>=48&&t<=57){return t-48}if(t>=97&&t<=102){return t-87}return t-55}function mn(t){const e=new Uint8Array(t.length/2);let i=0;for(let r=0;r<t.length;r+=2){const n=pn(t.charCodeAt(r));const s=pn(t.charCodeAt(r+1));e[i++]=n<<4|s}return e}function bn(t){const e=BigInt(1e9);return BigInt(Math.trunc(t[0]))*e+BigInt(Math.trunc(t[1]))}function vn(t){const e=Number(BigInt.asUintN(32,t));const i=Number(BigInt.asUintN(32,t>>BigInt(32)));return{low:e,high:i}}function wn(t){const e=bn(t);return vn(e)}function gn(t){const e=bn(t);return e.toString()}const yn=typeof BigInt!=="undefined"?gn:si;function xn(t){return t}function kn(t){if(t===undefined)return undefined;return mn(t)}const Sn={encodeHrTime:wn,encodeSpanContext:mn,encodeOptionalSpanContext:kn};function _n(t){if(t===undefined){return Sn}const e=t.useLongBits??true;const i=t.useHex??false;return{encodeHrTime:e?wn:yn,encodeSpanContext:i?xn:mn,encodeOptionalSpanContext:i?xn:kn}}function Tn(t){const e={attributes:Cn(t.attributes),droppedAttributesCount:0};const i=t.schemaUrl;if(i&&i!=="")e.schemaUrl=i;return e}function En(t){return{name:t.name,version:t.version}}function Cn(t){return Object.keys(t).map((e=>Mn(e,t[e])))}function Mn(t,e){return{key:t,value:An(e)}}function An(t){const e=typeof t;if(e==="string")return{stringValue:t};if(e==="number"){if(!Number.isInteger(t))return{doubleValue:t};return{intValue:t}}if(e==="boolean")return{boolValue:t};if(t instanceof Uint8Array)return{bytesValue:t};if(Array.isArray(t))return{arrayValue:{values:t.map(An)}};if(e==="object"&&t!=null)return{kvlistValue:{values:Object.entries(t).map((([t,e])=>Mn(t,e)))}};return{}}var Pn;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE"})(Pn||(Pn={}));var In;(function(t){t["COUNTER"]="COUNTER";t["GAUGE"]="GAUGE";t["HISTOGRAM"]="HISTOGRAM";t["UP_DOWN_COUNTER"]="UP_DOWN_COUNTER";t["OBSERVABLE_COUNTER"]="OBSERVABLE_COUNTER";t["OBSERVABLE_GAUGE"]="OBSERVABLE_GAUGE";t["OBSERVABLE_UP_DOWN_COUNTER"]="OBSERVABLE_UP_DOWN_COUNTER"})(In||(In={}));var On;(function(t){t[t["HISTOGRAM"]=0]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=1]="EXPONENTIAL_HISTOGRAM";t[t["GAUGE"]=2]="GAUGE";t[t["SUM"]=3]="SUM"})(On||(On={}));function Ln(t){return t!==undefined&&t!==null}function jn(t){let e=Object.keys(t);if(e.length===0)return"";e=e.sort();return JSON.stringify(e.map((e=>[e,t[e]])))}function Rn(t){return`${t.name}:${t.version??""}:${t.schemaUrl??""}`}class Nn extends Error{constructor(t){super(t);Object.setPrototypeOf(this,Nn.prototype)}}function zn(t,e){let i;const r=new Promise((function t(r,n){i=setTimeout((function t(){n(new Nn("Operation timed out."))}),e)}));return Promise.race([t,r]).then((t=>{clearTimeout(i);return t}),(t=>{clearTimeout(i);throw t}))}async function $n(t){return Promise.all(t.map((async t=>{try{const e=await t;return{status:"fulfilled",value:e}}catch(t){return{status:"rejected",reason:t}}})))}function Dn(t){return t.status==="rejected"}function Fn(t,e){const i=[];t.forEach((t=>{i.push(...e(t))}));return i}function Un(t,e){if(t.size!==e.size){return false}for(const i of t){if(!e.has(i)){return false}}return true}function Bn(t,e){let i=0;let r=t.length-1;let n=t.length;while(r>=i){const s=i+Math.trunc((r-i)/2);if(t[s]<e){i=s+1}else{n=s;r=s-1}}return n}function qn(t,e){return t.toLowerCase()===e.toLowerCase()}var Vn;(function(t){t[t["DROP"]=0]="DROP";t[t["SUM"]=1]="SUM";t[t["LAST_VALUE"]=2]="LAST_VALUE";t[t["HISTOGRAM"]=3]="HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=4]="EXPONENTIAL_HISTOGRAM"})(Vn||(Vn={}));class Hn{kind=Vn.DROP;createAccumulation(){return undefined}merge(t,e){return undefined}diff(t,e){return undefined}toMetricData(t,e,i,r){return undefined}}function Gn(t){const e=t.map((()=>0));e.push(0);return{buckets:{boundaries:t,counts:e},sum:0,count:0,hasMinMax:false,min:Infinity,max:-Infinity}}class Zn{startTime;_boundaries;_recordMinMax;_current;constructor(t,e,i=true,r=Gn(e)){this.startTime=t;this._boundaries=e;this._recordMinMax=i;this._current=r}record(t){if(Number.isNaN(t)){return}this._current.count+=1;this._current.sum+=t;if(this._recordMinMax){this._current.min=Math.min(t,this._current.min);this._current.max=Math.max(t,this._current.max);this._current.hasMinMax=true}const e=Bn(this._boundaries,t);this._current.buckets.counts[e]+=1}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class Wn{_boundaries;_recordMinMax;kind=Vn.HISTOGRAM;constructor(t,e){this._boundaries=t;this._recordMinMax=e}createAccumulation(t){return new Zn(t,this._boundaries,this._recordMinMax)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=n[t]+s[t]}let a=Infinity;let c=-Infinity;if(this._recordMinMax){if(i.hasMinMax&&r.hasMinMax){a=Math.min(i.min,r.min);c=Math.max(i.max,r.max)}else if(i.hasMinMax){a=i.min;c=i.max}else if(r.hasMinMax){a=r.min;c=r.max}}return new Zn(t.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:i.count+r.count,sum:i.sum+r.sum,hasMinMax:this._recordMinMax&&(i.hasMinMax||r.hasMinMax),min:a,max:c})}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();const n=i.buckets.counts;const s=r.buckets.counts;const o=new Array(n.length);for(let t=0;t<n.length;t++){o[t]=s[t]-n[t]}return new Zn(e.startTime,i.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:i.buckets.boundaries,counts:o},count:r.count-i.count,sum:r.sum-i.sum,hasMinMax:false,min:Infinity,max:-Infinity})}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:On.HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===In.GAUGE||t.type===In.UP_DOWN_COUNTER||t.type===In.OBSERVABLE_GAUGE||t.type===In.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,buckets:n.buckets,count:n.count}}}))}}}class Xn{backing;indexBase;indexStart;indexEnd;constructor(t=new Yn,e=0,i=0,r=0){this.backing=t;this.indexBase=e;this.indexStart=i;this.indexEnd=r}get offset(){return this.indexStart}get length(){if(this.backing.length===0){return 0}if(this.indexEnd===this.indexStart&&this.at(0)===0){return 0}return this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},((t,e)=>this.at(e)))}at(t){const e=this.indexBase-this.indexStart;if(t<e){t+=this.backing.length}t-=e;return this.backing.countAt(t)}incrementBucket(t,e){this.backing.increment(t,e)}decrementBucket(t,e){this.backing.decrement(t,e)}trim(){for(let t=0;t<this.length;t++){if(this.at(t)!==0){this.indexStart+=t;break}else if(t===this.length-1){this.indexStart=this.indexEnd=this.indexBase=0;return}}for(let t=this.length-1;t>=0;t--){if(this.at(t)!==0){this.indexEnd-=this.length-t-1;break}}this._rotate()}downscale(t){this._rotate();const e=1+this.indexEnd-this.indexStart;const i=1<<t;let r=0;let n=0;for(let t=this.indexStart;t<=this.indexEnd;){let s=t%i;if(s<0){s+=i}for(let o=s;o<i&&r<e;o++){this._relocateBucket(n,r);r++;t++}n++}this.indexStart>>=t;this.indexEnd>>=t;this.indexBase=this.indexStart}clone(){return new Xn(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const t=this.indexBase-this.indexStart;if(t===0){return}else if(t>0){this.backing.reverse(0,this.backing.length);this.backing.reverse(0,t);this.backing.reverse(t,this.backing.length)}else{this.backing.reverse(0,this.backing.length);this.backing.reverse(0,this.backing.length+t)}this.indexBase=this.indexStart}_relocateBucket(t,e){if(t===e){return}this.incrementBucket(t,this.backing.emptyBucket(e))}}class Yn{_counts;constructor(t=[0]){this._counts=t}get length(){return this._counts.length}countAt(t){return this._counts[t]}growTo(t,e,i){const r=new Array(t).fill(0);r.splice(i,this._counts.length-e,...this._counts.slice(e));r.splice(0,e,...this._counts.slice(0,e));this._counts=r}reverse(t,e){const i=Math.floor((t+e)/2)-t;for(let r=0;r<i;r++){const i=this._counts[t+r];this._counts[t+r]=this._counts[e-r-1];this._counts[e-r-1]=i}}emptyBucket(t){const e=this._counts[t];this._counts[t]=0;return e}increment(t,e){this._counts[t]+=e}decrement(t,e){if(this._counts[t]>=e){this._counts[t]-=e}else{this._counts[t]=0}}clone(){return new Yn([...this._counts])}}const Jn=52;const Kn=2146435072;const Qn=1048575;const ts=1023;const es=-1023+1;const is=ts;const rs=Math.pow(2,-1022);function ns(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=(i&Kn)>>20;return r-ts}function ss(t){const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);const i=e.getUint32(0);const r=e.getUint32(4);const n=(i&Qn)*Math.pow(2,32);return n+r}function os(t,e){if(t===0||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY||Number.isNaN(t)){return t}return t*Math.pow(2,e)}function as(t){t--;t|=t>>1;t|=t>>2;t|=t>>4;t|=t>>8;t|=t>>16;t++;return t}class cs extends Error{}class us{_shift;constructor(t){this._shift=-t}mapToIndex(t){if(t<rs){return this._minNormalLowerBoundaryIndex()}const e=ns(t);const i=this._rightShift(ss(t)-1,Jn);return e+i>>this._shift}lowerBoundary(t){const e=this._minNormalLowerBoundaryIndex();if(t<e){throw new cs(`underflow: ${t} is < minimum lower boundary: ${e}`)}const i=this._maxNormalLowerBoundaryIndex();if(t>i){throw new cs(`overflow: ${t} is > maximum lower boundary: ${i}`)}return os(1,t<<this._shift)}get scale(){if(this._shift===0){return 0}return-this._shift}_minNormalLowerBoundaryIndex(){let t=es>>this._shift;if(this._shift<2){t--}return t}_maxNormalLowerBoundaryIndex(){return is>>this._shift}_rightShift(t,e){return Math.floor(t*Math.pow(2,-e))}}class fs{_scale;_scaleFactor;_inverseFactor;constructor(t){this._scale=t;this._scaleFactor=os(Math.LOG2E,t);this._inverseFactor=os(Math.LN2,-t)}mapToIndex(t){if(t<=rs){return this._minNormalLowerBoundaryIndex()-1}if(ss(t)===0){const e=ns(t);return(e<<this._scale)-1}const e=Math.floor(Math.log(t)*this._scaleFactor);const i=this._maxNormalLowerBoundaryIndex();if(e>=i){return i}return e}lowerBoundary(t){const e=this._maxNormalLowerBoundaryIndex();if(t>=e){if(t===e){return 2*Math.exp((t-(1<<this._scale))/this._scaleFactor)}throw new cs(`overflow: ${t} is > maximum lower boundary: ${e}`)}const i=this._minNormalLowerBoundaryIndex();if(t<=i){if(t===i){return rs}else if(t===i-1){return Math.exp((t+(1<<this._scale))/this._scaleFactor)/2}throw new cs(`overflow: ${t} is < minimum lower boundary: ${i}`)}return Math.exp(t*this._inverseFactor)}get scale(){return this._scale}_minNormalLowerBoundaryIndex(){return es<<this._scale}_maxNormalLowerBoundaryIndex(){return(is+1<<this._scale)-1}}const ls=-10;const hs=20;const ds=Array.from({length:31},((t,e)=>{if(e>10){return new fs(e-10)}return new us(e-10)}));function ps(t){if(t>hs||t<ls){throw new cs(`expected scale >= ${ls} && <= ${hs}, got: ${t}`)}return ds[t+10]}class ms{low;high;static combine(t,e){return new ms(Math.min(t.low,e.low),Math.max(t.high,e.high))}constructor(t,e){this.low=t;this.high=e}}const bs=20;const vs=160;const ws=2;class gs{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(t,e=vs,i=true,r=0,n=0,s=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Xn,u=new Xn,f=ps(bs)){this.startTime=t;this._maxSize=e;this._recordMinMax=i;this._sum=r;this._count=n;this._zeroCount=s;this._min=o;this._max=a;this._positive=c;this._negative=u;this._mapping=f;if(this._maxSize<ws){Xt.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${ws}`);this._maxSize=ws}}record(t){this.updateByIncrement(t,1)}setStartTime(t){this.startTime=t}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){if(this._count===this._zeroCount){return 0}return this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(t,e){if(Number.isNaN(t)){return}if(t>this._max){this._max=t}if(t<this._min){this._min=t}this._count+=e;if(t===0){this._zeroCount+=e;return}this._sum+=t*e;if(t>0){this._updateBuckets(this._positive,t,e)}else{this._updateBuckets(this._negative,-t,e)}}merge(t){if(this._count===0){this._min=t.min;this._max=t.max}else if(t.count!==0){if(t.min<this.min){this._min=t.min}if(t.max>this.max){this._max=t.max}}this.startTime=t.startTime;this._sum+=t.sum;this._count+=t.count;this._zeroCount+=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._mergeBuckets(this.positive,t,t.positive,e);this._mergeBuckets(this.negative,t,t.negative,e)}diff(t){this._min=Infinity;this._max=-Infinity;this._sum-=t.sum;this._count-=t.count;this._zeroCount-=t.zeroCount;const e=this._minScale(t);this._downscale(this.scale-e);this._diffBuckets(this.positive,t,t.positive,e);this._diffBuckets(this.negative,t,t.negative,e)}clone(){return new gs(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(t,e,i){let r=this._mapping.mapToIndex(e);let n=false;let s=0;let o=0;if(t.length===0){t.indexStart=r;t.indexEnd=t.indexStart;t.indexBase=t.indexStart}else if(r<t.indexStart&&t.indexEnd-r>=this._maxSize){n=true;o=r;s=t.indexEnd}else if(r>t.indexEnd&&r-t.indexStart>=this._maxSize){n=true;o=t.indexStart;s=r}if(n){const t=this._changeScale(s,o);this._downscale(t);r=this._mapping.mapToIndex(e)}this._incrementIndexBy(t,r,i)}_incrementIndexBy(t,e,i){if(i===0){return}if(t.length===0){t.indexStart=t.indexEnd=t.indexBase=e}if(e<t.indexStart){const i=t.indexEnd-e;if(i>=t.backing.length){this._grow(t,i+1)}t.indexStart=e}else if(e>t.indexEnd){const i=e-t.indexStart;if(i>=t.backing.length){this._grow(t,i+1)}t.indexEnd=e}let r=e-t.indexBase;if(r<0){r+=t.backing.length}t.incrementBucket(r,i)}_grow(t,e){const i=t.backing.length;const r=t.indexBase-t.indexStart;const n=i-r;let s=as(e);if(s>this._maxSize){s=this._maxSize}const o=s-r;t.backing.growTo(s,n,o)}_changeScale(t,e){let i=0;while(t-e>=this._maxSize){t>>=1;e>>=1;i++}return i}_downscale(t){if(t===0){return}if(t<0){throw new Error(`impossible change of scale: ${this.scale}`)}const e=this._mapping.scale-t;this._positive.downscale(t);this._negative.downscale(t);this._mapping=ps(e)}_minScale(t){const e=Math.min(this.scale,t.scale);const i=ms.combine(this._highLowAtScale(this.positive,this.scale,e),this._highLowAtScale(t.positive,t.scale,e));const r=ms.combine(this._highLowAtScale(this.negative,this.scale,e),this._highLowAtScale(t.negative,t.scale,e));return Math.min(e-this._changeScale(i.high,i.low),e-this._changeScale(r.high,r.low))}_highLowAtScale(t,e,i){if(t.length===0){return new ms(0,-1)}const r=e-i;return new ms(t.indexStart>>r,t.indexEnd>>r)}_mergeBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){this._incrementIndexBy(t,n+e>>s,i.at(e))}}_diffBuckets(t,e,i,r){const n=i.offset;const s=e.scale-r;for(let e=0;e<i.length;e++){const r=n+e>>s;let o=r-t.indexBase;if(o<0){o+=t.backing.length}t.decrementBucket(o,i.at(e))}t.trim()}}class ys{_maxSize;_recordMinMax;kind=Vn.EXPONENTIAL_HISTOGRAM;constructor(t,e){this._maxSize=t;this._recordMinMax=e}createAccumulation(t){return new gs(t,this._maxSize,this._recordMinMax)}merge(t,e){const i=e.clone();i.merge(t);return i}diff(t,e){const i=e.clone();i.diff(t);return i}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:On.EXPONENTIAL_HISTOGRAM,dataPoints:i.map((([e,i])=>{const n=i.toPointValue();const s=t.type===In.GAUGE||t.type===In.UP_DOWN_COUNTER||t.type===In.OBSERVABLE_GAUGE||t.type===In.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:e,startTime:i.startTime,endTime:r,value:{min:n.hasMinMax?n.min:undefined,max:n.hasMinMax?n.max:undefined,sum:!s?n.sum:undefined,positive:{offset:n.positive.offset,bucketCounts:n.positive.bucketCounts},negative:{offset:n.negative.offset,bucketCounts:n.negative.bucketCounts},count:n.count,scale:n.scale,zeroCount:n.zeroCount}}}))}}}class xs{startTime;_current;sampleTime;constructor(t,e=0,i=[0,0]){this.startTime=t;this._current=e;this.sampleTime=i}record(t){this._current=t;this.sampleTime=ei(Date.now())}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class ks{kind=Vn.LAST_VALUE;createAccumulation(t){return new xs(t)}merge(t,e){const i=oi(e.sampleTime)>=oi(t.sampleTime)?e:t;return new xs(t.startTime,i.toPointValue(),i.sampleTime)}diff(t,e){const i=oi(e.sampleTime)>=oi(t.sampleTime)?e:t;return new xs(e.startTime,i.toPointValue(),i.sampleTime)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:On.GAUGE,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()})))}}}class Ss{startTime;monotonic;_current;reset;constructor(t,e,i=0,r=false){this.startTime=t;this.monotonic=e;this._current=i;this.reset=r}record(t){if(this.monotonic&&t<0){return}this._current+=t}setStartTime(t){this.startTime=t}toPointValue(){return this._current}}class _s{monotonic;kind=Vn.SUM;constructor(t){this.monotonic=t}createAccumulation(t){return new Ss(t,this.monotonic)}merge(t,e){const i=t.toPointValue();const r=e.toPointValue();if(e.reset){return new Ss(e.startTime,this.monotonic,r,e.reset)}return new Ss(t.startTime,this.monotonic,i+r)}diff(t,e){const i=t.toPointValue();const r=e.toPointValue();if(this.monotonic&&i>r){return new Ss(e.startTime,this.monotonic,r,true)}return new Ss(e.startTime,this.monotonic,r-i)}toMetricData(t,e,i,r){return{descriptor:t,aggregationTemporality:e,dataPointType:On.SUM,dataPoints:i.map((([t,e])=>({attributes:t,startTime:e.startTime,endTime:r,value:e.toPointValue()}))),isMonotonic:this.monotonic}}}class Ts{static DEFAULT_INSTANCE=new Hn;createAggregator(t){return Ts.DEFAULT_INSTANCE}}class Es{static MONOTONIC_INSTANCE=new _s(true);static NON_MONOTONIC_INSTANCE=new _s(false);createAggregator(t){switch(t.type){case In.COUNTER:case In.OBSERVABLE_COUNTER:case In.HISTOGRAM:{return Es.MONOTONIC_INSTANCE}default:{return Es.NON_MONOTONIC_INSTANCE}}}}class Cs{static DEFAULT_INSTANCE=new ks;createAggregator(t){return Cs.DEFAULT_INSTANCE}}class Ms{static DEFAULT_INSTANCE=new Wn([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],true);createAggregator(t){return Ms.DEFAULT_INSTANCE}}class As{_recordMinMax;_boundaries;constructor(t,e=true){this._recordMinMax=e;if(t==null){throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array")}t=t.concat();t=t.sort(((t,e)=>t-e));const i=t.lastIndexOf(-Infinity);let r=t.indexOf(Infinity);if(r===-1){r=undefined}this._boundaries=t.slice(i+1,r)}createAggregator(t){return new Wn(this._boundaries,this._recordMinMax)}}class Ps{_maxSize;_recordMinMax;constructor(t=160,e=true){this._maxSize=t;this._recordMinMax=e}createAggregator(t){return new ys(this._maxSize,this._recordMinMax)}}class Is{_resolve(t){switch(t.type){case In.COUNTER:case In.UP_DOWN_COUNTER:case In.OBSERVABLE_COUNTER:case In.OBSERVABLE_UP_DOWN_COUNTER:{return Ls}case In.GAUGE:case In.OBSERVABLE_GAUGE:{return js}case In.HISTOGRAM:{if(t.advice.explicitBucketBoundaries){return new As(t.advice.explicitBucketBoundaries)}return Rs}}Xt.warn(`Unable to recognize instrument type: ${t.type}`);return Os}createAggregator(t){return this._resolve(t).createAggregator(t)}}const Os=new Ts;const Ls=new Es;const js=new Cs;const Rs=new Ms;const Ns=new Is;var zs;(function(t){t[t["DEFAULT"]=0]="DEFAULT";t[t["DROP"]=1]="DROP";t[t["SUM"]=2]="SUM";t[t["LAST_VALUE"]=3]="LAST_VALUE";t[t["EXPLICIT_BUCKET_HISTOGRAM"]=4]="EXPLICIT_BUCKET_HISTOGRAM";t[t["EXPONENTIAL_HISTOGRAM"]=5]="EXPONENTIAL_HISTOGRAM"})(zs||(zs={}));function $s(t){switch(t.type){case zs.DEFAULT:return Ns;case zs.DROP:return Os;case zs.SUM:return Ls;case zs.LAST_VALUE:return js;case zs.EXPONENTIAL_HISTOGRAM:{const e=t;return new Ps(e.options?.maxSize,e.options?.recordMinMax)}case zs.EXPLICIT_BUCKET_HISTOGRAM:{const e=t;if(e.options==null){return Rs}else{return new As(e.options?.boundaries,e.options?.recordMinMax)}}default:throw new Error("Unsupported Aggregation")}}const Ds=t=>({type:zs.DEFAULT});const Fs=t=>Pn.CUMULATIVE;class Us{_shutdown=false;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(t){this._aggregationSelector=t?.aggregationSelector??Ds;this._aggregationTemporalitySelector=t?.aggregationTemporalitySelector??Fs;this._metricProducers=t?.metricProducers??[];this._cardinalitySelector=t?.cardinalitySelector}setMetricProducer(t){if(this._sdkMetricProducer){throw new Error("MetricReader can not be bound to a MeterProvider again.")}this._sdkMetricProducer=t;this.onInitialized()}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}selectCardinalityLimit(t){return this._cardinalitySelector?this._cardinalitySelector(t):2e3}onInitialized(){}async collect(t){if(this._sdkMetricProducer===undefined){throw new Error("MetricReader is not bound to a MetricProducer")}if(this._shutdown){throw new Error("MetricReader is shutdown")}const[e,...i]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:t?.timeoutMillis}),...this._metricProducers.map((e=>e.collect({timeoutMillis:t?.timeoutMillis})))]);const r=e.errors.concat(Fn(i,(t=>t.errors)));const n=e.resourceMetrics.resource;const s=e.resourceMetrics.scopeMetrics.concat(Fn(i,(t=>t.resourceMetrics.scopeMetrics)));return{resourceMetrics:{resource:n,scopeMetrics:s},errors:r}}async shutdown(t){if(this._shutdown){Xt.error("Cannot call shutdown twice.");return}if(t?.timeoutMillis==null){await this.onShutdown()}else{await zn(this.onShutdown(),t.timeoutMillis)}this._shutdown=true}async forceFlush(t){if(this._shutdown){Xt.warn("Cannot forceFlush on already shutdown MetricReader.");return}if(t?.timeoutMillis==null){await this.onForceFlush();return}await zn(this.onForceFlush(),t.timeoutMillis)}}class Bs extends Us{_interval;_exporter;_exportInterval;_exportTimeout;constructor(t){super({aggregationSelector:t.exporter.selectAggregation?.bind(t.exporter),aggregationTemporalitySelector:t.exporter.selectAggregationTemporality?.bind(t.exporter),metricProducers:t.metricProducers});if(t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<=0){throw Error("exportIntervalMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportTimeoutMillis<=0){throw Error("exportTimeoutMillis must be greater than 0")}if(t.exportTimeoutMillis!==undefined&&t.exportIntervalMillis!==undefined&&t.exportIntervalMillis<t.exportTimeoutMillis){throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis")}this._exportInterval=t.exportIntervalMillis??6e4;this._exportTimeout=t.exportTimeoutMillis??3e4;this._exporter=t.exporter}async _runOnce(){try{await zn(this._doRun(),this._exportTimeout)}catch(t){if(t instanceof Nn){Xt.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout);return}ze(t)}}async _doRun(){const{resourceMetrics:t,errors:e}=await this.collect({timeoutMillis:this._exportTimeout});if(e.length>0){Xt.error("PeriodicExportingMetricReader: metrics collection errors",...e)}if(t.resource.asyncAttributesPending){try{await(t.resource.waitForAsyncAttributes?.())}catch(t){Xt.debug("Error while resolving async portion of resource: ",t);ze(t)}}if(t.scopeMetrics.length===0){return}const i=await fr._export(this._exporter,t);if(i.code!==fi.SUCCESS){throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${i.error})`)}}onInitialized(){this._interval=setInterval((()=>{void this._runOnce()}),this._exportInterval);if(typeof this._interval!=="number"){this._interval.unref()}}async onForceFlush(){await this._runOnce();await this._exporter.forceFlush()}async onShutdown(){if(this._interval){clearInterval(this._interval)}await this.onForceFlush();await this._exporter.shutdown()}}class qs{_registeredViews=[];addView(t){this._registeredViews.push(t)}findViews(t,e){const i=this._registeredViews.filter((i=>this._matchInstrument(i.instrumentSelector,t)&&this._matchMeter(i.meterSelector,e)));return i}_matchInstrument(t,e){return(t.getType()===undefined||e.type===t.getType())&&t.getNameFilter().match(e.name)&&t.getUnitFilter().match(e.unit)}_matchMeter(t,e){return t.getNameFilter().match(e.name)&&(e.version===undefined||t.getVersionFilter().match(e.version))&&(e.schemaUrl===undefined||t.getSchemaUrlFilter().match(e.schemaUrl))}}function Vs(t,e,i){if(!Ws(t)){Xt.warn(`Invalid metric name: "${t}". The metric name should be a ASCII string with a length no greater than 255 characters.`)}return{name:t,type:e,description:i?.description??"",unit:i?.unit??"",valueType:i?.valueType??ct.DOUBLE,advice:i?.advice??{}}}function Hs(t,e){return{name:t.name??e.name,description:t.description??e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function Gs(t,e){return qn(t.name,e.name)&&t.unit===e.unit&&t.type===e.type&&t.valueType===e.valueType}const Zs=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function Ws(t){return t.match(Zs)!=null}class Xs{_writableMetricStorage;_descriptor;constructor(t,e){this._writableMetricStorage=t;this._descriptor=e}_record(t,e={},i=Wt.active()){if(typeof t!=="number"){Xt.warn(`non-number value provided to metric ${this._descriptor.name}: ${t}`);return}if(this._descriptor.valueType===ct.INT&&!Number.isInteger(t)){Xt.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._writableMetricStorage.record(t,e,i,ei(Date.now()))}}class Ys extends Xs{add(t,e,i){this._record(t,e,i)}}class Js extends Xs{add(t,e,i){if(t<0){Xt.warn(`negative value provided to counter ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class Ks extends Xs{record(t,e,i){this._record(t,e,i)}}class Qs extends Xs{record(t,e,i){if(t<0){Xt.warn(`negative value provided to histogram ${this._descriptor.name}: ${t}`);return}this._record(t,e,i)}}class to{_observableRegistry;_metricStorages;_descriptor;constructor(t,e,i){this._observableRegistry=i;this._descriptor=t;this._metricStorages=e}addCallback(t){this._observableRegistry.addCallback(t,this)}removeCallback(t){this._observableRegistry.removeCallback(t,this)}}class eo extends to{}class io extends to{}class ro extends to{}function no(t){return t instanceof to}class so{_meterSharedState;constructor(t){this._meterSharedState=t}createGauge(t,e){const i=Vs(t,In.GAUGE,e);const r=this._meterSharedState.registerMetricStorage(i);return new Ks(r,i)}createHistogram(t,e){const i=Vs(t,In.HISTOGRAM,e);const r=this._meterSharedState.registerMetricStorage(i);return new Qs(r,i)}createCounter(t,e){const i=Vs(t,In.COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new Js(r,i)}createUpDownCounter(t,e){const i=Vs(t,In.UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerMetricStorage(i);return new Ys(r,i)}createObservableGauge(t,e){const i=Vs(t,In.OBSERVABLE_GAUGE,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new io(i,r,this._meterSharedState.observableRegistry)}createObservableCounter(t,e){const i=Vs(t,In.OBSERVABLE_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new eo(i,r,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(t,e){const i=Vs(t,In.OBSERVABLE_UP_DOWN_COUNTER,e);const r=this._meterSharedState.registerAsyncMetricStorage(i);return new ro(i,r,this._meterSharedState.observableRegistry)}addBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.addBatchCallback(t,e)}removeBatchObservableCallback(t,e){this._meterSharedState.observableRegistry.removeBatchCallback(t,e)}}class oo{_instrumentDescriptor;constructor(t){this._instrumentDescriptor=t}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(t){this._instrumentDescriptor=Vs(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:t,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class ao{_hash;_valueMap=new Map;_keyMap=new Map;constructor(t){this._hash=t}get(t,e){e??=this._hash(t);return this._valueMap.get(e)}getOrDefault(t,e){const i=this._hash(t);if(this._valueMap.has(i)){return this._valueMap.get(i)}const r=e();if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,r);return r}set(t,e,i){i??=this._hash(t);if(!this._keyMap.has(i)){this._keyMap.set(i,t)}this._valueMap.set(i,e)}has(t,e){e??=this._hash(t);return this._valueMap.has(e)}*keys(){const t=this._keyMap.entries();let e=t.next();while(e.done!==true){yield[e.value[1],e.value[0]];e=t.next()}}*entries(){const t=this._valueMap.entries();let e=t.next();while(e.done!==true){yield[this._keyMap.get(e.value[0]),e.value[1],e.value[0]];e=t.next()}}get size(){return this._valueMap.size}}class co extends ao{constructor(){super(jn)}}class uo{_aggregator;_activeCollectionStorage=new co;_cumulativeMemoStorage=new co;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":true};_overflowHashCode;constructor(t,e){this._aggregator=t;this._cardinalityLimit=(e??2e3)-1;this._overflowHashCode=jn(this._overflowAttributes)}record(t,e,i,r){let n=this._activeCollectionStorage.get(e);if(!n){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const e=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,(()=>this._aggregator.createAccumulation(r)));e?.record(t);return}n=this._aggregator.createAccumulation(r);this._activeCollectionStorage.set(e,n)}n?.record(t)}batchCumulate(t,e){Array.from(t.entries()).forEach((([t,i,r])=>{const n=this._aggregator.createAccumulation(e);n?.record(i);let s=n;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}else{if(this._cumulativeMemoStorage.size>=this._cardinalityLimit){t=this._overflowAttributes;r=this._overflowHashCode;if(this._cumulativeMemoStorage.has(t,r)){const e=this._cumulativeMemoStorage.get(t,r);s=this._aggregator.diff(e,n)}}}if(this._activeCollectionStorage.has(t,r)){const e=this._activeCollectionStorage.get(t,r);s=this._aggregator.merge(e,s)}this._cumulativeMemoStorage.set(t,n,r);this._activeCollectionStorage.set(t,s,r)}))}collect(){const t=this._activeCollectionStorage;this._activeCollectionStorage=new co;return t}}class fo{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(t,e){this._aggregator=t;e.forEach((t=>{this._unreportedAccumulations.set(t,[])}))}buildMetrics(t,e,i,r){this._stashAccumulations(i);const n=this._getMergedUnreportedAccumulations(t);let s=n;let o;if(this._reportHistory.has(t)){const e=this._reportHistory.get(t);const i=e.collectionTime;o=e.aggregationTemporality;if(o===Pn.CUMULATIVE){s=fo.merge(e.accumulations,n,this._aggregator)}else{s=fo.calibrateStartTime(e.accumulations,n,i)}}else{o=t.selectAggregationTemporality(e.type)}this._reportHistory.set(t,{accumulations:s,collectionTime:r,aggregationTemporality:o});const a=lo(s);if(a.length===0){return undefined}return this._aggregator.toMetricData(e,o,a,r)}_stashAccumulations(t){const e=this._unreportedAccumulations.keys();for(const i of e){let e=this._unreportedAccumulations.get(i);if(e===undefined){e=[];this._unreportedAccumulations.set(i,e)}e.push(t)}}_getMergedUnreportedAccumulations(t){let e=new co;const i=this._unreportedAccumulations.get(t);this._unreportedAccumulations.set(t,[]);if(i===undefined){return e}for(const t of i){e=fo.merge(e,t,this._aggregator)}return e}static merge(t,e,i){const r=t;const n=e.entries();let s=n.next();while(s.done!==true){const[e,o,a]=s.value;if(t.has(e,a)){const n=t.get(e,a);const s=i.merge(n,o);r.set(e,s,a)}else{r.set(e,o,a)}s=n.next()}return r}static calibrateStartTime(t,e,i){for(const[r,n]of t.keys()){const t=e.get(r,n);t?.setStartTime(i)}return e}}function lo(t){return Array.from(t.entries())}class ho extends oo{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,r,n){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new uo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new fo(e,r)}record(t,e){const i=new co;Array.from(t.entries()).forEach((([t,e])=>{i.set(this._attributesProcessor.process(t),e)}));this._deltaMetricStorage.batchCumulate(i,e)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}function po(t,e){let i="";if(t.unit!==e.unit){i+=`\t- Unit '${t.unit}' does not match '${e.unit}'\n`}if(t.type!==e.type){i+=`\t- Type '${t.type}' does not match '${e.type}'\n`}if(t.valueType!==e.valueType){i+=`\t- Value Type '${t.valueType}' does not match '${e.valueType}'\n`}if(t.description!==e.description){i+=`\t- Description '${t.description}' does not match '${e.description}'\n`}return i}function mo(t,e){return`\t- use valueType '${t.valueType}' on instrument creation or use an instrument name other than '${e.name}'`}function bo(t,e){return`\t- use unit '${t.unit}' on instrument creation or use an instrument name other than '${e.name}'`}function vo(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'`}function wo(t,e){const i={name:e.name,type:e.type,unit:e.unit};const r=JSON.stringify(i);return`\t- create a new view with a name other than '${t.name}' and InstrumentSelector '${r}'\n \t- OR - create a new view with the name ${t.name} and description '${t.description}' and InstrumentSelector ${r}\n \t- OR - create a new view with the name ${e.name} and description '${t.description}' and InstrumentSelector ${r}`}function go(t,e){if(t.valueType!==e.valueType){return mo(t,e)}if(t.unit!==e.unit){return bo(t,e)}if(t.type!==e.type){return vo(t,e)}if(t.description!==e.description){return wo(t,e)}return""}class yo{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new yo}getStorages(t){let e=[];for(const t of this._sharedRegistry.values()){e=e.concat(t)}const i=this._perCollectorRegistry.get(t);if(i!=null){for(const t of i.values()){e=e.concat(t)}}return e}register(t){this._registerStorage(t,this._sharedRegistry)}registerForCollector(t,e){let i=this._perCollectorRegistry.get(t);if(i==null){i=new Map;this._perCollectorRegistry.set(t,i)}this._registerStorage(e,i)}findOrUpdateCompatibleStorage(t){const e=this._sharedRegistry.get(t.name);if(e===undefined){return null}return this._findOrUpdateCompatibleStorage(t,e)}findOrUpdateCompatibleCollectorStorage(t,e){const i=this._perCollectorRegistry.get(t);if(i===undefined){return null}const r=i.get(e.name);if(r===undefined){return null}return this._findOrUpdateCompatibleStorage(e,r)}_registerStorage(t,e){const i=t.getInstrumentDescriptor();const r=e.get(i.name);if(r===undefined){e.set(i.name,[t]);return}r.push(t)}_findOrUpdateCompatibleStorage(t,e){let i=null;for(const r of e){const e=r.getInstrumentDescriptor();if(Gs(e,t)){if(e.description!==t.description){if(t.description.length>e.description.length){r.updateDescription(t.description)}Xt.warn("A view or instrument with the name ",t.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",po(e,t),"The longer description will be used.\nTo resolve the conflict:",go(e,t))}i=r}else{Xt.warn("A view or instrument with the name ",t.name," has already been registered and is incompatible with another registered view.\n","Details:\n",po(e,t),"To resolve the conflict:\n",go(e,t))}}return i}}class xo{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,i,r){this._backingStorages.forEach((n=>{n.record(t,e,i,r)}))}}class ko{_instrumentName;_valueType;_buffer=new co;constructor(t,e){this._instrumentName=t;this._valueType=e}observe(t,e={}){if(typeof t!=="number"){Xt.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}if(this._valueType===ct.INT&&!Number.isInteger(t)){Xt.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`);t=Math.trunc(t);if(!Number.isInteger(t)){return}}this._buffer.set(e,t)}}class So{_buffer=new Map;observe(t,e,i={}){if(!no(t)){return}let r=this._buffer.get(t);if(r==null){r=new co;this._buffer.set(t,r)}if(typeof e!=="number"){Xt.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}if(t._descriptor.valueType===ct.INT&&!Number.isInteger(e)){Xt.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`);e=Math.trunc(e);if(!Number.isInteger(e)){return}}r.set(i,e)}}class _o{_callbacks=[];_batchCallbacks=[];addCallback(t,e){const i=this._findCallback(t,e);if(i>=0){return}this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){const i=this._findCallback(t,e);if(i<0){return}this._callbacks.splice(i,1)}addBatchCallback(t,e){const i=new Set(e.filter(no));if(i.size===0){Xt.error("BatchObservableCallback is not associated with valid instruments",e);return}const r=this._findBatchCallback(t,i);if(r>=0){return}this._batchCallbacks.push({callback:t,instruments:i})}removeBatchCallback(t,e){const i=new Set(e.filter(no));const r=this._findBatchCallback(t,i);if(r<0){return}this._batchCallbacks.splice(r,1)}async observe(t,e){const i=this._observeCallbacks(t,e);const r=this._observeBatchCallbacks(t,e);const n=await $n([...i,...r]);const s=n.filter(Dn).map((t=>t.reason));return s}_observeCallbacks(t,e){return this._callbacks.map((async({callback:i,instrument:r})=>{const n=new ko(r._descriptor.name,r._descriptor.valueType);let s=Promise.resolve(i(n));if(e!=null){s=zn(s,e)}await s;r._metricStorages.forEach((e=>{e.record(n._buffer,t)}))}))}_observeBatchCallbacks(t,e){return this._batchCallbacks.map((async({callback:i,instruments:r})=>{const n=new So;let s=Promise.resolve(i(n));if(e!=null){s=zn(s,e)}await s;r.forEach((e=>{const i=n._buffer.get(e);if(i==null){return}e._metricStorages.forEach((e=>{e.record(i,t)}))}))}))}_findCallback(t,e){return this._callbacks.findIndex((i=>i.callback===t&&i.instrument===e))}_findBatchCallback(t,e){return this._batchCallbacks.findIndex((i=>i.callback===t&&Un(i.instruments,e)))}}class To extends oo{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,i,r,n){super(t);this._attributesProcessor=i;this._aggregationCardinalityLimit=n;this._deltaMetricStorage=new uo(e,this._aggregationCardinalityLimit);this._temporalMetricStorage=new fo(e,r)}record(t,e,i,r){e=this._attributesProcessor.process(e,i);this._deltaMetricStorage.record(t,e,i,r)}collect(t,e){const i=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,i,e)}}class Eo{process(t,e){return t}}class Co{_processors;constructor(t){this._processors=t}process(t,e){let i=t;for(const t of this._processors){i=t.process(i,e)}return i}}function Mo(){return Po}function Ao(t){return new Co(t)}const Po=new Eo;class Io{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new yo;observableRegistry=new _o;meter;constructor(t,e){this._meterProviderSharedState=t;this._instrumentationScope=e;this.meter=new so(this)}registerMetricStorage(t){const e=this._registerMetricStorage(t,To);if(e.length===1){return e[0]}return new xo(e)}registerAsyncMetricStorage(t){const e=this._registerMetricStorage(t,ho);return e}async collect(t,e,i){const r=await this.observableRegistry.observe(e,i?.timeoutMillis);const n=this.metricStorageRegistry.getStorages(t);if(n.length===0){return null}const s=n.map((i=>i.collect(t,e))).filter(Ln);if(s.length===0){return{errors:r}}return{scopeMetrics:{scope:this._instrumentationScope,metrics:s},errors:r}}_registerMetricStorage(t,e){const i=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope);let r=i.map((i=>{const r=Hs(i,t);const n=this.metricStorageRegistry.findOrUpdateCompatibleStorage(r);if(n!=null){return n}const s=i.aggregation.createAggregator(r);const o=new e(r,s,i.attributesProcessor,this._meterProviderSharedState.metricCollectors,i.aggregationCardinalityLimit);this.metricStorageRegistry.register(o);return o}));if(r.length===0){const i=this._meterProviderSharedState.selectAggregations(t.type);const n=i.map((([i,r])=>{const n=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(i,t);if(n!=null){return n}const s=r.createAggregator(t);const o=i.selectCardinalityLimit(t.type);const a=new e(t,s,Mo(),[i],o);this.metricStorageRegistry.registerForCollector(i,a);return a}));r=r.concat(n)}return r}}class Oo{resource;viewRegistry=new qs;metricCollectors=[];meterSharedStates=new Map;constructor(t){this.resource=t}getMeterSharedState(t){const e=Rn(t);let i=this.meterSharedStates.get(e);if(i==null){i=new Io(this,t);this.meterSharedStates.set(e,i)}return i}selectAggregations(t){const e=[];for(const i of this.metricCollectors){e.push([i,$s(i.selectAggregation(t))])}return e}}class Lo{_sharedState;_metricReader;constructor(t,e){this._sharedState=t;this._metricReader=e}async collect(t){const e=ei(Date.now());const i=[];const r=[];const n=Array.from(this._sharedState.meterSharedStates.values()).map((async n=>{const s=await n.collect(this,e,t);if(s?.scopeMetrics!=null){i.push(s.scopeMetrics)}if(s?.errors!=null){r.push(...s.errors)}}));await Promise.all(n);return{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:i},errors:r}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}}const jo=/[\^$\\.+?()[\]{}|]/g;class Ro{_matchAll;_regexp;constructor(t){if(t==="*"){this._matchAll=true;this._regexp=/.*/}else{this._matchAll=false;this._regexp=new RegExp(Ro.escapePattern(t))}}match(t){if(this._matchAll){return true}return this._regexp.test(t)}static escapePattern(t){return`^${t.replace(jo,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}}class No{_matchAll;_pattern;constructor(t){this._matchAll=t===undefined;this._pattern=t}match(t){if(this._matchAll){return true}if(t===this._pattern){return true}return false}}class zo{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new Ro(t?.name??"*");this._type=t?.type;this._unitFilter=new No(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class $o{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new No(t?.name);this._versionFilter=new No(t?.version);this._schemaUrlFilter=new No(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function Do(t){return t.instrumentName==null&&t.instrumentType==null&&t.instrumentUnit==null&&t.meterName==null&&t.meterVersion==null&&t.meterSchemaUrl==null}function Fo(t){if(Do(t)){throw new Error("Cannot create view with no selector arguments supplied")}if(t.name!=null&&(t?.instrumentName==null||Ro.hasWildcard(t.instrumentName))){throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}}class Uo{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){Fo(t);if(t.attributesProcessors!=null){this.attributesProcessor=Ao(t.attributesProcessors)}else{this.attributesProcessor=Mo()}this.name=t.name;this.description=t.description;this.aggregation=$s(t.aggregation??{type:zs.DEFAULT});this.instrumentSelector=new zo({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit});this.meterSelector=new $o({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl});this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}}class Bo{_sharedState;_shutdown=false;constructor(t){this._sharedState=new Oo(t?.resource??mr());if(t?.views!=null&&t.views.length>0){for(const e of t.views){this._sharedState.viewRegistry.addView(new Uo(e))}}if(t?.readers!=null&&t.readers.length>0){for(const e of t.readers){const t=new Lo(this._sharedState,e);e.setMetricProducer(t);this._sharedState.metricCollectors.push(t)}}}getMeter(t,e="",i={}){if(this._shutdown){Xt.warn("A shutdown MeterProvider cannot provide a Meter");return at()}return this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:i.schemaUrl}).meter}async shutdown(t){if(this._shutdown){Xt.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=true;await Promise.all(this._sharedState.metricCollectors.map((e=>e.shutdown(t))))}async forceFlush(t){if(this._shutdown){Xt.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map((e=>e.forceFlush(t))))}}var qo;(function(t){t[t["AGGREGATION_TEMPORALITY_UNSPECIFIED"]=0]="AGGREGATION_TEMPORALITY_UNSPECIFIED";t[t["AGGREGATION_TEMPORALITY_DELTA"]=1]="AGGREGATION_TEMPORALITY_DELTA";t[t["AGGREGATION_TEMPORALITY_CUMULATIVE"]=2]="AGGREGATION_TEMPORALITY_CUMULATIVE"})(qo||(qo={}));function Vo(t,e){const i=_n(e);const r=Tn(t.resource);return{resource:r,schemaUrl:r.schemaUrl,scopeMetrics:Ho(t.scopeMetrics,i)}}function Ho(t,e){return Array.from(t.map((t=>({scope:En(t.scope),metrics:t.metrics.map((t=>Go(t,e))),schemaUrl:t.scope.schemaUrl}))))}function Go(t,e){const i={name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit};const r=Jo(t.aggregationTemporality);switch(t.dataPointType){case On.SUM:i.sum={aggregationTemporality:r,isMonotonic:t.isMonotonic,dataPoints:Wo(t,e)};break;case On.GAUGE:i.gauge={dataPoints:Wo(t,e)};break;case On.HISTOGRAM:i.histogram={aggregationTemporality:r,dataPoints:Xo(t,e)};break;case On.EXPONENTIAL_HISTOGRAM:i.exponentialHistogram={aggregationTemporality:r,dataPoints:Yo(t,e)};break}return i}function Zo(t,e,i){const r={attributes:Cn(t.attributes),startTimeUnixNano:i.encodeHrTime(t.startTime),timeUnixNano:i.encodeHrTime(t.endTime)};switch(e){case ct.INT:r.asInt=t.value;break;case ct.DOUBLE:r.asDouble=t.value;break}return r}function Wo(t,e){return t.dataPoints.map((i=>Zo(i,t.descriptor.valueType,e)))}function Xo(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:Cn(t.attributes),bucketCounts:i.buckets.counts,explicitBounds:i.buckets.boundaries,count:i.count,sum:i.sum,min:i.min,max:i.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}}))}function Yo(t,e){return t.dataPoints.map((t=>{const i=t.value;return{attributes:Cn(t.attributes),count:i.count,min:i.min,max:i.max,sum:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},scale:i.scale,zeroCount:i.zeroCount,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}}))}function Jo(t){switch(t){case Pn.DELTA:return qo.AGGREGATION_TEMPORALITY_DELTA;case Pn.CUMULATIVE:return qo.AGGREGATION_TEMPORALITY_CUMULATIVE}}function Ko(t,e){return{resourceMetrics:t.map((t=>Vo(t,e)))}}const Qo=256;const ta=512;function ea(t,e){let i=t&255|Qo;if(e){i|=ta}return i}function ia(t,e){const i=t.spanContext();const r=t.status;const n=t.parentSpanContext?.spanId?e.encodeSpanContext(t.parentSpanContext?.spanId):undefined;return{traceId:e.encodeSpanContext(i.traceId),spanId:e.encodeSpanContext(i.spanId),parentSpanId:n,traceState:i.traceState?.serialize(),name:t.name,kind:t.kind==null?0:t.kind+1,startTimeUnixNano:e.encodeHrTime(t.startTime),endTimeUnixNano:e.encodeHrTime(t.endTime),attributes:Cn(t.attributes),droppedAttributesCount:t.droppedAttributesCount,events:t.events.map((t=>na(t,e))),droppedEventsCount:t.droppedEventsCount,status:{code:r.code,message:r.message},links:t.links.map((t=>ra(t,e))),droppedLinksCount:t.droppedLinksCount,flags:ea(i.traceFlags,t.parentSpanContext?.isRemote)}}function ra(t,e){return{attributes:t.attributes?Cn(t.attributes):[],spanId:e.encodeSpanContext(t.context.spanId),traceId:e.encodeSpanContext(t.context.traceId),traceState:t.context.traceState?.serialize(),droppedAttributesCount:t.droppedAttributesCount||0,flags:ea(t.context.traceFlags,t.context.isRemote)}}function na(t,e){return{attributes:t.attributes?Cn(t.attributes):[],name:t.name,timeUnixNano:e.encodeHrTime(t.time),droppedAttributesCount:t.droppedAttributesCount||0}}function sa(t,e){const i=_n(e);return{resourceSpans:aa(t,i)}}function oa(t){const e=new Map;for(const i of t){let t=e.get(i.resource);if(!t){t=new Map;e.set(i.resource,t)}const r=`${i.instrumentationScope.name}@${i.instrumentationScope.version||""}:${i.instrumentationScope.schemaUrl||""}`;let n=t.get(r);if(!n){n=[];t.set(r,n)}n.push(i)}return e}function aa(t,e){const i=oa(t);const r=[];const n=i.entries();let s=n.next();while(!s.done){const[t,i]=s.value;const o=[];const a=i.values();let c=a.next();while(!c.done){const t=c.value;if(t.length>0){const i=t.map((t=>ia(t,e)));o.push({scope:En(t[0].instrumentationScope),spans:i,schemaUrl:t[0].instrumentationScope.schemaUrl})}c=a.next()}const u=Tn(t);const f={resource:u,scopeSpans:o,schemaUrl:u.schemaUrl};r.push(f);s=n.next()}return r}const ca={serializeRequest:t=>{const e=Ko([t],{useLongBits:false});const i=new TextEncoder;return i.encode(JSON.stringify(e))},deserializeResponse:t=>{if(t.length===0){return{}}const e=new TextDecoder;return JSON.parse(e.decode(t))}};const ua={serializeRequest:t=>{const e=sa(t,{useHex:true,useLongBits:false});const i=new TextEncoder;return i.encode(JSON.stringify(e))},deserializeResponse:t=>{if(t.length===0){return{}}const e=new TextDecoder;return JSON.parse(e.decode(t))}};const fa=5;const la=1e3;const ha=5e3;const da=1.5;const pa=.2;function ma(){return Math.random()*(2*pa)-pa}class ba{_transport;constructor(t){this._transport=t}retry(t,e,i){return new Promise(((r,n)=>{setTimeout((()=>{this._transport.send(t,e).then(r,n)}),i)}))}async send(t,e){const i=Date.now()+e;let r=await this._transport.send(t,e);let n=fa;let s=la;while(r.status==="retryable"&&n>0){n--;const e=Math.max(Math.min(s,ha)+ma(),0);s=s*da;const o=r.retryInMillis??e;const a=i-Date.now();if(o>a){return r}r=await this.retry(t,a,o)}return r}shutdown(){return this._transport.shutdown()}}function va(t){return new ba(t.transport)}function wa(t){const e=[429,502,503,504];return e.includes(t)}function ga(t){if(t==null){return undefined}const e=Number.parseInt(t,10);if(Number.isInteger(e)){return e>0?e*1e3:-1}const i=new Date(t).getTime()-Date.now();if(i>=0){return i}return 0}class ya{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=await this._parameters.headers();const r=await new Promise((r=>{const n=new XMLHttpRequest;n.timeout=e;n.open("POST",this._parameters.url);Object.entries(i).forEach((([t,e])=>{n.setRequestHeader(t,e)}));n.ontimeout=t=>{r({status:"failure",error:new Error("XHR request timed out")})};n.onreadystatechange=()=>{if(n.status>=200&&n.status<=299){Xt.debug("XHR success");r({status:"success"})}else if(n.status&&wa(n.status)){r({status:"retryable",retryInMillis:ga(n.getResponseHeader("Retry-After"))})}else if(n.status!==0){r({status:"failure",error:new Error("XHR request failed with non-retryable status")})}};n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})};n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})};n.send(t)}));return r}shutdown(){}}function xa(t){return new ya(t)}class ka{_params;constructor(t){this._params=t}async send(t){const e=(await this._params.headers())["Content-Type"];return new Promise((i=>{if(navigator.sendBeacon(this._params.url,new Blob([t],{type:e}))){Xt.debug("SendBeacon success");i({status:"success"})}else{i({status:"failure",error:new Error("SendBeacon failed")})}}))}shutdown(){}}function Sa(t){return new ka(t)}class _a{_parameters;constructor(t){this._parameters=t}async send(t,e){const i=new AbortController;const r=setTimeout((()=>i.abort()),e);try{const e=!!globalThis.location;const r=new URL(this._parameters.url);const n=await fetch(r.href,{method:"POST",headers:await this._parameters.headers(),body:t,signal:i.signal,keepalive:e,mode:e?globalThis.location?.origin===r.origin?"same-origin":"cors":"no-cors"});if(n.status>=200&&n.status<=299){Xt.debug("response success");return{status:"success"}}else if(wa(n.status)){const t=n.headers.get("Retry-After");const e=ga(t);return{status:"retryable",retryInMillis:e}}return{status:"failure",error:new Error("Fetch request failed with non-retryable status")}}catch(t){if(t?.name==="AbortError"){return{status:"failure",error:new Error("Fetch request timed out",{cause:t})}}return{status:"failure",error:new Error("Fetch request errored",{cause:t})}}finally{clearTimeout(r)}}shutdown(){}}function Ta(t){return new _a(t)}function Ea(t,e){return hn(t,e,va({transport:xa(t)}))}function Ca(t,e){return hn(t,e,va({transport:Ta(t)}))}function Ma(t,e){return hn(t,e,va({transport:Sa({url:t.url,headers:t.headers})}))}function Aa(t){const e={};Object.entries(t??{}).forEach((([t,i])=>{if(typeof i!=="undefined"){e[t]=String(i)}else{Xt.warn(`Header "${t}" has invalid value (${i}) and will be ignored`)}}));return e}function Pa(t,e,i){return async()=>{const r={...await i()};const n={};if(e!=null){Object.assign(n,await e())}if(t!=null){Object.assign(n,Aa(await t()))}return Object.assign(n,r)}}function Ia(t){if(t==null){return undefined}try{const e=globalThis.location?.href;return new URL(t,e).href}catch{throw new Error(`Configuration: Could not parse user-provided export URL: '${t}'`)}}function Oa(t,e,i){return{...nn(t,e,i),headers:Pa(t.headers,e.headers,i.headers),url:Ia(t.url)??e.url??i.url}}function La(t,e){return{...sn(),headers:async()=>t,url:"http://localhost:4318/"+e}}function ja(t){if(typeof t.headers==="function"){return t.headers}return rn(t.headers)}function Ra(t,e,i){return Oa({url:t.url,timeoutMillis:t.timeoutMillis,headers:ja(t),concurrencyLimit:t.concurrencyLimit},{},La(i,e))}function Na(t,e,i,r){const n=za(t.headers);const s=Ra(t,i,r);return n(s,e)}function za(t){if(!t&&typeof navigator.sendBeacon==="function"){return Ma}else if(typeof globalThis.fetch!=="undefined"){return Ca}else{return Ea}}class $a extends Qr{constructor(t={}){super(Na(t,ua,"v1/traces",{"Content-Type":"application/json"}))}}function Da(t){return typeof t==="object"&&t!==null&&"addEventListener"in t&&typeof t.addEventListener==="function"&&"removeEventListener"in t&&typeof t.removeEventListener==="function"}const Fa="OT_ZONE_CONTEXT";class Ua{_enabled=false;_zoneCounter=0;_activeContextFromZone(t){return t&&t.get(Fa)||U}_bindFunction(t,e){const i=this;const r=function(...r){return i.with(t,(()=>e.apply(this,r)))};Object.defineProperty(r,"length",{enumerable:false,configurable:true,writable:false,value:e.length});return r}_bindListener(t,e){const i=e;if(i.__ot_listeners!==undefined){return e}i.__ot_listeners={};if(typeof i.addEventListener==="function"){i.addEventListener=this._patchAddEventListener(i,i.addEventListener,t)}if(typeof i.removeEventListener==="function"){i.removeEventListener=this._patchRemoveEventListener(i,i.removeEventListener)}return e}_createZoneName(){this._zoneCounter++;const t=Math.random();return`${this._zoneCounter}-${t}`}_createZone(t,e){return Zone.current.fork({name:t,properties:{[Fa]:e}})}_getActiveZone(){return Zone.current}_patchAddEventListener(t,e,i){const r=this;return function(n,s,o){if(t.__ot_listeners===undefined){t.__ot_listeners={}}let a=t.__ot_listeners[n];if(a===undefined){a=new WeakMap;t.__ot_listeners[n]=a}const c=r.bind(i,s);a.set(s,c);return e.call(this,n,c,o)}}_patchRemoveEventListener(t,e){return function(i,r){if(t.__ot_listeners===undefined||t.__ot_listeners[i]===undefined){return e.call(this,i,r)}const n=t.__ot_listeners[i];const s=n.get(r);n.delete(r);return e.call(this,i,s||r)}}active(){if(!this._enabled){return U}const t=this._getActiveZone();const e=this._activeContextFromZone(t);if(e){return e}return U}bind(t,e){if(t===undefined){t=this.active()}if(typeof e==="function"){return this._bindFunction(t,e)}else if(Da(e)){this._bindListener(t,e)}return e}disable(){this._enabled=false;return this}enable(){this._enabled=true;return this}with(t,e,i,...r){const n=this._createZoneName();const s=this._createZone(n,t);return s.run(e,i,r)}}var Ba={};var qa;function Va(){if(qa)return Ba;qa=1;var t=Ba&&Ba.__assign||function(){t=Object.assign||function(t){for(var e,i=1,r=arguments.length;i<r;i++){e=arguments[i];for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n))t[n]=e[n]}return t};return t.apply(this,arguments)};
2
+ /**
3
+ * @license Angular v<unknown>
4
+ * (c) 2010-2025 Google LLC. https://angular.io/
5
+ * License: MIT
6
+ */(function(t){t()})((function(){var e=globalThis;function i(t){var i=e["__Zone_symbol_prefix"]||"__zone_symbol__";return i+t}function r(){var t=e["performance"];function r(e){t&&t["mark"]&&t["mark"](e)}function n(e,i){t&&t["measure"]&&t["measure"](e,i)}r("Zone");var s=function(){function t(t,e){this._parent=t;this._name=e?e.name||"unnamed":"<root>";this._properties=e&&e.properties||{};this._zoneDelegate=new a(this,this._parent&&this._parent._zoneDelegate,e)}t.assertZonePatched=function(){if(e["Promise"]!==M["ZoneAwarePromise"]){throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` "+"has been overwritten.\n"+"Most likely cause is that a Promise polyfill has been loaded "+"after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. "+"If you must load one, do so before loading zone.js.)")}};Object.defineProperty(t,"root",{get:function(){var e=t.current;while(e.parent){e=e.parent}return e},enumerable:false,configurable:true});Object.defineProperty(t,"current",{get:function(){return P.zone},enumerable:false,configurable:true});Object.defineProperty(t,"currentTask",{get:function(){return I},enumerable:false,configurable:true});t.__load_patch=function(s,o,a){if(a===void 0){a=false}if(M.hasOwnProperty(s)){var c=e[i("forceDuplicateZoneCheck")]===true;if(!a&&c){throw Error("Already loaded patch: "+s)}}else if(!e["__Zone_disable_"+s]){var u="Zone:"+s;r(u);M[s]=o(e,t,A);n(u,u)}};Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:false,configurable:true});t.prototype.get=function(t){var e=this.getZoneWith(t);if(e)return e._properties[t]};t.prototype.getZoneWith=function(t){var e=this;while(e){if(e._properties.hasOwnProperty(t)){return e}e=e._parent}return null};t.prototype.fork=function(t){if(!t)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,t)};t.prototype.wrap=function(t,e){if(typeof t!=="function"){throw new Error("Expecting function got: "+t)}var i=this._zoneDelegate.intercept(this,t,e);var r=this;return function(){return r.runGuarded(i,this,arguments,e)}};t.prototype.run=function(t,e,i,r){P={parent:P,zone:this};try{return this._zoneDelegate.invoke(this,t,e,i,r)}finally{P=P.parent}};t.prototype.runGuarded=function(t,e,i,r){if(e===void 0){e=null}P={parent:P,zone:this};try{try{return this._zoneDelegate.invoke(this,t,e,i,r)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{P=P.parent}};t.prototype.runTask=function(t,e,i){if(t.zone!=this){throw new Error("A task can only be run in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")")}var r=t;var n=t.type,s=t.data,o=s===void 0?{}:s,a=o.isPeriodic,c=a===void 0?false:a,u=o.isRefreshable,f=u===void 0?false:u;if(t.state===g&&(n===C||n===E)){return}var l=t.state!=k;l&&r._transitionTo(k,x);var h=I;I=r;P={parent:P,zone:this};try{if(n==E&&t.data&&!c&&!f){t.cancelFn=undefined}try{return this._zoneDelegate.invokeTask(this,r,e,i)}catch(t){if(this._zoneDelegate.handleError(this,t)){throw t}}}finally{var d=t.state;if(d!==g&&d!==_){if(n==C||c||f&&d===y){l&&r._transitionTo(x,k,y)}else{var p=r._zoneDelegates;this._updateTaskCount(r,-1);l&&r._transitionTo(g,k,g);if(f){r._zoneDelegates=p}}}P=P.parent;I=h}};t.prototype.scheduleTask=function(t){if(t.zone&&t.zone!==this){var e=this;while(e){if(e===t.zone){throw Error("can not reschedule task to ".concat(this.name," which is descendants of the original zone ").concat(t.zone.name))}e=e.parent}}t._transitionTo(y,g);var i=[];t._zoneDelegates=i;t._zone=this;try{t=this._zoneDelegate.scheduleTask(this,t)}catch(e){t._transitionTo(_,y,g);this._zoneDelegate.handleError(this,e);throw e}if(t._zoneDelegates===i){this._updateTaskCount(t,1)}if(t.state==y){t._transitionTo(x,y)}return t};t.prototype.scheduleMicroTask=function(t,e,i,r){return this.scheduleTask(new c(T,t,e,i,r,undefined))};t.prototype.scheduleMacroTask=function(t,e,i,r,n){return this.scheduleTask(new c(E,t,e,i,r,n))};t.prototype.scheduleEventTask=function(t,e,i,r,n){return this.scheduleTask(new c(C,t,e,i,r,n))};t.prototype.cancelTask=function(t){if(t.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(t.zone||w).name+"; Execution: "+this.name+")");if(t.state!==x&&t.state!==k){return}t._transitionTo(S,x,k);try{this._zoneDelegate.cancelTask(this,t)}catch(e){t._transitionTo(_,S);this._zoneDelegate.handleError(this,e);throw e}this._updateTaskCount(t,-1);t._transitionTo(g,S);t.runCount=-1;return t};t.prototype._updateTaskCount=function(t,e){var i=t._zoneDelegates;if(e==-1){t._zoneDelegates=null}for(var r=0;r<i.length;r++){i[r]._updateTaskCount(t.type,e)}};t.__symbol__=i;return t}();var o={name:"",onHasTask:function(t,e,i,r){return t.hasTask(i,r)},onScheduleTask:function(t,e,i,r){return t.scheduleTask(i,r)},onInvokeTask:function(t,e,i,r,n,s){return t.invokeTask(i,r,n,s)},onCancelTask:function(t,e,i,r){return t.cancelTask(i,r)}};var a=function(){function t(t,e,i){this._taskCounts={microTask:0,macroTask:0,eventTask:0};this._zone=t;this._parentDelegate=e;this._forkZS=i&&(i&&i.onFork?i:e._forkZS);this._forkDlgt=i&&(i.onFork?e:e._forkDlgt);this._forkCurrZone=i&&(i.onFork?this._zone:e._forkCurrZone);this._interceptZS=i&&(i.onIntercept?i:e._interceptZS);this._interceptDlgt=i&&(i.onIntercept?e:e._interceptDlgt);this._interceptCurrZone=i&&(i.onIntercept?this._zone:e._interceptCurrZone);this._invokeZS=i&&(i.onInvoke?i:e._invokeZS);this._invokeDlgt=i&&(i.onInvoke?e:e._invokeDlgt);this._invokeCurrZone=i&&(i.onInvoke?this._zone:e._invokeCurrZone);this._handleErrorZS=i&&(i.onHandleError?i:e._handleErrorZS);this._handleErrorDlgt=i&&(i.onHandleError?e:e._handleErrorDlgt);this._handleErrorCurrZone=i&&(i.onHandleError?this._zone:e._handleErrorCurrZone);this._scheduleTaskZS=i&&(i.onScheduleTask?i:e._scheduleTaskZS);this._scheduleTaskDlgt=i&&(i.onScheduleTask?e:e._scheduleTaskDlgt);this._scheduleTaskCurrZone=i&&(i.onScheduleTask?this._zone:e._scheduleTaskCurrZone);this._invokeTaskZS=i&&(i.onInvokeTask?i:e._invokeTaskZS);this._invokeTaskDlgt=i&&(i.onInvokeTask?e:e._invokeTaskDlgt);this._invokeTaskCurrZone=i&&(i.onInvokeTask?this._zone:e._invokeTaskCurrZone);this._cancelTaskZS=i&&(i.onCancelTask?i:e._cancelTaskZS);this._cancelTaskDlgt=i&&(i.onCancelTask?e:e._cancelTaskDlgt);this._cancelTaskCurrZone=i&&(i.onCancelTask?this._zone:e._cancelTaskCurrZone);this._hasTaskZS=null;this._hasTaskDlgt=null;this._hasTaskDlgtOwner=null;this._hasTaskCurrZone=null;var r=i&&i.onHasTask;var n=e&&e._hasTaskZS;if(r||n){this._hasTaskZS=r?i:o;this._hasTaskDlgt=e;this._hasTaskDlgtOwner=this;this._hasTaskCurrZone=this._zone;if(!i.onScheduleTask){this._scheduleTaskZS=o;this._scheduleTaskDlgt=e;this._scheduleTaskCurrZone=this._zone}if(!i.onInvokeTask){this._invokeTaskZS=o;this._invokeTaskDlgt=e;this._invokeTaskCurrZone=this._zone}if(!i.onCancelTask){this._cancelTaskZS=o;this._cancelTaskDlgt=e;this._cancelTaskCurrZone=this._zone}}}Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});t.prototype.fork=function(t,e){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,t,e):new s(t,e)};t.prototype.intercept=function(t,e,i){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,t,e,i):e};t.prototype.invoke=function(t,e,i,r,n){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,t,e,i,r,n):e.apply(i,r)};t.prototype.handleError=function(t,e){return this._handleErrorZS?this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,t,e):true};t.prototype.scheduleTask=function(t,e){var i=e;if(this._scheduleTaskZS){if(this._hasTaskZS){i._zoneDelegates.push(this._hasTaskDlgtOwner)}i=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,t,e);if(!i)i=e}else{if(e.scheduleFn){e.scheduleFn(e)}else if(e.type==T){b(e)}else{throw new Error("Task is missing scheduleFn.")}}return i};t.prototype.invokeTask=function(t,e,i,r){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,t,e,i,r):e.callback.apply(i,r)};t.prototype.cancelTask=function(t,e){var i;if(this._cancelTaskZS){i=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,t,e)}else{if(!e.cancelFn){throw Error("Task is not cancelable")}i=e.cancelFn(e)}return i};t.prototype.hasTask=function(t,e){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,t,e)}catch(e){this.handleError(t,e)}};t.prototype._updateTaskCount=function(t,e){var i=this._taskCounts;var r=i[t];var n=i[t]=r+e;if(n<0){throw new Error("More tasks executed then were scheduled.")}if(r==0||n==0){var s={microTask:i["microTask"]>0,macroTask:i["macroTask"]>0,eventTask:i["eventTask"]>0,change:t};this.hasTask(this._zone,s)}};return t}();var c=function(){function t(i,r,n,s,o,a){this._zone=null;this.runCount=0;this._zoneDelegates=null;this._state="notScheduled";this.type=i;this.source=r;this.data=s;this.scheduleFn=o;this.cancelFn=a;if(!n){throw new Error("callback is not defined")}this.callback=n;var c=this;if(i===C&&s&&s.useG){this.invoke=t.invokeTask}else{this.invoke=function(){return t.invokeTask.call(e,c,this,arguments)}}}t.invokeTask=function(t,e,i){if(!t){t=this}O++;try{t.runCount++;return t.zone.runTask(t,e,i)}finally{if(O==1){v()}O--}};Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:false,configurable:true});Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:false,configurable:true});t.prototype.cancelScheduleRequest=function(){this._transitionTo(g,y)};t.prototype._transitionTo=function(t,e,i){if(this._state===e||this._state===i){this._state=t;if(t==g){this._zoneDelegates=null}}else{throw new Error("".concat(this.type," '").concat(this.source,"': can not transition to '").concat(t,"', expecting state '").concat(e,"'").concat(i?" or '"+i+"'":"",", was '").concat(this._state,"'."))}};t.prototype.toString=function(){if(this.data&&typeof this.data.handleId!=="undefined"){return this.data.handleId.toString()}else{return Object.prototype.toString.call(this)}};t.prototype.toJSON=function(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}};return t}();var u=i("setTimeout");var f=i("Promise");var l=i("then");var h=[];var d=false;var p;function m(t){if(!p){if(e[f]){p=e[f].resolve(0)}}if(p){var i=p[l];if(!i){i=p["then"]}i.call(p,t)}else{e[u](t,0)}}function b(t){if(O===0&&h.length===0){m(v)}t&&h.push(t)}function v(){if(!d){d=true;while(h.length){var t=h;h=[];for(var e=0;e<t.length;e++){var i=t[e];try{i.zone.runTask(i,null,null)}catch(t){A.onUnhandledError(t)}}}A.microtaskDrainDone();d=false}}var w={name:"NO ZONE"};var g="notScheduled",y="scheduling",x="scheduled",k="running",S="canceling",_="unknown";var T="microTask",E="macroTask",C="eventTask";var M={};var A={symbol:i,currentZoneFrame:function(){return P},onUnhandledError:L,microtaskDrainDone:L,scheduleMicroTask:b,showUncaughtError:function(){return!s[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:L,patchMethod:function(){return L},bindArguments:function(){return[]},patchThen:function(){return L},patchMacroTask:function(){return L},patchEventPrototype:function(){return L},isIEOrEdge:function(){return false},getGlobalObjects:function(){return undefined},ObjectDefineProperty:function(){return L},ObjectGetOwnPropertyDescriptor:function(){return undefined},ObjectCreate:function(){return undefined},ArraySlice:function(){return[]},patchClass:function(){return L},wrapWithCurrentZone:function(){return L},filterProperties:function(){return[]},attachOriginToPatched:function(){return L},_redefineProperty:function(){return L},patchCallbacks:function(){return L},nativeScheduleMicroTask:m};var P={parent:null,zone:new s(null,null)};var I=null;var O=0;function L(){}n("Zone","Zone");return s}function n(){var t;var e=globalThis;var n=e[i("forceDuplicateZoneCheck")]===true;if(e["Zone"]&&(n||typeof e["Zone"].__symbol__!=="function")){throw new Error("Zone already loaded.")}(t=e["Zone"])!==null&&t!==void 0?t:e["Zone"]=r();return e["Zone"]}var s=Object.getOwnPropertyDescriptor;var o=Object.defineProperty;var a=Object.getPrototypeOf;var c=Object.create;var u=Array.prototype.slice;var f="addEventListener";var l="removeEventListener";var h=i(f);var d=i(l);var p="true";var m="false";var b=i("");function v(t,e){return Zone.current.wrap(t,e)}function w(t,e,i,r,n){return Zone.current.scheduleMacroTask(t,e,i,r,n)}var g=i;var y=typeof window!=="undefined";var x=y?window:undefined;var k=y&&x||globalThis;var S="removeAttribute";function _(t,e){for(var i=t.length-1;i>=0;i--){if(typeof t[i]==="function"){t[i]=v(t[i],e+"_"+i)}}return t}function T(t,e){var i=t.constructor["name"];var r=function(r){var n=e[r];var o=t[n];if(o){var a=s(t,n);if(!E(a)){return"continue"}t[n]=function(t){var e=function(){return t.apply(this,_(arguments,i+"."+n))};F(e,t);return e}(o)}};for(var n=0;n<e.length;n++){r(n)}}function E(t){if(!t){return true}if(t.writable===false){return false}return!(typeof t.get==="function"&&typeof t.set==="undefined")}var C=typeof WorkerGlobalScope!=="undefined"&&self instanceof WorkerGlobalScope;var M=!("nw"in k)&&typeof k.process!=="undefined"&&k.process.toString()==="[object process]";var A=!M&&!C&&!!(y&&x["HTMLElement"]);var P=typeof k.process!=="undefined"&&k.process.toString()==="[object process]"&&!C&&!!(y&&x["HTMLElement"]);var I={};var O=g("enable_beforeunload");var L=function(t){t=t||k.event;if(!t){return}var e=I[t.type];if(!e){e=I[t.type]=g("ON_PROPERTY"+t.type)}var i=this||t.target||k;var r=i[e];var n;if(A&&i===x&&t.type==="error"){var s=t;n=r&&r.call(this,s.message,s.filename,s.lineno,s.colno,s.error);if(n===true){t.preventDefault()}}else{n=r&&r.apply(this,arguments);if(t.type==="beforeunload"&&k[O]&&typeof n==="string"){t.returnValue=n}else if(n!=undefined&&!n){t.preventDefault()}}return n};function j(t,e,i){var r=s(t,e);if(!r&&i){var n=s(i,e);if(n){r={enumerable:true,configurable:true}}}if(!r||!r.configurable){return}var a=g("on"+e+"patched");if(t.hasOwnProperty(a)&&t[a]){return}delete r.writable;delete r.value;var c=r.get;var u=r.set;var f=e.slice(2);var l=I[f];if(!l){l=I[f]=g("ON_PROPERTY"+f)}r.set=function(e){var i=this;if(!i&&t===k){i=k}if(!i){return}var r=i[l];if(typeof r==="function"){i.removeEventListener(f,L)}u===null||u===void 0?void 0:u.call(i,null);i[l]=e;if(typeof e==="function"){i.addEventListener(f,L,false)}};r.get=function(){var i=this;if(!i&&t===k){i=k}if(!i){return null}var n=i[l];if(n){return n}else if(c){var s=c.call(this);if(s){r.set.call(this,s);if(typeof i[S]==="function"){i.removeAttribute(e)}return s}}return null};o(t,e,r);t[a]=true}function R(t,e,i){if(e){for(var r=0;r<e.length;r++){j(t,"on"+e[r],i)}}else{var n=[];for(var s in t){if(s.slice(0,2)=="on"){n.push(s)}}for(var o=0;o<n.length;o++){j(t,n[o],i)}}}var N=g("originalInstance");function z(t){var e=k[t];if(!e)return;k[g(t)]=e;k[t]=function(){var i=_(arguments,t);switch(i.length){case 0:this[N]=new e;break;case 1:this[N]=new e(i[0]);break;case 2:this[N]=new e(i[0],i[1]);break;case 3:this[N]=new e(i[0],i[1],i[2]);break;case 4:this[N]=new e(i[0],i[1],i[2],i[3]);break;default:throw new Error("Arg list too long.")}};F(k[t],e);var i=new e((function(){}));var r;for(r in i){if(t==="XMLHttpRequest"&&r==="responseBlob")continue;(function(e){if(typeof i[e]==="function"){k[t].prototype[e]=function(){return this[N][e].apply(this[N],arguments)}}else{o(k[t].prototype,e,{set:function(i){if(typeof i==="function"){this[N][e]=v(i,t+"."+e);F(this[N][e],i)}else{this[N][e]=i}},get:function(){return this[N][e]}})}})(r)}for(r in e){if(r!=="prototype"&&e.hasOwnProperty(r)){k[t][r]=e[r]}}}function $(t,e,i){var r=t;while(r&&!r.hasOwnProperty(e)){r=a(r)}if(!r&&t[e]){r=t}var n=g(e);var o=null;if(r&&(!(o=r[n])||!r.hasOwnProperty(n))){o=r[n]=r[e];var c=r&&s(r,e);if(E(c)){var u=i(o,n,e);r[e]=function(){return u(this,arguments)};F(r[e],o)}}return o}function D(t,e,i){var r=null;function n(t){var e=t.data;e.args[e.cbIdx]=function(){t.invoke.apply(this,arguments)};r.apply(e.target,e.args);return t}r=$(t,e,(function(t){return function(e,r){var s=i(e,r);if(s.cbIdx>=0&&typeof r[s.cbIdx]==="function"){return w(s.name,r[s.cbIdx],s,n)}else{return t.apply(e,r)}}}))}function F(t,e){t[g("OriginalDelegate")]=e}var U=false;var B=false;function q(){if(U){return B}U=true;try{var t=x.navigator.userAgent;if(t.indexOf("MSIE ")!==-1||t.indexOf("Trident/")!==-1||t.indexOf("Edge/")!==-1){B=true}}catch(t){}return B}function V(t){return typeof t==="function"}function H(t){return typeof t==="number"}var G={useG:true};var Z={};var W={};var X=new RegExp("^"+b+"(\\w+)(true|false)$");var Y=g("propagationStopped");function J(t,e){var i=(e?e(t):t)+m;var r=(e?e(t):t)+p;var n=b+i;var s=b+r;Z[t]={};Z[t][m]=n;Z[t][p]=s}function K(e,i,r,n){var s=n&&n.add||f;var o=n&&n.rm||l;var c=n&&n.listeners||"eventListeners";var u=n&&n.rmAll||"removeAllListeners";var h=g(s);var d="."+s+":";var v="prependListener";var w="."+v+":";var y=function(t,e,i){if(t.isRemoved){return}var r=t.callback;if(typeof r==="object"&&r.handleEvent){t.callback=function(t){return r.handleEvent(t)};t.originalDelegate=r}var n;try{t.invoke(t,e,[i])}catch(t){n=t}var s=t.options;if(s&&typeof s==="object"&&s.once){var a=t.originalDelegate?t.originalDelegate:t.callback;e[o].call(e,i.type,a,s)}return n};function x(t,r,n){r=r||e.event;if(!r){return}var s=t||r.target||e;var o=s[Z[r.type][n?p:m]];if(o){var a=[];if(o.length===1){var c=y(o[0],s,r);c&&a.push(c)}else{var u=o.slice();for(var f=0;f<u.length;f++){if(r&&r[Y]===true){break}var c=y(u[f],s,r);c&&a.push(c)}}if(a.length===1){throw a[0]}else{var l=function(t){var e=a[t];i.nativeScheduleMicroTask((function(){throw e}))};for(var f=0;f<a.length;f++){l(f)}}}}var k=function(t){return x(this,t,false)};var S=function(t){return x(this,t,true)};function _(i,r){if(!i){return false}var n=true;if(r&&r.useG!==undefined){n=r.useG}var f=r&&r.vh;var l=true;if(r&&r.chkDup!==undefined){l=r.chkDup}var y=false;if(r&&r.rt!==undefined){y=r.rt}var x=i;while(x&&!x.hasOwnProperty(s)){x=a(x)}if(!x&&i[s]){x=i}if(!x){return false}if(x[h]){return false}var _=r&&r.eventNameToString;var T={};var E=x[h]=x[s];var C=x[g(o)]=x[o];var A=x[g(c)]=x[c];var P=x[g(u)]=x[u];var I;if(r&&r.prepend){I=x[g(r.prepend)]=x[r.prepend]}function O(e,i){if(!i){return e}if(typeof e==="boolean"){return{capture:e,passive:true}}if(!e){return{passive:true}}if(typeof e==="object"&&e.passive!==false){return t(t({},e),{passive:true})}return e}var L=function(t){if(T.isExisting){return}return E.call(T.target,T.eventName,T.capture?S:k,T.options)};var j=function(t){if(!t.isRemoved){var e=Z[t.eventName];var i=void 0;if(e){i=e[t.capture?p:m]}var r=i&&t.target[i];if(r){for(var n=0;n<r.length;n++){var s=r[n];if(s===t){r.splice(n,1);t.isRemoved=true;if(t.removeAbortListener){t.removeAbortListener();t.removeAbortListener=null}if(r.length===0){t.allRemoved=true;t.target[i]=null}break}}}}if(!t.allRemoved){return}return C.call(t.target,t.eventName,t.capture?S:k,t.options)};var R=function(t){return E.call(T.target,T.eventName,t.invoke,T.options)};var N=function(t){return I.call(T.target,T.eventName,t.invoke,T.options)};var z=function(t){return C.call(t.target,t.eventName,t.invoke,t.options)};var $=n?L:R;var D=n?j:z;var U=function(t,e){var i=typeof e;return i==="function"&&t.callback===e||i==="object"&&t.originalDelegate===e};var B=(r===null||r===void 0?void 0:r.diff)||U;var q=Zone[g("UNPATCHED_EVENTS")];var V=e[g("PASSIVE_EVENTS")];function H(e){if(typeof e==="object"&&e!==null){var i=t({},e);if(e.signal){i.signal=e.signal}return i}return e}var Y=function(t,i,s,o,a,c){if(a===void 0){a=false}if(c===void 0){c=false}return function(){var u=this||e;var h=arguments[0];if(r&&r.transferEventName){h=r.transferEventName(h)}var d=arguments[1];if(!d){return t.apply(this,arguments)}if(M&&h==="uncaughtException"){return t.apply(this,arguments)}var b=false;if(typeof d!=="function"){if(!d.handleEvent){return t.apply(this,arguments)}b=true}if(f&&!f(t,d,u,arguments)){return}var v=!!V&&V.indexOf(h)!==-1;var w=H(O(arguments[2],v));var g=w===null||w===void 0?void 0:w.signal;if(g===null||g===void 0?void 0:g.aborted){return}if(q){for(var y=0;y<q.length;y++){if(h===q[y]){if(v){return t.call(u,h,d,w)}else{return t.apply(this,arguments)}}}}var x=!w?false:typeof w==="boolean"?true:w.capture;var k=w&&typeof w==="object"?w.once:false;var S=Zone.current;var E=Z[h];if(!E){J(h,_);E=Z[h]}var C=E[x?p:m];var A=u[C];var P=false;if(A){P=true;if(l){for(var y=0;y<A.length;y++){if(B(A[y],d)){return}}}}else{A=u[C]=[]}var I;var L=u.constructor["name"];var j=W[L];if(j){I=j[h]}if(!I){I=L+i+(_?_(h):h)}T.options=w;if(k){T.options.once=false}T.target=u;T.capture=x;T.eventName=h;T.isExisting=P;var R=n?G:undefined;if(R){R.taskData=T}if(g){T.options.signal=undefined}var N=S.scheduleEventTask(I,d,R,s,o);if(g){T.options.signal=g;var z=function(){return N.zone.cancelTask(N)};t.call(g,"abort",z,{once:true});N.removeAbortListener=function(){return g.removeEventListener("abort",z)}}T.target=null;if(R){R.taskData=null}if(k){T.options.once=true}if(typeof N.options!=="boolean"){N.options=w}N.target=u;N.capture=x;N.eventName=h;if(b){N.originalDelegate=d}if(!c){A.push(N)}else{A.unshift(N)}if(a){return u}}};x[s]=Y(E,d,$,D,y);if(I){x[v]=Y(I,w,N,D,y,true)}x[o]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=arguments[2];var s=!n?false:typeof n==="boolean"?true:n.capture;var o=arguments[1];if(!o){return C.apply(this,arguments)}if(f&&!f(C,o,t,arguments)){return}var a=Z[i];var c;if(a){c=a[s?p:m]}var u=c&&t[c];if(u){for(var l=0;l<u.length;l++){var h=u[l];if(B(h,o)){u.splice(l,1);h.isRemoved=true;if(u.length===0){h.allRemoved=true;t[c]=null;if(!s&&typeof i==="string"){var d=b+"ON_PROPERTY"+i;t[d]=null}}h.zone.cancelTask(h);if(y){return t}return}}}return C.apply(this,arguments)};x[c]=function(){var t=this||e;var i=arguments[0];if(r&&r.transferEventName){i=r.transferEventName(i)}var n=[];var s=Q(t,_?_(i):i);for(var o=0;o<s.length;o++){var a=s[o];var c=a.originalDelegate?a.originalDelegate:a.callback;n.push(c)}return n};x[u]=function(){var t=this||e;var i=arguments[0];if(!i){var n=Object.keys(t);for(var s=0;s<n.length;s++){var a=n[s];var c=X.exec(a);var f=c&&c[1];if(f&&f!=="removeListener"){this[u].call(this,f)}}this[u].call(this,"removeListener")}else{if(r&&r.transferEventName){i=r.transferEventName(i)}var l=Z[i];if(l){var h=l[m];var d=l[p];var b=t[h];var v=t[d];if(b){var w=b.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}if(v){var w=v.slice();for(var s=0;s<w.length;s++){var g=w[s];var x=g.originalDelegate?g.originalDelegate:g.callback;this[o].call(this,i,x,g.options)}}}}if(y){return this}};F(x[s],E);F(x[o],C);if(P){F(x[u],P)}if(A){F(x[c],A)}return true}var T=[];for(var E=0;E<r.length;E++){T[E]=_(r[E],n)}return T}function Q(t,e){if(!e){var i=[];for(var r in t){var n=X.exec(r);var s=n&&n[1];if(s&&(!e||s===e)){var o=t[r];if(o){for(var a=0;a<o.length;a++){i.push(o[a])}}}}return i}var c=Z[e];if(!c){J(e);c=Z[e]}var u=t[c[m]];var f=t[c[p]];if(!u){return f?f.slice():[]}else{return f?u.concat(f):u.slice()}}function tt(t,e){var i=t["Event"];if(i&&i.prototype){e.patchMethod(i.prototype,"stopImmediatePropagation",(function(t){return function(e,i){e[Y]=true;t&&t.apply(e,i)}}))}}function et(t,e){e.patchMethod(t,"queueMicrotask",(function(t){return function(t,e){Zone.current.scheduleMicroTask("queueMicrotask",e[0])}}))}var it=g("zoneTask");function rt(t,e,i,r){var n=null;var s=null;e+=r;i+=r;var o={};function a(e){var i=e.data;i.args[0]=function(){return e.invoke.apply(this,arguments)};var r=n.apply(t,i.args);if(H(r)){i.handleId=r}else{i.handle=r;i.isRefreshable=V(r.refresh)}return e}function c(e){var i=e.data,r=i.handle,n=i.handleId;return s.call(t,r!==null&&r!==void 0?r:n)}n=$(t,e,(function(i){return function(n,s){var u;if(V(s[0])){var f={isRefreshable:false,isPeriodic:r==="Interval",delay:r==="Timeout"||r==="Interval"?s[1]||0:undefined,args:s};var l=s[0];s[0]=function t(){try{return l.apply(this,arguments)}finally{var e=f.handle,i=f.handleId,r=f.isPeriodic,n=f.isRefreshable;if(!r&&!n){if(i){delete o[i]}else if(e){e[it]=null}}}};var h=w(e,s[0],f,a,c);if(!h){return h}var d=h.data,p=d.handleId,m=d.handle,b=d.isRefreshable,v=d.isPeriodic;if(p){o[p]=h}else if(m){m[it]=h;if(b&&!v){var g=m.refresh;m.refresh=function(){var t=h.zone,e=h.state;if(e==="notScheduled"){h._state="scheduled";t._updateTaskCount(h,1)}else if(e==="running"){h._state="scheduling"}return g.call(this)}}}return(u=m!==null&&m!==void 0?m:p)!==null&&u!==void 0?u:h}else{return i.apply(t,s)}}}));s=$(t,i,(function(e){return function(i,r){var n=r[0];var s;if(H(n)){s=o[n];delete o[n]}else{s=n===null||n===void 0?void 0:n[it];if(s){n[it]=null}else{s=n}}if(s===null||s===void 0?void 0:s.type){if(s.cancelFn){s.zone.cancelTask(s)}}else{e.apply(t,r)}}}))}function nt(t,e){var i=e.getGlobalObjects(),r=i.isBrowser,n=i.isMix;if(!r&&!n||!t["customElements"]||!("customElements"in t)){return}var s=["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"];e.patchCallbacks(e,t.customElements,"customElements","define",s)}function st(t,e){if(Zone[e.symbol("patchEventTarget")]){return}var i=e.getGlobalObjects(),r=i.eventNames,n=i.zoneSymbolEventNames,s=i.TRUE_STR,o=i.FALSE_STR,a=i.ZONE_SYMBOL_PREFIX;for(var c=0;c<r.length;c++){var u=r[c];var f=u+o;var l=u+s;var h=a+f;var d=a+l;n[u]={};n[u][o]=h;n[u][s]=d}var p=t["EventTarget"];if(!p||!p.prototype){return}e.patchEventTarget(t,e,[p&&p.prototype]);return true}function ot(t,e){e.patchEventPrototype(t,e)}function at(t,e,i){if(!i||i.length===0){return e}var r=i.filter((function(e){return e.target===t}));if(r.length===0){return e}var n=r[0].ignoreProperties;return e.filter((function(t){return n.indexOf(t)===-1}))}function ct(t,e,i,r){if(!t){return}var n=at(t,e,i);R(t,n,r)}function ut(t){return Object.getOwnPropertyNames(t).filter((function(t){return t.startsWith("on")&&t.length>2})).map((function(t){return t.substring(2)}))}function ft(t,e){if(M&&!P){return}if(Zone[t.symbol("patchEvents")]){return}var i=e["__Zone_ignore_on_properties"];var r=[];if(A){var n=window;r=r.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]);var s=[];ct(n,ut(n),i?i.concat(s):i,a(n))}r=r.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(var o=0;o<r.length;o++){var c=e[r[o]];(c===null||c===void 0?void 0:c.prototype)&&ct(c.prototype,ut(c.prototype),i)}}function lt(t){t.__load_patch("legacy",(function(e){var i=e[t.__symbol__("legacyPatch")];if(i){i()}}));t.__load_patch("timers",(function(t){var e="set";var i="clear";rt(t,e,i,"Timeout");rt(t,e,i,"Interval");rt(t,e,i,"Immediate")}));t.__load_patch("requestAnimationFrame",(function(t){rt(t,"request","cancel","AnimationFrame");rt(t,"mozRequest","mozCancel","AnimationFrame");rt(t,"webkitRequest","webkitCancel","AnimationFrame")}));t.__load_patch("blocking",(function(t,e){var i=["alert","prompt","confirm"];for(var r=0;r<i.length;r++){var n=i[r];$(t,n,(function(i,r,n){return function(r,s){return e.current.run(i,t,s,n)}}))}}));t.__load_patch("EventTarget",(function(t,e,i){ot(t,i);st(t,i);var r=t["XMLHttpRequestEventTarget"];if(r&&r.prototype){i.patchEventTarget(t,i,[r.prototype])}}));t.__load_patch("MutationObserver",(function(t,e,i){z("MutationObserver");z("WebKitMutationObserver")}));t.__load_patch("IntersectionObserver",(function(t,e,i){z("IntersectionObserver")}));t.__load_patch("FileReader",(function(t,e,i){z("FileReader")}));t.__load_patch("on_property",(function(t,e,i){ft(i,t)}));t.__load_patch("customElements",(function(t,e,i){nt(t,i)}));t.__load_patch("XHR",(function(t,e){c(t);var i=g("xhrTask");var r=g("xhrSync");var n=g("xhrListener");var s=g("xhrScheduled");var o=g("xhrURL");var a=g("xhrErrorBeforeScheduled");function c(t){var c=t["XMLHttpRequest"];if(!c){return}var u=c.prototype;function f(t){return t[i]}var l=u[h];var p=u[d];if(!l){var m=t["XMLHttpRequestEventTarget"];if(m){var b=m.prototype;l=b[h];p=b[d]}}var v="readystatechange";var y="scheduled";function x(t){var r=t.data;var o=r.target;o[s]=false;o[a]=false;var c=o[n];if(!l){l=o[h];p=o[d]}if(c){p.call(o,v,c)}var u=o[n]=function(){if(o.readyState===o.DONE){if(!r.aborted&&o[s]&&t.state===y){var i=o[e.__symbol__("loadfalse")];if(o.status!==0&&i&&i.length>0){var n=t.invoke;t.invoke=function(){var i=o[e.__symbol__("loadfalse")];for(var s=0;s<i.length;s++){if(i[s]===t){i.splice(s,1)}}if(!r.aborted&&t.state===y){n.call(t)}};i.push(t)}else{t.invoke()}}else if(!r.aborted&&o[s]===false){o[a]=true}}};l.call(o,v,u);var f=o[i];if(!f){o[i]=t}M.apply(o,r.args);o[s]=true;return t}function k(){}function S(t){var e=t.data;e.aborted=true;return A.apply(e.target,e.args)}var _=$(u,"open",(function(){return function(t,e){t[r]=e[2]==false;t[o]=e[1];return _.apply(t,e)}}));var T="XMLHttpRequest.send";var E=g("fetchTaskAborting");var C=g("fetchTaskScheduling");var M=$(u,"send",(function(){return function(t,i){if(e.current[C]===true){return M.apply(t,i)}if(t[r]){return M.apply(t,i)}else{var n={target:t,url:t[o],isPeriodic:false,args:i,aborted:false};var s=w(T,k,n,x,S);if(t&&t[a]===true&&!n.aborted&&s.state===y){s.invoke()}}}}));var A=$(u,"abort",(function(){return function(t,i){var r=f(t);if(r&&typeof r.type=="string"){if(r.cancelFn==null||r.data&&r.data.aborted){return}r.zone.cancelTask(r)}else if(e.current[E]===true){return A.apply(t,i)}}}))}}));t.__load_patch("geolocation",(function(t){if(t["navigator"]&&t["navigator"].geolocation){T(t["navigator"].geolocation,["getCurrentPosition","watchPosition"])}}));t.__load_patch("PromiseRejectionEvent",(function(t,e){function i(e){return function(i){var r=Q(t,e);r.forEach((function(r){var n=t["PromiseRejectionEvent"];if(n){var s=new n(e,{promise:i.promise,reason:i.rejection});r.invoke(s)}}))}}if(t["PromiseRejectionEvent"]){e[g("unhandledPromiseRejectionHandler")]=i("unhandledrejection");e[g("rejectionHandledHandler")]=i("rejectionhandled")}}));t.__load_patch("queueMicrotask",(function(t,e,i){et(t,i)}))}function ht(t){t.__load_patch("ZoneAwarePromise",(function(t,e,i){var r=Object.getOwnPropertyDescriptor;var n=Object.defineProperty;function s(t){if(t&&t.toString===Object.prototype.toString){var e=t.constructor&&t.constructor.name;return(e?e:"")+": "+JSON.stringify(t)}return t?t.toString():Object.prototype.toString.call(t)}var o=i.symbol;var a=[];var c=t[o("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")]!==false;var u=o("Promise");var f=o("then");var l="__creationTrace__";i.onUnhandledError=function(t){if(i.showUncaughtError()){var e=t&&t.rejection;if(e){console.error("Unhandled Promise rejection:",e instanceof Error?e.message:e,"; Zone:",t.zone.name,"; Task:",t.task&&t.task.source,"; Value:",e,e instanceof Error?e.stack:undefined)}else{console.error(t)}}};i.microtaskDrainDone=function(){var t=function(){var t=a.shift();try{t.zone.runGuarded((function(){if(t.throwOriginal){throw t.rejection}throw t}))}catch(t){d(t)}};while(a.length){t()}};var h=o("unhandledPromiseRejectionHandler");function d(t){i.onUnhandledError(t);try{var r=e[h];if(typeof r==="function"){r.call(this,t)}}catch(t){}}function p(t){return t&&typeof t.then==="function"}function m(t){return t}function b(t){return D.reject(t)}var v=o("state");var w=o("value");var g=o("finally");var y=o("parentPromiseValue");var x=o("parentPromiseState");var k="Promise.then";var S=null;var _=true;var T=false;var E=0;function C(t,e){return function(i){try{I(t,e,i)}catch(e){I(t,false,e)}}}var M=function(){var t=false;return function e(i){return function(){if(t){return}t=true;i.apply(null,arguments)}}};var A="Promise resolved with itself";var P=o("currentTaskTrace");function I(t,r,o){var u=M();if(t===o){throw new TypeError(A)}if(t[v]===S){var f=null;try{if(typeof o==="object"||typeof o==="function"){f=o&&o.then}}catch(e){u((function(){I(t,false,e)}))();return t}if(r!==T&&o instanceof D&&o.hasOwnProperty(v)&&o.hasOwnProperty(w)&&o[v]!==S){L(o);I(t,o[v],o[w])}else if(r!==T&&typeof f==="function"){try{f.call(o,u(C(t,r)),u(C(t,false)))}catch(e){u((function(){I(t,false,e)}))()}}else{t[v]=r;var h=t[w];t[w]=o;if(t[g]===g){if(r===_){t[v]=t[x];t[w]=t[y]}}if(r===T&&o instanceof Error){var d=e.currentTask&&e.currentTask.data&&e.currentTask.data[l];if(d){n(o,P,{configurable:true,enumerable:false,writable:true,value:d})}}for(var p=0;p<h.length;){j(t,h[p++],h[p++],h[p++],h[p++])}if(h.length==0&&r==T){t[v]=E;var m=o;try{throw new Error("Uncaught (in promise): "+s(o)+(o&&o.stack?"\n"+o.stack:""))}catch(t){m=t}if(c){m.throwOriginal=true}m.rejection=o;m.promise=t;m.zone=e.current;m.task=e.currentTask;a.push(m);i.scheduleMicroTask()}}}return t}var O=o("rejectionHandledHandler");function L(t){if(t[v]===E){try{var i=e[O];if(i&&typeof i==="function"){i.call(this,{rejection:t[w],promise:t})}}catch(t){}t[v]=T;for(var r=0;r<a.length;r++){if(t===a[r].promise){a.splice(r,1)}}}}function j(t,e,i,r,n){L(t);var s=t[v];var o=s?typeof r==="function"?r:m:typeof n==="function"?n:b;e.scheduleMicroTask(k,(function(){try{var r=t[w];var n=!!i&&g===i[g];if(n){i[y]=r;i[x]=s}var a=e.run(o,undefined,n&&o!==b&&o!==m?[]:[r]);I(i,true,a)}catch(t){I(i,false,t)}}),i)}var R="function ZoneAwarePromise() { [native code] }";var N=function(){};var z=t.AggregateError;var D=function(){function t(e){var i=this;if(!(i instanceof t)){throw new Error("Must be an instanceof Promise.")}i[v]=S;i[w]=[];try{var r=M();e&&e(r(C(i,_)),r(C(i,T)))}catch(t){I(i,false,t)}}t.toString=function(){return R};t.resolve=function(e){if(e instanceof t){return e}return I(new this(null),_,e)};t.reject=function(t){return I(new this(null),T,t)};t.withResolvers=function(){var e={};e.promise=new t((function(t,i){e.resolve=t;e.reject=i}));return e};t.any=function(e){if(!e||typeof e[Symbol.iterator]!=="function"){return Promise.reject(new z([],"All promises were rejected"))}var i=[];var r=0;try{for(var n=0,s=e;n<s.length;n++){var o=s[n];r++;i.push(t.resolve(o))}}catch(t){return Promise.reject(new z([],"All promises were rejected"))}if(r===0){return Promise.reject(new z([],"All promises were rejected"))}var a=false;var c=[];return new t((function(t,e){for(var n=0;n<i.length;n++){i[n].then((function(e){if(a){return}a=true;t(e)}),(function(t){c.push(t);r--;if(r===0){a=true;e(new z(c,"All promises were rejected"))}}))}}))};t.race=function(t){var e;var i;var r=new this((function(t,r){e=t;i=r}));function n(t){e(t)}function s(t){i(t)}for(var o=0,a=t;o<a.length;o++){var c=a[o];if(!p(c)){c=this.resolve(c)}c.then(n,s)}return r};t.all=function(e){return t.allWithCallback(e)};t.allSettled=function(e){var i=this&&this.prototype instanceof t?this:t;return i.allWithCallback(e,{thenCallback:function(t){return{status:"fulfilled",value:t}},errorCallback:function(t){return{status:"rejected",reason:t}}})};t.allWithCallback=function(t,e){var i;var r;var n=new this((function(t,e){i=t;r=e}));var s=2;var o=0;var a=[];var c=function(t){if(!p(t)){t=u.resolve(t)}var n=o;try{t.then((function(t){a[n]=e?e.thenCallback(t):t;s--;if(s===0){i(a)}}),(function(t){if(!e){r(t)}else{a[n]=e.errorCallback(t);s--;if(s===0){i(a)}}}))}catch(t){r(t)}s++;o++};var u=this;for(var f=0,l=t;f<l.length;f++){var h=l[f];c(h)}s-=2;if(s===0){i(a)}return n};Object.defineProperty(t.prototype,Symbol.toStringTag,{get:function(){return"Promise"},enumerable:false,configurable:true});Object.defineProperty(t.prototype,Symbol.species,{get:function(){return t},enumerable:false,configurable:true});t.prototype.then=function(i,r){var n;var s=(n=this.constructor)===null||n===void 0?void 0:n[Symbol.species];if(!s||typeof s!=="function"){s=this.constructor||t}var o=new s(N);var a=e.current;if(this[v]==S){this[w].push(a,o,i,r)}else{j(this,a,o,i,r)}return o};t.prototype.catch=function(t){return this.then(null,t)};t.prototype.finally=function(i){var r;var n=(r=this.constructor)===null||r===void 0?void 0:r[Symbol.species];if(!n||typeof n!=="function"){n=t}var s=new n(N);s[g]=g;var o=e.current;if(this[v]==S){this[w].push(o,s,i,i)}else{j(this,o,s,i,i)}return s};return t}();D["resolve"]=D.resolve;D["reject"]=D.reject;D["race"]=D.race;D["all"]=D.all;var F=t[u]=t["Promise"];t["Promise"]=D;var U=o("thenPatched");function B(t){var e=t.prototype;var i=r(e,"then");if(i&&(i.writable===false||!i.configurable)){return}var n=e.then;e[f]=n;t.prototype.then=function(t,e){var i=this;var r=new D((function(t,e){n.call(i,t,e)}));return r.then(t,e)};t[U]=true}i.patchThen=B;function q(t){return function(e,i){var r=t.apply(e,i);if(r instanceof D){return r}var n=r.constructor;if(!n[U]){B(n)}return r}}if(F){B(F);$(t,"fetch",(function(t){return q(t)}))}Promise[e.__symbol__("uncaughtPromiseErrors")]=a;return D}))}function dt(t){t.__load_patch("toString",(function(t){var e=Function.prototype.toString;var i=g("OriginalDelegate");var r=g("Promise");var n=g("Error");var s=function s(){if(typeof this==="function"){var o=this[i];if(o){if(typeof o==="function"){return e.call(o)}else{return Object.prototype.toString.call(o)}}if(this===Promise){var a=t[r];if(a){return e.call(a)}}if(this===Error){var c=t[n];if(c){return e.call(c)}}}return e.call(this)};s[i]=e;Function.prototype.toString=s;var o=Object.prototype.toString;var a="[object Promise]";Object.prototype.toString=function(){if(typeof Promise==="function"&&this instanceof Promise){return a}return o.call(this)}}))}function pt(t,e,i,r,n){var s=Zone.__symbol__(r);if(e[s]){return}var o=e[s]=e[r];e[r]=function(s,a,c){if(a&&a.prototype){n.forEach((function(e){var n="".concat(i,".").concat(r,"::")+e;var s=a.prototype;try{if(s.hasOwnProperty(e)){var o=t.ObjectGetOwnPropertyDescriptor(s,e);if(o&&o.value){o.value=t.wrapWithCurrentZone(o.value,n);t._redefineProperty(a.prototype,e,o)}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}else if(s[e]){s[e]=t.wrapWithCurrentZone(s[e],n)}}catch(t){}}))}return o.call(e,s,a,c)};t.attachOriginToPatched(e[r],o)}function mt(t){t.__load_patch("util",(function(t,e,i){var r=ut(t);i.patchOnProperties=R;i.patchMethod=$;i.bindArguments=_;i.patchMacroTask=D;var n=e.__symbol__("BLACK_LISTED_EVENTS");var a=e.__symbol__("UNPATCHED_EVENTS");if(t[a]){t[n]=t[a]}if(t[n]){e[n]=e[a]=t[n]}i.patchEventPrototype=tt;i.patchEventTarget=K;i.isIEOrEdge=q;i.ObjectDefineProperty=o;i.ObjectGetOwnPropertyDescriptor=s;i.ObjectCreate=c;i.ArraySlice=u;i.patchClass=z;i.wrapWithCurrentZone=v;i.filterProperties=at;i.attachOriginToPatched=F;i._redefineProperty=Object.defineProperty;i.patchCallbacks=pt;i.getGlobalObjects=function(){return{globalSources:W,zoneSymbolEventNames:Z,eventNames:r,isBrowser:A,isMix:P,isNode:M,TRUE_STR:p,FALSE_STR:m,ZONE_SYMBOL_PREFIX:b,ADD_EVENT_LISTENER_STR:f,REMOVE_EVENT_LISTENER_STR:l}}}))}function bt(t){ht(t);dt(t);mt(t)}var vt=n();bt(vt);lt(vt)}));return Ba}Va();class Ha{emit(t){}}const Ga=new Ha;class Za{getLogger(t,e,i){return new Ha}}const Wa=new Za;class Xa{constructor(t,e,i,r){this._provider=t;this.name=e;this.version=i;this.options=r}emit(t){this._getLogger().emit(t)}_getLogger(){if(this._delegate){return this._delegate}const t=this._provider._getDelegateLogger(this.name,this.version,this.options);if(!t){return Ga}this._delegate=t;return this._delegate}}class Ya{getLogger(t,e,i){var r;return(r=this._getDelegateLogger(t,e,i))!==null&&r!==void 0?r:new Xa(this,t,e,i)}_getDelegate(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Wa}_setDelegate(t){this._delegate=t}_getDelegateLogger(t,e,i){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getLogger(t,e,i)}}const Ja=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};const Ka=Symbol.for("io.opentelemetry.js.api.logs");const Qa=Ja;function tc(t,e,i){return r=>r===t?e:i}const ec=1;class ic{constructor(){this._proxyLoggerProvider=new Ya}static getInstance(){if(!this._instance){this._instance=new ic}return this._instance}setGlobalLoggerProvider(t){if(Qa[Ka]){return this.getLoggerProvider()}Qa[Ka]=tc(ec,t,Wa);this._proxyLoggerProvider._setDelegate(t);return t}getLoggerProvider(){var t,e;return(e=(t=Qa[Ka])===null||t===void 0?void 0:t.call(Qa,ec))!==null&&e!==void 0?e:this._proxyLoggerProvider}getLogger(t,e,i){return this.getLoggerProvider().getLogger(t,e,i)}disable(){delete Qa[Ka];this._proxyLoggerProvider=new Ya}}const rc=ic.getInstance();function nc(t,e,i,r){for(let n=0,s=t.length;n<s;n++){const s=t[n];if(e){s.setTracerProvider(e)}if(i){s.setMeterProvider(i)}if(r&&s.setLoggerProvider){s.setLoggerProvider(r)}if(!s.getConfig().enabled){s.enable()}}}function sc(t){t.forEach((t=>t.disable()))}function oc(t){const e=t.tracerProvider||de.getTracerProvider();const i=t.meterProvider||te.getMeterProvider();const r=t.loggerProvider||rc.getLoggerProvider();const n=t.instrumentations?.flat()??[];nc(n,e,i,r);return()=>{sc(n)}}let ac=console.error.bind(console);function cc(t,e,i){const r=!!t[e]&&Object.prototype.propertyIsEnumerable.call(t,e);Object.defineProperty(t,e,{configurable:true,enumerable:r,writable:true,value:i})}const uc=(t,e,i)=>{if(!t||!t[e]){ac("no original function "+String(e)+" to wrap");return}if(!i){ac("no wrapper function");ac((new Error).stack);return}const r=t[e];if(typeof r!=="function"||typeof i!=="function"){ac("original object and wrapper must be functions");return}const n=i(r,e);cc(n,"__original",r);cc(n,"__unwrap",(()=>{if(t[e]===n){cc(t,e,r)}}));cc(n,"__wrapped",true);cc(t,e,n);return n};const fc=(t,e,i)=>{if(!t){ac("must provide one or more modules to patch");ac((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){ac("must provide one or more functions to wrap on modules");return}t.forEach((t=>{e.forEach((e=>{uc(t,e,i)}))}))};const lc=(t,e)=>{if(!t||!t[e]){ac("no function to unwrap.");ac((new Error).stack);return}const i=t[e];if(!i.__unwrap){ac("no original to unwrap to -- has "+String(e)+" already been unwrapped?")}else{i.__unwrap();return}};const hc=(t,e)=>{if(!t){ac("must provide one or more modules to patch");ac((new Error).stack);return}else if(!Array.isArray(t)){t=[t]}if(!(e&&Array.isArray(e))){ac("must provide one or more functions to unwrap on modules");return}t.forEach((t=>{e.forEach((e=>{lc(t,e)}))}))};class dc{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(t,e,i){this.instrumentationName=t;this.instrumentationVersion=e;this.setConfig(i);this._diag=Xt.createComponentLogger({namespace:t});this._tracer=de.getTracer(t,e);this._meter=te.getMeter(t,e);this._logger=rc.getLogger(t,e);this._updateMetricInstruments()}_wrap=uc;_unwrap=lc;_massWrap=fc;_massUnwrap=hc;get meter(){return this._meter}setMeterProvider(t){this._meter=t.getMeter(this.instrumentationName,this.instrumentationVersion);this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(t){this._logger=t.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const t=this.init()??[];if(!Array.isArray(t)){return[t]}return t}_updateMetricInstruments(){return}getConfig(){return this._config}setConfig(t){this._config={enabled:true,...t}}setTracerProvider(t){this._tracer=t.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(t,e,i,r){if(!t){return}try{t(i,r)}catch(t){this._diag.error(`Error running span customization hook due to exception in handler`,{triggerName:e},t)}}}class pc extends dc{constructor(t,e,i){super(t,e,i);if(this._config.enabled){this.enable()}}}function mc(t){return typeof t==="function"&&typeof t.__original==="function"&&typeof t.__unwrap==="function"&&t.__wrapped===true}var bc;(function(t){t["EVENT_TYPE"]="event_type";t["TARGET_ELEMENT"]="target_element";t["TARGET_XPATH"]="target_xpath";t["HTTP_URL"]="http.url"})(bc||(bc={}));const vc="0.53.0";const wc="@opentelemetry/instrumentation-user-interaction";const gc="OT_ZONE_CONTEXT";const yc="Navigation:";const xc=["click"];function kc(){return false}class Sc extends pc{version=vc;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(t={}){super(wc,vc,t);this._eventNames=new Set(t?.eventNames??xc);this._shouldPreventSpanCreation=typeof t?.shouldPreventSpanCreation==="function"?t.shouldPreventSpanCreation:kc}init(){}_checkForTimeout(t,e){const i=this._spansData.get(e);if(i){if(t.source==="setTimeout"){i.hrTimeLastTimeout=ri()}else if(t.source!=="Promise.then"&&t.source!=="setTimeout"){i.hrTimeLastTimeout=undefined}}}_allowEventName(t){return this._eventNames.has(t)}_createSpan(t,e,i){if(!(t instanceof HTMLElement)){return undefined}if(!t.getAttribute){return undefined}if(t.hasAttribute("disabled")){return undefined}if(!this._allowEventName(e)){return undefined}const r=Yr(t,true);try{const n=this.tracer.startSpan(e,{attributes:{[bc.EVENT_TYPE]:e,[bc.TARGET_ELEMENT]:t.tagName,[bc.TARGET_XPATH]:r,[bc.HTTP_URL]:window.location.href}},i?de.setSpan(Wt.active(),i):undefined);if(this._shouldPreventSpanCreation(e,t,n)===true){return undefined}this._spansData.set(n,{taskCount:0});return n}catch(t){this._diag.error("failed to start create new user interaction span",t)}return undefined}_decrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount--;if(e.taskCount===0){this._tryToEndSpan(t,e.hrTimeLastTimeout)}}}_getCurrentSpan(t){const e=t.get(gc);if(e){return de.getSpan(e)}return e}_incrementTask(t){const e=this._spansData.get(t);if(e){e.taskCount++}}addPatchedListener(t,e,i,r){let n=this._wrappedListeners.get(i);if(!n){n=new Map;this._wrappedListeners.set(i,n)}let s=n.get(e);if(!s){s=new Map;n.set(e,s)}if(s.has(t)){return false}s.set(t,r);return true}removePatchedListener(t,e,i){const r=this._wrappedListeners.get(i);if(!r){return undefined}const n=r.get(e);if(!n){return undefined}const s=n.get(t);if(s){n.delete(t);if(n.size===0){r.delete(e);if(r.size===0){this._wrappedListeners.delete(i)}}}return s}_invokeListener(t,e,i){if(typeof t==="function"){return t.apply(e,i)}else{return t.handleEvent(i[0])}}_patchAddEventListener(){const t=this;return e=>function i(r,n,s){if(!n){return e.call(this,r,n,s)}const o=s&&typeof s==="object"&&s.once;const a=function(...e){let i;const s=e[0];const a=s?.target;if(s){i=t._eventsSpanMap.get(s)}if(o){t.removePatchedListener(this,r,n)}const c=t._createSpan(a,r,i);if(c){if(s){t._eventsSpanMap.set(s,c)}return Wt.with(de.setSpan(Wt.active(),c),(()=>{const i=t._invokeListener(n,this,e);c.end();return i}))}else{return t._invokeListener(n,this,e)}};if(t.addPatchedListener(this,r,n,a)){return e.call(this,r,a,s)}}}_patchRemoveEventListener(){const t=this;return e=>function i(r,n,s){const o=t.removePatchedListener(this,r,n);if(o){return e.call(this,r,o,s)}else{return e.call(this,r,n,s)}}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi();this._wrap(history,"replaceState",this._patchHistoryMethod());this._wrap(history,"pushState",this._patchHistoryMethod());this._wrap(history,"back",this._patchHistoryMethod());this._wrap(history,"forward",this._patchHistoryMethod());this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const t=this;return e=>function i(...r){const n=`${location.pathname}${location.hash}${location.search}`;const s=e.apply(this,r);const o=`${location.pathname}${location.hash}${location.search}`;if(n!==o){t._updateInteractionName(o)}return s}}_unpatchHistoryApi(){if(mc(history.replaceState))this._unwrap(history,"replaceState");if(mc(history.pushState))this._unwrap(history,"pushState");if(mc(history.back))this._unwrap(history,"back");if(mc(history.forward))this._unwrap(history,"forward");if(mc(history.go))this._unwrap(history,"go")}_updateInteractionName(t){const e=de.getSpan(Wt.active());if(e&&typeof e.updateName==="function"){e.updateName(`${yc} ${t}`)}}_patchZoneCancelTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._decrementTask(s)}return e.call(this,r)}}_patchZoneScheduleTask(){const t=this;return e=>function i(r){const n=Zone.current;const s=t._getCurrentSpan(n);if(s&&t._shouldCountTask(r,n)){t._incrementTask(s);t._checkForTimeout(r,s)}return e.call(this,r)}}_patchZoneRunTask(){const t=this;return e=>function i(r,n,s){const o=Array.isArray(s)&&s[0]instanceof Event?s[0]:undefined;const a=o?.target;let c;const u=this;if(a){c=t._createSpan(a,r.eventName);if(c){t._incrementTask(c);return u.run((()=>{try{return Wt.with(de.setSpan(Wt.active(),c),(()=>{const t=Zone.current;r._zone=t;return e.call(t,r,n,s)}))}finally{t._decrementTask(c)}}))}}else{c=t._getCurrentSpan(u)}try{return e.call(u,r,n,s)}finally{if(c&&t._shouldCountTask(r,u)){t._decrementTask(c)}}}}_shouldCountTask(t,e){if(t._zone){e=t._zone}if(!e||!t.data||t.data.isPeriodic){return false}const i=this._getCurrentSpan(e);if(!i){return false}if(!this._spansData.get(i)){return false}return t.type==="macroTask"||t.type==="microTask"}_tryToEndSpan(t,e){if(t){const i=this._spansData.get(t);if(i){t.end(e);this._spansData.delete(t)}}}enable(){const t=this._getZoneWithPrototype();this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!t);if(t){if(mc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask");this._diag.debug("removing previous patch from method runTask")}if(mc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask");this._diag.debug("removing previous patch from method scheduleTask")}if(mc(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask");this._diag.debug("removing previous patch from method cancelTask")}this._zonePatched=true;this._wrap(t.prototype,"runTask",this._patchZoneRunTask());this._wrap(t.prototype,"scheduleTask",this._patchZoneScheduleTask());this._wrap(t.prototype,"cancelTask",this._patchZoneCancelTask())}else{this._zonePatched=false;const t=this._getPatchableEventTargets();t.forEach((t=>{if(mc(t.addEventListener)){this._unwrap(t,"addEventListener");this._diag.debug("removing previous patch from method addEventListener")}if(mc(t.removeEventListener)){this._unwrap(t,"removeEventListener");this._diag.debug("removing previous patch from method removeEventListener")}this._wrap(t,"addEventListener",this._patchAddEventListener());this._wrap(t,"removeEventListener",this._patchRemoveEventListener())}))}this._patchHistoryApi()}disable(){const t=this._getZoneWithPrototype();this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!t);if(t&&this._zonePatched){if(mc(t.prototype.runTask)){this._unwrap(t.prototype,"runTask")}if(mc(t.prototype.scheduleTask)){this._unwrap(t.prototype,"scheduleTask")}if(mc(t.prototype.cancelTask)){this._unwrap(t.prototype,"cancelTask")}}else{const t=this._getPatchableEventTargets();t.forEach((t=>{if(mc(t.addEventListener)){this._unwrap(t,"addEventListener")}if(mc(t.removeEventListener)){this._unwrap(t,"removeEventListener")}}))}this._unpatchHistoryApi()}_getZoneWithPrototype(){const t=window;return t.Zone}}var _c={exports:{}};var Tc=_c.exports;var Ec;function Cc(){if(Ec)return _c.exports;Ec=1;(function(t,e){(function(i,r){var n="1.0.41",s="",o="?",a="function",c="undefined",u="object",f="string",l="major",h="model",d="name",p="type",m="vendor",b="version",v="architecture",w="console",g="mobile",y="tablet",x="smarttv",k="wearable",S="embedded",_=500;var T="Amazon",E="Apple",C="ASUS",M="BlackBerry",A="Browser",P="Chrome",I="Edge",O="Firefox",L="Google",j="Honor",R="Huawei",N="Lenovo",z="LG",$="Microsoft",D="Motorola",F="Nvidia",U="OnePlus",B="Opera",q="OPPO",V="Samsung",H="Sharp",G="Sony",Z="Xiaomi",W="Zebra",X="Facebook",Y="Chromium OS",J="Mac OS",K=" Browser";var Q=function(t,e){var i={};for(var r in t){if(e[r]&&e[r].length%2===0){i[r]=e[r].concat(t[r])}else{i[r]=t[r]}}return i},tt=function(t){var e={};for(var i=0;i<t.length;i++){e[t[i].toUpperCase()]=t[i]}return e},et=function(t,e){return typeof t===f?it(e).indexOf(it(t))!==-1:false},it=function(t){return t.toLowerCase()},rt=function(t){return typeof t===f?t.replace(/[^\d\.]/g,s).split(".")[0]:r},nt=function(t,e){if(typeof t===f){t=t.replace(/^\s\s*/,s);return typeof e===c?t:t.substring(0,_)}};var st=function(t,e){var i=0,n,s,o,c,f,l;while(i<e.length&&!f){var h=e[i],d=e[i+1];n=s=0;while(n<h.length&&!f){if(!h[n]){break}f=h[n++].exec(t);if(!!f){for(o=0;o<d.length;o++){l=f[++s];c=d[o];if(typeof c===u&&c.length>0){if(c.length===2){if(typeof c[1]==a){this[c[0]]=c[1].call(this,l)}else{this[c[0]]=c[1]}}else if(c.length===3){if(typeof c[1]===a&&!(c[1].exec&&c[1].test)){this[c[0]]=l?c[1].call(this,l,c[2]):r}else{this[c[0]]=l?l.replace(c[1],c[2]):r}}else if(c.length===4){this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):r}}else{this[c]=l?l:r}}}}i+=2}},ot=function(t,e){for(var i in e){if(typeof e[i]===u&&e[i].length>0){for(var n=0;n<e[i].length;n++){if(et(e[i][n],t)){return i===o?r:i}}}else if(et(e[i],t)){return i===o?r:i}}return e.hasOwnProperty("*")?e["*"]:t};var at={"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},ct={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"};var ut={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[b,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[b,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,b],[/opios[\/ ]+([\w\.]+)/i],[b,[d,B+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[b,[d,B+" GX"]],[/\bopr\/([\w\.]+)/i],[b,[d,B]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[b,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[b,[d,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[d,b],[/quark(?:pc)?\/([-\w\.]+)/i],[b,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[b,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[b,[d,"UC"+A]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[b,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[b,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[b,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[b,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[b,[d,"Smart Lenovo "+A]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+A],b],[/\bfocus\/([\w\.]+)/i],[b,[d,O+" Focus"]],[/\bopt\/([\w\.]+)/i],[b,[d,B+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[b,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[b,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[b,[d,B+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[b,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[b,[d,O]],[/\bqihoobrowser\/?([\w\.]*)/i],[b,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],b],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],b],[/samsungbrowser\/([\w\.]+)/i],[b,[d,V+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[b,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],b],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,b],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[b,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,X],b],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[d,b],[/\bgsa\/([\w\.]+) .*safari\//i],[b,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[b,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[b,[d,P+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,P+" WebView"],b],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[b,[d,"Android "+A]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,b],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[b,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[b,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[b,ot,at]],[/(webkit|khtml)\/([\w\.]+)/i],[d,b],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],b],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,b],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[b,[d,O+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[d,[b,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[b,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[v,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[v,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[v,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[v,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[v,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[v,/ower/,s,it]],[/ sun4\w[;\)]/i],[[v,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[v,it]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[h,[m,V],[p,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[h,[m,V],[p,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[h,[m,E],[p,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[h,[m,E],[p,y]],[/(macintosh);/i],[h,[m,E]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[h,[m,H],[p,g]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[h,[m,j],[p,y]],[/honor([-\w ]+)[;\)]/i],[h,[m,j],[p,g]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[h,[m,R],[p,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[h,[m,R],[p,g]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[h,/_/g," "],[m,Z],[p,y]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[h,/_/g," "],[m,Z],[p,g]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[h,[m,q],[p,g]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[h,[m,ot,{OnePlus:["304","403","203"],"*":q}],[p,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[h,[m,"Vivo"],[p,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[h,[m,"Realme"],[p,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[h,[m,D],[p,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[h,[m,D],[p,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[h,[m,z],[p,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[h,[m,z],[p,g]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[h,[m,N],[p,y]],[/(nokia) (t[12][01])/i],[m,h,[p,y]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[h,/_/g," "],[p,g],[m,"Nokia"]],[/(pixel (c|tablet))\b/i],[h,[m,L],[p,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[h,[m,L],[p,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[h,[m,G],[p,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[h,"Xperia Tablet"],[m,G],[p,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[h,[m,U],[p,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[h,[m,T],[p,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[h,/(.+)/g,"Fire Phone $1"],[m,T],[p,g]],[/(playbook);[-\w\),; ]+(rim)/i],[h,m,[p,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[h,[m,M],[p,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[h,[m,C],[p,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[h,[m,C],[p,g]],[/(nexus 9)/i],[h,[m,"HTC"],[p,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[m,[h,/_/g," "],[p,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[h,[m,"TCL"],[p,y]],[/(itel) ((\w+))/i],[[m,it],h,[p,ot,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[h,[m,"Acer"],[p,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[h,[m,"Meizu"],[p,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[h,[m,"Ulefone"],[p,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[h,[m,"Energizer"],[p,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[h,[m,"Cat"],[p,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[h,[m,"Smartfren"],[p,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[h,[m,"Nothing"],[p,g]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[h,[m,"Archos"],[p,y]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[h,[m,"Archos"],[p,g]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[m,h,[p,y]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[m,h,[p,g]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[m,h,[p,y]],[/(surface duo)/i],[h,[m,$],[p,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[h,[m,"Fairphone"],[p,g]],[/(u304aa)/i],[h,[m,"AT&T"],[p,g]],[/\bsie-(\w*)/i],[h,[m,"Siemens"],[p,g]],[/\b(rct\w+) b/i],[h,[m,"RCA"],[p,y]],[/\b(venue[\d ]{2,7}) b/i],[h,[m,"Dell"],[p,y]],[/\b(q(?:mv|ta)\w+) b/i],[h,[m,"Verizon"],[p,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[h,[m,"Barnes & Noble"],[p,y]],[/\b(tm\d{3}\w+) b/i],[h,[m,"NuVision"],[p,y]],[/\b(k88) b/i],[h,[m,"ZTE"],[p,y]],[/\b(nx\d{3}j) b/i],[h,[m,"ZTE"],[p,g]],[/\b(gen\d{3}) b.+49h/i],[h,[m,"Swiss"],[p,g]],[/\b(zur\d{3}) b/i],[h,[m,"Swiss"],[p,y]],[/\b((zeki)?tb.*\b) b/i],[h,[m,"Zeki"],[p,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[m,"Dragon Touch"],h,[p,y]],[/\b(ns-?\w{0,9}) b/i],[h,[m,"Insignia"],[p,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[h,[m,"NextBook"],[p,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[m,"Voice"],h,[p,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[m,"LvTel"],h,[p,g]],[/\b(ph-1) /i],[h,[m,"Essential"],[p,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[h,[m,"Envizen"],[p,y]],[/\b(trio[-\w\. ]+) b/i],[h,[m,"MachSpeed"],[p,y]],[/\btu_(1491) b/i],[h,[m,"Rotor"],[p,y]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[h,[m,F],[p,y]],[/(sprint) (\w+)/i],[m,h,[p,g]],[/(kin\.[onetw]{3})/i],[[h,/\./g," "],[m,$],[p,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[h,[m,W],[p,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[h,[m,W],[p,g]],[/smart-tv.+(samsung)/i],[m,[p,x]],[/hbbtv.+maple;(\d+)/i],[[h,/^/,"SmartTV"],[m,V],[p,x]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[m,z],[p,x]],[/(apple) ?tv/i],[m,[h,E+" TV"],[p,x]],[/crkey/i],[[h,P+"cast"],[m,L],[p,x]],[/droid.+aft(\w+)( bui|\))/i],[h,[m,T],[p,x]],[/(shield \w+ tv)/i],[h,[m,F],[p,x]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[h,[m,H],[p,x]],[/(bravia[\w ]+)( bui|\))/i],[h,[m,G],[p,x]],[/(mi(tv|box)-?\w+) bui/i],[h,[m,Z],[p,x]],[/Hbbtv.*(technisat) (.*);/i],[m,h,[p,x]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[m,nt],[h,nt],[p,x]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[h,[p,x]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,x]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[m,h,[p,w]],[/droid.+; (shield)( bui|\))/i],[h,[m,F],[p,w]],[/(playstation \w+)/i],[h,[m,G],[p,w]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[h,[m,$],[p,w]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[h,[m,V],[p,k]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[m,h,[p,k]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[h,[m,q],[p,k]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[h,[m,E],[p,k]],[/(opwwe\d{3})/i],[h,[m,U],[p,k]],[/(moto 360)/i],[h,[m,D],[p,k]],[/(smartwatch 3)/i],[h,[m,G],[p,k]],[/(g watch r)/i],[h,[m,z],[p,k]],[/droid.+; (wt63?0{2,3})\)/i],[h,[m,W],[p,k]],[/droid.+; (glass) \d/i],[h,[m,L],[p,k]],[/(pico) (4|neo3(?: link|pro)?)/i],[m,h,[p,k]],[/; (quest( \d| pro)?)/i],[h,[m,X],[p,k]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[m,[p,S]],[/(aeobc)\b/i],[h,[m,T],[p,S]],[/(homepod).+mac os/i],[h,[m,E],[p,S]],[/windows iot/i],[[p,S]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[h,[p,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[h,[p,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[p,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[p,g]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[h,[m,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[b,[d,I+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[d,b],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[b,[d,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[d,b],[/ladybird\//i],[[d,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[b,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,b],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[d,[b,ot,ct]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[b,ot,ct],[d,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[b,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,J],[b,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[b,d],[/(ubuntu) ([\w\.]+) like android/i],[[d,/(.+)/,"$1 Touch"],b],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[d,b],[/\(bb(10);/i],[b,[d,M]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[b,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[b,[d,O+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[b,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[b,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[b,[d,P+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,Y],b],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[d,b],[/(sunos) ?([\w\.\d]*)/i],[[d,"Solaris"],b],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[d,b]]};var ft=function(t,e){if(typeof t===u){e=t;t=r}if(!(this instanceof ft)){return new ft(t,e).getResult()}var n=typeof i!==c&&i.navigator?i.navigator:r;var o=t||(n&&n.userAgent?n.userAgent:s);var w=n&&n.userAgentData?n.userAgentData:r;var x=e?Q(ut,e):ut;var k=n&&n.userAgent==o;this.getBrowser=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.browser);t[l]=rt(t[b]);if(k&&n&&n.brave&&typeof n.brave.isBrave==a){t[d]="Brave"}return t};this.getCPU=function(){var t={};t[v]=r;st.call(t,o,x.cpu);return t};this.getDevice=function(){var t={};t[m]=r;t[h]=r;t[p]=r;st.call(t,o,x.device);if(k&&!t[p]&&w&&w.mobile){t[p]=g}if(k&&t[h]=="Macintosh"&&n&&typeof n.standalone!==c&&n.maxTouchPoints&&n.maxTouchPoints>2){t[h]="iPad";t[p]=y}return t};this.getEngine=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.engine);return t};this.getOS=function(){var t={};t[d]=r;t[b]=r;st.call(t,o,x.os);if(k&&!t[d]&&w&&w.platform&&w.platform!="Unknown"){t[d]=w.platform.replace(/chrome os/i,Y).replace(/macos/i,J)}return t};this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}};this.getUA=function(){return o};this.setUA=function(t){o=typeof t===f&&t.length>_?nt(t,_):t;return this};this.setUA(o);return this};ft.VERSION=n;ft.BROWSER=tt([d,b,l]);ft.CPU=tt([v]);ft.DEVICE=tt([h,m,p,w,g,x,y,k,S]);ft.ENGINE=ft.OS=tt([d,b]);{if(t.exports){e=t.exports=ft}e.UAParser=ft}var lt=typeof i!==c&&(i.jQuery||i.Zepto);if(lt&&!lt.ua){var ht=new ft;lt.ua=ht.getResult();lt.ua.get=function(){return ht.getUA()};lt.ua.set=function(t){ht.setUA(t);var e=ht.getResult();for(var i in e){lt.ua[i]=e[i]}}}})(typeof window==="object"?window:Tc)})(_c,_c.exports);return _c.exports}var Mc=Cc();var Ac=dn(Mc);const Pc="service.name";const Ic="service.version";const Oc="eAzROSTiqNd3i+M9Jw6q5Tld0jarZc617sJB//pvb5c=";let Lc=false;function jc(){if(Lc){return}Lc=true;const t=window.XMLHttpRequest;if(!t){console.error("[TracingService] XMLHttpRequest not available");return}window.XMLHttpRequest=function(){const e=new t;const i=e.open;const r=e.send;let n=false;e.open=function(t,e,...r){const s=typeof e==="string"?e:e.toString();n=s.includes("collector.jaak.ai");return i.apply(this,[t,e,...r])};e.send=function(...t){if(n){this.setRequestHeader("Authorization",`Bearer ${Oc}`)}return r.apply(this,t)};return e};for(const e in t){if(t.hasOwnProperty(e)){window.XMLHttpRequest[e]=t[e]}}const e=window.fetch;window.fetch=function(t,i){const r=typeof t==="string"?t:t instanceof URL?t.href:t.url;if(r.includes("collector.jaak.ai")){const t=new Headers(i?.headers||{});t.set("Authorization",`Bearer ${Oc}`);i={...i,headers:t}}return e.call(this,t,i)};navigator.sendBeacon=function(){return false}}class Rc{provider=null;tracer=null;sessionTraceId=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;enableAutoInstrumentation;spanProcessor=null;parser;geoCache=null;geoCacheTimestamp=0;GEO_CACHE_DURATION_MS=60*60*1e3;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/traces";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.enableAutoInstrumentation=t.enableAutoInstrumentation??false;this.parser=new Ac}initialize(){try{jc();const t=new $a({url:this.collectorUrl,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Oc}`},useSendBeacon:false});const e={export:(e,i)=>{if(this.debug){console.log("[TracingService] 📤 Exporting",e.length,"spans to collector")}t.export(e,(t=>{if(t.code!==0){console.error("[TracingService] ❌ Export failed:",t)}i(t)}))},shutdown:async()=>t.shutdown(),forceFlush:async()=>t.forceFlush()};this.spanProcessor=new Nr(e,{maxQueueSize:100,maxExportBatchSize:10,scheduledDelayMillis:5e3,exportTimeoutMillis:3e4});this.provider=new Xr({spanProcessors:[this.spanProcessor]});const i=new Ua;const r=new ji;this.provider.register({contextManager:i,propagator:r});this.tracer=de.getTracer(this.serviceName,this.serviceVersion);if(this.enableAutoInstrumentation){this.initializeAutoInstrumentation()}}catch(t){console.error("[TracingService] Failed to initialize:",t)}}initializeAutoInstrumentation(){try{oc({instrumentations:[new Sc({eventNames:["click","submit"],shouldPreventSpanCreation:(t,e)=>e.tagName==="BUTTON"||e.tagName==="A"||e.tagName==="FORM"})]})}catch(t){console.error("[TracingService] Failed to initialize auto-instrumentation:",t)}}getDeviceInfo(){const t=this.parser.getResult();return{type:t.device.type||"desktop",vendor:t.device.vendor||"unknown",model:t.device.model||"unknown"}}getBrowserInfo(){const t=this.parser.getResult();return{name:t.browser.name||"unknown",version:t.browser.version||"unknown",major:t.browser.major||"unknown"}}getOSInfo(){const t=this.parser.getResult();return{name:t.os.name||"unknown",version:t.os.version||"unknown"}}setSessionTraceId(t){if(t&&t.length===32&&/^[a-f0-9]{32}$/i.test(t)){this.sessionTraceId=t.toLowerCase();if(this.debug){console.log("[TracingService] Session trace ID set:",this.sessionTraceId)}}else if(t){console.warn("[TracingService] Invalid trace ID format. Must be 32 hex characters:",t)}}getSessionTraceId(){return this.sessionTraceId}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t).map((t=>t.toString(16).padStart(2,"0"))).join("")}async getGeoLocation(){const t=Date.now();if(this.geoCache&&t-this.geoCacheTimestamp<this.GEO_CACHE_DURATION_MS){return this.geoCache}try{const e=await fetch("https://ipapi.co/json/",{signal:AbortSignal.timeout(5e3)});if(!e.ok){return{}}const i=await e.json();this.geoCache={country:i.country_name,region:i.region,city:i.city,latitude:i.latitude,longitude:i.longitude};this.geoCacheTimestamp=t;return this.geoCache}catch(t){console.warn("[TracingService] Failed to fetch geo location:",t);return this.geoCache||{}}}startSpan(t,e){if(!this.tracer){console.warn("[TracingService] Tracer not initialized, returning no-op span");return de.getTracer("noop").startSpan("noop")}try{let i=Wt.active();if(this.sessionTraceId&&!de.getSpan(i)){const t={traceId:this.sessionTraceId,spanId:this.generateSpanId(),traceFlags:gt.SAMPLED,isRemote:true};const e=de.wrapSpanContext(t);i=de.setSpan(i,e)}const r=this.getDeviceInfo();const n=this.getBrowserInfo();const s=this.getOSInfo();const o=this.tracer.startSpan(t,{attributes:{...e,component:this.serviceName.includes("stamps")?"jaak-stamps":"jaak-visage",[Pc]:this.serviceName,[Ic]:this.serviceVersion,"deployment.environment":this.environment,"trace.id":this.sessionTraceId||"auto-generated","device.type":r.type,"device.vendor":r.vendor,"device.model":r.model,"browser.name":n.name,"browser.version":n.version,"browser.major":n.major,"os.name":s.name,"os.version":s.version,user_agent:navigator.userAgent,...this.customerId&&{"customer.id":this.customerId},...this.tenantId&&{"tenant.id":this.tenantId}}},i);this.getGeoLocation().then((t=>{if(t.country)o.setAttribute("geo.country",t.country);if(t.region)o.setAttribute("geo.region",t.region);if(t.city)o.setAttribute("geo.city",t.city)})).catch((t=>console.warn("Failed to add geo attributes:",t)));if(this.debug){console.log(`[TracingService] Started span: ${t}`,{traceId:o.spanContext().traceId,spanId:o.spanContext().spanId,sessionTraceId:this.sessionTraceId,attributes:e})}return o}catch(t){console.error("[TracingService] Failed to start span:",t);return de.getTracer("noop").startSpan("noop")}}endSpan(t){if(!t){console.warn("[TracingService] endSpan called with null/undefined span");return}try{t.end()}catch(t){console.error("[TracingService] ❌ Failed to end span:",t)}}addSpanEvent(t,e,i){if(!t)return;try{t.addEvent(e,i);if(this.debug){console.log(`[TracingService] Added event to span: ${e}`,i)}}catch(t){console.error("[TracingService] Failed to add span event:",t)}}recordException(t,e){if(!t)return;try{t.recordException(e);t.setStatus({code:Zt.ERROR,message:e.message})}catch(t){console.error("[TracingService] Failed to record exception:",t)}}setSpanAttribute(t,e,i){if(!t)return;try{t.setAttribute(e,i);if(this.debug){console.log(`[TracingService] Set attribute: ${e} = ${i}`)}}catch(t){console.error("[TracingService] Failed to set span attribute:",t)}}async trace(t,e,i){const r=this.startSpan(t,i);try{const t=await Wt.with(de.setSpan(Wt.active(),r),(async()=>await e()));r.setStatus({code:Zt.OK});return t}catch(t){this.recordException(r,t);throw t}finally{this.endSpan(r)}}async traceAsync(t,e,i){return this.trace(t,e,i)}async flush(){try{if(!this.spanProcessor){console.warn("[TracingService] No span processor available to flush");return}await this.spanProcessor.forceFlush()}catch(t){console.error("[TracingService] ❌ Failed to flush spans:",t);throw t}}async cleanup(){try{if(this.spanProcessor){await this.spanProcessor.forceFlush();await this.spanProcessor.shutdown()}if(this.provider){await this.provider.shutdown()}}catch(t){console.error("[TracingService] Failed to cleanup:",t)}}getCurrentTraceId(){try{const t=de.getSpan(Wt.active());return t?.spanContext().traceId}catch{return undefined}}getCurrentSpanId(){try{const t=de.getSpan(Wt.active());return t?.spanContext().spanId}catch{return undefined}}}var Nc;(function(t){t[t["DELTA"]=0]="DELTA";t[t["CUMULATIVE"]=1]="CUMULATIVE";t[t["LOWMEMORY"]=2]="LOWMEMORY"})(Nc||(Nc={}));const zc=()=>Pn.CUMULATIVE;const $c=t=>{switch(t){case In.COUNTER:case In.OBSERVABLE_COUNTER:case In.GAUGE:case In.HISTOGRAM:case In.OBSERVABLE_GAUGE:return Pn.DELTA;case In.UP_DOWN_COUNTER:case In.OBSERVABLE_UP_DOWN_COUNTER:return Pn.CUMULATIVE}};const Dc=t=>{switch(t){case In.COUNTER:case In.HISTOGRAM:return Pn.DELTA;case In.GAUGE:case In.UP_DOWN_COUNTER:case In.OBSERVABLE_UP_DOWN_COUNTER:case In.OBSERVABLE_COUNTER:case In.OBSERVABLE_GAUGE:return Pn.CUMULATIVE}};function Fc(){const t="cumulative".toLowerCase();if(t==="cumulative"){return zc}if(t==="delta"){return $c}if(t==="lowmemory"){return Dc}Xt.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${t}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`);return zc}function Uc(t){if(t!=null){if(t===Nc.DELTA){return $c}else if(t===Nc.LOWMEMORY){return Dc}return zc}return Fc()}const Bc=Object.freeze({type:zs.DEFAULT});function qc(t){return t?.aggregationPreference??(()=>Bc)}class Vc extends Qr{_aggregationTemporalitySelector;_aggregationSelector;constructor(t,e){super(t);this._aggregationSelector=qc(e);this._aggregationTemporalitySelector=Uc(e?.temporalityPreference)}selectAggregation(t){return this._aggregationSelector(t)}selectAggregationTemporality(t){return this._aggregationTemporalitySelector(t)}}class Hc extends Vc{constructor(t){super(Na(t??{},ca,"v1/metrics",{"Content-Type":"application/json"}),t)}}class Gc{meterProvider=null;meter=null;collectorUrl;serviceName;serviceVersion;debug;customerId;tenantId;environment;exportIntervalMillis;metricReader=null;captureCounter=null;errorCounter=null;modelLoadCounter=null;userInteractionCounter=null;captureLatencyHistogram=null;modelLoadLatencyHistogram=null;detectionLatencyHistogram=null;imageSizeHistogram=null;activeSessionsGauge=null;memoryUsageGauge=null;activeSessions=0;gaugeValues=new Map;constructor(t={}){this.collectorUrl=t.collectorUrl||"https://collector.jaak.ai/v1/metrics";this.serviceName=t.serviceName||"jaak-stamps-webcomponent";this.serviceVersion=t.serviceVersion||"2.1.0";this.debug=t.debug||false;this.customerId=t.customerId;this.tenantId=t.tenantId;this.environment=t.environment||"production";this.exportIntervalMillis=t.exportIntervalMillis||6e4}initialize(){try{const t=new Hc({url:this.collectorUrl,headers:{"Content-Type":"application/json"}});this.metricReader=new Bs({exporter:t,exportIntervalMillis:this.exportIntervalMillis,exportTimeoutMillis:3e4});this.meterProvider=new Bo({readers:[this.metricReader]});this.meter=this.meterProvider.getMeter(this.serviceName,this.serviceVersion);this.initializeMetrics();if(this.debug){console.log("[MetricsService] Initialized successfully",{collectorUrl:this.collectorUrl,serviceName:this.serviceName,serviceVersion:this.serviceVersion,environment:this.environment,customerId:this.customerId,tenantId:this.tenantId,exportIntervalMillis:this.exportIntervalMillis})}}catch(t){console.error("[MetricsService] Failed to initialize:",t)}}initializeMetrics(){if(!this.meter)return;const t=this.getBaseAttributes();try{this.captureCounter=this.meter.createCounter("jaak.captures.total",{description:"Total number of document captures",unit:"1"});this.errorCounter=this.meter.createCounter("jaak.errors.total",{description:"Total number of errors",unit:"1"});this.modelLoadCounter=this.meter.createCounter("jaak.model.loads.total",{description:"Total number of model loads",unit:"1"});this.userInteractionCounter=this.meter.createCounter("jaak.user.interactions.total",{description:"Total user interactions (clicks, etc.)",unit:"1"});this.captureLatencyHistogram=this.meter.createHistogram("jaak.capture.duration",{description:"Duration of capture operations",unit:"ms"});this.modelLoadLatencyHistogram=this.meter.createHistogram("jaak.model.load.duration",{description:"Duration of model loading",unit:"ms"});this.detectionLatencyHistogram=this.meter.createHistogram("jaak.detection.duration",{description:"Duration of detection inference",unit:"ms"});this.imageSizeHistogram=this.meter.createHistogram("jaak.image.size",{description:"Size of captured images",unit:"bytes"});this.activeSessionsGauge=this.meter.createObservableGauge("jaak.sessions.active",{description:"Number of active capture sessions",unit:"1"});this.activeSessionsGauge.addCallback((e=>{e.observe(this.activeSessions,t)}));if("memory"in performance){this.memoryUsageGauge=this.meter.createObservableGauge("jaak.memory.usage",{description:"JavaScript heap memory usage",unit:"bytes"});this.memoryUsageGauge.addCallback((e=>{const i=performance.memory;if(i){e.observe(i.usedJSHeapSize,t)}}))}if(this.debug){console.log("[MetricsService] Business metrics initialized")}}catch(t){console.error("[MetricsService] Failed to initialize metrics:",t)}}getBaseAttributes(){const t={"service.name":this.serviceName,"service.version":this.serviceVersion,"deployment.environment":this.environment};if(this.customerId){t["customer.id"]=this.customerId}if(this.tenantId){t["tenant.id"]=this.tenantId}return t}incrementCounter(t,e=1,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"captures":this.captureCounter?.add(e,n);break;case"errors":this.errorCounter?.add(e,n);break;case"model_loads":this.modelLoadCounter?.add(e,n);break;case"user_interactions":this.userInteractionCounter?.add(e,n);break;default:if(this.meter){const i=this.meter.createCounter(`jaak.${t}.total`,{description:`Total ${t}`,unit:"1"});i.add(e,n)}}if(this.debug){console.log(`[MetricsService] Counter incremented: ${t} += ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to increment counter:",t)}}recordHistogram(t,e,i){try{const r=this.getBaseAttributes();const n={...r,...i};switch(t){case"capture_duration":this.captureLatencyHistogram?.record(e,n);break;case"model_load_duration":this.modelLoadLatencyHistogram?.record(e,n);break;case"detection_duration":this.detectionLatencyHistogram?.record(e,n);break;case"image_size":this.imageSizeHistogram?.record(e,n);break;default:if(this.meter){const i=this.meter.createHistogram(`jaak.${t}`,{description:`Distribution of ${t}`,unit:"ms"});i.record(e,n)}}if(this.debug){console.log(`[MetricsService] Histogram recorded: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to record histogram:",t)}}setGauge(t,e,i){try{this.gaugeValues.set(t,e);if(t==="active_sessions"){this.activeSessions=e}if(this.debug){console.log(`[MetricsService] Gauge set: ${t} = ${e}`,i)}}catch(t){console.error("[MetricsService] Failed to set gauge:",t)}}async measureDuration(t,e,i){const r=performance.now();try{const n=await e();const s=performance.now()-r;this.recordHistogram(t,s,i);return n}catch(e){const n=performance.now()-r;this.recordHistogram(t,n,{...i,error:true});throw e}}async flush(){try{if(this.metricReader){await this.metricReader.forceFlush()}if(this.debug){console.log("[MetricsService] Metrics flushed")}}catch(t){console.error("[MetricsService] Failed to flush metrics:",t)}}async cleanup(){try{if(this.metricReader){await this.metricReader.forceFlush();await this.metricReader.shutdown()}if(this.meterProvider){await this.meterProvider.shutdown()}if(this.debug){console.log("[MetricsService] Cleaned up successfully")}}catch(t){console.error("[MetricsService] Failed to cleanup:",t)}}recordCapture(t,e,i){this.incrementCounter("captures",1,{side:t,mode:e});this.recordHistogram("capture_duration",i,{side:t,mode:e})}recordError(t,e){this.incrementCounter("errors",1,{error_type:t,operation:e})}recordModelLoad(t,e,i){this.incrementCounter("model_loads",1,{model_type:t,cached:i});this.recordHistogram("model_load_duration",e,{model_type:t,cached:i})}recordDetection(t,e){this.recordHistogram("detection_duration",t,{detections_found:e})}recordImageSize(t,e){this.recordHistogram("image_size",e,{side:t})}updateActiveSessions(t){this.setGauge("active_sessions",t)}recordUserInteraction(t){this.incrementCounter("user_interactions",1,{interaction_type:t})}}class Zc{services=new Map;constructor(t){this.initializeServices(t)}initializeServices(t){const e=new n;const i=new s(e);const r=new o(e,t.preferredCamera);const a=new f(t.debug,t.useDocumentClassification,t.useDocumentDetector);let c=null;if(t.enableTelemetry!==false){c=new Rc({collectorUrl:t.telemetryCollectorUrl||"https://collector.jaak.ai/v1/traces",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",propagateTraceHeaderCorsUrls:t.propagateTraceHeaderCorsUrls||[],enableAutoInstrumentation:true});c.initialize()}let u=null;if(t.enableMetrics!==false){u=new Gc({collectorUrl:t.metricsCollectorUrl||"https://collector.jaak.ai/v1/metrics",serviceName:"jaak-stamps-webcomponent",serviceVersion:"2.1.0",debug:t.debug,customerId:t.customerId,tenantId:t.tenantId,environment:t.environment||"production",exportIntervalMillis:t.metricsExportIntervalMillis||6e4});u.initialize()}this.services.set("eventBus",e);this.services.set("stateManager",i);this.services.set("cameraService",r);this.services.set("detectionService",a);if(c){this.services.set("tracingService",c)}if(u){this.services.set("metricsService",u)}}get(t){const e=this.services.get(t);if(!e){throw new Error(`Service ${t} not found`)}return e}getEventBus(){return this.get("eventBus")}getStateManager(){return this.get("stateManager")}getCameraService(){return this.get("cameraService")}getDetectionService(){return this.get("detectionService")}getTracingService(){try{return this.get("tracingService")}catch{return null}}getMetricsService(){try{return this.get("metricsService")}catch{return null}}updateConfig(t){}async cleanup(){this.getDetectionService().cleanup();const t=this.getMetricsService();if(t){await t.cleanup()}const e=this.getTracingService();if(e){await e.cleanup()}this.getEventBus().clear();this.services.clear()}}class Wc{apiEndpoint="/api/v1/license/validate";baseUrl;static ENVIRONMENT_URLS={dev:"https://api.dev.jaak.ai",qa:"https://api.qa.jaak.ai",staging:"https://api.sandbox.jaak.ai",prod:"https://services.api.jaak.ai"};constructor(t="prod"){this.baseUrl=Wc.ENVIRONMENT_URLS[t]}async validateLicense(t,e,i="jaak-stamps-web"){const r=e||this.generateTraceId();const n={license:e?`L${r}`:t,origin:"web",app_id:i,product:"kyc",metadata:{sdk_version:"2.1.0"}};const s={"Content-Type":"application/json"};s["traceparent"]=`00-${r}-${this.generateSpanId()}-01`;try{const t=await fetch(`${this.baseUrl}${this.apiEndpoint}`,{method:"POST",headers:s,body:JSON.stringify(n)});if(!t.ok){const e=await t.json().catch((()=>({})));throw{error:e.error||"license_validation_failed",error_description:e.error_description||`HTTP ${t.status}: ${t.statusText}`,status_code:t.status}}const e=await t.json();return{...e,traceId:r}}catch(t){if(t.error){throw t}throw{error:"network_error",error_description:"Failed to connect to license validation service",status_code:0}}}generateTraceId(){const t=new Uint8Array(16);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}generateSpanId(){const t=new Uint8Array(8);crypto.getRandomValues(t);return Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("")}static extractTraceIdFromLicense(t){if(!t||typeof t!=="string"){return null}const e=t.startsWith("L")?t.slice(1):t;if(e.length===32&&/^[a-f0-9]{32}$/i.test(e)){return e.toLowerCase()}console.warn("[LicenseValidationService] Invalid license format for trace ID:",t);return null}}const Xc=":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background:#333;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);color:#ffffff;font-size:12px;font-weight:500;text-align:center;white-space:normal;padding:13px;max-width:300px;z-index:20;height:fit-content;width:fit-content;animation:slideInFromTopCentered 0.3s ease-out}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.back-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:320px}.back-capture-buttons{display:flex;gap:12px;align-items:center;justify-content:center;flex-wrap:wrap}.capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.capture-button:hover{background:#f8f9fa}.capture-button:active{background:#e9ecef;transform:translateY(1px)}.capture-button:disabled,.capture-button.primary-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.back-capture-section{bottom:16px;max-width:300px}.back-capture-buttons{flex-direction:column;gap:8px;width:100%}.capture-button,.back-capture-buttons .skip-button{width:100%;max-width:200px;padding:10px 20px;font-size:13px}.capture-button:disabled,.capture-button.primary-button:disabled,.skip-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.skip-explanation{background:rgba(0, 0, 0, 0.5);color:#ffffff;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:500;text-align:center;margin-bottom:12px;box-shadow:0 2px 8px rgba(0, 0, 0, 0.2);backdrop-filter:blur(12px);border:1px solid rgba(255, 255, 255, 0.1);animation:fadeIn 0.3s ease-in-out}@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.guide-text.performance-warning-text{animation:gentlePulse 2s ease-in-out infinite;background:rgba(255, 107, 107, 0.3);border:1px solid rgba(255, 107, 107, 0.5)}@keyframes gentlePulse{0%,100%{transform:translate(-50%, -50%) scale(1);background:rgba(255, 107, 107, 0.3)}50%{transform:translate(-50%, -50%) scale(1.02);background:rgba(255, 107, 107, 0.4)}}.skip-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateY(1px)}.skip-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(0, 0, 0, 0.2);border-top:2px solid #333333;border-radius:50%;animation:spin 1s linear infinite;display:inline-block;margin-right:8px;vertical-align:middle}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}@keyframes slideInFromTopCentered{0%{opacity:0;transform:translate(-50%, -50%) translateY(-8px) scale(0.95)}100%{opacity:1;transform:translate(-50%, -50%) translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:flex-start;align-items:center;gap:8px;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:0;font-weight:400;display:flex;align-items:center;gap:6px}.camera-label .autofocus-icon{font-size:12px;color:#ffffff !important;opacity:0.8;flex-shrink:0}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9;flex-shrink:0}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}.guide-text{font-size:11px;padding:4px 8px;border-radius:8px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromTop 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}.manual-capture-section{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;display:flex;flex-direction:column;align-items:center;width:100%;max-width:300px}.manual-capture-button{pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.manual-capture-button:hover{background:#f8f9fa}.manual-capture-button:active{background:#e9ecef;transform:translateY(1px)}.manual-capture-button:disabled{cursor:not-allowed !important;transform:none !important;opacity:0.7 !important;transition:none !important}@media (max-width: 480px){.manual-capture-section{bottom:16px;max-width:280px}.manual-capture-button{padding:10px 20px;font-size:13px}.manual-capture-button:disabled{opacity:0.7 !important;cursor:not-allowed !important}}.license-error-container{display:flex;align-items:center;justify-content:center;padding:40px 20px;height:100%;width:100%;background:#f5f7fa;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif}.license-error-card{background:#ffffff;border-radius:8px;box-shadow:0 2px 12px rgba(0, 0, 0, 0.1);max-width:480px;width:100%;padding:48px 32px;text-align:center}.license-error-icon{color:#dc3545;margin-bottom:24px}.license-error-title{color:#2c3e50;font-size:24px;font-weight:600;margin:0 0 16px 0}.license-error-message{color:#495057;font-size:16px;line-height:1.6;margin:0 0 24px 0}.license-error-help{color:#6c757d;font-size:14px;margin:0 0 32px 0}.license-error-help a{color:#007bff;text-decoration:none;font-weight:500}.license-error-help a:hover{text-decoration:underline}.license-error-footer{color:#adb5bd;font-size:12px;font-weight:500;padding-top:24px;border-top:1px solid #e9ecef}@media (max-width: 640px){.license-error-card{padding:32px 24px}.license-error-title{font-size:20px}.license-error-message{font-size:14px}}";const Yc=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady");this.traceIdGenerated=e(this,"traceIdGenerated")}get el(){return i(this)}debug=false;alignmentTolerance=15;maskSize=90;cropMargin=20;useDocumentClassification=false;useDocumentDetector=true;preferredCamera="auto";captureDelay=1500;enableBackDocumentTimer=false;backDocumentTimerDuration=20;telemetryCollectorUrl="https://collector.jaak.ai/v1/traces";metricsCollectorUrl="https://collector.jaak.ai/v1/metrics";enableTelemetry=true;enableMetrics=true;customerId;tenantId;environment="production";propagateTraceHeaderCorsUrls;metricsExportIntervalMillis=6e4;license;licenseEnvironment="prod";traceId;appId="jaak-stamps-web";captureCompleted;isReady;traceIdGenerated;detectionBoxes=[];sideAlignment={top:false,right:false,bottom:false,left:false};isMaskReady=false;shouldMirrorVideo=true;showCameraSelector=false;isSwitchingCamera=false;hasDocumentDetected=false;cameraInfoWithAutofocus={availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null};currentStatus={message:"Preparando capturador...",description:"Configurando herramientas de captura",type:"initializing",isInitialized:false};performanceData={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0};backDocumentTimerRemaining=0;showManualCaptureButton=false;performanceDegradedMode=false;showPerformanceMessage=false;captureStateVersion=0;processingButton=null;licenseValid=true;licenseError=null;licenseValidationService=null;serviceContainer;eventBus;stateManager;cameraService;detectionService;tracingService;metricsService;videoRef;detectionContainer;videoStream;animationId;lastDetectedBox;startTime;hasScreenshotTaken=false;alignmentStartTime;alignmentTimer;backDocumentTimer;orientationTimer;performanceMetrics={fps:0,inferenceTime:0,memoryUsage:0,onnxLoadTime:0,frameProcessingTime:0,totalDetections:0,successfulDetections:0,detectionRate:0,lastUpdateTime:0};performanceUpdateInterval;frameSkipCounter=0;BASE_FRAME_SKIP=2;MAX_FRAME_SKIP=8;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;performanceHistory=[];PERFORMANCE_HISTORY_SIZE=10;PERFORMANCE_THRESHOLD_MS=2e3;SLOW_FRAMES_TO_TRIGGER=2;slowFrameCount=0;processedFramesCount=0;hasAutoSwitchedToManual=false;canvasPool=[];MAX_CANVAS_POOL_SIZE=3;async componentWillLoad(){await new Promise((t=>setTimeout(t,50)));this.updateStatus("Validando licencia...","Verificando autorización de uso","initializing");await this.validateLicense();if(!this.licenseValid){return}}async componentDidLoad(){try{if(!this.licenseValid){return}this.updateStatus("Preparando capturador...","Configurando herramientas de captura","initializing");await this.initializeServices();this.updateStatus("Preparando funciones...","Configurando herramientas de trabajo","initializing");await this.setupEventListeners();this.updateStatus("Configurando cámara...","Detectando dispositivos disponibles","initializing");await this.initializeComponent();if(this.debug){this.initializePerformanceMonitor()}}catch(t){this.updateStatus("Error de inicialización",t.message,"error")}}async initializeServices(){const t=this.propagateTraceHeaderCorsUrls?this.propagateTraceHeaderCorsUrls.split(",").map((t=>t.trim())):[];const e={debug:this.debug,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,cropMargin:this.cropMargin,useDocumentClassification:this.useDocumentClassification,useDocumentDetector:this.useDocumentDetector,preferredCamera:this.preferredCamera,captureDelay:this.captureDelay,telemetryCollectorUrl:this.telemetryCollectorUrl,metricsCollectorUrl:this.metricsCollectorUrl,enableTelemetry:this.enableTelemetry,enableMetrics:this.enableMetrics,customerId:this.customerId,tenantId:this.tenantId,environment:this.environment,propagateTraceHeaderCorsUrls:t,metricsExportIntervalMillis:this.metricsExportIntervalMillis};this.serviceContainer=new Zc(e);this.eventBus=this.serviceContainer.getEventBus();this.stateManager=this.serviceContainer.getStateManager();this.cameraService=this.serviceContainer.getCameraService();this.detectionService=this.serviceContainer.getDetectionService();this.tracingService=this.serviceContainer.getTracingService();this.metricsService=this.serviceContainer.getMetricsService();if(this.tracingService&&this.traceId){this.tracingService.setSessionTraceId(this.traceId)}if(this.tracingService){const t=this.tracingService.startSpan("component.initialize",{"component.debug":this.debug,"component.useDocumentDetector":this.useDocumentDetector,"component.useDocumentClassification":this.useDocumentClassification});this.tracingService.endSpan(t)}}async validateLicense(){if(!this.license){console.error("❌ No license provided for JAAK Stamps component");this.licenseError='Este componente requiere una licencia válida. Por favor, proporcione una licencia usando el atributo "license".';this.licenseValid=false;this.updateStatus("Error de licencia","Licencia no proporcionada","error");return}try{console.log("🔑 Validating license for JAAK Stamps...");this.licenseValidationService=new Wc(this.licenseEnvironment);const t=await this.licenseValidationService.validateLicense(this.license,this.traceId,this.appId);if(t&&t.access_token){this.licenseValid=true;this.licenseError=null;console.log("✅ License validated successfully for JAAK Stamps");if(t.traceId){this.traceIdGenerated.emit({traceId:t.traceId});console.log("📋 TraceId:",t.traceId)}}else{this.licenseValid=false;this.licenseError="La licencia proporcionada no es válida. Por favor, verifique su licencia e intente nuevamente.";this.updateStatus("Error de licencia","Licencia inválida","error");console.error("❌ Invalid license for JAAK Stamps")}}catch(t){this.licenseValid=false;const e=t;this.licenseError=e.error_description||"Error al validar la licencia. Por favor, verifique su conexión e intente nuevamente.";this.updateStatus("Error de licencia","Fallo en la validación","error");console.error("❌ License validation failed for JAAK Stamps:",t)}}async setupEventListeners(){this.eventBus.on("state-changed",(()=>{this.handleStateChange()}))}async initializeComponent(){this.validateProps();if(this.debug){this.stateManager.updateCaptureState({isLoading:true});await new Promise((t=>setTimeout(t,500)))}this.updateStatus("Detectando cámaras...","Buscando dispositivos de captura","initializing");await this.cameraService.detectDeviceType();await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","initializing");await this.loadOnnxRuntime();this.initializeResizeObserver()}validateProps(){if(this.maskSize<50||this.maskSize>100){this.maskSize=90}if(this.cropMargin<0||this.cropMargin>100){this.cropMargin=0}const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){this.preferredCamera="auto"}if(this.captureDelay<0||this.captureDelay>1e4){this.captureDelay=1500}}async loadOnnxRuntime(){if(!window.ort){this.updateStatus("Preparando herramientas...","Configurando funciones de captura","initializing");const t=document.createElement("script");t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.0/dist/ort.min.js";document.head.appendChild(t);await new Promise((e=>{t.onload=()=>{setTimeout((async()=>{await this.finalizeInitialization();e(undefined)}),300)}}))}else{setTimeout((async()=>{await this.finalizeInitialization()}),300)}}async finalizeInitialization(){this.stateManager.updateCaptureState({isLoading:false});const t=await this.checkCameraPermissions();if(t){this.currentStatus={message:"Listo para capturar",description:"",type:"ready",isInitialized:true}}else{this.currentStatus={message:"Permisos de cámara requeridos",description:"Por favor, otorgue permisos de cámara para continuar",type:"error",isInitialized:true}}this.emitReadyEvent()}updateStatus(t,e,i="loading"){this.currentStatus={message:t,description:e,type:i,isInitialized:this.currentStatus.isInitialized}}emitReadyEvent(){const t=!!window.ort&&this.detectionService.isModelLoaded();this.isReady.emit(t)}async checkCameraPermissions(){try{if(!navigator.permissions){try{const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()));return true}catch{return false}}const t=await navigator.permissions.query({name:"camera"});return t.state==="granted"}catch(t){return false}}handleStateChange(){}initializeResizeObserver(){if("ResizeObserver"in window&&this.detectionContainer){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.detectionContainer.parentElement)}window.addEventListener("orientationchange",(()=>{if(this.orientationTimer){clearTimeout(this.orientationTimer)}this.orientationTimer=window.setTimeout((()=>{this.handleResize();this.orientationTimer=undefined}),300)}))}handleResize(){if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}}triggerRerender(){this.captureStateVersion=this.captureStateVersion+1}getGuideText(t){if(t==="completed"){return"Proceso completado"}if(this.showPerformanceMessage&&t==="front"){return"Modo manual activado por rendimiento. Use el botón para capturar."}if(t==="front"){if(this.showManualCaptureButton){return"Posicione el frente de su documento en el marco y presione el botón para capturar"}return"Alinee su identificación con el marco"}else if(t==="back"){if(this.useDocumentDetector){return"Si tu documento no tiene lado trasero, da clic en el botón para continuar con el proceso"}else{return"Posicione el reverso de su documento en el marco y capture, o salte este paso"}}return"Alinee su identificación con el marco"}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const r=e/i;const n=t.width/t.height;let s,o;let a=0,c=0;if(r>n){s=t.width;o=t.width/r;c=(t.height-o)/2}else{o=t.height;s=t.height*r;a=(t.width-s)/2}const u=85.6/53.98;const f=o*u;let l,h;const d=this.maskSize/100;if(f<=s){h=o*d;l=h*u}else{l=s*d;h=l/u}const p=l/t.width*100;const m=h/t.height*100;const b=a+s/2;const v=c+o/2;const w=b/t.width*100;const g=v/t.height*100;this.el.style.setProperty("--mask-width",`${p}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${w}%`);this.el.style.setProperty("--mask-center-y",`${g}%`);this.isMaskReady=true}isComponentReady(){if(!this.currentStatus.isInitialized){return{ready:false,message:"El componente aún se está inicializando",status:"initializing"}}if(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing"){return{ready:false,message:"El componente está cargando recursos",status:"loading"}}if(!this.serviceContainer||!this.stateManager||!this.cameraService||!this.detectionService){return{ready:false,message:"Los servicios del componente no están disponibles",status:"error"}}return{ready:true}}async getCapturedImages(){const t=this.isComponentReady();if(!t.ready){throw new Error(t.message)}const e=this.stateManager.getCaptureState();if(e.step!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return this.stateManager.getCapturedImages()}async isProcessCompleted(){const t=this.isComponentReady();if(!t.ready){return false}return this.stateManager.isProcessCompleted()}async startCapture(){const t=this.tracingService?.startSpan("capture.start");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.setSpanAttribute(t,"error.message",e.message);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}try{await this.startDetection();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true}}catch(e){this.updateStatus("Error al iniciar captura",e.message,"error");if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async stopCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.exitSession();return{success:true}}catch(t){return{success:false,error:t.message}}}async resetCapture(){const t=this.isComponentReady();if(!t.ready){return{success:false,error:t.message}}try{this.resetDetection();return{success:true}}catch(t){return{success:false,error:t.message}}}async skipBackCapture(){console.log("🟡 Botón clicked: Saltar reverso");this.processingButton="skip-back";await new Promise((t=>setTimeout(t,100)));const t=this.isComponentReady();if(!t.ready){this.processingButton=null;return{success:false,error:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();if(t.step==="back"&&e.front.fullFrame){this.completeProcess(true);return{success:true}}else{return{success:false,error:"No se puede saltar el reverso en el estado actual"}}}catch(t){return{success:false,error:t.message}}finally{this.processingButton=null}}async getStatus(){const t=this.isComponentReady();if(!t.ready){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:t.status,componentMessage:t.message}}try{const t=this.stateManager.getCaptureState();const e=this.stateManager.getCapturedImages();return{isVideoActive:t.isVideoActive,captureStep:t.step,hasImages:!!(e.front.fullFrame||e.back.fullFrame),isProcessCompleted:this.stateManager.isProcessCompleted(),isModelPreloaded:this.detectionService.isModelLoaded(),componentStatus:"ready"}}catch(t){return{isVideoActive:false,captureStep:"front",hasImages:false,isProcessCompleted:false,isModelPreloaded:false,componentStatus:"error",componentMessage:t.message}}}async preloadModel(){const t=this.tracingService?.startSpan("model.preload");const e=this.isComponentReady();if(!e.ready){this.updateStatus(e.message,"Espere a que termine la inicialización",e.status);if(t){this.tracingService?.setSpanAttribute(t,"error",true);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}if(this.detectionService.isModelLoaded()){this.updateStatus("Reconocimiento listo","","ready");if(t){this.tracingService?.setSpanAttribute(t,"cached",true);this.tracingService?.endSpan(t)}return{success:true,message:"Model already loaded"}}try{const e=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:true})}try{const t=performance.now();const e=this.tracingService?.startSpan("model.detection.load");await this.detectionService.loadModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("detection",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","detection");this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{const t=performance.now();const e=this.tracingService?.startSpan("model.classification.load");await this.detectionService.loadClassificationModel();if(e)this.tracingService?.endSpan(e);const i=performance.now()-t;this.metricsService?.recordModelLoad("classification",i,false)}catch(t){this.metricsService?.recordError("model_load_failed","classification");this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}const i=performance.now();const r=i-e;if(this.debug){this.recordOnnxPerformance(r,0)}if(t){this.tracingService?.setSpanAttribute(t,"loadTime",r)}this.updateStatus("Finalizando configuración...","Preparando herramientas para captura","loading");await new Promise((t=>setTimeout(t,300)));this.updateStatus("Reconocimiento preparado","","ready");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}this.emitReadyEvent();if(t){this.tracingService?.setSpanAttribute(t,"success",true);this.tracingService?.endSpan(t)}return{success:true,message:"Models preloaded successfully"}}catch(e){this.updateStatus("Error de configuración","No se pudieron preparar las herramientas necesarias","error");if(this.stateManager){this.stateManager.updateCaptureState({isLoading:false})}if(t){this.tracingService?.recordException(t,e);this.tracingService?.endSpan(t)}return{success:false,error:e.message}}}async getCameraInfo(){const t=this.isComponentReady();if(!t.ready){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}try{return await this.cameraService.getCameraInfo()}catch(t){return{availableCameras:[],selectedCameraId:null,deviceType:"desktop",isMultipleCamerasAvailable:false,preferredFacing:null,error:t.message}}}async setPreferredCamera(t){const e=this.isComponentReady();if(!e.ready){return{success:false,error:e.message,selectedCamera:null,availableCameras:0}}try{this.preferredCamera=t;this.serviceContainer.updateConfig({preferredCamera:t});await this.cameraService.enumerateDevices();await this.updateCameraInfoWithAutofocus();const e=this.stateManager.getCaptureState();if(e.isVideoActive){const t=this.cameraService.getSelectedCameraId();if(t){await this.cameraService.switchCamera(t)}}return{success:true,selectedCamera:this.cameraService.getSelectedCameraId(),availableCameras:this.cameraService.getAvailableCameras().length}}catch(t){return{success:false,error:t.message,selectedCamera:null,availableCameras:0}}}async setCaptureDelay(t){if(t<0||t>1e4){return{success:false,error:"Capture delay must be between 0 and 10000 milliseconds",captureDelay:this.captureDelay}}this.captureDelay=t;if(this.serviceContainer){this.serviceContainer.updateConfig({captureDelay:t})}return{success:true,captureDelay:this.captureDelay}}async getCaptureDelay(){return this.captureDelay}checkDeviceCapabilities(){const t=navigator.deviceMemory;return{canUseML:true,reason:"Dispositivo compatible con detección automática.",memoryMB:t?t*1024:null}}async startDetection(){try{const t=this.checkDeviceCapabilities();if(!t.canUseML&&this.useDocumentDetector){this.switchToManualModeWithWarning(t.reason);return}if(!this.detectionService.isModelLoaded()){const t=performance.now();this.updateStatus("Preparando reconocimiento...","Configurando detección de documentos","loading");this.stateManager.updateCaptureState({isLoading:true});try{await this.detectionService.loadModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para detección automática ${t}. Modo manual activado - funciona igual de bien!`);return}else{this.switchToManualModeWithError("Error al cargar modelo de detección");throw t}}this.updateStatus("Optimizando detección...","Configurando reconocimiento de documentos","loading");try{await this.detectionService.loadClassificationModel()}catch(t){if(t.message.includes("Out of memory")||t.message.includes("no available backend")){const t=navigator.deviceMemory?`(${navigator.deviceMemory}GB disponible)`:"";this.switchToManualModeWithWarning(`Memoria insuficiente para clasificación automática ${t}. Modo manual activado para optimizar rendimiento.`);return}else{this.switchToManualModeWithError("Error al cargar modelo de clasificación");throw t}}const e=performance.now();const i=e-t;if(this.debug){this.recordOnnxPerformance(i,0)}}this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let e;try{e=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}if(this.useDocumentDetector){this.updateStatus("Analizando estabilidad...","Evaluando rendimiento del sistema","loading")}else{this.updateStatus("Captura activa","Posicione su documento y use el botón para capturar","active")}try{await this.initializeVideoStream(e)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});if(!this.useDocumentDetector){this.showManualCaptureButton=true}this.detectFrame()}catch(t){this.updateStatus("Error al iniciar","No se pudo preparar la captura","error");this.stateManager.updateCaptureState({isLoading:false})}}async initializeVideoStream(t){if(this.videoRef){this.videoRef.srcObject=t;this.videoStream=t;const e=this.cameraService.isRearCamera(t);this.shouldMirrorVideo=!e;return new Promise((t=>{this.videoRef.onloadedmetadata=async()=>{await this.videoRef.play();this.stateManager.updateCaptureState({isVideoActive:true});if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}t()}}))}else{throw new Error("Video element not available")}}async detectFrame(){try{const t=performance.now();const e=this.stateManager.getCaptureState();if(!this.videoRef||!this.detectionContainer||!this.detectionService.isModelLoaded())return;if(!this.useDocumentDetector||this.performanceDegradedMode){this.showManualCaptureButton=true;if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}else if(!this.performanceDegradedMode){this.showManualCaptureButton=false}if(e.isDetectionPaused){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;const i=this.getAdaptiveFrameSkip();if(this.frameSkipCounter<=i){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const r=Date.now();if(r-this.lastInferenceTime<this.MIN_INFERENCE_INTERVAL){if(e.step!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=r;const n=performance.now();let s;let o;let a;try{s=this.detectionService.preprocess(this.videoRef)}catch(t){this.switchToManualModeWithError("Error al procesar imagen");return}try{o=await this.detectionService.runInference(s);a=performance.now()-n}catch(t){this.switchToManualModeWithError("Error en detección automática");return}this.processedFramesCount++;if(this.debug){this.recordOnnxPerformance(0,a)}if(this.startTime&&Date.now()-this.startTime<5e3){o.forEach((t=>{const i=this.detectionService.isCardInFrame(t);const r=i?t.score*1.2:t.score;if(r>e.bestScore){this.stateManager.updateCaptureState({bestScore:r})}}))}const c=this.hasDocumentDetected;this.hasDocumentDetected=o.length>0;if(!c&&this.hasDocumentDetected&&e.step==="back"&&this.enableBackDocumentTimer){this.startBackDocumentTimer()}if(o.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}if(this.debug){this.updateDetectionBoxes(o)}else{this.detectionBoxes=[]}this.updateMaskColor(o);const u=performance.now();const f=u-t;if(this.useDocumentDetector&&!this.hasAutoSwitchedToManual){if(f>=this.PERFORMANCE_THRESHOLD_MS){this.slowFrameCount++;if(this.slowFrameCount>=this.SLOW_FRAMES_TO_TRIGGER){this.switchToManualMode()}}else{if(this.slowFrameCount>0){this.slowFrameCount=0}}if(this.processedFramesCount===2){this.updateStatus("Captura activa","Buscando documento en el marco de captura","active")}}if(this.debug){this.recordFrameProcessing(f,o.length)}if(e.step!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){const e=this.stateManager.getCaptureState();if(e.step!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}disconnectedCallback(){this.cleanup()}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(this.orientationTimer){clearTimeout(this.orientationTimer);this.orientationTimer=undefined}this.releaseOnnxResources();if(this.performanceUpdateInterval){clearInterval(this.performanceUpdateInterval);this.performanceUpdateInterval=undefined}this.canvasPool=[];this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.serviceContainer?.cleanup()}render(){const t=this.stateManager?.getCaptureState()||{isVideoActive:false,showFlipAnimation:false,showSuccessAnimation:false,step:"front",isCapturing:false};const e=this.cameraInfoWithAutofocus;return r("div",{key:"a52b452a7aef6574a5e4b74a88c7bd3f9d45fd15",class:"detector-container"},!this.licenseValid&&this.licenseError&&r("div",{key:"18a99579e0b74ceb2cf1c4c3e21a864d2ec7d944",class:"license-error-container"},r("div",{key:"3431722f4f47824c172a5b6f3a2ad9bd3bf377f2",class:"license-error-card"},r("svg",{key:"bf3854de3ba865a58c5c91cfd7a85d3d725be0df",class:"license-error-icon",width:"64",height:"64",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r("path",{key:"209e3a2a22333ec90e102a7156eb644b529f47c7",d:"M12 22C12 22 20 18 20 12V5L12 2L4 5V12C4 18 12 22 12 22Z",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),r("path",{key:"7b0dc1cd29a9055e552885b23f4537c19932556d",d:"M12 8V12",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"}),r("circle",{key:"8ea686ebfb31a5744303f313fd104c03c02a5472",cx:"12",cy:"16",r:"0.5",fill:"currentColor",stroke:"currentColor","stroke-width":"1"})),r("h2",{key:"7e0ec3ec23b80176cbec9c706999746d62486f3c",class:"license-error-title"},"Licencia Requerida"),r("p",{key:"261a91e2c20feb09319dc4f319fb79611cc36a46",class:"license-error-message"},this.licenseError),r("p",{key:"2e3cc8da0f4a8ebfd52db469b0f0900514d1d7f8",class:"license-error-help"},"Contacte a soporte: ",r("a",{key:"283eea87e2f69dce1ea7376e3a63fed780633499",href:"mailto:support@jaak.ai"},"support@jaak.ai")),r("div",{key:"b4227ed25a4fb4d953c753671d27ac8c931a435f",class:"license-error-footer"},"JAAK Stamps"))),this.licenseValid&&r("div",{key:"cb33431cf6992f6e7466273406f729c42c1cbcdb",class:"video-container"},r("video",{key:"b44befd61ad616fd36fe1e98fd089a2443bc65b6",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:t.isVideoActive?"block":"none"}}),r("div",{key:"8cee95ddab5f771a87d43fa434a3ba0c241d2f3e",ref:t=>this.detectionContainer=t,class:`detection-overlay ${this.shouldMirrorVideo?"mirror":""}`},this.debug&&this.detectionBoxes.map(((t,e)=>r("div",{key:e,class:"detection-box",style:{position:"absolute",left:`${t.x}px`,top:`${t.y}px`,width:`${t.w}px`,height:`${t.h}px`,border:"2px solid #32406C",pointerEvents:"none",boxSizing:"border-box"}})))),this.isMaskReady&&r("div",{key:"00a749ad234294695d9a292911b41fdacafd219a",class:"overlay-mask"},r("div",{key:"e344df8a709fca5225985ccc9f8def75ddbd393c",class:"card-outline"},r("div",{key:"2dcae9e414f2b7131397d49a3d5ecabfc7cd5eb8",class:"side side-top"}),r("div",{key:"48ac3f06fa4a2c83741df378719911f682811caa",class:"side side-right"}),r("div",{key:"238a3269b2a12d528e8a1889d3109ee319c7fd88",class:"side side-bottom"}),r("div",{key:"b02eec6c102d7e9fb03ef24dfce7c75e081ff1c4",class:"side side-left"})),!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"15588129ca8027a6ec1c81d70001142986966826",class:`guide-text ${this.showPerformanceMessage?"performance-warning-text":""}`},this.getGuideText(t.step)),t.step==="back"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"f15fd9bddc20c54afcca7be79c3cf2f9ee2b74f7",class:"back-capture-section"},r("div",{key:"e3284e1301840a9555857fa879de9f4ca91dc21b",class:"back-capture-buttons"},(!this.useDocumentDetector||this.performanceDegradedMode||this.showManualCaptureButton)&&r("button",{key:"8508d13e117deb3b223308497b1db976643b86f2",class:"capture-button primary-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-back"&&r("span",{key:"99bd464541d9ee8589bc11e937c5ad6bca9d95c8",class:"button-spinner"}),"Capturar Reverso"),r("button",{key:"3de5f0a142f9dfdfe4578c0fcbe004bb5fe94c56",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button",disabled:this.processingButton!==null},this.processingButton==="skip-back"&&r("span",{key:"268ce949bf5155b3729298f23eea0d7ec15b3590",class:"button-spinner"}),this.enableBackDocumentTimer&&this.backDocumentTimerRemaining>0?`Saltar reverso (${this.backDocumentTimerRemaining}s)`:"Saltar reverso"))),t.isVideoActive&&r("div",{key:"bb5c00ad882c303d8a2b6ddc79c9d5b27ff9824e",class:"camera-controls"},r("button",{key:"7d231b550b58a8336f125a1a7fe7235c8bb3d7dd",class:`camera-selector-button ${this.isSwitchingCamera?"loading":""}`,onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara",disabled:this.isSwitchingCamera},this.isSwitchingCamera?r("div",{class:"button-spinner"}):"Cámaras")),this.showCameraSelector&&e.availableCameras.length>0&&r("div",{key:"95d1e0d0937f7ef821ff3ad167cd42e25fd1c87f",class:"camera-selector-dropdown"},r("div",{key:"e42219e5895c82f40c559c27c4f80f3145fc0a0e",class:"camera-selector-header"},r("span",{key:"544a6fb2e08211ab6c44b0bfb281124bee318fae"},"Seleccionar Cámara"),r("button",{key:"7c4a71243278491ee7dbcc7ab2564bc7e92f5da3",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),r("div",{key:"c9d24e0bd906d20370214fdfd24ae91abfda98e1",class:"camera-list"},e.availableCameras.map((t=>r("button",{key:t.id,class:`camera-option ${e.selectedCameraId===t.id?"selected":""}`,onClick:()=>this.handleCameraSwitch(t.id),type:"button"},r("span",{class:"camera-label"},t.label||`Cámara ${e.availableCameras.indexOf(t)+1}`,t.hasAutofocus&&r("span",{class:"autofocus-icon",title:"Autofoco disponible"},"⦿")),e.selectedCameraId===t.id&&r("span",{class:"selected-indicator"},"✓"))))),r("div",{key:"8c2e1d2ed02bc55c84f3f726e5be577686d0f32d",class:"device-info"},r("small",{key:"142410a86e4f819b96ffc9573816994351588a3e"},"Dispositivo: ",e.deviceType))),this.showManualCaptureButton&&t.step==="front"&&!t.showFlipAnimation&&!t.showSuccessAnimation&&r("div",{key:"48c33b2d6c8c80d18fba6e5f454faaa24c28fbd9",class:"manual-capture-section"},r("button",{key:"e3d5bfe9ef8b8f16bf669b66bce4e7a500113798",class:"manual-capture-button",onClick:()=>this.takeManualScreenshot(),type:"button",disabled:this.processingButton!==null},this.processingButton==="capture-front"&&r("span",{key:"f50640fe4308c765011e6ed175528920228df5e7",class:"button-spinner"}),"Capturar Frente"))),t.isCapturing&&r("div",{key:"080ab315293fa1fe5b1d97aa2511a2ffe2b013f4",class:"capture-animation"}),t.showFlipAnimation&&r("div",{key:"b062c546af50b799bb1fb7dda07b3ffa601c4bac",class:"flip-animation"},r("div",{key:"f7162dc31673c7db1d8e03a658a722a3d323b28e",class:"id-card-icon"}),r("div",{key:"d950952b480342d80d37df5c48031d72be4ac01a",class:"flip-text"},"¡Voltea tu identificación!")),t.showSuccessAnimation&&r("div",{key:"bd576fd28065aa712e42636c5fd0e3566d26cc25",class:"success-animation"},r("div",{key:"6ca5c24510df790bd1c955c5e2936909c4767560",class:"check-icon"}),r("div",{key:"3420164eacddbe1a9aa0a181528ba0be7683af56",class:"success-text"},"¡Proceso completado!")),r("div",{key:"8ec2b295b233e7bb8ab0cc1c183adedd4e3c7e04",class:`component-status status-${this.currentStatus.type}`},(this.currentStatus.type==="loading"||this.currentStatus.type==="initializing")&&r("div",{key:"97c8e7e6219984673ebc631da111c17bf72a83cb",class:"status-spinner"}),r("div",{key:"7ca06c48f295892ff77eceff6245891ef7d9dd5e",class:"status-content"},r("div",{key:"08056c7ec8fd66d23e0b6714c08aeccc092cf46a",class:"status-message"},this.currentStatus.message),this.currentStatus.description&&r("div",{key:"1e32ca14de53cc2f105822ed5a58e691918b307b",class:"status-description"},this.currentStatus.description))),this.debug&&r("div",{key:"c25022d9aadd37ead9ae7d1cf7c7d916cdeb9cc1",class:"performance-monitor"},r("div",{key:"f0f99c7e820532432ba64726ef0c2aeabeb3309f",class:"performance-expanded"},r("div",{key:"e839e90c9cb0f33068ac3311e41914aa52610149",class:"metrics-row"},r("div",{key:"9f74f4877a048e63f542f2df54f569f79d6f8bd0",class:"metric-compact"},r("span",{key:"21ec7255706d6fb2cfec035c4be92295ee0216b6",class:"metric-label"},"FPS"),r("span",{key:"c8be17f3dc752304bf6b7fd9746f11783f7ff6ca",class:`metric-value ${this.performanceData.fps<15?"warning":this.performanceData.fps<10?"danger":"good"}`},this.performanceData.fps)),r("div",{key:"79187257ea30ead7fb41534a94272a3a855e050b",class:"metric-compact"},r("span",{key:"cc53dc282c1fe4234217207c2085fa2be06a5458",class:"metric-label"},"MEM"),r("span",{key:"032002ff63b3a2349b34833668fed8d6337e2063",class:`metric-value ${this.performanceData.memoryUsage>100?"warning":this.performanceData.memoryUsage>200?"danger":"good"}`},this.performanceData.memoryUsage,"MB"))),r("div",{key:"e628febd5bbfb9f593e029b10827635ddd0344fb",class:"metrics-row"},r("div",{key:"b2fe558bab709ff6b6781648b13ebc66238f3298",class:"metric-compact"},r("span",{key:"d7d816aff11503657781f8ebe9cb5f0f07c7279e",class:"metric-label"},"INF"),r("span",{key:"3d735d092b5b39d0e96f4ac59b3bf2acde739fab",class:`metric-value ${this.performanceData.inferenceTime>100?"warning":this.performanceData.inferenceTime>200?"danger":"good"}`},this.performanceData.inferenceTime,"ms")),r("div",{key:"9a83fd4fe43e8a3760aaea1f134c3101b8757681",class:"metric-compact"},r("span",{key:"8136ab82b50230537f19cd58ed2da0956d291287",class:"metric-label"},"FRAME"),r("span",{key:"6221cc10edff8c4b0e4034a3734deb548416a3e6",class:`metric-value ${this.performanceData.frameProcessingTime>50?"warning":this.performanceData.frameProcessingTime>100?"danger":"good"}`},this.performanceData.frameProcessingTime,"ms"))),r("div",{key:"a31bad44d5c2c5fd5417ed82589c0f103bba1d32",class:"metrics-row"},r("div",{key:"1441d11e0d83b3b44dfa963e415c3074691eb4f2",class:"metric-compact"},r("span",{key:"9fe5643129aa7a842f75644b6f71b1ff80993f1b",class:"metric-label"},"DET"),r("span",{key:"0604065a3867e71a745bfb4e804c7e96048cb70e",class:"metric-value good"},this.performanceData.successfulDetections,"/",this.performanceData.totalDetections)),r("div",{key:"daff0fede819f2b59a4ddb83560dc53f6151c2c9",class:"metric-compact"},r("span",{key:"75a55c4a4e36b98af3620866ec6f7842b9ef81f7",class:"metric-label"},"RATE"),r("span",{key:"61776c3fd4c3200d5e18cc28d917c538b282625a",class:`metric-value ${this.performanceData.detectionRate<30?"danger":this.performanceData.detectionRate<60?"warning":"good"}`},this.performanceData.detectionRate,"%"))))),r("div",{key:"4092c684ee3a148ec40e266fd16a718f2c2f2f52",class:"watermark"},r("img",{key:"d7bae6157d22675f8b71dbf1afdf345374398c82",src:"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}updateDetectionBoxes(t){if(!this.videoRef||!this.detectionContainer)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;const r=this.detectionContainer.parentElement;const n=r.getBoundingClientRect();const s=n.width;const o=n.height;if(e===0||i===0)return;const a=e/i;const c=s/o;let u,f;let l=0,h=0;if(a>c){u=s;f=s/a;h=(o-f)/2}else{f=o;u=o*a;l=(s-u)/2}const d=320;const p=u/d;const m=f/d;this.detectionBoxes=t.map((t=>({x:t.x*p+l,y:t.y*m+h,w:t.w*p,h:t.h*m,score:t.score})))}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const r=this.el.shadowRoot?.querySelector(".side-top");const n=this.el.shadowRoot?.querySelector(".side-right");const s=this.el.shadowRoot?.querySelector(".side-bottom");const o=this.el.shadowRoot?.querySelector(".side-left");let a=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){a=t.reduce(((t,e)=>e.score>t.score?e:t));const e={INPUT_SIZE:320,ID1_ASPECT_RATIO:85.6/53.98,shouldMirrorVideo:this.shouldMirrorVideo,alignmentTolerance:this.alignmentTolerance,maskSize:this.maskSize,videoRef:this.videoRef};c=this.detectionService.checkSideAlignment(a,e);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}r?.classList.toggle("aligned",c.top);n?.classList.toggle("aligned",c.right);s?.classList.toggle("aligned",c.bottom);o?.classList.toggle("aligned",c.left);const u=this.detectionService.areAllSidesAligned(c);const f=this.stateManager.getCaptureState();if(f.step==="back"&&this.enableBackDocumentTimer&&a){const t=c.top||c.right||c.bottom||c.left;if(t){this.startBackDocumentTimer()}}if(u&&a){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){const t=Date.now();if(!this.alignmentStartTime){this.alignmentStartTime=t}const e=t-this.alignmentStartTime;if(e>=this.captureDelay){this.lastDetectedBox=a;this.takeScreenshot().catch((()=>{}));this.hasScreenshotTaken=true;this.alignmentStartTime=undefined;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")));if(this.alignmentStartTime){this.alignmentStartTime=undefined}if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}}}async takeManualScreenshot(){console.log("🔵 Botón clicked: Capturar (Frente/Reverso)");const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.manual");const i=this.stateManager?.getCaptureState();const r=i?.step==="front"?"front":"back";if(i?.step==="front"){this.processingButton="capture-front";if(e)this.tracingService?.setSpanAttribute(e,"side","front")}else if(i?.step==="back"){this.processingButton="capture-back";if(e)this.tracingService?.setSpanAttribute(e,"side","back")}this.metricsService?.recordUserInteraction("manual_capture_button");console.log("🔵 processingButton set to:",this.processingButton);await new Promise((t=>setTimeout(t,100)));if(!this.videoRef){this.processingButton=null;if(e){this.tracingService?.setSpanAttribute(e,"error","no_video_ref");this.tracingService?.endSpan(e)}return}await this.takeScreenshotWithMaskCoordinates();const n=performance.now()-t;this.metricsService?.recordCapture(r,"manual",n);if(e){this.tracingService?.setSpanAttribute(e,"success",true);this.tracingService?.endSpan(e)}}async takeScreenshotWithMaskCoordinates(){if(!this.videoRef||!this.detectionContainer)return;this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const t=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const e=t.getContext("2d",{alpha:false});e.clearRect(0,0,t.width,t.height);e.drawImage(this.videoRef,0,0,t.width,t.height);const i=this.detectionContainer.parentElement;const r=i.getBoundingClientRect();const n=parseFloat(this.el.style.getPropertyValue("--mask-width").replace("%",""))||90;const s=parseFloat(this.el.style.getPropertyValue("--mask-height").replace("%",""))||56.25;const o=parseFloat(this.el.style.getPropertyValue("--mask-center-x").replace("%",""))||50;const a=parseFloat(this.el.style.getPropertyValue("--mask-center-y").replace("%",""))||50;const c=this.videoRef.videoWidth;const u=this.videoRef.videoHeight;const f=c/u;const l=r.width/r.height;let h,d;let p=0,m=0;if(f>l){h=r.width;d=r.width/f;m=(r.height-d)/2}else{d=r.height;h=r.height*f;p=(r.width-h)/2}const b=n/100*r.width;const v=s/100*r.height;const w=o/100*r.width;const g=a/100*r.height;const y=c/h;const x=u/d;const k=(w-p)*y;const S=(g-m)*x;const _=b*y;const T=v*x;const E=Math.max(0,k-_/2-this.cropMargin);const C=Math.max(0,S-T/2-this.cropMargin);const M=Math.min(_+2*this.cropMargin,c-E);const A=Math.min(T+2*this.cropMargin,u-C);const P=this.getPooledCanvas(M,A);const I=P.getContext("2d",{alpha:false});I.clearRect(0,0,P.width,P.height);I.drawImage(this.videoRef,E,C,M,A,0,0,M,A);const O=this.stateManager.getCaptureState();if(O.step==="front"){this.stateManager.setCapturedImages({front:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});if(this.useDocumentClassification){try{const e=await this.detectionService.classifyDocument(P);if(e&&e.class==="passport"){this.completeProcess(true);this.returnCanvasToPool(t);this.returnCanvasToPool(P);this.processingButton=null;return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});this.triggerRerender();setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.triggerRerender();this.startBackDocumentTimer();this.processingButton=null}),3e3)}else if(O.step==="back"){this.stateManager.setCapturedImages({back:{fullFrame:t.toDataURL("image/jpeg"),cropped:P.toDataURL("image/jpeg")}});this.completeProcess(false);this.processingButton=null}this.returnCanvasToPool(t);this.returnCanvasToPool(P)}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;const t=performance.now();const e=this.tracingService?.startSpan("capture.screenshot.auto");this.stateManager.updateCaptureState({isCapturing:true});this.triggerCaptureAnimation();const i=this.getPooledCanvas(this.videoRef.videoWidth,this.videoRef.videoHeight);const r=i.getContext("2d",{alpha:false});r.clearRect(0,0,i.width,i.height);r.drawImage(this.videoRef,0,0,i.width,i.height);const n=320;const s=this.videoRef.videoWidth/n;const o=this.videoRef.videoHeight/n;const a=Math.max(0,this.lastDetectedBox.x*s-this.cropMargin);const c=Math.max(0,this.lastDetectedBox.y*o-this.cropMargin);const u=Math.min(this.lastDetectedBox.w*s+2*this.cropMargin,this.videoRef.videoWidth-a);const f=Math.min(this.lastDetectedBox.h*o+2*this.cropMargin,this.videoRef.videoHeight-c);const l=this.getPooledCanvas(u,f);const h=l.getContext("2d",{alpha:false});h.clearRect(0,0,l.width,l.height);h.drawImage(this.videoRef,a,c,u,f,0,0,u,f);const d=this.stateManager.getCaptureState();if(d.step==="front"){const r=i.toDataURL("image/jpeg");const n=l.toDataURL("image/jpeg");this.stateManager.setCapturedImages({front:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("front","auto",s);this.metricsService?.recordImageSize("front",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","front")}if(this.useDocumentClassification){try{const t=await this.detectionService.classifyDocument(l);if(t&&t.class==="passport"){if(e){this.tracingService?.setSpanAttribute(e,"document.type","passport");this.tracingService?.endSpan(e)}this.completeProcess(true);return}}catch(t){}}this.stateManager.updateCaptureState({step:"back",isDetectionPaused:true,showFlipAnimation:true});if(e){this.tracingService?.endSpan(e)}setTimeout((()=>{this.stateManager.updateCaptureState({showFlipAnimation:false,isDetectionPaused:false});this.startBackDocumentTimer()}),3e3)}else if(d.step==="back"){const r=i.toDataURL("image/jpeg");const n=l.toDataURL("image/jpeg");this.stateManager.setCapturedImages({back:{fullFrame:r,cropped:n}});const s=performance.now()-t;this.metricsService?.recordCapture("back","auto",s);this.metricsService?.recordImageSize("back",r.length);if(e){this.tracingService?.setSpanAttribute(e,"side","back");this.tracingService?.endSpan(e)}this.completeProcess(false)}this.returnCanvasToPool(i);this.returnCanvasToPool(l)}triggerCaptureAnimation(){const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.stateManager.updateCaptureState({isCapturing:false});t?.classList.remove("capturing")}),600)}switchToManualMode(){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.stopPerformanceMonitoring();this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.showPerformanceMessage=true;setTimeout((()=>{this.showPerformanceMessage=false}),5e3)}switchToManualModeWithWarning(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"active");this.continueWithCameraSetup()}async continueWithCameraSetup(){try{this.updateStatus("Configurando cámara...","Buscando dispositivos disponibles","loading");try{await this.cameraService.enumerateDevices()}catch(t){throw new Error(`Error al enumerar dispositivos: ${t.message}`)}try{await this.updateCameraInfoWithAutofocus()}catch(t){throw new Error(`Error al actualizar información de cámara: ${t.message}`)}this.updateStatus("Ajustando cámara...","Configurando calidad de imagen","loading");let t;try{t=await this.cameraService.setupCamera()}catch(t){throw new Error(`Error al configurar cámara: ${t.message}`)}this.updateStatus("Captura manual","Posicione su documento y use el botón para capturar","active");try{await this.initializeVideoStream(t)}catch(t){throw new Error(`Error al inicializar video: ${t.message}`)}if(this.detectionContainer){const t=this.detectionContainer.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}this.startTime=Date.now();this.stateManager.updateCaptureState({isLoading:false});this.showManualCaptureButton=true}catch(t){this.updateStatus("Error de cámara",t.message,"error");throw t}}switchToManualModeWithError(t){if(!this.useDocumentDetector||this.hasAutoSwitchedToManual){return}this.releaseOnnxResources();this.resetMaskToWhite();this.detectionBoxes=[];this.hasAutoSwitchedToManual=true;this.performanceDegradedMode=true;this.showManualCaptureButton=true;this.useDocumentDetector=false;this.updateStatus("Modo manual activado",t,"error");this.continueWithCameraSetup().catch((()=>{setTimeout((()=>{this.updateStatus("Captura manual","Use el botón para capturar","ready")}),5e3)}))}stopPerformanceMonitoring(){}releaseOnnxResources(){try{if(this.detectionService){this.detectionService.cleanup()}}catch(t){}}async completeProcess(t=false){this.stateManager.updateCaptureState({step:"completed",showSuccessAnimation:true});const e=this.stateManager.getCapturedImages();e.metadata.processCompleted=true;e.metadata.backCaptureSkipped=t;this.stateManager.setCapturedImages(e);this.stopDetection();this.updateStatus("Proceso completado",`Imágenes capturadas exitosamente`,"ready");const i={...e,timestamp:(new Date).toISOString()};if(this.tracingService){try{await this.tracingService.flush()}catch(t){console.error("[my-component] Failed to flush traces:",t)}}this.captureCompleted.emit(i);setTimeout((()=>{this.stateManager.updateCaptureState({showSuccessAnimation:false})}),3e3)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}this.clearBackDocumentTimer();this.detectionBoxes=[]}startBackDocumentTimer(){if(!this.enableBackDocumentTimer)return;if(this.backDocumentTimer){clearInterval(this.backDocumentTimer)}this.backDocumentTimerRemaining=this.backDocumentTimerDuration;this.backDocumentTimer=window.setInterval((()=>{this.backDocumentTimerRemaining--;if(this.backDocumentTimerRemaining<=0){this.clearBackDocumentTimer();this.skipBackCapture()}}),1e3)}clearBackDocumentTimer(){if(this.backDocumentTimer){clearInterval(this.backDocumentTimer);this.backDocumentTimer=undefined}this.backDocumentTimerRemaining=0}toggleCameraSelector(){if(this.isSwitchingCamera)return;this.showCameraSelector=!this.showCameraSelector}async updateCameraInfoWithAutofocus(){try{const t=await this.cameraService.getCameraInfo();this.cameraInfoWithAutofocus=t}catch(t){}}async handleCameraSwitch(t){if(this.isSwitchingCamera)return;try{this.showCameraSelector=false;const e=this.cameraService.getSelectedCameraId();if(e===t){return}this.isSwitchingCamera=true;if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}await this.cameraService.switchCamera(t);const i=await this.cameraService.setupCamera();await this.initializeVideoStream(i);await this.updateCameraInfoWithAutofocus()}catch(t){try{const t=await this.cameraService.setupCamera();await this.initializeVideoStream(t)}catch(t){this.updateStatus("Error al cambiar cámara","No se pudo cambiar el dispositivo","error")}}finally{this.isSwitchingCamera=false}}resetDetection(){const t=this.stateManager.getCaptureState();const e=t.isVideoActive;this.stateManager.reset();if(e){this.stateManager.updateCaptureState({isVideoActive:true})}this.hasScreenshotTaken=false;this.startTime=Date.now();this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;this.detectionBoxes=[];this.alignmentStartTime=undefined;this.hasDocumentDetected=false;this.processedFramesCount=0;this.slowFrameCount=0;this.hasAutoSwitchedToManual=false;this.performanceDegradedMode=false;this.showPerformanceMessage=false;if(this.alignmentTimer){clearTimeout(this.alignmentTimer);this.alignmentTimer=undefined}if(e&&this.detectionService.isModelLoaded()){this.updateStatus("Captura reiniciada","Buscando documento en el marco de captura","active");this.detectFrame()}else{this.updateStatus("Listo para capturar","","ready")}}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.stateManager.updateCaptureState({isVideoActive:false,isLoading:false})}this.isMaskReady=false;this.updateStatus("Captura finalizada","","ready");this.detectionBoxes=[];this.cleanup()}initializePerformanceMonitor(){this.performanceMetrics.lastUpdateTime=performance.now();this.performanceUpdateInterval=window.setInterval((()=>{this.updatePerformanceMetrics()}),500)}updatePerformanceMetrics(){const t=performance.now();const e=t-this.performanceMetrics.lastUpdateTime;if(e>0){this.performanceMetrics.fps=Math.round(1e3/(e/this.frameSkipCounter||1))}if("memory"in performance){const t=performance.memory;this.performanceMetrics.memoryUsage=Math.round(t.usedJSHeapSize/1048576)}if(this.performanceMetrics.totalDetections>0){this.performanceMetrics.successfulDetections=this.performanceMetrics.successfulDetections;const t=this.performanceMetrics.successfulDetections/this.performanceMetrics.totalDetections*100;this.performanceMetrics.detectionRate=Math.round(t)}this.performanceData={fps:this.performanceMetrics.fps,inferenceTime:this.performanceMetrics.inferenceTime,memoryUsage:this.performanceMetrics.memoryUsage,onnxLoadTime:this.performanceMetrics.onnxLoadTime,frameProcessingTime:this.performanceMetrics.frameProcessingTime,totalDetections:this.performanceMetrics.totalDetections,successfulDetections:this.performanceMetrics.successfulDetections,detectionRate:this.performanceMetrics.detectionRate};this.performanceMetrics.lastUpdateTime=t}recordOnnxPerformance(t,e){this.performanceMetrics.onnxLoadTime=Math.round(t);this.performanceMetrics.inferenceTime=Math.round(e)}recordFrameProcessing(t,e){this.performanceMetrics.frameProcessingTime=Math.round(t);this.performanceMetrics.totalDetections++;if(e>0){this.performanceMetrics.successfulDetections++}this.performanceHistory.push(t);if(this.performanceHistory.length>this.PERFORMANCE_HISTORY_SIZE){this.performanceHistory.shift()}}getAdaptiveFrameSkip(){if(this.consecutiveFailures>20)return this.MAX_FRAME_SKIP;if(this.performanceMetrics.inferenceTime>200)return 6;if(this.performanceMetrics.memoryUsage>200)return 5;if(this.performanceHistory.length>0){const t=this.performanceHistory.reduce(((t,e)=>t+e),0)/this.performanceHistory.length;if(t>100)return 4;if(t>80)return 3;if(t>60)return this.BASE_FRAME_SKIP+1}if(this.performanceMetrics.memoryUsage>150)return 4;return this.BASE_FRAME_SKIP}resetMaskToWhite(){const t=this.el.shadowRoot?.querySelector(".card-outline");const e=this.el.shadowRoot?.querySelectorAll(".corner");const i=this.el.shadowRoot?.querySelector(".side-top");const r=this.el.shadowRoot?.querySelector(".side-right");const n=this.el.shadowRoot?.querySelector(".side-bottom");const s=this.el.shadowRoot?.querySelector(".side-left");t?.classList.remove("perfect-match");e?.forEach((t=>t.classList.remove("perfect-match")));i?.classList.remove("aligned");r?.classList.remove("aligned");n?.classList.remove("aligned");s?.classList.remove("aligned");this.sideAlignment={top:false,right:false,bottom:false,left:false}}getPooledCanvas(t,e){const i=this.canvasPool.findIndex((i=>i.width===t&&i.height===e));if(i!==-1){return this.canvasPool.splice(i,1)[0]}if(this.canvasPool.length>0){const i=this.canvasPool.pop();i.width=t;i.height=e;return i}const r=document.createElement("canvas");r.width=t;r.height=e;return r}returnCanvasToPool(t){if(this.canvasPool.length<this.MAX_CANVAS_POOL_SIZE){const e=t.getContext("2d");e.clearRect(0,0,t.width,t.height);this.canvasPool.push(t)}}};Yc.style=Xc;export{Yc as jaak_stamps};
7
+ //# sourceMappingURL=p-dfecb452.entry.js.map