@jaak.ai/stamps 2.0.0-beta.3 → 2.0.0-dev.17

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.
Files changed (36) hide show
  1. package/README.md +19 -104
  2. package/dist/cjs/{index-BfhtOB0D.js → index-DGM9-FNg.js} +2 -5
  3. package/dist/cjs/index-DGM9-FNg.js.map +1 -0
  4. package/dist/cjs/jaak-stamps-webcomponent.cjs.js +2 -2
  5. package/dist/cjs/jaak-stamps.cjs.entry.js +39 -749
  6. package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
  7. package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
  8. package/dist/cjs/loader.cjs.js +2 -2
  9. package/dist/collection/components/my-component/my-component.css +7 -237
  10. package/dist/collection/components/my-component/my-component.js +38 -886
  11. package/dist/collection/components/my-component/my-component.js.map +1 -1
  12. package/dist/components/index.js +0 -3
  13. package/dist/components/index.js.map +1 -1
  14. package/dist/components/jaak-stamps.js +39 -760
  15. package/dist/components/jaak-stamps.js.map +1 -1
  16. package/dist/esm/{index-BP1Q4KOg.js → index-DqoVMnc7.js} +2 -5
  17. package/dist/esm/index-DqoVMnc7.js.map +1 -0
  18. package/dist/esm/jaak-stamps-webcomponent.js +3 -3
  19. package/dist/esm/jaak-stamps.entry.js +39 -749
  20. package/dist/esm/jaak-stamps.entry.js.map +1 -1
  21. package/dist/esm/loader.js +3 -3
  22. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
  23. package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
  24. package/dist/jaak-stamps-webcomponent/p-45dcdc80.entry.js +2 -0
  25. package/dist/jaak-stamps-webcomponent/p-45dcdc80.entry.js.map +1 -0
  26. package/dist/jaak-stamps-webcomponent/p-DqoVMnc7.js +3 -0
  27. package/dist/jaak-stamps-webcomponent/p-DqoVMnc7.js.map +1 -0
  28. package/dist/types/components/my-component/my-component.d.ts +2 -56
  29. package/dist/types/components.d.ts +0 -36
  30. package/package.json +1 -1
  31. package/dist/cjs/index-BfhtOB0D.js.map +0 -1
  32. package/dist/esm/index-BP1Q4KOg.js.map +0 -1
  33. package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js +0 -2
  34. package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js.map +0 -1
  35. package/dist/jaak-stamps-webcomponent/p-BP1Q4KOg.js +0 -3
  36. package/dist/jaak-stamps-webcomponent/p-BP1Q4KOg.js.map +0 -1
@@ -1,2 +0,0 @@
1
- import{r as t,c as e,a as i,h as s}from"./p-BP1Q4KOg.js";const a=":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,canvas{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,canvas.mirror{transform:rotateY(180deg)}canvas{z-index:1}video{z-index:0}.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;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7);opacity:0.8}.card-outline.perfect-match{box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7)}.side{position:absolute;background:#999;transition:background-color 0.3s ease}.side.aligned{background:#28a745}.side-top{top:0;left:0;width:100%;height:3px}.side-right{top:0;right:0;width:3px;height:100%}.side-bottom{bottom:0;left:0;width:100%;height:3px}.side-left{top:0;left:0;width:3px;height:100%}.corner{position:absolute;width:20px;height:20px;border:2px solid #999;z-index:12}.corner-tl{top:-10px;left:-10px;border-right:none;border-bottom:none}.corner-tr{top:-10px;right:-10px;border-left:none;border-bottom:none}.corner-bl{bottom:-10px;left:-10px;border-right:none;border-top:none}.corner-br{bottom:-10px;right:-10px;border-left:none;border-top:none}.corner.perfect-match{border-color:#28a745}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);color:#fff;font-size:14px;font-weight:600;text-align:center;white-space:normal;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;z-index:20}.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 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 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);animation:drawCheck 0.4s ease-out 0.2s both}.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-button{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;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:translateX(-50%) translateY(0)}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto}.flip-camera-button{height:40px;padding:0 16px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.6);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{height:40px;padding:0 16px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.6);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}.flip-camera-button:hover,.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.flip-camera-button:active,.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.85);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)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;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:10px 16px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:space-between;align-items:center;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:8px;font-weight:400}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9}.device-info{padding:8px 16px;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}.flip-camera-button{height:36px;padding:0 12px;font-size:11px;border-radius: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:10px 14px}.camera-option{padding:8px 14px}.device-info{padding:6px 14px}}.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))}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.8);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:20px}.loading-spinner{width:60px;height:60px;border:4px solid rgba(255, 255, 255, 0.2);border-top:4px solid #007bff;border-radius:50%;animation:spin 1s linear infinite;margin-bottom:20px}.loading-text{color:white;font-size:16px;font-weight:500;text-align:center;opacity:0.9}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}";const o=class{constructor(i){t(this,i);this.captureCompleted=e(this,"captureCompleted");this.isReady=e(this,"isReady")}get el(){return i(this)}debug=false;alignmentTolerance=10;maskSize=90;cropMargin=0;useDocumentClassification=false;preferredCamera="auto";captureCompleted;isReady;isVideoActive=false;statusMessage="Presione el botón para activar la cámara";statusColor="#aaa";bestScore=0;capturedFullFrame=null;capturedCroppedId=null;capturedBackFullFrame=null;capturedBackCroppedId=null;captureStep="front";isCapturing=false;showFlipAnimation=false;showSuccessAnimation=false;shouldMirrorVideo=true;sideAlignment={top:false,right:false,bottom:false,left:false};isDetectionPaused=false;isLoading=false;isModelPreloaded=false;isMaskReady=false;availableCameras=[];selectedCameraId=null;showCameraSelector=false;isMultipleCamerasAvailable=false;videoRef;canvasRef;session;startTime;videoStream;animationId;hasScreenshotTaken=false;lastDetectedBox;mobileNetSession;mobileNetClassMap;deviceType="desktop";preferredCameraFacing=null;frameSkipCounter=0;FRAME_SKIP=2;consecutiveFailures=0;MAX_FAILURES=30;lastInferenceTime=0;MIN_INFERENCE_INTERVAL=50;preprocessCanvas;preprocessCtx;captureCanvas;captureCtx;MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx";MOBILENET_MODEL_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";MOBILENET_CLASSES_PATH="https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";INPUT_SIZE=320;CONFIDENCE_THRESHOLD=.6;ID1_ASPECT_RATIO=85.6/53.98;debugLog(...t){if(this.debug){console.log(...t)}}validateMaskSize(){if(this.maskSize<50||this.maskSize>100){console.warn(`maskSize debe estar entre 50 y 100. Valor actual: ${this.maskSize}. Usando valor por defecto: 90`);this.maskSize=90}}validateCropMargin(){if(this.cropMargin<0||this.cropMargin>100){console.warn(`cropMargin debe estar entre 0 y 100. Valor actual: ${this.cropMargin}. Usando valor por defecto: 0`);this.cropMargin=0}}validatePreferredCamera(){const t=["auto","front","back"];if(!t.includes(this.preferredCamera)){console.warn(`preferredCamera debe ser uno de: ${t.join(", ")}. Valor actual: ${this.preferredCamera}. Usando valor por defecto: 'auto'`);this.preferredCamera="auto"}}emitReadyEvent(){const t=!!window.ort&&this.isModelPreloaded;this.isReady.emit(t);this.debugLog("🟢 isReady event emitted:",t)}isRearCamera(t){const e=t.getVideoTracks()[0];if(!e)return false;const i=e.getSettings();return i.facingMode==="environment"}async detectDeviceTypeAndCameras(){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"}this.debugLog("📱 Device type detected:",this.deviceType);await this.enumerateAndDetectCameras();this.loadCameraPreference()}async enumerateAndDetectCameras(){try{const t=await this.checkCameraPermission();if(t==="denied"){this.debugLog("❌ Camera permission denied");this.statusMessage="Permiso de cámara denegado";this.statusColor="#ff6b6b";return}if(t==="prompt"){const t=await navigator.mediaDevices.getUserMedia({video:true});t.getTracks().forEach((t=>t.stop()))}const e=await navigator.mediaDevices.enumerateDevices();this.availableCameras=e.filter((t=>t.kind==="videoinput"));this.isMultipleCamerasAvailable=this.availableCameras.length>1;this.debugLog("📹 Available cameras:",{count:this.availableCameras.length,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable,cameras:this.availableCameras.map((t=>({id:t.deviceId,label:t.label||"Unknown Camera"})))});this.setInitialCameraPreference()}catch(t){this.debugLog("❌ Error enumerating cameras:",t);this.handleCameraPermissionError(t)}}async checkCameraPermission(){try{if(!navigator.permissions){return"prompt"}const t=await navigator.permissions.query({name:"camera"});return t.state}catch(t){this.debugLog("⚠️ Could not check camera permission:",t);return"prompt"}}handleCameraPermissionError(t){if(t.name==="NotAllowedError"){this.statusMessage="Permiso de cámara denegado. Active el permiso en configuración.";this.statusColor="#ff6b6b";this.availableCameras=[];this.isMultipleCamerasAvailable=false}else if(t.name==="NotFoundError"){this.statusMessage="No se encontraron cámaras disponibles.";this.statusColor="#ff6b6b";this.availableCameras=[];this.isMultipleCamerasAvailable=false}else if(t.name==="NotReadableError"){this.statusMessage="Cámara en uso por otra aplicación.";this.statusColor="#ff6b6b";this.availableCameras=[];this.isMultipleCamerasAvailable=false}else{this.statusMessage="Error al acceder a las cámaras.";this.statusColor="#ff6b6b";this.availableCameras=[];this.isMultipleCamerasAvailable=false}}setInitialCameraPreference(){if(this.availableCameras.length===0)return;if(this.preferredCamera==="front"){this.preferredCameraFacing="user";const t=this.availableCameras.find((t=>t.label.toLowerCase().includes("front")||t.label.toLowerCase().includes("user")||t.label.toLowerCase().includes("selfie")||!t.label.toLowerCase().includes("back")&&!t.label.toLowerCase().includes("rear")));if(t){this.selectedCameraId=t.deviceId;this.debugLog("👤 User selected front camera:",t.label)}else{this.selectedCameraId=this.availableCameras[0].deviceId;this.debugLog("⚠️ Front camera not found, using first available:",this.availableCameras[0].label)}}else if(this.preferredCamera==="back"){this.preferredCameraFacing="environment";const t=this.availableCameras.find((t=>t.label.toLowerCase().includes("back")||t.label.toLowerCase().includes("rear")||t.label.toLowerCase().includes("environment")));if(t){this.selectedCameraId=t.deviceId;this.debugLog("📷 User selected back camera:",t.label)}else{this.selectedCameraId=this.availableCameras[0].deviceId;this.debugLog("⚠️ Back camera not found, using first available:",this.availableCameras[0].label)}}else{if(this.deviceType==="mobile"||this.deviceType==="tablet"){this.preferredCameraFacing="environment";const t=this.availableCameras.find((t=>t.label.toLowerCase().includes("back")||t.label.toLowerCase().includes("rear")||t.label.toLowerCase().includes("environment")));if(t){this.selectedCameraId=t.deviceId;this.debugLog("📱 Auto-selected rear camera for mobile:",t.label)}else{this.selectedCameraId=this.availableCameras[0].deviceId;this.debugLog("📱 Rear camera not found, using first available:",this.availableCameras[0].label)}}else{this.selectedCameraId=this.availableCameras[0].deviceId;this.debugLog("💻 Auto-selected desktop camera:",this.availableCameras[0].label)}}}loadCameraPreference(){try{const t=localStorage.getItem("jaak-stamps-camera-preference");if(t){const e=JSON.parse(t);const i=this.availableCameras.some((t=>t.deviceId===e.cameraId));if(i){this.selectedCameraId=e.cameraId;this.preferredCameraFacing=e.facing;this.debugLog("💾 Loaded camera preference:",e)}}}catch(t){this.debugLog("⚠️ Error loading camera preference:",t)}}saveCameraPreference(){try{const t={cameraId:this.selectedCameraId,facing:this.preferredCameraFacing,timestamp:Date.now()};localStorage.setItem("jaak-stamps-camera-preference",JSON.stringify(t));this.debugLog("💾 Saved camera preference:",t)}catch(t){this.debugLog("⚠️ Error saving camera preference:",t)}}async switchCamera(t){if(!this.isVideoActive||this.selectedCameraId===t)return;try{const e=this.availableCameras.find((e=>e.deviceId===t));if(!e){this.debugLog("❌ Selected camera not found, re-enumerating...");await this.enumerateAndDetectCameras();return}this.statusMessage="Cambiando cámara...";this.statusColor="#007bff";if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}this.selectedCameraId=t;const i=e.label.toLowerCase().includes("back")||e.label.toLowerCase().includes("rear")||e.label.toLowerCase().includes("environment");this.preferredCameraFacing=i?"environment":"user";this.saveCameraPreference();await this.setupCameraWithRetry();this.debugLog("🔄 Switched to camera:",e.label)}catch(t){this.debugLog("❌ Error switching camera:",t);this.handleCameraPermissionError(t)}}async setupCameraWithRetry(t=3){for(let e=1;e<=t;e++){try{await this.setupCamera();return}catch(i){this.debugLog(`❌ Camera setup attempt ${e} failed:`,i);if(e===t){this.handleCameraPermissionError(i);throw i}await new Promise((t=>setTimeout(t,500*e)))}}}toggleCameraSelector(){this.showCameraSelector=!this.showCameraSelector;this.debugLog("📹 Camera selector toggled:",{showCameraSelector:this.showCameraSelector,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable,availableCameras:this.availableCameras.length,isVideoActive:this.isVideoActive})}async flipCamera(){if(!this.isMultipleCamerasAvailable)return;const t=this.availableCameras.findIndex((t=>t.deviceId===this.selectedCameraId));const e=(t+1)%this.availableCameras.length;const i=this.availableCameras[e];await this.switchCamera(i.deviceId)}async componentDidLoad(){this.validateMaskSize();this.validateCropMargin();this.validatePreferredCamera();await this.detectDeviceTypeAndCameras();if(!window.ort){const t=document.createElement("script");t.src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js";document.head.appendChild(t);t.onload=()=>{this.emitReadyEvent()}}else{this.emitReadyEvent()}this.initializeCanvasPool();this.setupResizeObserver()}setupResizeObserver(){if("ResizeObserver"in window&&this.canvasRef){const t=new ResizeObserver((()=>{this.handleResize()}));t.observe(this.canvasRef.parentElement)}}handleResize(){if(this.canvasRef){const t=this.canvasRef.parentElement;const e=t.getBoundingClientRect();this.canvasRef.width=e.width;this.canvasRef.height=e.height;this.updateMaskDimensions(e);this.debugLog("📐 Canvas resized:",{width:e.width,height:e.height})}}updateMaskDimensions(t){if(!this.videoRef)return;const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0)return;const s=e/i;const a=t.width/t.height;let o,r;let n=0,c=0;if(s>a){o=t.width;r=t.width/s;c=(t.height-r)/2}else{r=t.height;o=t.height*s;n=(t.width-o)/2}const h=r*this.ID1_ASPECT_RATIO;let d,l;const f=this.maskSize/100;if(h<=o){l=r*f;d=l*this.ID1_ASPECT_RATIO}else{d=o*f;l=d/this.ID1_ASPECT_RATIO}const p=d/t.width*100;const m=l/t.height*100;const b=n+o/2;const u=c+r/2;const g=b/t.width*100;const x=u/t.height*100;this.el.style.setProperty("--mask-width",`${p}%`);this.el.style.setProperty("--mask-height",`${m}%`);this.el.style.setProperty("--mask-center-x",`${g}%`);this.el.style.setProperty("--mask-center-y",`${x}%`);this.isMaskReady=true;this.debugLog("🎯 Mask dimensions updated:",{video:{width:e,height:i},displayed:{width:o,height:r},mask:{widthPercent:p,heightPercent:m},center:{x:g,y:x},offset:{x:n,y:c}})}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");this.captureCtx=this.captureCanvas.getContext("2d",{alpha:false});this.debugLog("🎨 Canvas pool initialized for performance")}disconnectedCallback(){this.cleanup()}async getCapturedImages(){if(this.captureStep!=="completed"){throw new Error("El proceso de captura no ha sido completado")}return{front:{fullFrame:this.capturedFullFrame,cropped:this.capturedCroppedId},back:{fullFrame:this.capturedBackFullFrame,cropped:this.capturedBackCroppedId},metadata:{hasBackCapture:!!(this.capturedBackFullFrame&&this.capturedBackCroppedId),totalImages:this.capturedBackFullFrame&&this.capturedBackCroppedId?4:2}}}async isProcessCompleted(){return this.captureStep==="completed"}async startCapture(){await this.startDetection()}async stopCapture(){this.exitSession()}async resetCapture(){this.resetDetection()}async getStatus(){return{isVideoActive:this.isVideoActive,captureStep:this.captureStep,statusMessage:this.statusMessage,hasImages:!!(this.capturedFullFrame||this.capturedBackFullFrame),isProcessCompleted:this.captureStep==="completed",isModelPreloaded:this.isModelPreloaded}}async preloadModel(){if(this.isModelPreloaded||this.session){this.debugLog("🚀 Model already preloaded or session exists");return{success:true,message:"Model already loaded"}}try{this.isLoading=true;this.statusMessage="Precargando modelos...";this.statusColor="#007bff";const t=this.MODEL_PATH;this.debugLog("🤖 Preloading detection model:",t);const e=this.getSessionOptions();this.session=await window.ort.InferenceSession.create(t,e);if(this.useDocumentClassification){await this.loadMobileNetModel()}this.isModelPreloaded=true;this.isLoading=false;this.statusMessage="Modelos precargados. Listo para comenzar detección";this.statusColor="#28a745";this.emitReadyEvent();this.debugLog("✅ Models preloaded successfully");return{success:true,message:"Models preloaded successfully"}}catch(t){this.debugLog("❌ Error preloading models:",t);this.isLoading=false;this.statusMessage="Error al precargar los modelos";this.statusColor="#ff6b6b";return{success:false,error:t.message}}}async skipBackCapture(){if(this.captureStep==="back"&&this.capturedFullFrame){this.completeProcess(true)}}async getCameraInfo(){return{availableCameras:this.availableCameras.map((t=>({id:t.deviceId,label:t.label||"Unknown Camera",selected:t.deviceId===this.selectedCameraId}))),selectedCameraId:this.selectedCameraId,deviceType:this.deviceType,isMultipleCamerasAvailable:this.isMultipleCamerasAvailable,preferredFacing:this.preferredCameraFacing,userPreferredCamera:this.preferredCamera}}async setPreferredCamera(t){this.preferredCamera=t;this.debugLog("🎯 Camera preference changed to:",t);await this.enumerateAndDetectCameras();if(this.isVideoActive&&this.selectedCameraId){await this.switchCamera(this.selectedCameraId)}return{success:true,selectedCamera:this.selectedCameraId,availableCameras:this.availableCameras.length}}async loadMobileNetModel(){try{this.debugLog("🤖 Loading MobileNet model...");const t=await fetch(this.MOBILENET_CLASSES_PATH);if(!t.ok){throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`)}this.mobileNetClassMap=await t.json();this.debugLog("📋 MobileNet classes loaded:",this.mobileNetClassMap);const e=this.getSessionOptions();this.mobileNetSession=await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH,e);this.debugLog("✅ MobileNet model loaded successfully")}catch(t){this.debugLog("❌ Error loading MobileNet model:",t);throw t}}preprocessMobileNet(t){const e=document.createElement("canvas");e.width=224;e.height=224;const i=e.getContext("2d");i.drawImage(t,0,0,224,224);const s=i.getImageData(0,0,224,224);const a=s.data;const o=224*224;const r=new Float32Array(3*o);for(let t=0;t<o;t++){r[t]=(a[t*4+0]/255-.5)/.5;r[o+t]=(a[t*4+1]/255-.5)/.5;r[2*o+t]=(a[t*4+2]/255-.5)/.5}return new window.ort.Tensor("float32",r,[1,3,224,224])}async classifyDocument(t){if(!this.mobileNetSession||!this.mobileNetClassMap){this.debugLog("⚠️ MobileNet model not loaded");return null}try{this.debugLog("🔍 Classifying document...");const e=this.preprocessMobileNet(t);const i={input:e};const s=await this.mobileNetSession.run(i);const a=s[Object.keys(s)[0]].data;const o=a.reduce(((t,e,i,s)=>e>s[t]?i:t),0);const r=a[o];const n=this.mobileNetClassMap[o.toString()]||"unknown";this.debugLog("📄 Document classification result:",{class:n,confidence:r.toFixed(3),classIndex:o});return{class:n,confidence:r,classIndex:o}}catch(t){this.debugLog("❌ Error classifying document:",t);return null}}cleanup(){if(this.animationId){cancelAnimationFrame(this.animationId)}if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()))}if(this.canvasRef){const t=this.canvasRef.getContext("2d");if(t){t.clearRect(0,0,this.canvasRef.width,this.canvasRef.height)}}this.cleanupCanvasPool()}cleanupCanvasPool(){if(this.preprocessCanvas){this.preprocessCtx=undefined;this.preprocessCanvas=undefined}if(this.captureCanvas){this.captureCtx=undefined;this.captureCanvas=undefined}if(this.session){this.session.release?.();this.session=undefined}if(this.mobileNetSession){this.mobileNetSession.release?.();this.mobileNetSession=undefined}this.mobileNetClassMap=undefined;this.isModelPreloaded=false;this.debugLog("🧹 Canvas pool cleaned up")}async getMaxResolution(){try{const t={};if(this.selectedCameraId){t.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){t.facingMode=this.preferredCameraFacing}else{t.facingMode="environment"}const e=await navigator.mediaDevices.getUserMedia({video:t});const i=e.getVideoTracks()[0];const s=i.getCapabilities();e.getTracks().forEach((t=>t.stop()));const a={};if(this.selectedCameraId){a.deviceId={exact:this.selectedCameraId}}else if(this.preferredCameraFacing){a.facingMode=this.preferredCameraFacing}else{a.facingMode="environment"}if(s.width&&s.height){const t=Math.min(s.width.max,1920);const e=Math.min(s.height.max,1080);const i=/iPad|Android/i.test(navigator.userAgent)&&window.innerWidth>=768;if(i){a.width={ideal:Math.min(t,1280)};a.height={ideal:Math.min(e,720)}}else{a.width={ideal:t};a.height={ideal:e}}this.debugLog("📐 Resolution capabilities:",{maxWidth:s.width.max,maxHeight:s.height.max,selectedWidth:a.width.ideal,selectedHeight:a.height.ideal,isTablet:i})}return a}catch(t){this.debugLog("⚠️ Could not get capabilities, using fallback");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){i.facingMode=this.preferredCameraFacing}else{i.facingMode="environment"}return i}}async setupCamera(){try{const t=await this.getMaxResolution();const e=await navigator.mediaDevices.getUserMedia({video:t,audio:false});if(this.videoRef){this.videoRef.srcObject=e;this.videoStream=e;const t=this.isRearCamera(e);this.shouldMirrorVideo=!t;this.debugLog("📹 Rear camera:",t);this.debugLog("🪞 Should mirror video:",this.shouldMirrorVideo);return new Promise((t=>{this.videoRef.onloadedmetadata=async()=>{await this.videoRef.play();this.isVideoActive=true;if(this.canvasRef){const t=this.canvasRef.parentElement;const e=t.getBoundingClientRect();this.updateMaskDimensions(e)}t()}}))}}catch(t){this.debugLog("❌ No se pudo acceder a la cámara:",t);this.handleCameraPermissionError(t)}}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,s,a]=[[],[],[]];const{data:o}=e;for(let t=0;t<o.length;t+=4){i.push(o[t]/255);s.push(o[t+1]/255);a.push(o[t+2]/255)}const r=new Float32Array(i.concat(s,a));return new window.ort.Tensor("float32",r,[1,3,this.INPUT_SIZE,this.INPUT_SIZE])}getSessionOptions(){return{executionProviders:["webgl","wasm"],graphOptimizationLevel:"all",logSeverityLevel:this.debug?2:4,logVerbosityLevel:0,enableCpuMemArena:true,enableMemPattern:true,executionMode:"parallel",interOpNumThreads:2,intraOpNumThreads:2}}async startDetection(){try{if(!this.session){this.isLoading=true;this.statusMessage="Cargando modelos...";this.statusColor="#007bff";const t=this.MODEL_PATH;this.debugLog("🤖 Loading detection model:",t);const e=this.getSessionOptions();this.session=await window.ort.InferenceSession.create(t,e);if(this.useDocumentClassification&&!this.mobileNetSession){await this.loadMobileNetModel()}this.isModelPreloaded=true;this.emitReadyEvent()}else{this.debugLog("🚀 Using preloaded models");this.statusMessage="Usando modelos precargados...";this.statusColor="#007bff"}this.statusMessage="Configurando cámara...";await this.setupCamera();this.startTime=Date.now();this.isLoading=false;this.detectFrame()}catch(t){this.debugLog("Error al inicializar:",t);this.statusMessage="Error al inicializar el detector";this.statusColor="#ff6b6b";this.isLoading=false}}async detectFrame(){try{if(!this.videoRef||!this.canvasRef||!this.session)return;if(this.isDetectionPaused){if(this.captureStep!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter++;if(this.frameSkipCounter<=this.FRAME_SKIP){if(this.captureStep!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.frameSkipCounter=0;const t=Date.now();if(t-this.lastInferenceTime<this.MIN_INFERENCE_INTERVAL){if(this.captureStep!=="completed"){this.animationId=requestAnimationFrame((()=>this.detectFrame()))}return}this.lastInferenceTime=t;const e=this.canvasRef.getContext("2d");const i=this.preprocess(this.videoRef);const s={[this.session.inputNames[0]]:i};const a=await this.session.run(s);const o=a[this.session.outputNames[0]].data;const r=[];for(let t=0;t<o.length;t+=6){const[e,i,s,a,n,c]=o.slice(t,t+6);if(n>this.CONFIDENCE_THRESHOLD){r.push({x:e,y:i,w:s-e,h:a-i,score:n,classId:c});if(this.startTime&&Date.now()-this.startTime<5e3){const t={x:e,y:i,w:s-e,h:a-i,score:n};const o=this.isCardInFrame(t);const r=o?n*1.2:n;if(r>this.bestScore){this.bestScore=r}}}}if(r.length===0){this.consecutiveFailures++}else{this.consecutiveFailures=0}e.clearRect(0,0,this.canvasRef.width,this.canvasRef.height);if(this.debug){this.drawDetections(e,r)}this.updateGuidanceStatus(r);this.updateMaskColor(r);if(this.captureStep!=="completed"){if(this.consecutiveFailures>this.MAX_FAILURES){setTimeout((()=>this.detectFrame()),200)}else{this.animationId=requestAnimationFrame((()=>this.detectFrame()))}}}catch(t){this.debugLog("Error en inferencia:",t);if(this.captureStep!=="completed"){setTimeout((()=>this.detectFrame()),100)}}}isCardInFrame(t){const e=t.x+t.w/2;const i=t.y+t.h/2;const s=this.INPUT_SIZE/2;const a=this.INPUT_SIZE/2;const o=40;const r=30;const n=Math.abs(e-s)<o&&Math.abs(i-a)<r;const c=t.w>150&&t.w<300&&t.h>90&&t.h<200;return n&&c}checkSideAlignment(t){if(!this.videoRef)return{top:false,right:false,bottom:false,left:false};const e=this.videoRef.videoWidth;const i=this.videoRef.videoHeight;if(e===0||i===0){return{top:false,right:false,bottom:false,left:false}}const s=e/i;const a=1;let o,r;if(s>a){o=this.INPUT_SIZE;r=this.INPUT_SIZE/s}else{r=this.INPUT_SIZE;o=this.INPUT_SIZE*s}const n=r*this.ID1_ASPECT_RATIO;let c,h;const d=this.maskSize/100;if(n<=o){h=r*d;c=h*this.ID1_ASPECT_RATIO}else{c=o*d;h=c/this.ID1_ASPECT_RATIO}const l=c*(this.INPUT_SIZE/o);const f=h*(this.INPUT_SIZE/r);const p=this.INPUT_SIZE/2;const m=this.INPUT_SIZE/2;const b=p-l/2;const u=p+l/2;const g=m-f/2;const x=m+f/2;let y=t.x;let w=t.x+t.w;const k=t.y;const v=t.y+t.h;if(this.shouldMirrorVideo){const t=y;const e=w;y=this.INPUT_SIZE-e;w=this.INPUT_SIZE-t}const C=this.alignmentTolerance;return{top:Math.abs(k-g)<=C,right:Math.abs(w-u)<=C,bottom:Math.abs(v-x)<=C,left:Math.abs(y-b)<=C}}areAllSidesAligned(t){return t.top&&t.right&&t.bottom&&t.left}updateMaskColor(t){const e=this.el.shadowRoot?.querySelector(".card-outline");const i=this.el.shadowRoot?.querySelectorAll(".corner");const s=this.el.shadowRoot?.querySelector(".side-top");const a=this.el.shadowRoot?.querySelector(".side-right");const o=this.el.shadowRoot?.querySelector(".side-bottom");const r=this.el.shadowRoot?.querySelector(".side-left");let n=null;let c={top:false,right:false,bottom:false,left:false};if(t.length>0){n=t.reduce(((t,e)=>e.score>t.score?e:t));c=this.checkSideAlignment(n);this.sideAlignment=c}else{this.sideAlignment={top:false,right:false,bottom:false,left:false}}s?.classList.toggle("aligned",c.top);a?.classList.toggle("aligned",c.right);o?.classList.toggle("aligned",c.bottom);r?.classList.toggle("aligned",c.left);const h=this.areAllSidesAligned(c);if(h&&n){e?.classList.add("perfect-match");i?.forEach((t=>t.classList.add("perfect-match")));if(!this.hasScreenshotTaken){this.lastDetectedBox=n;this.takeScreenshot().catch((t=>{this.debugLog("❌ Error taking screenshot:",t)}));this.hasScreenshotTaken=true;setTimeout((()=>{this.hasScreenshotTaken=false}),2e3)}}else{e?.classList.remove("perfect-match");i?.forEach((t=>t.classList.remove("perfect-match")))}}updateGuidanceStatus(t){if(t.length===0){this.statusMessage="Posicione la identificación dentro del marco";this.statusColor="#ff6b6b"}else{const e=t.reduce(((t,e)=>e.score>t.score?e:t));const i=this.checkSideAlignment(e);const s=[i.top,i.right,i.bottom,i.left].filter(Boolean).length;const a=this.areAllSidesAligned(i);if(a){this.statusMessage="Identificación perfectamente alineada. Mantenga inmóvil";this.statusColor="#00ff00"}else if(s>0){this.statusMessage=`Alinee los lados restantes (${s}/4 lados correctos)`;this.statusColor="#ffb366"}else if(e.w<150){this.statusMessage="Identificación detectada. Acerque al marco";this.statusColor="#ffb366"}else{this.statusMessage="Identificación detectada. Alinee con el marco";this.statusColor="#ffb366"}}}drawDetections(t,e){if(!this.videoRef)return;const i=this.videoRef.videoWidth;const s=this.videoRef.videoHeight;const a=this.canvasRef.width;const o=this.canvasRef.height;if(i===0||s===0)return;const r=i/s;const n=a/o;let c,h;let d=0,l=0;if(r>n){c=a;h=a/r;l=(o-h)/2}else{h=o;c=o*r;d=(a-c)/2}const f=c/this.INPUT_SIZE;const p=h/this.INPUT_SIZE;e.forEach((e=>{const i=e.x*f+d;const s=e.y*p+l;const a=e.w*f;const o=e.h*p;t.strokeStyle="#32406C";t.lineWidth=2;t.strokeRect(i,s,a,o)}))}async takeScreenshot(){if(!this.videoRef||!this.lastDetectedBox)return;this.triggerCaptureAnimation();if(!this.captureCanvas||!this.captureCtx){this.initializeCanvasPool()}this.captureCanvas.width=this.videoRef.videoWidth;this.captureCanvas.height=this.videoRef.videoHeight;this.captureCtx.drawImage(this.videoRef,0,0,this.captureCanvas.width,this.captureCanvas.height);const t=this.videoRef.videoWidth/this.INPUT_SIZE;const e=this.videoRef.videoHeight/this.INPUT_SIZE;const i=Math.max(0,this.lastDetectedBox.x*t-this.cropMargin);const s=Math.max(0,this.lastDetectedBox.y*e-this.cropMargin);const a=Math.min(this.lastDetectedBox.w*t+2*this.cropMargin,this.videoRef.videoWidth-i);const o=Math.min(this.lastDetectedBox.h*e+2*this.cropMargin,this.videoRef.videoHeight-s);const r=document.createElement("canvas");r.width=a;r.height=o;const n=r.getContext("2d",{alpha:false});n.drawImage(this.videoRef,i,s,a,o,0,0,a,o);if(this.captureStep==="front"){this.capturedFullFrame=this.captureCanvas.toDataURL("image/png");this.capturedCroppedId=r.toDataURL("image/png");if(this.useDocumentClassification){if(!this.mobileNetSession){try{await this.loadMobileNetModel()}catch(t){this.debugLog("⚠️ Failed to load classification model, continuing without classification:",t)}}if(this.mobileNetSession){const t=await this.classifyDocument(r);if(t&&t.class==="passport"){this.debugLog("📄 Passport detected - skipping back capture");this.completeProcess(true);return}}}this.captureStep="back";this.statusMessage="Voltee la identificación y muestre la parte trasera";this.statusColor="#007bff";this.isDetectionPaused=true;setTimeout((()=>{this.showFlipAnimation=true;setTimeout((()=>{this.showFlipAnimation=false;this.isDetectionPaused=false}),3e3)}),800);this.debugLog("📸 FRENTE capturado. Esperando trasera...")}else if(this.captureStep==="back"){this.capturedBackFullFrame=this.captureCanvas.toDataURL("image/png");this.capturedBackCroppedId=r.toDataURL("image/png");this.completeProcess(false);this.debugLog("📸 TRASERA capturada. Proceso completado. Detector detenido. Imágenes emitidas.")}}triggerCaptureAnimation(){this.isCapturing=true;const t=this.el.shadowRoot?.querySelector(".card-outline");t?.classList.add("capturing");setTimeout((()=>{this.isCapturing=false;t?.classList.remove("capturing")}),600)}stopDetection(){if(this.animationId){cancelAnimationFrame(this.animationId);this.animationId=undefined}if(this.canvasRef){const t=this.canvasRef.getContext("2d");t.clearRect(0,0,this.canvasRef.width,this.canvasRef.height)}this.debugLog("🛑 Detector de identificación detenido")}resetDetection(){this.bestScore=0;this.startTime=Date.now();this.statusMessage="Sistema reiniciado. Posicione la identificación";this.statusColor="#aaa";this.hasScreenshotTaken=false;this.capturedFullFrame=null;this.capturedCroppedId=null;this.capturedBackFullFrame=null;this.capturedBackCroppedId=null;this.captureStep="front";this.isCapturing=false;this.showFlipAnimation=false;this.showSuccessAnimation=false;this.isDetectionPaused=false;this.isLoading=false;this.lastDetectedBox=undefined;this.isModelPreloaded=false;this.frameSkipCounter=0;this.consecutiveFailures=0;this.lastInferenceTime=0;if(this.canvasRef){const t=this.canvasRef.getContext("2d");t.clearRect(0,0,this.canvasRef.width,this.canvasRef.height)}if(this.isVideoActive&&this.session){this.detectFrame()}}completeProcess(t=false){this.captureStep="completed";this.statusMessage=t?"Proceso completado (solo frente capturado)":"Proceso de captura completado exitosamente";this.statusColor="#28a745";this.stopDetection();const e={front:{fullFrame:this.capturedFullFrame,cropped:this.capturedCroppedId},back:{fullFrame:this.capturedBackFullFrame,cropped:this.capturedBackCroppedId},timestamp:(new Date).toISOString(),metadata:{totalImages:t?2:4,processCompleted:true,backCaptureSkipped:t}};this.captureCompleted.emit(e);setTimeout((()=>{this.showSuccessAnimation=true;setTimeout((()=>{this.showSuccessAnimation=false}),3e3)}),800)}exitSession(){if(this.videoStream){this.videoStream.getTracks().forEach((t=>t.stop()));this.videoStream=undefined;this.isVideoActive=false;this.statusMessage="Sesión finalizada.";this.statusColor="#aaa"}this.isLoading=false;if(this.canvasRef){const t=this.canvasRef.getContext("2d");t.clearRect(0,0,this.canvasRef.width,this.canvasRef.height)}this.cleanup()}render(){return s("div",{key:"b90673f523dbf112786eb7184f56415055765c0c",class:"detector-container"},s("div",{key:"925c5c886e9af53b460281244958e722de670a70",class:"video-container"},s("video",{key:"4a0074e33a81b4694c6c99e3ece256c1ac8fe1d5",ref:t=>this.videoRef=t,autoplay:true,muted:true,playsinline:true,class:this.shouldMirrorVideo?"mirror":"",style:{display:this.isVideoActive?"block":"none"}}),s("canvas",{key:"a7b7f3b35c0535c11f6a4a155502dbe016f590b7",ref:t=>this.canvasRef=t,class:this.shouldMirrorVideo?"mirror":""}),this.isMaskReady&&s("div",{key:"695b6a2f97e29b0b9c5b9d43682a951caff376a1",class:"overlay-mask"},s("div",{key:"768875c39d5917c6a04306037d03d9e1aed114bd",class:"card-outline"},s("div",{key:"a56536deb7b8c99145d1bef6fee84e5801798644",class:"side side-top"}),s("div",{key:"df413058c7e787f9c8a95a429a4f7186de07f5f6",class:"side side-right"}),s("div",{key:"37e074e3d4c914457f97720f9ab1f1ac2c70c4f1",class:"side side-bottom"}),s("div",{key:"772d3d40925c75ba5d39e2e7dd6405f7cc88d292",class:"side side-left"}),s("div",{key:"d4e624782b3f4b4b8dbb8286b3acf003e433928c",class:"corner corner-tl"}),s("div",{key:"63f0ccfbbe3c1d413ca6912f36cab4afa6334bb2",class:"corner corner-tr"}),s("div",{key:"20012a50fe3d98ddfa669f5283a871c757522797",class:"corner corner-bl"}),s("div",{key:"9d82646bd08a6ca2b8c5782629fc68fd93cf1287",class:"corner corner-br"}),!this.showFlipAnimation&&!this.showSuccessAnimation&&s("div",{key:"79fcbdb52e434a45aa6f2748d6d84500beb2e844",class:"guide-text"},this.statusMessage)),this.captureStep==="back"&&!this.showFlipAnimation&&!this.showSuccessAnimation&&s("button",{key:"16e587d645e2489a3410fe80bfc014738f08f02f",class:"skip-button",onClick:()=>this.skipBackCapture(),type:"button"},"Saltar reverso"),this.isVideoActive&&s("div",{key:"d46d6881a9e1b63bdd849f5a8c6e96a2caefdefb",class:"camera-controls"},this.isMultipleCamerasAvailable&&s("button",{key:"afb4b44d691471f8af6e894e061aecb6c82259da",class:"flip-camera-button",onClick:()=>this.flipCamera(),type:"button",title:"Cambiar cámara"},"Girar cámara"),s("button",{key:"4e0680c2da9e6cc70b5880e8f5db9830c080acf9",class:"camera-selector-button",onClick:()=>this.toggleCameraSelector(),type:"button",title:"Seleccionar cámara"},"Cámaras"),this.debug&&s("div",{key:"fc59922452a216273f742d3158559f6b2a1da43e",style:{position:"absolute",top:"50px",right:"0",background:"rgba(0,0,0,0.8)",color:"white",padding:"8px",fontSize:"10px",borderRadius:"4px",whiteSpace:"nowrap"}},"Cámaras: ",this.availableCameras.length,s("br",{key:"8f112283d1e0518a395dc6d94e1caa46fee0a86b"}),"Múltiples: ",this.isMultipleCamerasAvailable?"Sí":"No",s("br",{key:"aacfd3ee868ee5d0819ce5ef693e3ef384867332"}),"Selector: ",this.showCameraSelector?"Visible":"Oculto",s("br",{key:"9927df7f56583c7388cee25e13526efc7e032eb1"}),"Video: ",this.isVideoActive?"Activo":"Inactivo")),this.showCameraSelector&&this.availableCameras.length>0&&s("div",{key:"c2914bf7f3175b8f0ddab977abbdefe3022d7d29",class:"camera-selector-dropdown"},s("div",{key:"0b5397e77ff33944f3620d78b1ab41275dffd7ac",class:"camera-selector-header"},s("span",{key:"78f0fb8e34a0cf2d16138522a98cbdb9eefd671f"},"Seleccionar Cámara"),s("button",{key:"0d4ea7b191d61d1d9b9c35462ce336148be73fcb",class:"close-selector",onClick:()=>this.toggleCameraSelector(),type:"button"},"×")),s("div",{key:"c16c7a106493ef7633a4cd35b06a4f45327a2e23",class:"camera-list"},this.availableCameras.map((t=>s("button",{key:t.deviceId,class:`camera-option ${this.selectedCameraId===t.deviceId?"selected":""}`,onClick:()=>{this.switchCamera(t.deviceId);this.toggleCameraSelector()},type:"button"},s("span",{class:"camera-label"},t.label||`Cámara ${this.availableCameras.indexOf(t)+1}`),this.selectedCameraId===t.deviceId&&s("span",{class:"selected-indicator"},"✓"))))),s("div",{key:"11d6f980c3995a8414da5f7e6921f963ca72aed4",class:"device-info"},s("small",{key:"78f5ff030f9e6e5021234a246599eb459b05d9f7"},"Dispositivo: ",this.deviceType)))),this.isCapturing&&s("div",{key:"ef7d32491d8bdb94b2d6456420c2ddbc80f03d81",class:"capture-animation"}),this.showFlipAnimation&&s("div",{key:"cfb5868ee75a9d1d1604c52f6fce1241090e4ac2",class:"flip-animation"},s("div",{key:"1b41035e63f88434aba6699d4e68e06bea2c1529",class:"id-card-icon"}),s("div",{key:"4e83af9d0d39ce37b7448c4a0783b60b42b858e2",class:"flip-text"},"¡Voltea tu identificación!")),this.showSuccessAnimation&&s("div",{key:"c7911e8be74b0fc7d7d18d7dcb52374645ca5f12",class:"success-animation"},s("div",{key:"18e5ea5cfa3eb35fe3b99c12e6fab8e27e09e85e",class:"check-icon"}),s("div",{key:"490d8fcd6540c3b4fdc95f7fb5e6f6697722c9ac",class:"success-text"},"¡Proceso completado!")),this.isLoading&&s("div",{key:"f7fbfec6be2d8e0dc4e522b85b7d67897575cf0e",class:"loading-overlay"},s("div",{key:"8282b92f19da6a9c7d22a64a0929b2b4d67c46be",class:"loading-spinner"}),s("div",{key:"7880b689297eb9d80a9b0023ba7933148fd8710a",class:"loading-text"},this.statusMessage)),s("div",{key:"887c951fb03097171d9bd466fe24e36d11a49954",class:"watermark"},s("img",{key:"314c9c172a4c6795c825741ea6f02b0e1186e93d",src:"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png",alt:"Powered by Jaak"}))))}};o.style=a;export{o as jaak_stamps};
2
- //# sourceMappingURL=p-14eb13d8.entry.js.map
@@ -1 +0,0 @@
1
- {"version":3,"names":["myComponentCss","JaakStamps","debug","alignmentTolerance","maskSize","cropMargin","useDocumentClassification","preferredCamera","captureCompleted","isReady","isVideoActive","statusMessage","statusColor","bestScore","capturedFullFrame","capturedCroppedId","capturedBackFullFrame","capturedBackCroppedId","captureStep","isCapturing","showFlipAnimation","showSuccessAnimation","shouldMirrorVideo","sideAlignment","top","right","bottom","left","isDetectionPaused","isLoading","isModelPreloaded","isMaskReady","availableCameras","selectedCameraId","showCameraSelector","isMultipleCamerasAvailable","videoRef","canvasRef","session","startTime","videoStream","animationId","hasScreenshotTaken","lastDetectedBox","mobileNetSession","mobileNetClassMap","deviceType","preferredCameraFacing","frameSkipCounter","FRAME_SKIP","consecutiveFailures","MAX_FAILURES","lastInferenceTime","MIN_INFERENCE_INTERVAL","preprocessCanvas","preprocessCtx","captureCanvas","captureCtx","MODEL_PATH","MOBILENET_MODEL_PATH","MOBILENET_CLASSES_PATH","INPUT_SIZE","CONFIDENCE_THRESHOLD","ID1_ASPECT_RATIO","debugLog","args","this","console","log","validateMaskSize","warn","validateCropMargin","validatePreferredCamera","validOptions","includes","join","emitReadyEvent","isDocumentReady","window","ort","emit","isRearCamera","stream","videoTrack","getVideoTracks","settings","getSettings","facingMode","detectDeviceTypeAndCameras","userAgent","navigator","isMobile","test","isTablet","innerWidth","enumerateAndDetectCameras","loadCameraPreference","permissionStatus","checkCameraPermission","tempStream","mediaDevices","getUserMedia","video","getTracks","forEach","track","stop","devices","enumerateDevices","filter","device","kind","length","count","cameras","map","cam","id","deviceId","label","setInitialCameraPreference","error","handleCameraPermissionError","permissions","permission","query","name","state","frontCamera","find","camera","toLowerCase","backCamera","rearCamera","saved","localStorage","getItem","preference","JSON","parse","isStillAvailable","some","cameraId","facing","saveCameraPreference","timestamp","Date","now","setItem","stringify","switchCamera","selectedCamera","setupCameraWithRetry","maxRetries","attempt","setupCamera","Promise","resolve","setTimeout","toggleCameraSelector","flipCamera","currentIndex","findIndex","nextIndex","nextCamera","componentDidLoad","script","document","createElement","src","head","appendChild","onload","initializeCanvasPool","setupResizeObserver","resizeObserver","ResizeObserver","handleResize","observe","parentElement","container","rect","getBoundingClientRect","width","height","updateMaskDimensions","containerRect","videoWidth","videoHeight","videoAspectRatio","containerAspectRatio","displayedVideoWidth","displayedVideoHeight","videoOffsetX","videoOffsetY","maxWidthByHeight","maskWidthInVideo","maskHeightInVideo","sizeRatio","maskWidthPercent","maskHeightPercent","videoCenterX","videoCenterY","videoCenterXPercent","videoCenterYPercent","el","style","setProperty","displayed","mask","widthPercent","heightPercent","center","x","y","offset","getContext","alpha","willReadFrequently","disconnectedCallback","cleanup","getCapturedImages","Error","front","fullFrame","cropped","back","metadata","hasBackCapture","totalImages","isProcessCompleted","startCapture","startDetection","stopCapture","exitSession","resetCapture","resetDetection","getStatus","hasImages","preloadModel","success","message","modelPath","sessionOptions","getSessionOptions","InferenceSession","create","loadMobileNetModel","skipBackCapture","completeProcess","getCameraInfo","selected","preferredFacing","userPreferredCamera","setPreferredCamera","classResponse","fetch","ok","json","preprocessMobileNet","canvas","tempCanvas","tempCtx","drawImage","imageData","getImageData","data","hw","arr","Float32Array","i","Tensor","classifyDocument","inputTensor","feeds","input","results","run","output","Object","keys","maxIdx","reduce","bestIdx","val","idx","confidence","className","toString","class","toFixed","classIndex","cancelAnimationFrame","ctx","clearRect","cleanupCanvasPool","undefined","release","getMaxResolution","videoConstraints","exact","capabilities","getCapabilities","constraints","maxWidth","Math","min","max","maxHeight","ideal","selectedWidth","selectedHeight","err","fallbackConstraints","audio","srcObject","isRear","onloadedmetadata","async","play","preprocess","R","G","B","push","transposedData","concat","executionProviders","graphOptimizationLevel","logSeverityLevel","logVerbosityLevel","enableCpuMemArena","enableMemPattern","executionMode","interOpNumThreads","intraOpNumThreads","detectFrame","requestAnimationFrame","currentTime","inputNames","outputNames","finalBoxes","x1","y1","x2","y2","score","classId","slice","w","h","currentBox","isWellPositioned","isCardInFrame","effectiveScore","drawDetections","updateGuidanceStatus","updateMaskColor","e","box","cardCenterX","cardCenterY","frameCenterX","frameCenterY","toleranceX","toleranceY","isCentered","abs","isGoodSize","checkSideAlignment","visualMaskWidth","visualMaskHeight","modelMaskWidth","modelMaskHeight","maskCenterX","maskCenterY","maskLeft","maskRight","maskTop","maskBottom","docLeft","docRight","docTop","docBottom","originalDocLeft","originalDocRight","tolerance","areAllSidesAligned","alignment","boxes","cardOutline","shadowRoot","querySelector","corners","querySelectorAll","topSide","rightSide","bottomSide","leftSide","bestBox","currentAlignment","best","current","classList","toggle","allSidesAligned","add","corner","takeScreenshot","catch","remove","alignedSides","Boolean","containerWidth","containerHeight","scaleX","scaleY","det","strokeStyle","lineWidth","strokeRect","triggerCaptureAnimation","cropX","cropY","cropWidth","cropHeight","croppedCanvas","croppedCtx","toDataURL","classification","stopDetection","skippedBack","capturedImages","toISOString","processCompleted","backCaptureSkipped","render","key","ref","autoplay","muted","playsinline","display","onClick","type","title","position","background","color","padding","fontSize","borderRadius","whiteSpace","indexOf","alt"],"sources":["src/components/my-component/my-component.css?tag=jaak-stamps&encapsulation=shadow","src/components/my-component/my-component.tsx"],"sourcesContent":[":host {\n display: block;\n width: 100%;\n height: 100%;\n font-family: system-ui, -apple-system, sans-serif;\n color: #1a1a1a;\n}\n\n.detector-container {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n}\n\nh1 {\n font-size: 24px;\n font-weight: 500;\n color: #333;\n margin: 0 0 24px 0;\n}\n\n.video-container {\n position: relative;\n width: 100%;\n height: 100%;\n background: #333;\n border: 1px solid #e0e0e0;\n border-radius: 8px;\n overflow: hidden;\n}\n\nvideo, canvas {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 8px;\n}\n\nvideo.mirror, canvas.mirror {\n transform: rotateY(180deg);\n}\n\ncanvas { \n z-index: 1; \n}\n\nvideo { \n z-index: 0; \n}\n\n\n.status {\n margin-top: 16px;\n font-size: 12px;\n color: #666;\n}\n\n/* Overlay mask for ID card guidance */\n.overlay-mask {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 10;\n display: block;\n pointer-events: none;\n}\n\n.card-outline {\n position: absolute;\n top: var(--mask-center-y, 50%);\n left: var(--mask-center-x, 50%);\n transform: translate(-50%, -50%);\n width: var(--mask-width, 88%);\n height: var(--mask-height, 55%);\n border: none;\n border-radius: 4px;\n background: transparent;\n box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7);\n opacity: 0.8;\n}\n\n.card-outline.perfect-match {\n box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7);\n}\n\n/* Lados individuales de la máscara */\n.side {\n position: absolute;\n background: #999;\n transition: background-color 0.3s ease;\n}\n\n.side.aligned {\n background: #28a745;\n}\n\n.side-top {\n top: 0;\n left: 0;\n width: 100%;\n height: 3px;\n}\n\n.side-right {\n top: 0;\n right: 0;\n width: 3px;\n height: 100%;\n}\n\n.side-bottom {\n bottom: 0;\n left: 0;\n width: 100%;\n height: 3px;\n}\n\n.side-left {\n top: 0;\n left: 0;\n width: 3px;\n height: 100%;\n}\n\n.corner {\n position: absolute;\n width: 20px;\n height: 20px;\n border: 2px solid #999;\n z-index: 12;\n}\n\n.corner-tl {\n top: -10px;\n left: -10px;\n border-right: none;\n border-bottom: none;\n}\n\n.corner-tr {\n top: -10px;\n right: -10px;\n border-left: none;\n border-bottom: none;\n}\n\n.corner-bl {\n bottom: -10px;\n left: -10px;\n border-right: none;\n border-top: none;\n}\n\n.corner-br {\n bottom: -10px;\n right: -10px;\n border-left: none;\n border-top: none;\n}\n\n.corner.perfect-match {\n border-color: #28a745;\n}\n\n.guide-text {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n color: #fff;\n font-size: 14px;\n font-weight: 600;\n text-align: center;\n white-space: normal;\n background: rgba(128, 128, 128, 0.8);\n padding: 12px 20px;\n border-radius: 20px;\n max-width: 300px;\n z-index: 20;\n}\n\n\n/* Animación de captura */\n.capture-animation {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: #fff;\n opacity: 0;\n z-index: 30;\n pointer-events: none;\n animation: captureFlash 0.6s ease-out;\n}\n\n@keyframes captureFlash {\n 0% {\n opacity: 0;\n }\n 15% {\n opacity: 0.8;\n }\n 30% {\n opacity: 0;\n }\n 45% {\n opacity: 0.4;\n }\n 60% {\n opacity: 0;\n }\n 100% {\n opacity: 0;\n }\n}\n\n/* Animación del marco durante captura */\n.card-outline.capturing {\n animation: pulseGreen 0.6s ease-out;\n}\n\n@keyframes pulseGreen {\n 0% {\n border-color: #28a745;\n box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0);\n }\n 50% {\n border-color: #28a745;\n box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 8px rgba(40, 167, 69, 0.6);\n }\n 100% {\n border-color: #28a745;\n box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0);\n }\n}\n\n/* Animación de voltear identificación */\n.flip-animation {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 35;\n pointer-events: none;\n opacity: 0;\n animation: showFlipInstruction 3s ease-in-out;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n}\n\n.id-card-icon {\n width: 80px;\n height: 50px;\n background: linear-gradient(135deg, #6c757d 0%, #495057 100%);\n border-radius: 8px;\n position: relative;\n animation: flipCard 2s ease-in-out infinite;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n}\n\n.id-card-icon::before {\n content: '';\n position: absolute;\n top: 8px;\n left: 8px;\n width: 16px;\n height: 12px;\n background: rgba(255, 255, 255, 0.9);\n border-radius: 2px;\n}\n\n.id-card-icon::after {\n content: '';\n position: absolute;\n top: 25px;\n left: 8px;\n width: 64px;\n height: 3px;\n background: rgba(255, 255, 255, 0.7);\n border-radius: 1px;\n box-shadow: 0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7);\n}\n\n.flip-text {\n margin-top: 12px;\n color: #fff;\n font-size: 14px;\n font-weight: 600;\n text-align: center;\n background: rgba(128, 128, 128, 0.8);\n padding: 12px 20px;\n border-radius: 20px;\n max-width: 300px;\n}\n\n@keyframes showFlipInstruction {\n 0% {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.8);\n }\n 15% {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n 85% {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n 100% {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.8);\n }\n}\n\n@keyframes flipCard {\n 0% {\n transform: rotateY(0deg);\n }\n 50% {\n transform: rotateY(180deg);\n }\n 100% {\n transform: rotateY(360deg);\n }\n}\n\n/* Animación de éxito */\n.success-animation {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n z-index: 35;\n pointer-events: none;\n opacity: 0;\n animation: showSuccessMessage 3s ease-in-out;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n}\n\n.check-icon {\n width: 80px;\n height: 80px;\n background: linear-gradient(135deg, #6c757d 0%, #495057 100%);\n border-radius: 50%;\n position: relative;\n animation: bounceSuccess 0.6s ease-out;\n box-shadow: 0 4px 16px rgba(108, 117, 125, 0.4);\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.check-icon::before {\n content: '';\n position: absolute;\n width: 20px;\n height: 35px;\n border: 4px solid #fff;\n border-top: none;\n border-left: none;\n transform: rotate(45deg);\n animation: drawCheck 0.4s ease-out 0.2s both;\n}\n\n.success-text {\n margin-top: 16px;\n color: #fff;\n font-size: 14px;\n font-weight: 600;\n text-align: center;\n background: rgba(128, 128, 128, 0.8);\n padding: 12px 20px;\n border-radius: 20px;\n max-width: 300px;\n animation: fadeInUp 0.5s ease-out 0.4s both;\n}\n\n@keyframes showSuccessMessage {\n 0% {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.5);\n }\n 15% {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n 85% {\n opacity: 1;\n transform: translate(-50%, -50%) scale(1);\n }\n 100% {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.9);\n }\n}\n\n@keyframes bounceSuccess {\n 0% {\n transform: scale(0);\n }\n 50% {\n transform: scale(1.1);\n }\n 100% {\n transform: scale(1);\n }\n}\n\n@keyframes drawCheck {\n 0% {\n width: 0;\n height: 0;\n }\n 50% {\n width: 20px;\n height: 0;\n }\n 100% {\n width: 20px;\n height: 35px;\n }\n}\n\n@keyframes fadeInUp {\n 0% {\n opacity: 0;\n transform: translateY(20px);\n }\n 100% {\n opacity: 1;\n transform: translateY(0);\n }\n}\n\n/* Bot\\u00f3n para saltar reverso */\n.skip-button {\n position: absolute;\n bottom: 20px;\n left: 50%;\n transform: translateX(-50%);\n z-index: 25;\n pointer-events: auto;\n background: #fff;\n color: #333;\n border: none;\n border-radius: 25px;\n padding: 12px 24px;\n font-size: 14px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.3s ease;\n}\n\n.skip-button:hover {\n background: #f8f9fa;\n}\n\n.skip-button:active {\n background: #e9ecef;\n transform: translateX(-50%) translateY(0);\n}\n\n/* Camera controls */\n.camera-controls {\n position: absolute;\n top: 16px;\n right: 16px;\n z-index: 25;\n display: flex;\n gap: 8px;\n pointer-events: auto;\n}\n\n.flip-camera-button {\n height: 40px;\n padding: 0 16px;\n border: none;\n border-radius: 8px;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(12px);\n color: #ffffff;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n border: 1px solid rgba(255, 255, 255, 0.1);\n white-space: nowrap;\n min-width: fit-content;\n}\n\n.camera-selector-button {\n height: 40px;\n padding: 0 16px;\n border: none;\n border-radius: 8px;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(12px);\n color: #ffffff;\n font-size: 12px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n border: 1px solid rgba(255, 255, 255, 0.1);\n white-space: nowrap;\n min-width: fit-content;\n}\n\n.flip-camera-button:hover,\n.camera-selector-button:hover {\n background: rgba(0, 0, 0, 0.8);\n border-color: rgba(255, 255, 255, 0.2);\n transform: translateY(-1px);\n}\n\n.flip-camera-button:active,\n.camera-selector-button:active {\n transform: translateY(0);\n background: rgba(0, 0, 0, 0.9);\n}\n\n/* Camera selector dropdown */\n.camera-selector-dropdown {\n position: absolute;\n top: 56px;\n right: 16px;\n z-index: 30;\n background: rgba(0, 0, 0, 0.85);\n backdrop-filter: blur(20px);\n border-radius: 12px;\n min-width: 260px;\n max-width: 300px;\n border: 1px solid rgba(255, 255, 255, 0.1);\n overflow: hidden;\n pointer-events: auto;\n animation: slideInFromTop 0.3s ease-out;\n}\n\n@keyframes slideInFromTop {\n 0% {\n opacity: 0;\n transform: translateY(-8px) scale(0.95);\n }\n 100% {\n opacity: 1;\n transform: translateY(0) scale(1);\n }\n}\n\n.camera-selector-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 12px 16px;\n border-bottom: 1px solid rgba(255, 255, 255, 0.1);\n}\n\n.camera-selector-header span {\n font-weight: 500;\n color: #ffffff;\n font-size: 13px;\n opacity: 0.9;\n}\n\n.close-selector {\n width: 20px;\n height: 20px;\n border: none;\n background: none;\n color: rgba(255, 255, 255, 0.7);\n font-size: 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: all 0.2s ease;\n}\n\n.close-selector:hover {\n background: rgba(255, 255, 255, 0.1);\n color: #ffffff;\n}\n\n.camera-list {\n padding: 4px 0;\n max-height: 240px;\n overflow-y: auto;\n}\n\n.camera-option {\n width: 100%;\n padding: 10px 16px;\n border: none;\n background: none;\n text-align: left;\n cursor: pointer;\n transition: all 0.2s ease;\n display: flex;\n justify-content: space-between;\n align-items: center;\n color: rgba(255, 255, 255, 0.9);\n}\n\n.camera-option:hover {\n background: rgba(255, 255, 255, 0.08);\n}\n\n.camera-option.selected {\n background: rgba(255, 255, 255, 0.12);\n color: #ffffff;\n}\n\n.camera-label {\n font-size: 13px;\n flex: 1;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-right: 8px;\n font-weight: 400;\n}\n\n.selected-indicator {\n font-size: 14px;\n color: #ffffff;\n opacity: 0.9;\n}\n\n.device-info {\n padding: 8px 16px;\n border-top: 1px solid rgba(255, 255, 255, 0.1);\n background: rgba(255, 255, 255, 0.05);\n}\n\n.device-info small {\n color: rgba(255, 255, 255, 0.6);\n font-size: 11px;\n text-transform: capitalize;\n font-weight: 400;\n}\n\n/* Responsive design for camera controls */\n@media (max-width: 480px) {\n .camera-controls {\n top: 12px;\n right: 12px;\n gap: 6px;\n }\n \n .flip-camera-button {\n height: 36px;\n padding: 0 12px;\n font-size: 11px;\n border-radius: 6px;\n }\n \n .camera-selector-button {\n height: 36px;\n padding: 0 12px;\n font-size: 11px;\n border-radius: 6px;\n }\n \n .camera-selector-dropdown {\n right: 12px;\n top: 48px;\n min-width: 240px;\n max-width: calc(100vw - 24px);\n }\n \n .camera-selector-header {\n padding: 10px 14px;\n }\n \n .camera-option {\n padding: 8px 14px;\n }\n \n .device-info {\n padding: 6px 14px;\n }\n}\n\n/* Marca de agua */\n.watermark {\n position: absolute;\n bottom: 12px;\n right: 12px;\n z-index: 15;\n pointer-events: none;\n opacity: 0.7;\n}\n\n.watermark img {\n height: 24px;\n width: auto;\n filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));\n}\n\n/* Animación de carga */\n.loading-overlay {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n z-index: 30;\n border-radius: 20px;\n}\n\n.loading-spinner {\n width: 60px;\n height: 60px;\n border: 4px solid rgba(255, 255, 255, 0.2);\n border-top: 4px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin-bottom: 20px;\n}\n\n.loading-text {\n color: white;\n font-size: 16px;\n font-weight: 500;\n text-align: center;\n opacity: 0.9;\n}\n\n@keyframes spin {\n 0% {\n transform: rotate(0deg);\n }\n 100% {\n transform: rotate(360deg);\n }\n}","import { Component, Element, State, Prop, Method, Event, EventEmitter, h } from '@stencil/core';\n\n@Component({\n tag: 'jaak-stamps',\n styleUrl: 'my-component.css',\n shadow: true,\n})\nexport class JaakStamps {\n @Element() el!: HTMLElement;\n @Prop() debug: boolean = false;\n @Prop() alignmentTolerance: number = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)\n @Prop() maskSize: number = 90; // Porcentaje del video que ocupará la máscara (default 90%)\n @Prop() cropMargin: number = 0; // Margen en píxeles para el recorte del documento (default 0)\n @Prop() useDocumentClassification: boolean = false; // Habilita la clasificación automática de documentos para determinar si solicitar reverso\n @Prop() preferredCamera: 'auto' | 'front' | 'back' = 'auto'; // Define qué cámara usar: 'auto' (automático según dispositivo), 'front' (frontal), 'back' (trasera)\n \n @Event() captureCompleted: EventEmitter<any>;\n @Event() isReady: EventEmitter<boolean>;\n \n @State() isVideoActive: boolean = false;\n @State() statusMessage: string = 'Presione el botón para activar la cámara';\n @State() statusColor: string = '#aaa';\n @State() bestScore: number = 0;\n @State() capturedFullFrame: string | null = null;\n @State() capturedCroppedId: string | null = null;\n @State() capturedBackFullFrame: string | null = null;\n @State() capturedBackCroppedId: string | null = null;\n @State() captureStep: 'front' | 'back' | 'completed' = 'front';\n @State() isCapturing: boolean = false;\n @State() showFlipAnimation: boolean = false;\n @State() showSuccessAnimation: boolean = false;\n @State() shouldMirrorVideo: boolean = true;\n @State() sideAlignment: { top: boolean; right: boolean; bottom: boolean; left: boolean } = {\n top: false,\n right: false,\n bottom: false,\n left: false\n };\n @State() isDetectionPaused: boolean = false;\n @State() isLoading: boolean = false;\n @State() isModelPreloaded: boolean = false;\n @State() isMaskReady: boolean = false;\n @State() availableCameras: MediaDeviceInfo[] = [];\n @State() selectedCameraId: string | null = null;\n @State() showCameraSelector: boolean = false;\n @State() isMultipleCamerasAvailable: boolean = false;\n \n private videoRef?: HTMLVideoElement;\n private canvasRef?: HTMLCanvasElement;\n private session?: any;\n private startTime?: number;\n private videoStream?: MediaStream;\n private animationId?: number;\n private hasScreenshotTaken: boolean = false;\n private lastDetectedBox?: any;\n private mobileNetSession?: any;\n private mobileNetClassMap?: any;\n \n // Camera management properties\n private deviceType: 'mobile' | 'desktop' | 'tablet' = 'desktop';\n private preferredCameraFacing: 'environment' | 'user' | null = null;\n \n // Performance optimization properties\n private frameSkipCounter: number = 0;\n private readonly FRAME_SKIP: number = 2; // Process every 3rd frame (reduces CPU by ~66%)\n private consecutiveFailures: number = 0;\n private readonly MAX_FAILURES: number = 30; // 0.5 seconds without detection\n private lastInferenceTime: number = 0;\n private readonly MIN_INFERENCE_INTERVAL: number = 50; // Minimum 50ms between inferences\n \n // Canvas pooling for memory optimization\n private preprocessCanvas?: HTMLCanvasElement;\n private preprocessCtx?: CanvasRenderingContext2D;\n private captureCanvas?: HTMLCanvasElement;\n private captureCtx?: CanvasRenderingContext2D;\n \n private readonly MODEL_PATH = \"https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx\";\n private readonly MOBILENET_MODEL_PATH = \"https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx\";\n private readonly MOBILENET_CLASSES_PATH = \"https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json\";\n private readonly INPUT_SIZE = 320;\n private readonly CONFIDENCE_THRESHOLD = 0.6;\n // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)\n private readonly ID1_ASPECT_RATIO = 85.60 / 53.98; // 1.5863320574...\n\n private debugLog(...args: any[]) {\n if (this.debug) {\n console.log(...args);\n }\n }\n\n private validateMaskSize() {\n if (this.maskSize < 50 || this.maskSize > 100) {\n console.warn(`maskSize debe estar entre 50 y 100. Valor actual: ${this.maskSize}. Usando valor por defecto: 90`);\n this.maskSize = 90;\n }\n }\n\n private validateCropMargin() {\n if (this.cropMargin < 0 || this.cropMargin > 100) {\n console.warn(`cropMargin debe estar entre 0 y 100. Valor actual: ${this.cropMargin}. Usando valor por defecto: 0`);\n this.cropMargin = 0;\n }\n }\n\n private validatePreferredCamera() {\n const validOptions = ['auto', 'front', 'back'];\n if (!validOptions.includes(this.preferredCamera)) {\n console.warn(`preferredCamera debe ser uno de: ${validOptions.join(', ')}. Valor actual: ${this.preferredCamera}. Usando valor por defecto: 'auto'`);\n this.preferredCamera = 'auto';\n }\n }\n\n private emitReadyEvent() {\n const isDocumentReady = !!(window as any).ort && this.isModelPreloaded;\n this.isReady.emit(isDocumentReady);\n this.debugLog('🟢 isReady event emitted:', isDocumentReady);\n }\n\n\n\n private isRearCamera(stream: MediaStream): boolean {\n const videoTrack = stream.getVideoTracks()[0];\n if (!videoTrack) return false;\n \n const settings = videoTrack.getSettings();\n return settings.facingMode === 'environment';\n }\n\n private async detectDeviceTypeAndCameras() {\n // Detect device type\n const userAgent = navigator.userAgent;\n const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);\n const isTablet = /iPad|Android/i.test(userAgent) && window.innerWidth >= 768;\n \n if (isTablet) {\n this.deviceType = 'tablet';\n } else if (isMobile) {\n this.deviceType = 'mobile';\n } else {\n this.deviceType = 'desktop';\n }\n \n this.debugLog('📱 Device type detected:', this.deviceType);\n \n // Enumerate available cameras\n await this.enumerateAndDetectCameras();\n \n // Load user preference\n this.loadCameraPreference();\n }\n\n private async enumerateAndDetectCameras() {\n try {\n // First, check if we have permission to enumerate devices\n const permissionStatus = await this.checkCameraPermission();\n \n if (permissionStatus === 'denied') {\n this.debugLog('❌ Camera permission denied');\n this.statusMessage = \"Permiso de cámara denegado\";\n this.statusColor = \"#ff6b6b\";\n return;\n }\n \n // Request minimal permission to get device labels\n if (permissionStatus === 'prompt') {\n const tempStream = await navigator.mediaDevices.getUserMedia({ video: true });\n tempStream.getTracks().forEach(track => track.stop());\n }\n \n // Now enumerate devices with labels\n const devices = await navigator.mediaDevices.enumerateDevices();\n this.availableCameras = devices.filter(device => device.kind === 'videoinput');\n \n this.isMultipleCamerasAvailable = this.availableCameras.length > 1;\n \n this.debugLog('📹 Available cameras:', {\n count: this.availableCameras.length,\n isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,\n cameras: this.availableCameras.map(cam => ({\n id: cam.deviceId,\n label: cam.label || 'Unknown Camera'\n }))\n });\n \n // Set initial camera preference based on device type\n this.setInitialCameraPreference();\n \n } catch (error) {\n this.debugLog('❌ Error enumerating cameras:', error);\n this.handleCameraPermissionError(error);\n }\n }\n\n private async checkCameraPermission(): Promise<'granted' | 'denied' | 'prompt'> {\n try {\n if (!navigator.permissions) {\n return 'prompt'; // Assume we need to prompt on older browsers\n }\n \n const permission = await navigator.permissions.query({ name: 'camera' as PermissionName });\n return permission.state;\n } catch (error) {\n this.debugLog('⚠️ Could not check camera permission:', error);\n return 'prompt';\n }\n }\n\n private handleCameraPermissionError(error: any) {\n if (error.name === 'NotAllowedError') {\n this.statusMessage = \"Permiso de cámara denegado. Active el permiso en configuración.\";\n this.statusColor = \"#ff6b6b\";\n this.availableCameras = [];\n this.isMultipleCamerasAvailable = false;\n } else if (error.name === 'NotFoundError') {\n this.statusMessage = \"No se encontraron cámaras disponibles.\";\n this.statusColor = \"#ff6b6b\";\n this.availableCameras = [];\n this.isMultipleCamerasAvailable = false;\n } else if (error.name === 'NotReadableError') {\n this.statusMessage = \"Cámara en uso por otra aplicación.\";\n this.statusColor = \"#ff6b6b\";\n this.availableCameras = [];\n this.isMultipleCamerasAvailable = false;\n } else {\n this.statusMessage = \"Error al acceder a las cámaras.\";\n this.statusColor = \"#ff6b6b\";\n this.availableCameras = [];\n this.isMultipleCamerasAvailable = false;\n }\n }\n\n private setInitialCameraPreference() {\n if (this.availableCameras.length === 0) return;\n \n // Apply user preference for camera selection\n if (this.preferredCamera === 'front') {\n // User explicitly wants front camera\n this.preferredCameraFacing = 'user';\n \n const frontCamera = this.availableCameras.find(camera => \n camera.label.toLowerCase().includes('front') || \n camera.label.toLowerCase().includes('user') ||\n camera.label.toLowerCase().includes('selfie') ||\n !camera.label.toLowerCase().includes('back') && !camera.label.toLowerCase().includes('rear')\n );\n \n if (frontCamera) {\n this.selectedCameraId = frontCamera.deviceId;\n this.debugLog('👤 User selected front camera:', frontCamera.label);\n } else {\n this.selectedCameraId = this.availableCameras[0].deviceId;\n this.debugLog('⚠️ Front camera not found, using first available:', this.availableCameras[0].label);\n }\n } else if (this.preferredCamera === 'back') {\n // User explicitly wants back camera\n this.preferredCameraFacing = 'environment';\n \n const backCamera = this.availableCameras.find(camera => \n camera.label.toLowerCase().includes('back') || \n camera.label.toLowerCase().includes('rear') ||\n camera.label.toLowerCase().includes('environment')\n );\n \n if (backCamera) {\n this.selectedCameraId = backCamera.deviceId;\n this.debugLog('📷 User selected back camera:', backCamera.label);\n } else {\n this.selectedCameraId = this.availableCameras[0].deviceId;\n this.debugLog('⚠️ Back camera not found, using first available:', this.availableCameras[0].label);\n }\n } else {\n // Auto mode - use device type to determine best camera\n if (this.deviceType === 'mobile' || this.deviceType === 'tablet') {\n // For mobile/tablet, prefer rear camera for document scanning\n this.preferredCameraFacing = 'environment';\n \n const rearCamera = this.availableCameras.find(camera => \n camera.label.toLowerCase().includes('back') || \n camera.label.toLowerCase().includes('rear') ||\n camera.label.toLowerCase().includes('environment')\n );\n \n if (rearCamera) {\n this.selectedCameraId = rearCamera.deviceId;\n this.debugLog('📱 Auto-selected rear camera for mobile:', rearCamera.label);\n } else {\n this.selectedCameraId = this.availableCameras[0].deviceId;\n this.debugLog('📱 Rear camera not found, using first available:', this.availableCameras[0].label);\n }\n } else {\n // For desktop, use first available camera (usually the only one)\n this.selectedCameraId = this.availableCameras[0].deviceId;\n this.debugLog('💻 Auto-selected desktop camera:', this.availableCameras[0].label);\n }\n }\n }\n\n private loadCameraPreference() {\n try {\n const saved = localStorage.getItem('jaak-stamps-camera-preference');\n if (saved) {\n const preference = JSON.parse(saved);\n \n // Validate that the saved camera is still available\n const isStillAvailable = this.availableCameras.some(\n camera => camera.deviceId === preference.cameraId\n );\n \n if (isStillAvailable) {\n this.selectedCameraId = preference.cameraId;\n this.preferredCameraFacing = preference.facing;\n this.debugLog('💾 Loaded camera preference:', preference);\n }\n }\n } catch (error) {\n this.debugLog('⚠️ Error loading camera preference:', error);\n }\n }\n\n private saveCameraPreference() {\n try {\n const preference = {\n cameraId: this.selectedCameraId,\n facing: this.preferredCameraFacing,\n timestamp: Date.now()\n };\n \n localStorage.setItem('jaak-stamps-camera-preference', JSON.stringify(preference));\n this.debugLog('💾 Saved camera preference:', preference);\n } catch (error) {\n this.debugLog('⚠️ Error saving camera preference:', error);\n }\n }\n\n private async switchCamera(cameraId: string) {\n if (!this.isVideoActive || this.selectedCameraId === cameraId) return;\n \n try {\n // Check if the selected camera is still available\n const selectedCamera = this.availableCameras.find(cam => cam.deviceId === cameraId);\n if (!selectedCamera) {\n this.debugLog('❌ Selected camera not found, re-enumerating...');\n await this.enumerateAndDetectCameras();\n return;\n }\n \n // Show loading state\n this.statusMessage = \"Cambiando cámara...\";\n this.statusColor = \"#007bff\";\n \n // Stop current stream\n if (this.videoStream) {\n this.videoStream.getTracks().forEach(track => track.stop());\n }\n \n // Update selected camera\n this.selectedCameraId = cameraId;\n \n // Update facing mode preference\n const isRearCamera = selectedCamera.label.toLowerCase().includes('back') || \n selectedCamera.label.toLowerCase().includes('rear') ||\n selectedCamera.label.toLowerCase().includes('environment');\n this.preferredCameraFacing = isRearCamera ? 'environment' : 'user';\n \n // Save preference\n this.saveCameraPreference();\n \n // Setup new camera with error handling\n await this.setupCameraWithRetry();\n \n this.debugLog('🔄 Switched to camera:', selectedCamera.label);\n \n } catch (error) {\n this.debugLog('❌ Error switching camera:', error);\n this.handleCameraPermissionError(error);\n }\n }\n\n private async setupCameraWithRetry(maxRetries: number = 3) {\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n await this.setupCamera();\n return; // Success\n } catch (error) {\n this.debugLog(`❌ Camera setup attempt ${attempt} failed:`, error);\n \n if (attempt === maxRetries) {\n // Last attempt failed, handle the error\n this.handleCameraPermissionError(error);\n throw error;\n }\n \n // Wait before retrying\n await new Promise(resolve => setTimeout(resolve, 500 * attempt));\n }\n }\n }\n\n private toggleCameraSelector() {\n this.showCameraSelector = !this.showCameraSelector;\n this.debugLog('📹 Camera selector toggled:', {\n showCameraSelector: this.showCameraSelector,\n isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,\n availableCameras: this.availableCameras.length,\n isVideoActive: this.isVideoActive\n });\n }\n\n private async flipCamera() {\n if (!this.isMultipleCamerasAvailable) return;\n \n const currentIndex = this.availableCameras.findIndex(\n camera => camera.deviceId === this.selectedCameraId\n );\n \n const nextIndex = (currentIndex + 1) % this.availableCameras.length;\n const nextCamera = this.availableCameras[nextIndex];\n \n await this.switchCamera(nextCamera.deviceId);\n }\n\n async componentDidLoad() {\n this.validateMaskSize();\n this.validateCropMargin();\n this.validatePreferredCamera();\n await this.detectDeviceTypeAndCameras();\n if (!(window as any).ort) {\n const script = document.createElement('script');\n script.src = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js';\n document.head.appendChild(script);\n \n // Wait for ONNX runtime to load before emitting ready event\n script.onload = () => {\n this.emitReadyEvent();\n };\n } else {\n // ONNX runtime already loaded\n this.emitReadyEvent();\n }\n \n // Initialize canvas pool for better performance\n this.initializeCanvasPool();\n this.setupResizeObserver();\n }\n\n private setupResizeObserver() {\n if ('ResizeObserver' in window && this.canvasRef) {\n const resizeObserver = new ResizeObserver(() => {\n this.handleResize();\n });\n resizeObserver.observe(this.canvasRef.parentElement!);\n }\n }\n\n private handleResize() {\n if (this.canvasRef) {\n const container = this.canvasRef.parentElement!;\n const rect = container.getBoundingClientRect();\n \n // Set canvas size to match container\n this.canvasRef.width = rect.width;\n this.canvasRef.height = rect.height;\n \n // Update mask positioning based on container and video dimensions\n this.updateMaskDimensions(rect);\n \n this.debugLog('📐 Canvas resized:', { width: rect.width, height: rect.height });\n }\n }\n\n private updateMaskDimensions(containerRect: DOMRect) {\n if (!this.videoRef) return;\n \n const videoWidth = this.videoRef.videoWidth;\n const videoHeight = this.videoRef.videoHeight;\n \n if (videoWidth === 0 || videoHeight === 0) return;\n \n // Calculate video aspect ratio and container aspect ratio\n const videoAspectRatio = videoWidth / videoHeight;\n const containerAspectRatio = containerRect.width / containerRect.height;\n \n // Determine how video fits in container (letterboxed or pillarboxed)\n let displayedVideoWidth, displayedVideoHeight;\n let videoOffsetX = 0, videoOffsetY = 0;\n \n if (videoAspectRatio > containerAspectRatio) {\n // Video is wider - letterboxed (black bars top/bottom)\n displayedVideoWidth = containerRect.width;\n displayedVideoHeight = containerRect.width / videoAspectRatio;\n videoOffsetY = (containerRect.height - displayedVideoHeight) / 2;\n } else {\n // Video is taller - pillarboxed (black bars left/right)\n displayedVideoHeight = containerRect.height;\n displayedVideoWidth = containerRect.height * videoAspectRatio;\n videoOffsetX = (containerRect.width - displayedVideoWidth) / 2;\n }\n \n // Calculate maximum possible mask size while preserving exact ID-1 aspect ratio\n // Determine the limiting dimension based on video orientation and ID-1 proportions\n \n // Calculate what would be the max width if limited by video height\n const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;\n \n let maskWidthInVideo, maskHeightInVideo;\n \n const sizeRatio = this.maskSize / 100;\n \n if (maxWidthByHeight <= displayedVideoWidth) {\n // Video height is the limiting factor\n maskHeightInVideo = displayedVideoHeight * sizeRatio;\n maskWidthInVideo = maskHeightInVideo * this.ID1_ASPECT_RATIO;\n } else {\n // Video width is the limiting factor\n maskWidthInVideo = displayedVideoWidth * sizeRatio;\n maskHeightInVideo = maskWidthInVideo / this.ID1_ASPECT_RATIO;\n }\n \n // Convert to percentages of the container\n const maskWidthPercent = (maskWidthInVideo / containerRect.width) * 100;\n const maskHeightPercent = (maskHeightInVideo / containerRect.height) * 100;\n \n // Calculate the center position of the displayed video area\n const videoCenterX = videoOffsetX + (displayedVideoWidth / 2);\n const videoCenterY = videoOffsetY + (displayedVideoHeight / 2);\n \n // Convert to percentages of the container\n const videoCenterXPercent = (videoCenterX / containerRect.width) * 100;\n const videoCenterYPercent = (videoCenterY / containerRect.height) * 100;\n \n // Update CSS custom properties for mask sizing and positioning\n this.el.style.setProperty('--mask-width', `${maskWidthPercent}%`);\n this.el.style.setProperty('--mask-height', `${maskHeightPercent}%`);\n this.el.style.setProperty('--mask-center-x', `${videoCenterXPercent}%`);\n this.el.style.setProperty('--mask-center-y', `${videoCenterYPercent}%`);\n \n // Mark mask as ready now that dimensions are calculated\n this.isMaskReady = true;\n \n this.debugLog('🎯 Mask dimensions updated:', {\n video: { width: videoWidth, height: videoHeight },\n displayed: { width: displayedVideoWidth, height: displayedVideoHeight },\n mask: { widthPercent: maskWidthPercent, heightPercent: maskHeightPercent },\n center: { x: videoCenterXPercent, y: videoCenterYPercent },\n offset: { x: videoOffsetX, y: videoOffsetY }\n });\n }\n \n private initializeCanvasPool() {\n // Preprocess canvas - reused for every inference\n this.preprocessCanvas = document.createElement('canvas');\n this.preprocessCanvas.width = this.INPUT_SIZE;\n this.preprocessCanvas.height = this.INPUT_SIZE;\n this.preprocessCtx = this.preprocessCanvas.getContext('2d', {\n alpha: false, // No transparency needed\n willReadFrequently: true // Optimize for frequent getImageData calls\n })!;\n \n // Capture canvas - reused for screenshots\n this.captureCanvas = document.createElement('canvas');\n this.captureCtx = this.captureCanvas.getContext('2d', {\n alpha: false\n })!;\n \n this.debugLog('🎨 Canvas pool initialized for performance');\n }\n\n disconnectedCallback() {\n this.cleanup();\n }\n\n @Method()\n async getCapturedImages() {\n if (this.captureStep !== 'completed') {\n throw new Error('El proceso de captura no ha sido completado');\n }\n\n return {\n front: {\n fullFrame: this.capturedFullFrame,\n cropped: this.capturedCroppedId\n },\n back: {\n fullFrame: this.capturedBackFullFrame,\n cropped: this.capturedBackCroppedId\n },\n metadata: {\n hasBackCapture: !!(this.capturedBackFullFrame && this.capturedBackCroppedId),\n totalImages: (this.capturedBackFullFrame && this.capturedBackCroppedId) ? 4 : 2\n }\n };\n }\n\n @Method()\n async isProcessCompleted() {\n return this.captureStep === 'completed';\n }\n\n @Method()\n async startCapture() {\n await this.startDetection();\n }\n\n @Method()\n async stopCapture() {\n this.exitSession();\n }\n\n @Method()\n async resetCapture() {\n this.resetDetection();\n }\n\n @Method()\n async getStatus() {\n return {\n isVideoActive: this.isVideoActive,\n captureStep: this.captureStep,\n statusMessage: this.statusMessage,\n hasImages: !!(this.capturedFullFrame || this.capturedBackFullFrame),\n isProcessCompleted: this.captureStep === 'completed',\n isModelPreloaded: this.isModelPreloaded\n };\n }\n\n @Method()\n async preloadModel() {\n if (this.isModelPreloaded || this.session) {\n this.debugLog('🚀 Model already preloaded or session exists');\n return { success: true, message: 'Model already loaded' };\n }\n\n try {\n this.isLoading = true;\n this.statusMessage = \"Precargando modelos...\";\n this.statusColor = \"#007bff\";\n \n const modelPath = this.MODEL_PATH;\n this.debugLog('🤖 Preloading detection model:', modelPath);\n \n // Configure ONNX Runtime with device-specific optimizations\n const sessionOptions = this.getSessionOptions();\n \n this.session = await (window as any).ort.InferenceSession.create(modelPath, sessionOptions);\n \n // Preload MobileNet model and classes only if classification is enabled\n if (this.useDocumentClassification) {\n await this.loadMobileNetModel();\n }\n \n this.isModelPreloaded = true;\n this.isLoading = false;\n this.statusMessage = \"Modelos precargados. Listo para comenzar detección\";\n this.statusColor = \"#28a745\";\n \n this.emitReadyEvent();\n this.debugLog('✅ Models preloaded successfully');\n return { success: true, message: 'Models preloaded successfully' };\n } catch (error) {\n this.debugLog('❌ Error preloading models:', error);\n this.isLoading = false;\n this.statusMessage = \"Error al precargar los modelos\";\n this.statusColor = \"#ff6b6b\";\n return { success: false, error: error.message };\n }\n }\n\n @Method()\n async skipBackCapture() {\n if (this.captureStep === 'back' && this.capturedFullFrame) {\n this.completeProcess(true);\n }\n }\n\n @Method()\n async getCameraInfo() {\n return {\n availableCameras: this.availableCameras.map(camera => ({\n id: camera.deviceId,\n label: camera.label || 'Unknown Camera',\n selected: camera.deviceId === this.selectedCameraId\n })),\n selectedCameraId: this.selectedCameraId,\n deviceType: this.deviceType,\n isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,\n preferredFacing: this.preferredCameraFacing,\n userPreferredCamera: this.preferredCamera\n };\n }\n\n @Method()\n async setPreferredCamera(camera: 'auto' | 'front' | 'back') {\n this.preferredCamera = camera;\n this.debugLog('🎯 Camera preference changed to:', camera);\n \n // Re-detect and apply new camera preference\n await this.enumerateAndDetectCameras();\n \n // If video is active, switch to the new preferred camera\n if (this.isVideoActive && this.selectedCameraId) {\n await this.switchCamera(this.selectedCameraId);\n }\n \n return {\n success: true,\n selectedCamera: this.selectedCameraId,\n availableCameras: this.availableCameras.length\n };\n }\n\n private async loadMobileNetModel() {\n try {\n this.debugLog('🤖 Loading MobileNet model...');\n \n // Load class map\n const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);\n if (!classResponse.ok) {\n throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);\n }\n this.mobileNetClassMap = await classResponse.json();\n this.debugLog('📋 MobileNet classes loaded:', this.mobileNetClassMap);\n \n // Load model\n const sessionOptions = this.getSessionOptions();\n this.mobileNetSession = await (window as any).ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);\n this.debugLog('✅ MobileNet model loaded successfully');\n \n } catch (error) {\n this.debugLog('❌ Error loading MobileNet model:', error);\n throw error;\n }\n }\n\n private preprocessMobileNet(canvas: HTMLCanvasElement) {\n // Create a temporary canvas for MobileNet preprocessing (224x224)\n const tempCanvas = document.createElement('canvas');\n tempCanvas.width = 224;\n tempCanvas.height = 224;\n const tempCtx = tempCanvas.getContext('2d')!;\n \n // Draw the cropped image onto the 224x224 canvas\n tempCtx.drawImage(canvas, 0, 0, 224, 224);\n \n // Get image data and preprocess for MobileNet\n const imageData = tempCtx.getImageData(0, 0, 224, 224);\n const data = imageData.data;\n const hw = 224 * 224;\n const arr = new Float32Array(3 * hw);\n \n // Normalize pixels: (pixel/255 - 0.5) / 0.5 = (pixel - 127.5) / 127.5\n for (let i = 0; i < hw; i++) {\n arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5; // R\n arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5; // G \n arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5; // B\n }\n \n return new (window as any).ort.Tensor('float32', arr, [1, 3, 224, 224]);\n }\n\n private async classifyDocument(canvas: HTMLCanvasElement) {\n if (!this.mobileNetSession || !this.mobileNetClassMap) {\n this.debugLog('⚠️ MobileNet model not loaded');\n return null;\n }\n\n try {\n this.debugLog('🔍 Classifying document...');\n \n // Preprocess image for MobileNet\n const inputTensor = this.preprocessMobileNet(canvas);\n \n // Run inference\n const feeds = { input: inputTensor };\n const results = await this.mobileNetSession.run(feeds);\n const output = results[Object.keys(results)[0]].data;\n \n // Find the class with highest confidence\n const maxIdx = output.reduce((bestIdx: number, val: number, idx: number, arr: number[]) => \n val > arr[bestIdx] ? idx : bestIdx, 0);\n const confidence = output[maxIdx];\n \n const className = this.mobileNetClassMap[maxIdx.toString()] || \"unknown\";\n \n this.debugLog('📄 Document classification result:', {\n class: className,\n confidence: confidence.toFixed(3),\n classIndex: maxIdx\n });\n \n return {\n class: className,\n confidence: confidence,\n classIndex: maxIdx\n };\n \n } catch (error) {\n this.debugLog('❌ Error classifying document:', error);\n return null;\n }\n }\n\n private cleanup() {\n if (this.animationId) {\n cancelAnimationFrame(this.animationId);\n }\n if (this.videoStream) {\n this.videoStream.getTracks().forEach(track => track.stop());\n }\n \n // Limpiar canvas en cleanup general\n if (this.canvasRef) {\n const ctx = this.canvasRef.getContext(\"2d\");\n if (ctx) {\n ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);\n }\n }\n \n // OPTIMIZATION: Clean up canvas pool\n this.cleanupCanvasPool();\n }\n \n private cleanupCanvasPool() {\n // Release canvas references for garbage collection\n if (this.preprocessCanvas) {\n this.preprocessCtx = undefined;\n this.preprocessCanvas = undefined;\n }\n if (this.captureCanvas) {\n this.captureCtx = undefined;\n this.captureCanvas = undefined;\n }\n \n // Disposed ONNX sessions\n if (this.session) {\n this.session.release?.();\n this.session = undefined;\n }\n if (this.mobileNetSession) {\n this.mobileNetSession.release?.();\n this.mobileNetSession = undefined;\n }\n this.mobileNetClassMap = undefined;\n this.isModelPreloaded = false;\n \n this.debugLog('🧹 Canvas pool cleaned up');\n }\n\n private async getMaxResolution(): Promise<MediaTrackConstraints> {\n try {\n // Build constraints with selected camera if available\n const videoConstraints: MediaTrackConstraints = {};\n \n if (this.selectedCameraId) {\n videoConstraints.deviceId = { exact: this.selectedCameraId };\n } else if (this.preferredCameraFacing) {\n videoConstraints.facingMode = this.preferredCameraFacing;\n } else {\n videoConstraints.facingMode = \"environment\";\n }\n \n // Get temporary stream to access capabilities\n const tempStream = await navigator.mediaDevices.getUserMedia({\n video: videoConstraints\n });\n \n const videoTrack = tempStream.getVideoTracks()[0];\n const capabilities = videoTrack.getCapabilities();\n \n // Detener el stream temporal\n tempStream.getTracks().forEach(track => track.stop());\n \n // Build constraints with resolution optimized for tablets\n const constraints: MediaTrackConstraints = {};\n \n // Set camera selection constraints\n if (this.selectedCameraId) {\n constraints.deviceId = { exact: this.selectedCameraId };\n } else if (this.preferredCameraFacing) {\n constraints.facingMode = this.preferredCameraFacing;\n } else {\n constraints.facingMode = \"environment\";\n };\n \n if (capabilities.width && capabilities.height) {\n // Limitar resolución máxima para tablets para evitar problemas de rendimiento\n const maxWidth = Math.min(capabilities.width.max, 1920);\n const maxHeight = Math.min(capabilities.height.max, 1080);\n \n // Para tablets, usar resolución moderada en lugar de máxima\n const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;\n \n if (isTablet) {\n constraints.width = { ideal: Math.min(maxWidth, 1280) };\n constraints.height = { ideal: Math.min(maxHeight, 720) };\n } else {\n constraints.width = { ideal: maxWidth };\n constraints.height = { ideal: maxHeight };\n }\n \n this.debugLog('📐 Resolution capabilities:', {\n maxWidth: capabilities.width.max,\n maxHeight: capabilities.height.max,\n selectedWidth: constraints.width.ideal,\n selectedHeight: constraints.height.ideal,\n isTablet\n });\n }\n \n return constraints;\n } catch (err) {\n this.debugLog('⚠️ Could not get capabilities, using fallback');\n // Optimized fallback for tablets\n const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;\n \n const fallbackConstraints: MediaTrackConstraints = {\n width: { ideal: isTablet ? 1280 : 1920 },\n height: { ideal: isTablet ? 720 : 1080 }\n };\n \n // Add camera selection to fallback\n if (this.selectedCameraId) {\n fallbackConstraints.deviceId = { exact: this.selectedCameraId };\n } else if (this.preferredCameraFacing) {\n fallbackConstraints.facingMode = this.preferredCameraFacing;\n } else {\n fallbackConstraints.facingMode = \"environment\";\n }\n \n return fallbackConstraints;\n }\n }\n\n private async setupCamera() {\n try {\n const constraints = await this.getMaxResolution();\n \n const stream = await navigator.mediaDevices.getUserMedia({\n video: constraints,\n audio: false\n });\n\n if (this.videoRef) {\n this.videoRef.srcObject = stream;\n this.videoStream = stream;\n \n // Determine if video should be mirrored\n const isRear = this.isRearCamera(stream);\n this.shouldMirrorVideo = !isRear;\n \n this.debugLog('📹 Rear camera:', isRear);\n this.debugLog('🪞 Should mirror video:', this.shouldMirrorVideo);\n \n return new Promise<void>((resolve) => {\n this.videoRef!.onloadedmetadata = async () => {\n await this.videoRef!.play();\n this.isVideoActive = true;\n \n // Update mask dimensions once video is loaded\n if (this.canvasRef) {\n const container = this.canvasRef.parentElement!;\n const rect = container.getBoundingClientRect();\n this.updateMaskDimensions(rect);\n }\n \n resolve();\n };\n });\n }\n } catch (err) {\n this.debugLog(\"❌ No se pudo acceder a la cámara:\", err);\n this.handleCameraPermissionError(err);\n }\n }\n\n private preprocess(video: HTMLVideoElement) {\n // OPTIMIZATION: Reuse canvas instead of creating new ones\n if (!this.preprocessCanvas || !this.preprocessCtx) {\n this.initializeCanvasPool();\n }\n \n // Clear and redraw on reused canvas\n this.preprocessCtx!.clearRect(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);\n this.preprocessCtx!.drawImage(video, 0, 0, this.INPUT_SIZE, this.INPUT_SIZE);\n \n const imageData = this.preprocessCtx!.getImageData(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);\n const [R, G, B] = [[], [], []] as number[][];\n const { data } = imageData;\n\n // Optimized pixel processing\n for (let i = 0; i < data.length; i += 4) {\n R.push(data[i] / 255);\n G.push(data[i + 1] / 255);\n B.push(data[i + 2] / 255);\n }\n\n const transposedData = new Float32Array(R.concat(G, B));\n return new (window as any).ort.Tensor(\"float32\", transposedData, [1, 3, this.INPUT_SIZE, this.INPUT_SIZE]);\n }\n\n private getSessionOptions() {\n return {\n executionProviders: [\n // Try WebGL first for GPU acceleration, fallback to WASM\n 'webgl',\n 'wasm'\n ],\n graphOptimizationLevel: 'all', // Maximum optimization\n logSeverityLevel: this.debug ? 2 : 4, // Reduce logging overhead in production\n logVerbosityLevel: 0,\n enableCpuMemArena: true,\n enableMemPattern: true,\n executionMode: 'parallel',\n interOpNumThreads: 2,\n intraOpNumThreads: 2,\n };\n }\n\n private async startDetection() {\n try {\n // Check if model is already preloaded\n if (!this.session) {\n this.isLoading = true;\n this.statusMessage = \"Cargando modelos...\";\n this.statusColor = \"#007bff\";\n \n const modelPath = this.MODEL_PATH;\n this.debugLog('🤖 Loading detection model:', modelPath);\n \n const sessionOptions = this.getSessionOptions();\n this.session = await (window as any).ort.InferenceSession.create(modelPath, sessionOptions);\n \n // Load MobileNet model if classification is enabled and not already loaded\n if (this.useDocumentClassification && !this.mobileNetSession) {\n await this.loadMobileNetModel();\n }\n \n this.isModelPreloaded = true;\n this.emitReadyEvent();\n } else {\n this.debugLog('🚀 Using preloaded models');\n this.statusMessage = \"Usando modelos precargados...\";\n this.statusColor = \"#007bff\";\n }\n \n this.statusMessage = \"Configurando cámara...\";\n await this.setupCamera();\n \n this.startTime = Date.now();\n this.isLoading = false;\n this.detectFrame();\n } catch (err) {\n this.debugLog(\"Error al inicializar:\", err);\n this.statusMessage = \"Error al inicializar el detector\";\n this.statusColor = \"#ff6b6b\";\n this.isLoading = false;\n }\n }\n\n private async detectFrame() {\n try {\n if (!this.videoRef || !this.canvasRef || !this.session) return;\n \n // Pausar detección si está marcado como pausado\n if (this.isDetectionPaused) {\n // Solo continuar el bucle sin procesar detección\n if (this.captureStep !== 'completed') {\n this.animationId = requestAnimationFrame(() => this.detectFrame());\n }\n return;\n }\n \n // OPTIMIZATION 1: Frame skipping for performance\n this.frameSkipCounter++;\n if (this.frameSkipCounter <= this.FRAME_SKIP) {\n if (this.captureStep !== 'completed') {\n this.animationId = requestAnimationFrame(() => this.detectFrame());\n }\n return;\n }\n this.frameSkipCounter = 0;\n \n // OPTIMIZATION 2: Throttle inference based on time\n const currentTime = Date.now();\n if (currentTime - this.lastInferenceTime < this.MIN_INFERENCE_INTERVAL) {\n if (this.captureStep !== 'completed') {\n this.animationId = requestAnimationFrame(() => this.detectFrame());\n }\n return;\n }\n this.lastInferenceTime = currentTime;\n \n const ctx = this.canvasRef.getContext(\"2d\")!;\n const inputTensor = this.preprocess(this.videoRef);\n const feeds = { [this.session.inputNames[0]]: inputTensor };\n const results = await this.session.run(feeds);\n const output = results[this.session.outputNames[0]].data;\n\n const finalBoxes = [];\n for (let i = 0; i < output.length; i += 6) {\n const [x1, y1, x2, y2, score, classId] = output.slice(i, i + 6);\n if (score > this.CONFIDENCE_THRESHOLD) {\n finalBoxes.push({ x: x1, y: y1, w: x2 - x1, h: y2 - y1, score, classId });\n\n if (this.startTime && Date.now() - this.startTime < 5000) {\n const currentBox = { x: x1, y: y1, w: x2 - x1, h: y2 - y1, score };\n const isWellPositioned = this.isCardInFrame(currentBox);\n const effectiveScore = isWellPositioned ? score * 1.2 : score;\n \n if (effectiveScore > this.bestScore) {\n this.bestScore = effectiveScore;\n \n }\n }\n }\n }\n \n // OPTIMIZATION 3: Adaptive frame rate based on detection success\n if (finalBoxes.length === 0) {\n this.consecutiveFailures++;\n } else {\n this.consecutiveFailures = 0;\n }\n\n ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);\n if (this.debug) {\n this.drawDetections(ctx, finalBoxes);\n }\n this.updateGuidanceStatus(finalBoxes);\n this.updateMaskColor(finalBoxes);\n \n // Solo continuar si no hemos completado el proceso\n if (this.captureStep !== 'completed') {\n // OPTIMIZATION 4: Reduce frame rate when no detection for better battery life\n if (this.consecutiveFailures > this.MAX_FAILURES) {\n // Reduce to ~5fps when no detection for 0.5 seconds\n setTimeout(() => this.detectFrame(), 200);\n } else {\n this.animationId = requestAnimationFrame(() => this.detectFrame());\n }\n }\n } catch (e) {\n this.debugLog(\"Error en inferencia:\", e);\n // Solo continuar si no hemos completado el proceso\n if (this.captureStep !== 'completed') {\n // On error, wait longer before retrying\n setTimeout(() => this.detectFrame(), 100);\n }\n }\n }\n\n private isCardInFrame(box: any) {\n const cardCenterX = box.x + box.w / 2;\n const cardCenterY = box.y + box.h / 2;\n const frameCenterX = this.INPUT_SIZE / 2;\n const frameCenterY = this.INPUT_SIZE / 2;\n const toleranceX = 40;\n const toleranceY = 30;\n \n const isCentered = Math.abs(cardCenterX - frameCenterX) < toleranceX && \n Math.abs(cardCenterY - frameCenterY) < toleranceY;\n const isGoodSize = box.w > 150 && box.w < 300 && box.h > 90 && box.h < 200;\n \n return isCentered && isGoodSize;\n }\n\n\n private checkSideAlignment(box: any) {\n if (!this.videoRef) return { top: false, right: false, bottom: false, left: false };\n \n // Get video dimensions to calculate actual mask boundaries in model space\n const videoWidth = this.videoRef.videoWidth;\n const videoHeight = this.videoRef.videoHeight;\n \n if (videoWidth === 0 || videoHeight === 0) {\n return { top: false, right: false, bottom: false, left: false };\n }\n \n // Calculate video aspect ratio\n const videoAspectRatio = videoWidth / videoHeight;\n \n // The model sees video stretched to 320x320, but we need to calculate where\n // the mask should be in this distorted space to match the visual mask\n \n // In the visual display, we calculate mask size based on the limiting dimension\n // We need to replicate this logic but account for the distortion in model space\n \n // Calculate the \"display\" dimensions (what the visual mask calculations use)\n const containerAspectRatio = 1; // Assume square container for simplicity\n let displayedVideoWidth, displayedVideoHeight;\n \n if (videoAspectRatio > containerAspectRatio) {\n // Video is wider - letterboxed in display\n displayedVideoWidth = this.INPUT_SIZE;\n displayedVideoHeight = this.INPUT_SIZE / videoAspectRatio;\n } else {\n // Video is taller - pillarboxed in display \n displayedVideoHeight = this.INPUT_SIZE;\n displayedVideoWidth = this.INPUT_SIZE * videoAspectRatio;\n }\n \n // Calculate mask dimensions using the same logic as updateMaskDimensions\n const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;\n \n let visualMaskWidth, visualMaskHeight;\n const sizeRatio = this.maskSize / 100;\n \n if (maxWidthByHeight <= displayedVideoWidth) {\n // Video height is the limiting factor\n visualMaskHeight = displayedVideoHeight * sizeRatio;\n visualMaskWidth = visualMaskHeight * this.ID1_ASPECT_RATIO;\n } else {\n // Video width is the limiting factor\n visualMaskWidth = displayedVideoWidth * sizeRatio;\n visualMaskHeight = visualMaskWidth / this.ID1_ASPECT_RATIO;\n }\n \n // Now map these visual mask dimensions to the distorted model space\n // The model stretches video to 320x320, so we need to apply the inverse transformation\n const modelMaskWidth = visualMaskWidth * (this.INPUT_SIZE / displayedVideoWidth);\n const modelMaskHeight = visualMaskHeight * (this.INPUT_SIZE / displayedVideoHeight);\n \n // Calculate mask boundaries in model coordinate system (always centered in 320x320)\n const maskCenterX = this.INPUT_SIZE / 2;\n const maskCenterY = this.INPUT_SIZE / 2;\n const maskLeft = maskCenterX - (modelMaskWidth / 2);\n const maskRight = maskCenterX + (modelMaskWidth / 2);\n const maskTop = maskCenterY - (modelMaskHeight / 2);\n const maskBottom = maskCenterY + (modelMaskHeight / 2);\n \n // Obtener las coordenadas del documento detectado\n let docLeft = box.x;\n let docRight = box.x + box.w;\n const docTop = box.y;\n const docBottom = box.y + box.h;\n \n // Si el video está en modo mirror, invertir las coordenadas horizontales\n if (this.shouldMirrorVideo) {\n const originalDocLeft = docLeft;\n const originalDocRight = docRight;\n docLeft = this.INPUT_SIZE - originalDocRight;\n docRight = this.INPUT_SIZE - originalDocLeft;\n }\n \n // Tolerancia para considerar que un lado está alineado (en píxeles)\n const tolerance = this.alignmentTolerance;\n \n return {\n top: Math.abs(docTop - maskTop) <= tolerance,\n right: Math.abs(docRight - maskRight) <= tolerance,\n bottom: Math.abs(docBottom - maskBottom) <= tolerance,\n left: Math.abs(docLeft - maskLeft) <= tolerance\n };\n }\n\n private areAllSidesAligned(alignment: { top: boolean; right: boolean; bottom: boolean; left: boolean }) {\n return alignment.top && alignment.right && alignment.bottom && alignment.left;\n }\n\n private updateMaskColor(boxes: any[]) {\n const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');\n const corners = this.el.shadowRoot?.querySelectorAll('.corner');\n const topSide = this.el.shadowRoot?.querySelector('.side-top');\n const rightSide = this.el.shadowRoot?.querySelector('.side-right');\n const bottomSide = this.el.shadowRoot?.querySelector('.side-bottom');\n const leftSide = this.el.shadowRoot?.querySelector('.side-left');\n \n let bestBox = null;\n let currentAlignment = { top: false, right: false, bottom: false, left: false };\n \n if (boxes.length > 0) {\n bestBox = boxes.reduce((best, current) => \n current.score > best.score ? current : best\n );\n currentAlignment = this.checkSideAlignment(bestBox);\n this.sideAlignment = currentAlignment;\n } else {\n // Reset alignment when no detection\n this.sideAlignment = { top: false, right: false, bottom: false, left: false };\n }\n \n // Actualizar colores de cada lado individualmente\n topSide?.classList.toggle('aligned', currentAlignment.top);\n rightSide?.classList.toggle('aligned', currentAlignment.right);\n bottomSide?.classList.toggle('aligned', currentAlignment.bottom);\n leftSide?.classList.toggle('aligned', currentAlignment.left);\n \n // Verificar si todos los lados están alineados\n const allSidesAligned = this.areAllSidesAligned(currentAlignment);\n \n if (allSidesAligned && bestBox) {\n cardOutline?.classList.add('perfect-match');\n corners?.forEach(corner => corner.classList.add('perfect-match'));\n \n if (!this.hasScreenshotTaken) {\n this.lastDetectedBox = bestBox;\n this.takeScreenshot().catch(error => {\n this.debugLog('❌ Error taking screenshot:', error);\n });\n this.hasScreenshotTaken = true;\n // Reset para permitir segunda captura\n setTimeout(() => {\n this.hasScreenshotTaken = false;\n }, 2000);\n }\n } else {\n cardOutline?.classList.remove('perfect-match');\n corners?.forEach(corner => corner.classList.remove('perfect-match'));\n }\n }\n\n private updateGuidanceStatus(boxes: any[]) {\n if (boxes.length === 0) {\n this.statusMessage = \"Posicione la identificación dentro del marco\";\n this.statusColor = \"#ff6b6b\";\n } else {\n const bestBox = boxes.reduce((best, current) => \n current.score > best.score ? current : best\n );\n \n const alignment = this.checkSideAlignment(bestBox);\n const alignedSides = [alignment.top, alignment.right, alignment.bottom, alignment.left].filter(Boolean).length;\n const allSidesAligned = this.areAllSidesAligned(alignment);\n \n if (allSidesAligned) {\n this.statusMessage = \"Identificación perfectamente alineada. Mantenga inmóvil\";\n this.statusColor = \"#00ff00\";\n } else if (alignedSides > 0) {\n this.statusMessage = `Alinee los lados restantes (${alignedSides}/4 lados correctos)`;\n this.statusColor = \"#ffb366\";\n } else if (bestBox.w < 150) {\n this.statusMessage = \"Identificación detectada. Acerque al marco\";\n this.statusColor = \"#ffb366\";\n } else {\n this.statusMessage = \"Identificación detectada. Alinee con el marco\";\n this.statusColor = \"#ffb366\";\n }\n }\n }\n\n private drawDetections(ctx: CanvasRenderingContext2D, boxes: any[]) {\n if (!this.videoRef) return;\n \n // Get video and container dimensions\n const videoWidth = this.videoRef.videoWidth;\n const videoHeight = this.videoRef.videoHeight;\n const containerWidth = this.canvasRef!.width;\n const containerHeight = this.canvasRef!.height;\n \n if (videoWidth === 0 || videoHeight === 0) return;\n \n // Calculate video aspect ratio and container aspect ratio\n const videoAspectRatio = videoWidth / videoHeight;\n const containerAspectRatio = containerWidth / containerHeight;\n \n // Determine how video fits in container (same logic as updateMaskDimensions)\n let displayedVideoWidth, displayedVideoHeight;\n let videoOffsetX = 0, videoOffsetY = 0;\n \n if (videoAspectRatio > containerAspectRatio) {\n // Video is wider - letterboxed (black bars top/bottom)\n displayedVideoWidth = containerWidth;\n displayedVideoHeight = containerWidth / videoAspectRatio;\n videoOffsetY = (containerHeight - displayedVideoHeight) / 2;\n } else {\n // Video is taller - pillarboxed (black bars left/right)\n displayedVideoHeight = containerHeight;\n displayedVideoWidth = containerHeight * videoAspectRatio;\n videoOffsetX = (containerWidth - displayedVideoWidth) / 2;\n }\n \n // Scale factor from model coordinates (320x320) to displayed video area\n const scaleX = displayedVideoWidth / this.INPUT_SIZE;\n const scaleY = displayedVideoHeight / this.INPUT_SIZE;\n \n boxes.forEach(det => {\n // Convert model coordinates to displayed video coordinates\n const x = det.x * scaleX + videoOffsetX;\n const y = det.y * scaleY + videoOffsetY;\n const w = det.w * scaleX;\n const h = det.h * scaleY;\n \n ctx.strokeStyle = \"#32406C\";\n ctx.lineWidth = 2;\n ctx.strokeRect(x, y, w, h);\n });\n }\n\n private async takeScreenshot() {\n if (!this.videoRef || !this.lastDetectedBox) return;\n \n // Activar animación\n this.triggerCaptureAnimation();\n \n // OPTIMIZATION: Reuse capture canvas for full frame\n if (!this.captureCanvas || !this.captureCtx) {\n this.initializeCanvasPool();\n }\n \n // Resize reused canvas for full frame\n this.captureCanvas!.width = this.videoRef.videoWidth;\n this.captureCanvas!.height = this.videoRef.videoHeight;\n this.captureCtx!.drawImage(this.videoRef, 0, 0, this.captureCanvas!.width, this.captureCanvas!.height);\n \n // Calcular las coordenadas de recorte basadas en la detección\n const scaleX = this.videoRef.videoWidth / this.INPUT_SIZE;\n const scaleY = this.videoRef.videoHeight / this.INPUT_SIZE;\n \n const cropX = Math.max(0, (this.lastDetectedBox.x * scaleX) - this.cropMargin);\n const cropY = Math.max(0, (this.lastDetectedBox.y * scaleY) - this.cropMargin);\n const cropWidth = Math.min((this.lastDetectedBox.w * scaleX) + (2 * this.cropMargin), this.videoRef.videoWidth - cropX);\n const cropHeight = Math.min((this.lastDetectedBox.h * scaleY) + (2 * this.cropMargin), this.videoRef.videoHeight - cropY);\n \n // OPTIMIZATION: Create temporary canvas only for cropped version\n // (We reuse main capture canvas for full frame)\n const croppedCanvas = document.createElement('canvas');\n croppedCanvas.width = cropWidth;\n croppedCanvas.height = cropHeight;\n const croppedCtx = croppedCanvas.getContext('2d', { alpha: false })!;\n \n // Recortar la identificación del frame completo\n croppedCtx.drawImage(\n this.videoRef,\n cropX, cropY, cropWidth, cropHeight, // Área de origen\n 0, 0, cropWidth, cropHeight // Área de destino\n );\n \n if (this.captureStep === 'front') {\n // Captura del frente usando canvas reutilizado\n this.capturedFullFrame = this.captureCanvas!.toDataURL('image/png');\n this.capturedCroppedId = croppedCanvas.toDataURL('image/png');\n \n // Check if document classification is enabled\n if (this.useDocumentClassification) {\n // Load MobileNet model if not loaded yet (lazy loading)\n if (!this.mobileNetSession) {\n try {\n await this.loadMobileNetModel();\n } catch (error) {\n this.debugLog('⚠️ Failed to load classification model, continuing without classification:', error);\n }\n }\n \n // Classify the cropped document if model is available\n if (this.mobileNetSession) {\n const classification = await this.classifyDocument(croppedCanvas);\n \n if (classification && classification.class === 'passport') {\n // If it's a passport, skip back capture since passports don't have a back side\n this.debugLog('📄 Passport detected - skipping back capture');\n this.completeProcess(true);\n return;\n }\n }\n }\n \n // For other IDs, continue with normal flow (back capture)\n this.captureStep = 'back';\n this.statusMessage = \"Voltee la identificación y muestre la parte trasera\";\n this.statusColor = \"#007bff\";\n \n // Pausar detección durante la animación de giro\n this.isDetectionPaused = true;\n \n // Mostrar animación de giro después de la captura\n setTimeout(() => {\n this.showFlipAnimation = true;\n setTimeout(() => {\n this.showFlipAnimation = false;\n // Reanudar detección después de que termine la animación\n this.isDetectionPaused = false;\n }, 3000);\n }, 800);\n \n this.debugLog('📸 FRENTE capturado. Esperando trasera...');\n } else if (this.captureStep === 'back') {\n // Captura de la trasera usando canvas reutilizado\n this.capturedBackFullFrame = this.captureCanvas!.toDataURL('image/png');\n this.capturedBackCroppedId = croppedCanvas.toDataURL('image/png');\n this.completeProcess(false);\n \n this.debugLog('📸 TRASERA capturada. Proceso completado. Detector detenido. Imágenes emitidas.');\n }\n }\n\n private triggerCaptureAnimation() {\n this.isCapturing = true;\n \n // Agregar clase de animación al marco\n const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');\n cardOutline?.classList.add('capturing');\n \n // Limpiar animación después de que termine\n setTimeout(() => {\n this.isCapturing = false;\n cardOutline?.classList.remove('capturing');\n }, 600);\n }\n\n private stopDetection() {\n if (this.animationId) {\n cancelAnimationFrame(this.animationId);\n this.animationId = undefined;\n }\n \n // Limpiar canvas para eliminar cualquier detección visual residual\n if (this.canvasRef) {\n const ctx = this.canvasRef.getContext(\"2d\")!;\n ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);\n }\n \n this.debugLog('🛑 Detector de identificación detenido');\n }\n\n private resetDetection() {\n this.bestScore = 0;\n this.startTime = Date.now();\n this.statusMessage = \"Sistema reiniciado. Posicione la identificación\";\n this.statusColor = \"#aaa\";\n this.hasScreenshotTaken = false;\n this.capturedFullFrame = null;\n this.capturedCroppedId = null;\n this.capturedBackFullFrame = null;\n this.capturedBackCroppedId = null;\n this.captureStep = 'front';\n this.isCapturing = false;\n this.showFlipAnimation = false;\n this.showSuccessAnimation = false;\n this.isDetectionPaused = false;\n this.isLoading = false;\n this.lastDetectedBox = undefined;\n this.isModelPreloaded = false;\n \n // Reset performance counters\n this.frameSkipCounter = 0;\n this.consecutiveFailures = 0;\n this.lastInferenceTime = 0;\n \n if (this.canvasRef) {\n const ctx = this.canvasRef.getContext(\"2d\")!;\n ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);\n }\n \n // Reiniciar el detector si estaba funcionando\n if (this.isVideoActive && this.session) {\n this.detectFrame();\n }\n }\n\n\n private completeProcess(skippedBack: boolean = false) {\n this.captureStep = 'completed';\n this.statusMessage = skippedBack ? \n \"Proceso completado (solo frente capturado)\" : \n \"Proceso de captura completado exitosamente\";\n this.statusColor = \"#28a745\";\n \n // Detener el detector\n this.stopDetection();\n \n // Emitir evento con las imágenes capturadas\n const capturedImages = {\n front: {\n fullFrame: this.capturedFullFrame,\n cropped: this.capturedCroppedId\n },\n back: {\n fullFrame: this.capturedBackFullFrame,\n cropped: this.capturedBackCroppedId\n },\n timestamp: new Date().toISOString(),\n metadata: {\n totalImages: skippedBack ? 2 : 4,\n processCompleted: true,\n backCaptureSkipped: skippedBack\n }\n };\n \n this.captureCompleted.emit(capturedImages);\n \n // Mostrar animación de éxito después de la captura\n setTimeout(() => {\n this.showSuccessAnimation = true;\n setTimeout(() => {\n this.showSuccessAnimation = false;\n }, 3000);\n }, 800);\n }\n\n private exitSession() {\n if (this.videoStream) {\n this.videoStream.getTracks().forEach(track => track.stop());\n this.videoStream = undefined;\n this.isVideoActive = false;\n this.statusMessage = \"Sesión finalizada.\";\n this.statusColor = \"#aaa\";\n }\n this.isLoading = false;\n \n // Limpiar canvas al finalizar sesión\n if (this.canvasRef) {\n const ctx = this.canvasRef.getContext(\"2d\")!;\n ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);\n }\n \n this.cleanup();\n }\n\n render() {\n return (\n <div class=\"detector-container\">\n <div class=\"video-container\">\n <video \n ref={el => this.videoRef = el}\n autoplay \n muted \n playsinline\n class={this.shouldMirrorVideo ? 'mirror' : ''}\n style={{ display: this.isVideoActive ? 'block' : 'none' }}\n />\n <canvas \n ref={el => this.canvasRef = el}\n class={this.shouldMirrorVideo ? 'mirror' : ''}\n />\n {this.isMaskReady && (\n <div class=\"overlay-mask\">\n <div class=\"card-outline\">\n <div class=\"side side-top\"></div>\n <div class=\"side side-right\"></div>\n <div class=\"side side-bottom\"></div>\n <div class=\"side side-left\"></div>\n <div class=\"corner corner-tl\"></div>\n <div class=\"corner corner-tr\"></div>\n <div class=\"corner corner-bl\"></div>\n <div class=\"corner corner-br\"></div>\n {!this.showFlipAnimation && !this.showSuccessAnimation && (\n <div class=\"guide-text\">{this.statusMessage}</div>\n )}\n </div>\n {this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (\n <button \n class=\"skip-button\" \n onClick={() => this.skipBackCapture()}\n type=\"button\"\n >\n Saltar reverso\n </button>\n )}\n \n {/* Camera controls - Always show for debugging */}\n {this.isVideoActive && (\n <div class=\"camera-controls\">\n {this.isMultipleCamerasAvailable && (\n <button \n class=\"flip-camera-button\" \n onClick={() => this.flipCamera()}\n type=\"button\"\n title=\"Cambiar cámara\"\n >\n Girar cámara\n </button>\n )}\n \n <button \n class=\"camera-selector-button\" \n onClick={() => this.toggleCameraSelector()}\n type=\"button\"\n title=\"Seleccionar cámara\"\n >\n Cámaras\n </button>\n \n {/* Debug info */}\n {this.debug && (\n <div style={{\n position: 'absolute',\n top: '50px',\n right: '0',\n background: 'rgba(0,0,0,0.8)',\n color: 'white',\n padding: '8px',\n fontSize: '10px',\n borderRadius: '4px',\n whiteSpace: 'nowrap'\n }}>\n Cámaras: {this.availableCameras.length}<br/>\n Múltiples: {this.isMultipleCamerasAvailable ? 'Sí' : 'No'}<br/>\n Selector: {this.showCameraSelector ? 'Visible' : 'Oculto'}<br/>\n Video: {this.isVideoActive ? 'Activo' : 'Inactivo'}\n </div>\n )}\n </div>\n )}\n \n {/* Camera selector dropdown - Show if selector is open and we have cameras */}\n {this.showCameraSelector && this.availableCameras.length > 0 && (\n <div class=\"camera-selector-dropdown\">\n <div class=\"camera-selector-header\">\n <span>Seleccionar Cámara</span>\n <button \n class=\"close-selector\" \n onClick={() => this.toggleCameraSelector()}\n type=\"button\"\n >\n ×\n </button>\n </div>\n <div class=\"camera-list\">\n {this.availableCameras.map((camera) => (\n <button\n key={camera.deviceId}\n class={`camera-option ${this.selectedCameraId === camera.deviceId ? 'selected' : ''}`}\n onClick={() => {\n this.switchCamera(camera.deviceId);\n this.toggleCameraSelector();\n }}\n type=\"button\"\n >\n <span class=\"camera-label\">\n {camera.label || `Cámara ${this.availableCameras.indexOf(camera) + 1}`}\n </span>\n {this.selectedCameraId === camera.deviceId && (\n <span class=\"selected-indicator\">✓</span>\n )}\n </button>\n ))}\n </div>\n <div class=\"device-info\">\n <small>Dispositivo: {this.deviceType}</small>\n </div>\n </div>\n )}\n </div>\n )}\n \n {this.isCapturing && (\n <div class=\"capture-animation\"></div>\n )}\n \n {this.showFlipAnimation && (\n <div class=\"flip-animation\">\n <div class=\"id-card-icon\"></div>\n <div class=\"flip-text\">¡Voltea tu identificación!</div>\n </div>\n )}\n \n {this.showSuccessAnimation && (\n <div class=\"success-animation\">\n <div class=\"check-icon\"></div>\n <div class=\"success-text\">¡Proceso completado!</div>\n </div>\n )}\n \n {this.isLoading && (\n <div class=\"loading-overlay\">\n <div class=\"loading-spinner\"></div>\n <div class=\"loading-text\">{this.statusMessage}</div>\n </div>\n )}\n \n <div class=\"watermark\">\n <img src=\"https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png\" alt=\"Powered by Jaak\" />\n </div>\n </div>\n\n\n\n </div>\n );\n }\n}\n"],"mappings":"yDAAA,MAAMA,EAAiB,4vT,MCOVC,EAAU,M,iIAEbC,MAAiB,MACjBC,mBAA6B,GAC7BC,SAAmB,GACnBC,WAAqB,EACrBC,0BAAqC,MACrCC,gBAA6C,OAE5CC,iBACAC,QAEAC,cAAyB,MACzBC,cAAwB,2CACxBC,YAAsB,OACtBC,UAAoB,EACpBC,kBAAmC,KACnCC,kBAAmC,KACnCC,sBAAuC,KACvCC,sBAAuC,KACvCC,YAA8C,QAC9CC,YAAuB,MACvBC,kBAA6B,MAC7BC,qBAAgC,MAChCC,kBAA6B,KAC7BC,cAAkF,CACzFC,IAAK,MACLC,MAAO,MACPC,OAAQ,MACRC,KAAM,OAECC,kBAA6B,MAC7BC,UAAqB,MACrBC,iBAA4B,MAC5BC,YAAuB,MACvBC,iBAAsC,GACtCC,iBAAkC,KAClCC,mBAA8B,MAC9BC,2BAAsC,MAEvCC,SACAC,UACAC,QACAC,UACAC,YACAC,YACAC,mBAA8B,MAC9BC,gBACAC,iBACAC,kBAGAC,WAA8C,UAC9CC,sBAAuD,KAGvDC,iBAA2B,EAClBC,WAAqB,EAC9BC,oBAA8B,EACrBC,aAAuB,GAChCC,kBAA4B,EACnBC,uBAAiC,GAG1CC,iBACAC,cACAC,cACAC,WAESC,WAAa,gFACbC,qBAAuB,gFACvBC,u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CAAApJ,MAAM,eACT6D,EAAA,SAAAuF,IAAA,4DAAqBnX,KAAKpB,eAOnCoB,KAAK/C,aACJ2U,EAAA,OAAAuF,IAAA,2CAAKpJ,MAAM,sBAGZ/N,KAAK9C,mBACJ0U,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,kBACT6D,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,iBACX6D,EAAA,OAAAuF,IAAA,2CAAKpJ,MAAM,aAAW,+BAIzB/N,KAAK7C,sBACJyU,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,qBACT6D,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,eACX6D,EAAA,OAAAuF,IAAA,2CAAKpJ,MAAM,gBAAc,yBAI5B/N,KAAKrC,WACJiU,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,mBACT6D,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,oBACX6D,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,gBAAgB/N,KAAKvD,gBAIpCmV,EAAK,OAAAuF,IAAA,2CAAApJ,MAAM,aACT6D,EAAA,OAAAuF,IAAA,2CAAK5Q,IAAI,yEAAyE6R,IAAI,sB","ignoreList":[]}
@@ -1,3 +0,0 @@
1
- const e="jaak-stamps-webcomponent";const t={hydratedSelectorName:"hydrated",lazyLoad:true,updatable:true,watchCallback:false};const n=()=>{};const r="";var s=Object.defineProperty;var o=(e,t)=>{for(var n in t)s(e,n,{get:t[n],enumerable:true})};var i=(e,t)=>{var n;const r=t.t;const s=Object.entries((n=r.o)!=null?n:{});s.map((([n,[r]])=>{if(r&31||r&32){const r=e[n];const s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),n);Object.defineProperty(e,n,{get(){return s.get.call(this)},set(e){s.set.call(this,e)},configurable:true,enumerable:true});e[n]=t.i.has(n)?t.i.get(n):r}}))};var l=e=>{if(e.__stencil__getHostRef){return e.__stencil__getHostRef()}return void 0};var a=(e,t)=>{e.__stencil__getHostRef=()=>t;t.l=e;{i(e,t)}};var f=(e,t)=>{const n={u:0,$hostElement$:e,t,i:new Map};{n.v=new Promise((e=>n.h=e))}{n.p=new Promise((e=>n.m=e));e["s-p"]=[];e["s-rc"]=[]}const r=n;e.__stencil__getHostRef=()=>r;return r};var c=(e,t)=>t in e;var u=(e,t)=>(0,console.error)(e,t);var v=new Map;var d=(e,t,n)=>{const r=e.$.replace(/-/g,"_");const s=e.S;if(!s){return void 0}const o=v.get(s);if(o){return o[r]}
2
- /*!__STENCIL_STATIC_IMPORT_SWITCH__*/return import(`./${s}.entry.js${""}`).then((e=>{{v.set(s,e)}return e[r]}),(e=>{u(e,t.$hostElement$)}))};var h=new Map;var p="sty-id";var m="{visibility:hidden}.hydrated{visibility:inherit}";var y="slot-fb{display:contents}slot-fb[hidden]{display:none}";var b=typeof window!=="undefined"?window:{};var w={u:0,j:"",jmp:e=>e(),raf:e=>requestAnimationFrame(e),ael:(e,t,n,r)=>e.addEventListener(t,n,r),rel:(e,t,n,r)=>e.removeEventListener(t,n,r),ce:(e,t)=>new CustomEvent(e,t)};var $=e=>Promise.resolve(e);var S=(()=>{try{new CSSStyleSheet;return typeof(new CSSStyleSheet).replaceSync==="function"}catch(e){}return false})();var g=false;var j=[];var O=[];var k=(e,t)=>n=>{e.push(n);if(!g){g=true;if(t&&w.u&4){M(E)}else{w.raf(E)}}};var C=e=>{for(let t=0;t<e.length;t++){try{e[t](performance.now())}catch(e){u(e)}}e.length=0};var E=()=>{C(j);{C(O);if(g=j.length>0){w.raf(E)}}};var M=e=>$().then(e);var x=k(O,true);var P=e=>{e=typeof e;return e==="object"||e==="function"};function N(e){var t,n,r;return(r=(n=(t=e.head)==null?void 0:t.querySelector('meta[name="csp-nonce"]'))==null?void 0:n.getAttribute("content"))!=null?r:void 0}var U=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var R={};o(R,{err:()=>W,map:()=>A,ok:()=>D,unwrap:()=>L,unwrapErr:()=>T});var D=e=>({isOk:true,isErr:false,value:e});var W=e=>({isOk:false,isErr:true,value:e});function A(e,t){if(e.isOk){const n=t(e.value);if(n instanceof Promise){return n.then((e=>D(e)))}else{return D(n)}}if(e.isErr){const t=e.value;return W(t)}throw"should never get here"}var L=e=>{if(e.isOk){return e.value}else{throw e.value}};var T=e=>{if(e.isErr){return e.value}else{throw e.value}};function z(e){const t=this.attachShadow({mode:"open"});if(S){const e=new CSSStyleSheet;e.replaceSync(r);t.adoptedStyleSheets.push(e)}}var F=(e,t="")=>{{return()=>{}}};var H=(e,t)=>{{return()=>{}}};var I=(e,t,...n)=>{let r=null;let s=null;let o=false;let i=false;const l=[];const a=t=>{for(let n=0;n<t.length;n++){r=t[n];if(Array.isArray(r)){a(r)}else if(r!=null&&typeof r!=="boolean"){if(o=typeof e!=="function"&&!P(r)){r=String(r)}if(o&&i){l[l.length-1].O+=r}else{l.push(o?V(null,r):r)}i=o}}};a(n);if(t){if(t.key){s=t.key}{const e=t.className||t.class;if(e){t.class=typeof e!=="object"?e:Object.keys(e).filter((t=>e[t])).join(" ")}}}const f=V(e,null);f.k=t;if(l.length>0){f.C=l}{f.M=s}return f};var V=(e,t)=>{const n={u:0,P:e,O:t,N:null,C:null};{n.k=null}{n.M=null}return n};var q={};var G=e=>e&&e.P===q;var Y=e=>{const t=U(e);return new RegExp(`(^|[^@]|@(?!supports\\s+selector\\s*\\([^{]*?${t}))(${t}\\b)`,"g")};Y("::slotted");Y(":host");Y(":host-context");var _=(e,t)=>{if(e!=null&&!P(e)){if(t&4){return e==="false"?false:e===""||!!e}if(t&2){return typeof e==="string"?parseFloat(e):typeof e==="number"?e:NaN}if(t&1){return String(e)}return e}return e};var B=e=>l(e).$hostElement$;var J=(e,t,n)=>{const r=B(e);return{emit:e=>K(r,t,{bubbles:true,composed:true,cancelable:true,detail:e})}};var K=(e,t,n)=>{const r=w.ce(t,n);e.dispatchEvent(r);return r};var Q=new WeakMap;var X=(e,t,n)=>{let r=h.get(e);if(S&&n){r=r||new CSSStyleSheet;if(typeof r==="string"){r=t}else{r.replaceSync(t)}}else{r=t}h.set(e,r)};var Z=(e,t,n)=>{var r;const s=te(t);const o=h.get(s);if(!b.document){return s}e=e.nodeType===11?e:b.document;if(o){if(typeof o==="string"){e=e.head||e;let n=Q.get(e);let i;if(!n){Q.set(e,n=new Set)}if(!n.has(s)){{i=document.querySelector(`[${p}="${s}"]`)||b.document.createElement("style");i.innerHTML=o;const n=(r=w.U)!=null?r:N(b.document);if(n!=null){i.setAttribute("nonce",n)}if(!(t.u&1)){if(e.nodeName==="HEAD"){const t=e.querySelectorAll("link[rel=preconnect]");const n=t.length>0?t[t.length-1].nextSibling:e.querySelector("style");e.insertBefore(i,(n==null?void 0:n.parentNode)===e?n:null)}else if("host"in e){if(S){const t=new CSSStyleSheet;t.replaceSync(o);e.adoptedStyleSheets=[t,...e.adoptedStyleSheets]}else{const t=e.querySelector("style");if(t){t.innerHTML=o+t.innerHTML}else{e.prepend(i)}}}else{e.append(i)}}if(t.u&1){e.insertBefore(i,null)}}if(t.u&4){i.innerHTML+=y}if(n){n.add(s)}}}else if(!e.adoptedStyleSheets.includes(o)){e.adoptedStyleSheets=[...e.adoptedStyleSheets,o]}}return s};var ee=e=>{const t=e.t;const n=e.$hostElement$;const r=t.u;const s=F("attachStyles",t.$);const o=Z(n.shadowRoot?n.shadowRoot:n.getRootNode(),t);if(r&10){n["s-sc"]=o;n.classList.add(o+"-h")}s()};var te=(e,t)=>"sc-"+e.$;var ne=(e,t,n,r,s,o,i)=>{if(n===r){return}let l=c(e,t);let a=t.toLowerCase();if(t==="class"){const t=e.classList;const s=se(n);let o=se(r);{t.remove(...s.filter((e=>e&&!o.includes(e))));t.add(...o.filter((e=>e&&!s.includes(e))))}}else if(t==="style"){{for(const t in n){if(!r||r[t]==null){if(t.includes("-")){e.style.removeProperty(t)}else{e.style[t]=""}}}}for(const t in r){if(!n||r[t]!==n[t]){if(t.includes("-")){e.style.setProperty(t,r[t])}else{e.style[t]=r[t]}}}}else if(t==="key");else if(t==="ref"){if(r){r(e)}}else if(!l&&t[0]==="o"&&t[1]==="n"){if(t[2]==="-"){t=t.slice(3)}else if(c(b,a)){t=a.slice(2)}else{t=a[2]+t.slice(3)}if(n||r){const s=t.endsWith(oe);t=t.replace(ie,"");if(n){w.rel(e,t,n,s)}if(r){w.ael(e,t,r,s)}}}else{const i=P(r);if((l||i&&r!==null)&&true){try{if(!e.tagName.includes("-")){const s=r==null?"":r;if(t==="list"){l=false}else if(n==null||e[t]!=s){if(typeof e.__lookupSetter__(t)==="function"){e[t]=s}else{e.setAttribute(t,s)}}}else if(e[t]!==r){e[t]=r}}catch(e){}}if(r==null||r===false){if(r!==false||e.getAttribute(t)===""){{e.removeAttribute(t)}}}else if((!l||o&4||s)&&!i&&e.nodeType===1){r=r===true?"":r;{e.setAttribute(t,r)}}}};var re=/\s/;var se=e=>{if(typeof e==="object"&&e&&"baseVal"in e){e=e.baseVal}if(!e||typeof e!=="string"){return[]}return e.split(re)};var oe="Capture";var ie=new RegExp(oe+"$");var le=(e,t,n,r)=>{const s=t.N.nodeType===11&&t.N.host?t.N.host:t.N;const o=e&&e.k||{};const i=t.k||{};{for(const e of ae(Object.keys(o))){if(!(e in i)){ne(s,e,o[e],void 0,n,t.u)}}}for(const e of ae(Object.keys(i))){ne(s,e,o[e],i[e],n,t.u)}};function ae(e){return e.includes("ref")?[...e.filter((e=>e!=="ref")),"ref"]:e}var fe;var ce=false;var ue=(e,t,n)=>{const r=t.C[n];let s=0;let o;let i;if(r.O!==null){o=r.N=b.document.createTextNode(r.O)}else{if(!b.document){throw new Error("You are trying to render a Stencil component in an environment that doesn't support the DOM. Make sure to populate the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) object before rendering a component.")}o=r.N=b.document.createElement(r.P);{le(null,r,ce)}if(r.C){for(s=0;s<r.C.length;++s){i=ue(e,r,s);if(i){o.appendChild(i)}}}}o["s-hn"]=fe;return o};var ve=(e,t,n,r,s,o)=>{let i=e;let l;if(i.shadowRoot&&i.tagName===fe){i=i.shadowRoot}for(;s<=o;++s){if(r[s]){l=ue(null,n,s);if(l){r[s].N=l;be(i,l,t)}}}};var de=(e,t,n)=>{for(let r=t;r<=n;++r){const t=e[r];if(t){const e=t.N;ye(t);if(e){e.remove()}}}};var he=(e,t,n,r,s=false)=>{let o=0;let i=0;let l=0;let a=0;let f=t.length-1;let c=t[0];let u=t[f];let v=r.length-1;let d=r[0];let h=r[v];let p;let m;while(o<=f&&i<=v){if(c==null){c=t[++o]}else if(u==null){u=t[--f]}else if(d==null){d=r[++i]}else if(h==null){h=r[--v]}else if(pe(c,d,s)){me(c,d,s);c=t[++o];d=r[++i]}else if(pe(u,h,s)){me(u,h,s);u=t[--f];h=r[--v]}else if(pe(c,h,s)){me(c,h,s);be(e,c.N,u.N.nextSibling);c=t[++o];h=r[--v]}else if(pe(u,d,s)){me(u,d,s);be(e,u.N,c.N);u=t[--f];d=r[++i]}else{l=-1;{for(a=o;a<=f;++a){if(t[a]&&t[a].M!==null&&t[a].M===d.M){l=a;break}}}if(l>=0){m=t[l];if(m.P!==d.P){p=ue(t&&t[i],n,l)}else{me(m,d,s);t[l]=void 0;p=m.N}d=r[++i]}else{p=ue(t&&t[i],n,i);d=r[++i]}if(p){{be(c.N.parentNode,p,c.N)}}}}if(o>f){ve(e,r[v+1]==null?null:r[v+1].N,n,r,i,v)}else if(i>v){de(t,o,f)}};var pe=(e,t,n=false)=>{if(e.P===t.P){if(!n){return e.M===t.M}if(n&&!e.M&&t.M){e.M=t.M}return true}return false};var me=(e,n,r=false)=>{const s=n.N=e.N;const o=e.C;const i=n.C;const l=n.O;if(l===null){{le(e,n,ce)}if(o!==null&&i!==null){he(s,o,n,i,r)}else if(i!==null){if(e.O!==null){s.textContent=""}ve(s,null,n,i,0,i.length-1)}else if(!r&&t.updatable&&o!==null){de(o,0,o.length-1)}}else if(e.O!==l){s.data=l}};var ye=e=>{{e.k&&e.k.ref&&e.k.ref(null);e.C&&e.C.map(ye)}};var be=(e,t,n)=>{{return e==null?void 0:e.insertBefore(t,n)}};var we=(e,t,n=false)=>{const r=e.$hostElement$;const s=e.R||V(null,null);const o=G(t);const i=o?t:I(null,null,t);fe=r.tagName;if(n&&i.k){for(const e of Object.keys(i.k)){if(r.hasAttribute(e)&&!["key","ref","style","class"].includes(e)){i.k[e]=r[e]}}}i.P=null;i.u|=4;e.R=i;i.N=s.N=r.shadowRoot||r;me(s,i,n)};var $e=(e,t)=>{if(t&&!e.D&&t["s-p"]){const n=t["s-p"].push(new Promise((r=>e.D=()=>{t["s-p"].splice(n-1,1);r()})))}};var Se=(e,t)=>{{e.u|=16}if(e.u&4){e.u|=512;return}$e(e,e.W);const n=()=>ge(e,t);return x(n)};var ge=(e,t)=>{const n=e.$hostElement$;const r=F("scheduleUpdate",e.t.$);const s=e.l;if(!s){throw new Error(`Can't render component <${n.tagName.toLowerCase()} /> with invalid Stencil runtime! Make sure this imported component is compiled with a \`externalRuntime: true\` flag. For more information, please refer to https://stenciljs.com/docs/custom-elements#externalruntime`)}let o;if(t){o=xe(s,"componentWillLoad",void 0,n)}else{o=xe(s,"componentWillUpdate",void 0,n)}o=je(o,(()=>xe(s,"componentWillRender",void 0,n)));r();return je(o,(()=>ke(e,s,t)))};var je=(e,t)=>Oe(e)?e.then(t).catch((e=>{console.error(e);t()})):t();var Oe=e=>e instanceof Promise||e&&e.then&&typeof e.then==="function";var ke=async(e,t,n)=>{var r;const s=e.$hostElement$;const o=F("update",e.t.$);const i=s["s-rc"];if(n){ee(e)}const l=F("render",e.t.$);{Ce(e,t,s,n)}if(i){i.map((e=>e()));s["s-rc"]=void 0}l();o();{const t=(r=s["s-p"])!=null?r:[];const n=()=>Ee(e);if(t.length===0){n()}else{Promise.all(t).then(n);e.u|=4;t.length=0}}};var Ce=(e,t,n,r)=>{try{t=t.render();{e.u&=-17}{e.u|=2}{{{we(e,t,r)}}}}catch(t){u(t,e.$hostElement$)}return null};var Ee=e=>{const t=e.t.$;const n=e.$hostElement$;const r=F("postUpdate",t);const s=e.l;const o=e.W;xe(s,"componentDidRender",void 0,n);if(!(e.u&64)){e.u|=64;{Pe(n)}xe(s,"componentDidLoad",void 0,n);r();{e.m(n);if(!o){Me()}}}else{xe(s,"componentDidUpdate",void 0,n);r()}{e.h(n)}{if(e.D){e.D();e.D=void 0}if(e.u&512){M((()=>Se(e,false)))}e.u&=-517}};var Me=t=>{M((()=>K(b,"appload",{detail:{namespace:e}})))};var xe=(e,t,n,r)=>{if(e&&e[t]){try{return e[t](n)}catch(e){u(e,r)}}return void 0};var Pe=e=>{var n;return e.classList.add((n=t.hydratedSelectorName)!=null?n:"hydrated")};var Ne=(e,t)=>l(e).i.get(t);var Ue=(e,t,n,r)=>{const s=l(e);if(!s){throw new Error(`Couldn't find host element for "${r.$}" as it is unknown to this Stencil runtime. This usually happens when integrating a 3rd party Stencil component with another Stencil component or application. Please reach out to the maintainers of the 3rd party Stencil component or report this on the Stencil Discord server (https://chat.stenciljs.com) or comment on this similar [GitHub issue](https://github.com/stenciljs/core/issues/5457).`)}const o=s.i.get(t);const i=s.u;const a=s.l;n=_(n,r.o[t][0]);const f=Number.isNaN(o)&&Number.isNaN(n);const c=n!==o&&!f;if((!(i&8)||o===void 0)&&c){s.i.set(t,n);if(a){if((i&(2|16))===2){if(a.componentShouldUpdate){if(a.componentShouldUpdate(n,o,t)===false){return}}Se(s,false)}}}};var Re=(e,n,r)=>{var s,o;const i=e.prototype;if(n.o||t.watchCallback){const a=Object.entries((s=n.o)!=null?s:{});a.map((([e,[t]])=>{if(t&31||r&2&&t&32){const{get:s,set:o}=Object.getOwnPropertyDescriptor(i,e)||{};if(s)n.o[e][0]|=2048;if(o)n.o[e][0]|=4096;if(r&1||!s){Object.defineProperty(i,e,{get(){{if((n.o[e][0]&2048)===0){return Ne(this,e)}const t=l(this);const r=t?t.l:i;if(!r)return;return r[e]}},configurable:true,enumerable:true})}Object.defineProperty(i,e,{set(s){const i=l(this);if(o){const r=t&32?this[e]:i.$hostElement$[e];if(typeof r==="undefined"&&i.i.get(e)){s=i.i.get(e)}else if(!i.i.get(e)&&r){i.i.set(e,r)}o.apply(this,[_(s,t)]);s=t&32?this[e]:i.$hostElement$[e];Ue(this,e,s,n);return}{if((r&1)===0||(n.o[e][0]&4096)===0){Ue(this,e,s,n);if(r&1&&!i.l){i.p.then((()=>{if(n.o[e][0]&4096&&i.l[e]!==i.i.get(e)){i.l[e]=s}}))}return}const o=()=>{const r=i.l[e];if(!i.i.get(e)&&r){i.i.set(e,r)}i.l[e]=_(s,t);Ue(this,e,i.l[e],n)};if(i.l){o()}else{i.p.then((()=>o()))}}}})}else if(r&1&&t&64){Object.defineProperty(i,e,{value(...t){var n;const r=l(this);return(n=r==null?void 0:r.v)==null?void 0:n.then((()=>{var n;return(n=r.l)==null?void 0:n[e](...t)}))}})}}));if(r&1){const r=new Map;i.attributeChangedCallback=function(e,s,o){w.jmp((()=>{var a;const f=r.get(e);if(this.hasOwnProperty(f)&&t.lazyLoad){o=this[f];delete this[f]}else if(i.hasOwnProperty(f)&&typeof this[f]==="number"&&this[f]==o){return}else if(f==null){const t=l(this);const r=t==null?void 0:t.u;if(r&&!(r&8)&&r&128&&o!==s){const r=t.l;const i=(a=n.A)==null?void 0:a[e];i==null?void 0:i.forEach((t=>{if(r[t]!=null){r[t].call(r,o,s,e)}}))}return}const c=Object.getOwnPropertyDescriptor(i,f);o=o===null&&typeof this[f]==="boolean"?false:o;if(o!==this[f]&&(!c.get||!!c.set)){this[f]=o}}))};e.observedAttributes=Array.from(new Set([...Object.keys((o=n.A)!=null?o:{}),...a.filter((([e,t])=>t[0]&15)).map((([e,t])=>{const n=t[1]||e;r.set(n,e);return n}))]))}}return e};var De=async(e,t,n,r)=>{let s;if((t.u&32)===0){t.u|=32;const r=n.S;if(r){const r=d(n,t);if(r&&"then"in r){const e=H();s=await r;e()}else{s=r}if(!s){throw new Error(`Constructor for "${n.$}#${t.L}" was not found`)}if(!s.isProxied){Re(s,n,2);s.isProxied=true}const o=F("createInstance",n.$);{t.u|=8}try{new s(t)}catch(t){u(t,e)}{t.u&=-9}o();We(t.l,e)}else{s=e.constructor;const n=e.localName;customElements.whenDefined(n).then((()=>t.u|=128))}if(s&&s.style){let e;if(typeof s.style==="string"){e=s.style}const t=te(n);if(!h.has(t)){const r=F("registerStyles",n.$);X(t,e,!!(n.u&1));r()}}}const o=t.W;const i=()=>Se(t,true);if(o&&o["s-rc"]){o["s-rc"].push(i)}else{i()}};var We=(e,t)=>{{xe(e,"connectedCallback",void 0,t)}};var Ae=e=>{if((w.u&1)===0){const t=l(e);const n=t.t;const r=F("connectedCallback",n.$);if(!(t.u&1)){t.u|=1;{let n=e;while(n=n.parentNode||n.host){if(n["s-p"]){$e(t,t.W=n);break}}}if(n.o){Object.entries(n.o).map((([t,[n]])=>{if(n&31&&e.hasOwnProperty(t)){const n=e[t];delete e[t];e[t]=n}}))}{De(e,t,n)}}else{if(t==null?void 0:t.l){We(t.l,e)}else if(t==null?void 0:t.p){t.p.then((()=>We(t.l,e)))}}r()}};var Le=(e,t)=>{{xe(e,"disconnectedCallback",void 0,t||e)}};var Te=async e=>{if((w.u&1)===0){const t=l(e);if(t==null?void 0:t.l){Le(t.l,e)}else if(t==null?void 0:t.p){t.p.then((()=>Le(t.l,e)))}}if(Q.has(e)){Q.delete(e)}if(e.shadowRoot&&Q.has(e.shadowRoot)){Q.delete(e.shadowRoot)}};var ze=(e,t={})=>{var n;if(!b.document){console.warn("Stencil: No document found. Skipping bootstrapping lazy components.");return}const r=F();const s=[];const o=t.exclude||[];const i=b.customElements;const a=b.document.head;const c=a.querySelector("meta[charset]");const u=b.document.createElement("style");const v=[];let d;let h=true;Object.assign(w,t);w.j=new URL(t.resourcesUrl||"./",b.document.baseURI).href;let p=false;e.map((e=>{e[1].map((t=>{const n={u:t[0],$:t[1],o:t[2],T:t[3]};if(n.u&4){p=true}{n.o=t[2]}const r=n.$;const a=class extends HTMLElement{constructor(e){super(e);this.hasRegisteredEventListeners=false;e=this;f(e,n);if(n.u&1){{if(!e.shadowRoot){z.call(e,n)}else{if(e.shadowRoot.mode!=="open"){throw new Error(`Unable to re-use existing shadow root for ${n.$}! Mode is set to ${e.shadowRoot.mode} but Stencil only supports open shadow roots.`)}}}}}connectedCallback(){l(this);if(!this.hasRegisteredEventListeners){this.hasRegisteredEventListeners=true}if(d){clearTimeout(d);d=null}if(h){v.push(this)}else{w.jmp((()=>Ae(this)))}}disconnectedCallback(){w.jmp((()=>Te(this)));w.raf((()=>{var e;const t=l(this);const n=v.findIndex((e=>e===this));if(n>-1){v.splice(n,1)}if(((e=t==null?void 0:t.R)==null?void 0:e.N)instanceof Node&&!t.R.N.isConnected){delete t.R.N}}))}componentOnReady(){return l(this).p}};n.S=e[0];if(!o.includes(r)&&!i.get(r)){s.push(r);i.define(r,Re(a,n,1))}}))}));if(s.length>0){if(p){u.textContent+=y}{u.textContent+=s.sort()+m}if(u.innerHTML.length){u.setAttribute("data-styles","");const e=(n=w.U)!=null?n:N(b.document);if(e!=null){u.setAttribute("nonce",e)}a.insertBefore(u,c?c.nextSibling:a.firstChild)}}h=false;if(v.length){v.map((e=>e.connectedCallback()))}else{{w.jmp((()=>d=setTimeout(Me,30)))}}r()};var Fe=e=>w.U=e;export{B as a,ze as b,J as c,n as g,I as h,$ as p,a as r,Fe as s};
3
- //# sourceMappingURL=p-BP1Q4KOg.js.map