@didit-protocol/sdk-web 0.5.3 → 0.6.0

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.
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Didit SDK for Web v0.5.3
2
+ * Didit SDK for Web v0.6.0
3
3
  * (c) 2026 Didit
4
4
  * @license MIT
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DiditSDK={})}(this,function(e){"use strict";const t="didit-pid-v1",i="didit_pid",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let a=null,o=null,r=null,s=null;function d(e){let t="",i=0;for(;i+2<e.length;i+=3){const a=e[i]<<16|e[i+1]<<8|e[i+2];t+=n[a>>18&63],t+=n[a>>12&63],t+=n[a>>6&63],t+=n[63&a]}if(i<e.length){const a=e.length-i,o=e[i]<<16|(a>1?e[i+1]:0)<<8;t+=n[o>>18&63],t+=n[o>>12&63],a>1&&(t+=n[o>>6&63])}return t}function l(e){return d(function(e){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const t=new Uint8Array(e);return crypto.getRandomValues(t),t}const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=Math.floor(256*Math.random());return t}(e))}function c(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function u(e){if(null==e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map(e=>u(e)).join(",")}]`;if("object"==typeof e){return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${u(e[t])}`).join(",")}}`}return JSON.stringify(e)}function h(e){return"string"==typeof e&&/^[A-Za-z0-9_-]{20,32}$/.test(e)}function f(){const e=function(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(t);return h(e)?e:null}catch{return null}}(),n=function(){try{if("undefined"==typeof document||!document.cookie)return null;const e=`${i}=`;for(const t of document.cookie.split(";")){const i=t.trim();if(i.startsWith(e)){const t=decodeURIComponent(i.substring(e.length));return h(t)?t:null}}return null}catch{return null}}();let o,r,s=!1;return e?(o=e,r=n===e?["localStorage","cookie"]:["localStorage"]):n?(o=n,r=["cookie"]):a&&h(a)?(o=a,r=["memory"]):(o=l(16),r=["fresh"],s=!0),a=o,e!==o&&function(e){try{if("undefined"==typeof localStorage)return;localStorage.setItem(t,e)}catch{}}(o),n!==o&&function(e){try{if("undefined"==typeof document)return;const t="undefined"!=typeof location&&"https:"===location.protocol,n=[`${i}=${encodeURIComponent(e)}`,"Path=/","Max-Age=63072000","SameSite=Lax"];t&&n.push("Secure"),document.cookie=n.join("; ")}catch{}}(o),{id:o,sources:r,wasCreated:s}}function m(e){const t=[],i=e.navigator.userAgent;return"undefined"!=typeof navigator&&navigator.webdriver&&t.push("webdriver"),/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(i)&&t.push("headless-ua"),!1===e.navigator.uaDataMobile&&/Android|iPhone|iPad/i.test(i)&&t.push("ua-mobile-mismatch"),{score:Math.min(1,t.length/4),flags:t}}function p(e){return u({platform:e.platform,navigator:{ua:e.navigator.userAgent,platform:e.navigator.platform,lang:e.navigator.language.split("-")[0],languages:[...e.navigator.languages].sort(),concurrency:e.navigator.hardwareConcurrency,memory:e.navigator.deviceMemory,maxTouch:e.navigator.maxTouchPoints,dpr:e.navigator.devicePixelRatio,screen:[e.navigator.screenWidth,e.navigator.screenHeight],colorDepth:e.navigator.colorDepth,timeZone:e.navigator.timeZone,uaDataPlatform:e.navigator.uaDataPlatform,uaDataBrands:e.navigator.uaDataBrands},webview:e.webview.kind})}async function g(e){try{return await async function(e){if("undefined"==typeof crypto||!crypto.subtle)throw new Error("WebCrypto SubtleCrypto is not available");const t=(new TextEncoder).encode(e),i=new Uint8Array(t.byteLength);i.set(t);const n=await crypto.subtle.digest("SHA-256",i.buffer);return d(new Uint8Array(n).slice(0,16))}(e)}catch{return`fnv-${c(e)}${c(`${e}:fallback`)}`}}async function v(){const e=f(),t=function(){const e="undefined"!=typeof navigator?navigator:null,t="undefined"!=typeof screen?screen:null;let i=null;try{i=Intl.DateTimeFormat().resolvedOptions().timeZone??null}catch{i=null}const n=e?e.userAgentData:void 0;return{userAgent:e?.userAgent??"",platform:e?.platform??null,language:e?.language??"",languages:e?.languages?[...e.languages]:[],hardwareConcurrency:"number"==typeof e?.hardwareConcurrency?e.hardwareConcurrency:null,deviceMemory:(()=>{const t=e?e.deviceMemory:void 0;return"number"==typeof t?t:null})(),maxTouchPoints:"number"==typeof e?.maxTouchPoints?e.maxTouchPoints:null,devicePixelRatio:"undefined"!=typeof window&&"number"==typeof window.devicePixelRatio?window.devicePixelRatio:null,screenWidth:"number"==typeof t?.width?t.width:null,screenHeight:"number"==typeof t?.height?t.height:null,colorDepth:"number"==typeof t?.colorDepth?t.colorDepth:null,timeZone:i,uaDataPlatform:n?.platform??null,uaDataMobile:"boolean"==typeof n?.mobile?n.mobile:null,uaDataBrands:n?.brands?n.brands.map(e=>`${e.brand} ${e.version}`):[]}}(),i={platform:"web",navigator:t,webview:{kind:(n=t.userAgent,/;\s?wv\)/.test(n)||/\bVersion\/[\d.]+\s+Chrome\/[\d.]+\s+Mobile\b/.test(n)?"android-webview":/FBAN|FBAV|Instagram|Line\/|MicroMessenger|Snapchat|musical_ly|BytedanceWebview/i.test(n)?"in-app-browser":!/iPhone|iPad|iPod/.test(n)||/Safari\//.test(n)||/CriOS|FxiOS|EdgiOS/.test(n)?"browser":"ios-webview")}};var n;const a={version:2,schema:"didit-fp-v2",platform:"web",collectedAt:(new Date).toISOString(),persistentId:e.id,persistentIdSources:e.sources,persistentIdWasCreated:e.wasCreated,signals:i,bot:m(i),compositeHash:""};return r=a,{...a,compositeHash:await g(p(i))}}async function b(){return"undefined"==typeof window||"undefined"==typeof navigator||"undefined"==typeof document?null:o||(s||(s=v().then(e=>(o=e,e),e=>{throw s=null,e})),s)}function y(e){if(!e)return{};const t={"X-Didit-FP-V2":"1"};return e.persistentId&&(t["X-Didit-PID"]=e.persistentId),e.compositeHash&&(t["X-Didit-FP-Hash"]=e.compositeHash),e.signals.webview.kind&&(t["X-Didit-FP-Webview"]=e.signals.webview.kind),e.bot.score&&(t["X-Didit-FP-Bot-Score"]=e.bot.score.toFixed(2)),t}const w="https://verification.didit.me",x=/^(security|payment|dispute|responsible_gambling)\.|^gameplay\.(bet_placed|bet_settled|p2p_settlement)$/,k=/^session\.(page_view|sdk_heartbeat|sdk_loaded|device_seen|bot_signal_observed)$|^bonus\.promotion_viewed$|^affiliate\.referral_clicked$/;class C extends Error{constructor(e,t,i){super(t),this.name="DiditEventError",this.type=e,this.status=i?.status,this.eventIds=i?.eventIds??[],this.errors=i?.errors}}let M,L={...{baseUrl:w,batchSize:25,flushIntervalMs:5e3,maxQueueSize:1e3}},T=[],B=0,_=0,S=Promise.resolve(),D=!1,E=!1,I=0;function $(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function z(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function j(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||void 0}catch{return}}function A(e){try{L.onError?.(e)}catch{}}function O(){return T.filter(e=>!e.sending)}function F(){void 0!==M&&clearTimeout(M),M=void 0}function P(){var e;!_&&O().length&&(e=B?Math.min(Math.max(1e3,L.flushIntervalMs)*2**B,6e4):L.flushIntervalMs,void 0===M&&(M=setTimeout(()=>{M=void 0,G().catch(()=>{})},e)))}function H(e=1/0,t=0){const i=[];let n=t;for(const t of T){if(i.length===L.batchSize)break;t.sending||n+t.bytes+(i.length?1:0)>e||(!i.length||t.token===i[0].token&&t.url===i[0].url)&&(n+=t.bytes+(i.length?1:0),i.push(t))}return i}function q(e,t,i){const n=function(e){return $(e)&&"string"==typeof e.detail?e.detail:void 0}(t),a=$(t)&&"string"==typeof t.code?t.code:"";let o="validation";return"event_monitoring_disabled"===a?o="monitoring_disabled":401!==e&&403!==e||(o=/expired/i.test(`${n} ${a}`)?"expired_token":"invalid_token"),new C(o,n??`Didit refused the events with status ${e}.`,{status:e,eventIds:i,errors:"validation"===o&&$(t)?t:void 0})}function V(e){return encodeURIComponent(e).replace(/%[\dA-F]{2}/g,"-").length}function N(e,t){const i=t?`,"fingerprint_v2":${JSON.stringify(t)}`:"";return`{"events":[${e.map(e=>e.json).join(",")}]${i}}`}async function R(e,t,i,n=!1){const a=N(e,i),o=n?V(a):0,r=new Set,s=[],d=(e,i)=>{t.results.push({eventId:e.id,outcome:"rejected",error:i}),t.rejectedCount++,r.add(e)};for(const t of e)t.sending=!0;I+=o;try{const o=await fetch(e[0].url,{method:"POST",redirect:"error",keepalive:n,headers:{"Content-Type":"application/json","X-Monitoring-Token":e[0].token,...y(i)},body:a}),c=await async function(e){try{return await e.json()}catch{return null}}(o);if(408===(l=o.status)||429===l||l>=500||!$(c))return!1;if(!o.ok){const t=q(o.status,c,e.map(e=>e.id));for(const i of e)d(i,t);return s.push(t),!0}const u=$(c)&&Array.isArray(c.results)?c.results:[];return e.forEach((e,i)=>{const n=u.filter(e=>$(e)&&e.index===i),a=n[0];if(1===n.length&&$(a))if("accepted"===a.outcome||"replayed"===a.outcome){if("string"!=typeof a.event_uuid||!a.event_uuid)return;const i={eventId:e.id,outcome:a.outcome,eventUuid:a.event_uuid};"string"==typeof a.status&&(i.status=a.status),"number"!=typeof a.score&&null!==a.score||(i.score=a.score),t.results.push(i),t["accepted"===a.outcome?"acceptedCount":"replayedCount"]++,r.add(e)}else if("rejected"===a.outcome&&$(a.errors)){const t=new C("validation","Didit rejected the event; see errors for the details.",{status:o.status,eventIds:[e.id],errors:a.errors});d(e,t),s.push(t)}}),r.size===e.length}catch{return!1}finally{I-=o,T=T.filter(e=>!r.has(e));for(const t of e)t.sending=!1;B=r.size===e.length?0:B+1,n&&P(),s.forEach(A)}var l}function U(){return{acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[]}}async function K(){const e={acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[]},t=await b().catch(()=>null);let i;for(F();(i=H()).length&&await R(i,e,t););return e.pendingCount=T.length,e}async function W(){if(!E){E=!0,F();try{const e=o??r,t=V(N([],e));let i;for(;(i=H(65536-I,t)).length;)R(i,U(),e,!0).catch(()=>{})}finally{E=!1,P()}}}function Z(){W().catch(()=>{})}function J(){"hidden"===document.visibilityState&&Z()}function X(e){const t=e?.monitoringToken,i=e?.event;if(!t||"string"!=typeof t)throw new C("invalid_token","monitoringToken is required.");if(!$(i)||!i.category||"string"!=typeof i.actionType||!i.actionType.trim())throw new C("validation","event.category and event.actionType are required.");if(i.occurredAt instanceof Date&&Number.isNaN(i.occurredAt.getTime()))throw new C("validation","event.occurredAt must be a valid date.");if("function"!=typeof fetch)throw new C("network","fetch is not available in this environment.");const n=i.eventId||("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():l(16)),a=JSON.stringify(function(e,t){const{session:i,transactionContext:n,subject:a,occurredAt:o}=e;return z({event_id:t,event_category:e.category,action_type:e.actionType,occurred_at:o instanceof Date?o.toISOString():o??(new Date).toISOString(),time_zone:e.timeZone??j(),subject:a&&z({full_name:a.fullName,email:a.email,phone:a.phone,country:a.country}),business:e.business,session:i&&z({session_id:i.sessionId,sequence:i.sequence,page_url:i.pageUrl,referrer:i.referrer}),transaction_context:n&&z({amount:n.amount,currency:n.currency,direction:n.direction,payment_reference_id:n.paymentReferenceId}),payload:e.payload,custom_values:e.customValues})}(i,n)),o=`${i.category}.${i.actionType}`;return function(e){let t;if(T.length>=L.maxQueueSize){for(const e of O())(!t||e.priority<t.priority)&&(t=e);(!t||e.priority<t.priority)&&(t=e),2===t.priority&&(t=void 0)}t&&t!==e&&T.splice(T.indexOf(t),1),t!==e&&T.push(e),t&&A(new C("dropped","The event queue is full, so the event was dropped before it was sent.",{eventIds:[t.id]}))}({id:n,json:a,bytes:V(a),token:t,url:`${(e.baseUrl??L.baseUrl).replace(/\/+$/,"")}/v1/events/batch/`,priority:x.test(o)?2:k.test(o)?0:1,sending:!1}),D||"undefined"==typeof window||"undefined"==typeof document||(D=!0,window.addEventListener("pagehide",Z),document.addEventListener("visibilitychange",J)),b().catch(()=>null),!_&&!B&&O().length>=L.batchSize?G().catch(()=>{}):P(),n}function G(){_++;const e=S.then(K).catch(()=>({acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[],pendingCount:T.length})).finally(()=>{_--,P()});return S=e,e}const Q=9999,Y=!0,ee=!0,te=!1,ie="didit-modal-overlay",ne="didit-modal-container",ae="didit-verification-iframe",oe="didit-close-button",re="didit-close-icon",se="didit-close-icon-legacy",de="didit-flow-sized",le="didit-size-animated",ce="didit-loading",ue="didit-confirm-overlay",he="didit-confirm-box",fe="didit-embedded",me="camera; microphone; fullscreen; autoplay; encrypted-media; geolocation; clipboard-write; digital-credentials-get",pe={defaultDocumentCamera:"document_camera",defaultLivenessCamera:"liveness_camera",showDocumentCameraSwitchButton:"document_camera_switch",showLivenessCameraSwitchButton:"liveness_camera_switch"},ge=["front","back"],ve="sdk_presentation",be="sdk_close_button",ye=["ar","fa","he"],we=["ar","bg","bn","ca","cnr","cs","da","de","el","en","es","et","fa","fi","fr","he","hi","hr","hu","hy","id","it","ja","ka","ko","lt","lv","mk","mn","ms","nl","no","pl","pt-BR","pt","ro","ru","sk","sl","so","sr","sv","th","tr","uk","uz","vi","zh-CN","zh-TW","zh"];class xe{static get isEnabled(){return this._enabled}static set isEnabled(e){this._enabled=e}static log(...e){this._enabled&&console.log("[DiditSDK]",...e)}static warn(...e){this._enabled&&console.warn("[DiditSDK]",...e)}static error(...e){this._enabled&&console.error("[DiditSDK]",...e)}}function ke(e,t){return{type:e,message:t||{sessionExpired:"Your verification session has expired.",networkError:"A network error occurred. Please try again.",cameraAccessDenied:"Camera access is required for verification.",unknown:t||"An unknown error occurred."}[e]}}function Ce(e){return ge.includes(e)}xe._enabled=!1;const Me=["defaultDocumentCamera","defaultLivenessCamera"],Le=["showDocumentCameraSwitchButton","showLivenessCameraSwitchButton"];function Te(e,t={}){const i=function(e){if(e.embedded)return[[ve,"embedded"]];const t=e.showCloseButton??Y;return[[ve,"modal"],[be,t?"true":"false"]]}(t);for(const e of Me){const n=t[e];void 0!==n&&(Ce(n)?i.push([pe[e],n]):xe.warn(`Ignoring ${e}: expected "front" or "back", got`,n))}for(const e of Le){const n=t[e];void 0!==n&&("boolean"==typeof n?i.push([pe[e],n?"true":"false"]):xe.warn(`Ignoring ${e}: expected a boolean, got`,n))}try{const t=new URL(e);return i.forEach(([e,i])=>t.searchParams.set(e,i)),t.toString()}catch{return e}}const Be={exitTitle:"Exit verification?",exitMessage:"Exiting will end your verification process. Are you sure?",continueButton:"Continue",exitButton:"Exit",ariaLabelModal:"Didit Verification",ariaLabelClose:"Close verification"},_e={ar:{exitTitle:"الخروج من التحقق؟",exitMessage:"سيؤدي الخروج إلى إنهاء عملية التحقق الخاصة بك. هل أنت متأكد؟",continueButton:"متابعة",exitButton:"خروج",ariaLabelModal:"التحقق من Didit",ariaLabelClose:"إغلاق التحقق"},bg:{exitTitle:"Излизане от верификацията?",exitMessage:"Излизането ще прекрати процеса на верификация. Сигурни ли сте?",continueButton:"Продължи",exitButton:"Изход",ariaLabelModal:"Верификация Didit",ariaLabelClose:"Затваряне на верификацията"},bn:{exitTitle:"যাচাইকরণ থেকে বের হবেন?",exitMessage:"বের হলে আপনার যাচাইকরণ প্রক্রিয়া শেষ হয়ে যাবে। আপনি কি নিশ্চিত?",continueButton:"চালিয়ে যান",exitButton:"বের হন",ariaLabelModal:"Didit যাচাইকরণ",ariaLabelClose:"যাচাইকরণ বন্ধ করুন"},bs:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},ca:{exitTitle:"Sortir de la verificació?",exitMessage:"Sortir finalitzarà el procés de verificació. N'esteu segur?",continueButton:"Continua",exitButton:"Sortir",ariaLabelModal:"Verificació Didit",ariaLabelClose:"Tancar verificació"},cnr:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},cs:{exitTitle:"Opravdu chcete odejít?",exitMessage:"Když odejdete, proces ověření se přeruší. Opravdu chcete skončit?",continueButton:"Zůstat",exitButton:"Odejít",ariaLabelModal:"Ověření Didit",ariaLabelClose:"Zavřít ověření"},da:{exitTitle:"Forlad verifikation?",exitMessage:"Hvis du forlader, afsluttes din verifikationsproces. Er du sikker?",continueButton:"Fortsæt",exitButton:"Forlad",ariaLabelModal:"Didit-verifikation",ariaLabelClose:"Luk verifikation"},de:{exitTitle:"Verifizierung verlassen?",exitMessage:"Das Verlassen beendet Ihren Verifizierungsprozess. Sind Sie sicher?",continueButton:"Fortfahren",exitButton:"Verlassen",ariaLabelModal:"Didit-Verifizierung",ariaLabelClose:"Verifizierung schließen"},el:{exitTitle:"Έξοδος από την επαλήθευση;",exitMessage:"Η έξοδος θα τερματίσει τη διαδικασία επαλήθευσης. Είστε σίγουροι;",continueButton:"Συνέχεια",exitButton:"Έξοδος",ariaLabelModal:"Επαλήθευση Didit",ariaLabelClose:"Κλείσιμο επαλήθευσης"},en:Be,es:{exitTitle:"¿Salir de la verificación?",exitMessage:"Salir terminará tu proceso de verificación. ¿Estás seguro?",continueButton:"Continuar",exitButton:"Salir",ariaLabelModal:"Verificación Didit",ariaLabelClose:"Cerrar verificación"},et:{exitTitle:"Lahkuda kinnitamisest?",exitMessage:"Lahkumine lõpetab teie kinnitamisprotsessi. Kas olete kindel?",continueButton:"Jätka",exitButton:"Lahku",ariaLabelModal:"Didit kinnitus",ariaLabelClose:"Sulge kinnitus"},fa:{exitTitle:"خروج از تأیید هویت؟",exitMessage:"خروج باعث پایان فرآیند تأیید هویت شما می‌شود. آیا مطمئن هستید؟",continueButton:"ادامه",exitButton:"خروج",ariaLabelModal:"تأیید هویت Didit",ariaLabelClose:"بستن تأیید هویت"},fi:{exitTitle:"Poistu vahvistuksesta?",exitMessage:"Poistuminen päättää vahvistusprosessisi. Oletko varma?",continueButton:"Jatka",exitButton:"Poistu",ariaLabelModal:"Didit-vahvistus",ariaLabelClose:"Sulje vahvistus"},fr:{exitTitle:"Quitter la vérification ?",exitMessage:"Quitter mettra fin à votre processus de vérification. Êtes-vous sûr ?",continueButton:"Continuer",exitButton:"Quitter",ariaLabelModal:"Vérification Didit",ariaLabelClose:"Fermer la vérification"},he:{exitTitle:"לצאת מהאימות?",exitMessage:"יציאה תסיים את תהליך האימות שלך. האם אתה בטוח?",continueButton:"המשך",exitButton:"יציאה",ariaLabelModal:"אימות Didit",ariaLabelClose:"סגירת אימות"},hi:{exitTitle:"सत्यापन से बाहर निकलें?",exitMessage:"बाहर निकलने से आपकी सत्यापन प्रक्रिया समाप्त हो जाएगी। क्या आप सुनिश्चित हैं?",continueButton:"जारी रखें",exitButton:"बाहर निकलें",ariaLabelModal:"Didit सत्यापन",ariaLabelClose:"सत्यापन बंद करें"},hr:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},hu:{exitTitle:"Kilépés az ellenőrzésből?",exitMessage:"A kilépés befejezi az ellenőrzési folyamatot. Biztos benne?",continueButton:"Folytatás",exitButton:"Kilépés",ariaLabelModal:"Didit ellenőrzés",ariaLabelClose:"Ellenőrzés bezárása"},hy:{exitTitle:"Դուրս գա՞լ ստուգումից",exitMessage:"Դուրս գալը կավարտի ձեր ստուգման գործընթացը։ Համոզված ե՞ք?",continueButton:"Շարունակել",exitButton:"Դուրս գալ",ariaLabelModal:"Didit ստուգում",ariaLabelClose:"Փակել ստուգումը"},id:{exitTitle:"Keluar dari verifikasi?",exitMessage:"Keluar akan mengakhiri proses verifikasi Anda. Apakah Anda yakin?",continueButton:"Lanjutkan",exitButton:"Keluar",ariaLabelModal:"Verifikasi Didit",ariaLabelClose:"Tutup verifikasi"},it:{exitTitle:"Uscire dalla verifica?",exitMessage:"L'uscita terminerà il processo di verifica. Sei sicuro?",continueButton:"Continua",exitButton:"Esci",ariaLabelModal:"Verifica Didit",ariaLabelClose:"Chiudi verifica"},ja:{exitTitle:"認証を終了しますか?",exitMessage:"終了すると認証プロセスが中断されます。よろしいですか?",continueButton:"続ける",exitButton:"終了",ariaLabelModal:"Didit 認証",ariaLabelClose:"認証を閉じる"},ka:{exitTitle:"გამოსვლა შემოწმებიდან?",exitMessage:"გამოსვლა დაასრულებს თქვენს შემოწმების პროცესს. დარწმუნებული ხართ?",continueButton:"გაგრძელება",exitButton:"გამოსვლა",ariaLabelModal:"Didit შემოწმება",ariaLabelClose:"შემოწმების დახურვა"},kk:{exitTitle:"Растаудан шығасыз ба?",exitMessage:"Шығу растау процесін аяқтайды. Сенімдісіз бе?",continueButton:"Жалғастыру",exitButton:"Шығу",ariaLabelModal:"Didit растауы",ariaLabelClose:"Растауды жабу"},ko:{exitTitle:"인증을 종료하시겠습니까?",exitMessage:"종료하면 인증 절차가 중단됩니다. 확실하십니까?",continueButton:"계속",exitButton:"종료",ariaLabelModal:"Didit 인증",ariaLabelClose:"인증 닫기"},ky:{exitTitle:"Текшерүүдөн чыгасызбы?",exitMessage:"Чыгуу текшерүү процессин токтотот. Ишенесизби?",continueButton:"Улантуу",exitButton:"Чыгуу",ariaLabelModal:"Didit текшерүүсү",ariaLabelClose:"Текшерүүнү жабуу"},lt:{exitTitle:"Išeiti iš patvirtinimo?",exitMessage:"Išėjimas nutrauks jūsų patvirtinimo procesą. Ar esate tikri?",continueButton:"Tęsti",exitButton:"Išeiti",ariaLabelModal:"Didit patvirtinimas",ariaLabelClose:"Uždaryti patvirtinimą"},lv:{exitTitle:"Iziet no verifikācijas?",exitMessage:"Iziešana pārtrauks jūsu verifikācijas procesu. Vai esat pārliecināts?",continueButton:"Turpināt",exitButton:"Iziet",ariaLabelModal:"Didit verifikācija",ariaLabelClose:"Aizvērt verifikāciju"},mk:{exitTitle:"Излези од верификацијата?",exitMessage:"Излегувањето ќе го прекине процесот на верификација. Дали сте сигурни?",continueButton:"Продолжи",exitButton:"Излези",ariaLabelModal:"Верификација Didit",ariaLabelClose:"Затвори верификација"},mn:{exitTitle:"Баталгаажуулалтаас гарах уу?",exitMessage:"Гарвал таны баталгаажуулалтын процесс дуусна. Та итгэлтэй байна уу?",continueButton:"Үргэлжлүүлэх",exitButton:"Гарах",ariaLabelModal:"Didit баталгаажуулалт",ariaLabelClose:"Баталгаажуулалтыг хаах"},ms:{exitTitle:"Keluar dari pengesahan?",exitMessage:"Keluar akan menamatkan proses pengesahan anda. Adakah anda pasti?",continueButton:"Teruskan",exitButton:"Keluar",ariaLabelModal:"Pengesahan Didit",ariaLabelClose:"Tutup pengesahan"},nl:{exitTitle:"Verificatie verlaten?",exitMessage:"Verlaten beëindigt uw verificatieproces. Weet u het zeker?",continueButton:"Doorgaan",exitButton:"Verlaten",ariaLabelModal:"Didit-verificatie",ariaLabelClose:"Verificatie sluiten"},no:{exitTitle:"Forlat verifisering?",exitMessage:"Å forlate vil avslutte verifiseringsprosessen. Er du sikker?",continueButton:"Fortsett",exitButton:"Forlat",ariaLabelModal:"Didit-verifisering",ariaLabelClose:"Lukk verifisering"},pl:{exitTitle:"Czy wyjść z weryfikacji?",exitMessage:"Wyjście zakończy proces weryfikacji. Czy na pewno?",continueButton:"Kontynuuj",exitButton:"Wyjdź",ariaLabelModal:"Weryfikacja Didit",ariaLabelClose:"Zamknij weryfikację"},"pt-BR":{exitTitle:"Sair da verificação?",exitMessage:"Sair encerrará seu processo de verificação. Tem certeza?",continueButton:"Continuar",exitButton:"Sair",ariaLabelModal:"Verificação Didit",ariaLabelClose:"Fechar verificação"},pt:{exitTitle:"Sair da verificação?",exitMessage:"Sair terminará o seu processo de verificação. Tem a certeza?",continueButton:"Continuar",exitButton:"Sair",ariaLabelModal:"Verificação Didit",ariaLabelClose:"Fechar verificação"},ro:{exitTitle:"Ieși din verificare?",exitMessage:"Ieșirea va încheia procesul de verificare. Ești sigur?",continueButton:"Continuă",exitButton:"Ieși",ariaLabelModal:"Verificare Didit",ariaLabelClose:"Închide verificarea"},ru:{exitTitle:"Выйти из верификации?",exitMessage:"Выход завершит процесс верификации. Вы уверены?",continueButton:"Продолжить",exitButton:"Выйти",ariaLabelModal:"Верификация Didit",ariaLabelClose:"Закрыть верификацию"},sk:{exitTitle:"Opustiť overenie?",exitMessage:"Odchodom ukončíte proces overenia. Ste si istí?",continueButton:"Pokračovať",exitButton:"Odísť",ariaLabelModal:"Overenie Didit",ariaLabelClose:"Zavrieť overenie"},sl:{exitTitle:"Zapustiti preverjanje?",exitMessage:"Izhod bo prekinil postopek preverjanja. Ali ste prepričani?",continueButton:"Nadaljuj",exitButton:"Izhod",ariaLabelModal:"Preverjanje Didit",ariaLabelClose:"Zapri preverjanje"},so:{exitTitle:"Ka baxdo xaqiijinta?",exitMessage:"Ka bixitaanku wuxuu dhammayn doonaa habka xaqiijintaada. Ma hubtaa?",continueButton:"Sii wad",exitButton:"Ka bax",ariaLabelModal:"Xaqiijinta Didit",ariaLabelClose:"Xir xaqiijinta"},sq:{exitTitle:"Dilni nga verifikimi?",exitMessage:"Dalja do të përfundojë procesin tuaj të verifikimit. A jeni të sigurt?",continueButton:"Vazhdo",exitButton:"Dil",ariaLabelModal:"Verifikimi Didit",ariaLabelClose:"Mbyll verifikimin"},sr:{exitTitle:"Изаћи из верификације?",exitMessage:"Изласком ћете прекинути процес верификације. Да ли сте сигурни?",continueButton:"Настави",exitButton:"Изађи",ariaLabelModal:"Верификација Didit",ariaLabelClose:"Затвори верификацију"},sv:{exitTitle:"Lämna verifiering?",exitMessage:"Att lämna avslutar din verifieringsprocess. Är du säker?",continueButton:"Fortsätt",exitButton:"Lämna",ariaLabelModal:"Didit-verifiering",ariaLabelClose:"Stäng verifiering"},th:{exitTitle:"ออกจากการยืนยันตัวตน?",exitMessage:"การออกจะสิ้นสุดกระบวนการยืนยันตัวตนของคุณ คุณแน่ใจหรือไม่?",continueButton:"ดำเนินการต่อ",exitButton:"ออก",ariaLabelModal:"การยืนยันตัวตน Didit",ariaLabelClose:"ปิดการยืนยันตัวตน"},tr:{exitTitle:"Doğrulamadan çıkmak istiyor musunuz?",exitMessage:"Çıkış, doğrulama sürecinizi sonlandıracak. Emin misiniz?",continueButton:"Devam et",exitButton:"Çıkış",ariaLabelModal:"Didit doğrulama",ariaLabelClose:"Doğrulamayı kapat"},uk:{exitTitle:"Вийти з верифікації?",exitMessage:"Вихід завершить процес верифікації. Ви впевнені?",continueButton:"Продовжити",exitButton:"Вийти",ariaLabelModal:"Верифікація Didit",ariaLabelClose:"Закрити верифікацію"},uz:{exitTitle:"Tekshiruvdan chiqasizmi?",exitMessage:"Chiqish tekshiruv jarayonini tugatadi. Ishonchingiz komilmi?",continueButton:"Davom etish",exitButton:"Chiqish",ariaLabelModal:"Didit tekshiruvi",ariaLabelClose:"Tekshiruvni yopish"},vi:{exitTitle:"Thoát khỏi xác minh?",exitMessage:"Thoát sẽ kết thúc quá trình xác minh của bạn. Bạn có chắc không?",continueButton:"Tiếp tục",exitButton:"Thoát",ariaLabelModal:"Xác minh Didit",ariaLabelClose:"Đóng xác minh"},"zh-CN":{exitTitle:"退出验证?",exitMessage:"退出将结束您的验证流程。确定要退出吗?",continueButton:"继续",exitButton:"退出",ariaLabelModal:"Didit 验证",ariaLabelClose:"关闭验证"},"zh-TW":{exitTitle:"退出驗證?",exitMessage:"退出將結束您的驗證流程。確定要退出嗎?",continueButton:"繼續",exitButton:"退出",ariaLabelModal:"Didit 驗證",ariaLabelClose:"關閉驗證"},zh:{exitTitle:"退出验证?",exitMessage:"退出将结束您的验证流程。确定要退出吗?",continueButton:"继续",exitButton:"退出",ariaLabelModal:"Didit 验证",ariaLabelClose:"关闭验证"}};function Se(e){return _e[e]??Be}class De{constructor(e,t){this.state={isOpen:!1,isLoading:!0,showConfirmation:!1},this.overlay=null,this.container=null,this.iframe=null,this.loadingEl=null,this.confirmOverlay=null,this.confirmationTrigger=null,this.boundHandleMessage=null,this.boundHandleKeydown=null,this.boundHandleFocusChange=null,this.confirmationFocusTimeout=null,this.firstLayoutTimeout=null,this.sizeTimeout=null,this.embedded=!1,this.embeddedContainer=null,this.language="en",this.pageBackground=null,this.previousBodyOverflow=null,this.modalId=`didit-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,this.config={zIndex:e?.zIndex??Q,showCloseButton:e?.showCloseButton??Y,showExitConfirmation:e?.showExitConfirmation??ee},this.callbacks=t,this.containerElement=e?.containerElement??document.body,this.embedded=e?.embedded??!1,this.embedded&&e?.embeddedContainerId&&(this.embeddedContainer=document.getElementById(e.embeddedContainerId))}injectStyles(){const e="didit-sdk-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .${ie} {\n display: none;\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n z-index: ${this.config.zIndex};\n justify-content: center;\n align-items: center;\n padding: 1rem;\n opacity: 0;\n transition: opacity 0.2s ease-out;\n }\n\n .${ie}.active {\n display: flex;\n opacity: 1;\n }\n\n .${ne} {\n position: relative;\n width: 100%;\n max-width: 440px;\n height: min(860px, calc(100vh - 2rem));\n height: min(860px, calc(100dvh - 2rem));\n border-radius: 16px;\n overflow: hidden;\n background: transparent;\n }\n\n .${ie}.active .${ne} {\n transform: scale(1);\n }\n\n .${ae} {\n width: 100%;\n height: 100%;\n border: none;\n display: block;\n }\n\n .${oe} {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 24px;\n height: 24px;\n background: transparent;\n border: none;\n cursor: pointer;\n padding: 0;\n z-index: 10;\n outline: none;\n }\n\n .${oe}:hover,\n .${oe}:focus {\n background: transparent;\n opacity: 0.5;\n }\n\n .${oe} svg {\n stroke: #666;\n stroke-width: 2;\n stroke-linecap: round;\n }\n\n .${ce} {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #fafafa;\n z-index: 5;\n }\n\n @media (prefers-color-scheme: dark) {\n .${ce} {\n background: #0b0b0d;\n }\n }\n\n .${ce}.hidden {\n display: none;\n }\n\n .${ce} svg {\n width: 4rem;\n height: 4rem;\n animation: didit-spin 1s linear infinite;\n }\n\n .${ce} circle {\n stroke: #e5e5e5;\n stroke-width: 2.5;\n fill: none;\n }\n\n .${ce} path {\n stroke: #525252;\n stroke-width: 2.5;\n stroke-linecap: round;\n fill: none;\n }\n\n @keyframes didit-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n\n .${ue} {\n display: none;\n position: absolute;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 20;\n justify-content: center;\n align-items: center;\n opacity: 0;\n transition: opacity 0.15s ease-out;\n }\n\n .${ue}.active {\n display: flex;\n opacity: 1;\n }\n\n .${he} {\n background: #fff;\n border-radius: 12px;\n padding: 1.5rem;\n text-align: center;\n max-width: 300px;\n margin: 1rem;\n transform: scale(0.95);\n transition: transform 0.15s ease-out;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n outline: none;\n }\n\n .${ue}.active .${he} {\n transform: scale(1);\n }\n\n .${he} h3 {\n color: #1a1a2e;\n margin: 0 0 0.5rem 0;\n font-size: 1.125rem;\n font-weight: 600;\n }\n\n .${he} p {\n color: #666;\n font-size: 0.875rem;\n margin: 0 0 1.25rem 0;\n line-height: 1.5;\n }\n\n .didit-confirm-actions {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 1rem;\n }\n\n .didit-confirm-actions [data-action="continue"] {\n background: #2563eb;\n color: #fff;\n border: none;\n padding: 0.625rem 1.25rem;\n border-radius: 8px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease;\n }\n\n .didit-confirm-actions [data-action="continue"]:hover {\n background: #1d4ed8;\n }\n\n .didit-confirm-actions [data-action="exit"] {\n background: transparent;\n border: none;\n font-family: inherit;\n font-weight: inherit;\n line-height: inherit;\n color: #666;\n font-size: 0.875rem;\n cursor: pointer;\n padding: 0.625rem;\n transition: color 0.15s ease;\n }\n\n .didit-confirm-actions [data-action="exit"]:hover {\n color: #1a1a2e;\n }\n\n .didit-confirm-actions button:focus-visible {\n outline: 2px solid #2567ff;\n outline-offset: 2px;\n }\n\n /*\n * Steps are phone-sized (440 x 860, above). On a computer the handoff card is wider\n * (board Start-Embedded): 960 x 660 on a window of 1000px or more, never wider than the\n * window less its margin and never taller than 90% of it. In a narrower window the\n * page stacks and the height follows its content (--didit-content-height, set from the\n * flow's layout message). Until the flow reports what it shows, the modal is the handoff\n * card at its final size with the spinner inside it (the flow stays hidden and lays itself\n * out for that size): it never opens small and grows. The first change of kind (a step\n * instead of the handoff, or the person continues on this computer) animates once.\n */\n @media (min-width: 541px) {\n .${ne}[data-didit-kind="handoff"],\n .${ne}[data-didit-kind="pending"] {\n max-width: min(960px, calc(100vw - 2rem));\n height: min(var(--didit-content-height, 660px), calc(100vh * 0.9));\n height: min(var(--didit-content-height, 660px), calc(100dvh * 0.9));\n }\n\n .${ne}.${le} {\n transition: max-width 0.25s ease, height 0.25s ease;\n }\n\n .${ne}[data-didit-kind="pending"] .${ae} {\n visibility: hidden;\n }\n }\n\n /*\n * While pending the card already looks like the first screen (ground, radius, shadow and\n * close button come from the flow-sized rules below, with the device theme); the loader\n * sits inside it on the card's own ground.\n */\n .${ne}[data-didit-kind="pending"] .${ce} {\n background: transparent;\n }\n\n .${ne}[data-didit-kind="pending"][data-didit-theme="dark"] .${ce} circle {\n stroke: rgba(255, 255, 255, 0.16);\n }\n\n .${ne}[data-didit-kind="pending"][data-didit-theme="dark"] .${ce} path {\n stroke: #f5f5f7;\n }\n\n @media (min-width: 1000px) {\n .${ne}[data-didit-kind="handoff"],\n .${ne}[data-didit-kind="pending"] {\n height: min(660px, calc(100vh * 0.9));\n height: min(660px, calc(100dvh * 0.9));\n }\n }\n\n @media (max-width: 540px) {\n .${ie} {\n padding: 0;\n }\n\n .${ne} {\n max-width: 100%;\n height: 100vh;\n height: 100dvh;\n border-radius: 0;\n }\n }\n\n /*\n * The hosted flow's layout message (didit:layout) brings the modal's size\n * (see above), theme and direction. Colours are the design system tokens\n * named beside them.\n */\n .${ne}.${de} {\n --didit-ground: #ffffff; /* site-ground */\n --didit-heading: #1a1a1a; /* c-heading */\n --didit-accent: #2567ff; /* c-accent */\n --didit-hover: rgba(120, 120, 128, 0.08); /* c-hover */\n --didit-close-fill: rgba(0, 0, 0, 0.06);\n --didit-drop: rgba(17, 24, 39, 0.35);\n --didit-ring: rgba(0, 0, 0, 0.06);\n background: var(--didit-ground);\n box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);\n }\n\n .${ne}.${de}[data-didit-theme="dark"] {\n --didit-ground: #0b0b0d;\n --didit-heading: #f5f5f7;\n --didit-accent: #4d8bff;\n --didit-hover: rgba(255, 255, 255, 0.06);\n --didit-close-fill: rgba(255, 255, 255, 0.06);\n --didit-drop: rgba(0, 0, 0, 0.55); /* c-shadow-pop, dark */\n --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */\n }\n\n .${re} {\n display: none;\n }\n\n .${de} .${oe} {\n top: 8px;\n right: 8px;\n width: 44px;\n height: 44px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n background: var(--didit-close-fill);\n color: var(--didit-heading);\n }\n\n .${de}[data-didit-dir="rtl"] .${oe} {\n right: auto;\n left: 8px;\n }\n\n .${de} .${oe}:hover,\n .${de} .${oe}:focus {\n background: var(--didit-close-fill);\n opacity: 1;\n }\n\n .${de} .${oe}:hover {\n background-image: linear-gradient(var(--didit-hover), var(--didit-hover));\n }\n\n .${de} .${oe}:focus-visible {\n outline: 2px solid var(--didit-accent);\n outline-offset: 2px;\n }\n\n .${de} .${se} {\n display: none;\n }\n\n .${de} .${oe} .${re} {\n display: block;\n stroke: currentColor;\n stroke-width: 1.75;\n stroke-linejoin: round;\n }\n\n /*\n * The exit confirmation is sized in rem, so with a large text size it\n * can be taller than a short flow: it scrolls inside the modal instead\n * of being clipped, and its width and actions follow a larger text size.\n * It never grows wider than the modal: a long word wraps instead.\n */\n .${de} .${ue} {\n padding: 1rem;\n overflow-y: auto;\n }\n\n .${de} .${he} {\n min-width: 0;\n max-width: max(300px, 18.75rem);\n margin: auto;\n overflow-wrap: anywhere;\n /* Focusing the dialog scrolls it into view start-aligned; this keeps\n * the overlay's top padding visible so the title is never clipped. */\n scroll-margin-top: 1rem;\n }\n\n .${de} .didit-confirm-actions {\n flex-wrap: wrap;\n }\n\n @media (max-width: 540px) {\n .${ne}.${de} {\n max-width: 100%;\n box-shadow: none;\n }\n }\n\n .${fe} {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n .${fe} .${ae} {\n width: 100%;\n height: 100%;\n max-height: none;\n }\n\n .${fe} .${ce} {\n border-radius: 0;\n }\n `,document.head.appendChild(t)}createDOM(){if(this.injectStyles(),this.embedded&&this.embeddedContainer)return void this.createEmbeddedDOM();const e=Se(this.language);if(this.overlay=document.createElement("div"),this.overlay.id=this.modalId,this.overlay.className=ie,this.overlay.setAttribute("role","dialog"),this.overlay.setAttribute("aria-modal","true"),this.overlay.setAttribute("aria-label",e.ariaLabelModal),this.container=document.createElement("div"),this.container.className=ne,this.loadingEl=document.createElement("div"),this.loadingEl.className=ce,this.loadingEl.innerHTML='\n <svg viewBox="0 0 24 24">\n <circle cx="12" cy="12" r="10" />\n <path d="M12 2a10 10 0 0 1 10 10" />\n </svg>\n ',this.config.showCloseButton){const t=document.createElement("button");t.className=oe,t.setAttribute("aria-label",e.ariaLabelClose),t.innerHTML=`\n <svg class="${se}" width="14" height="14" viewBox="0 0 14 14">\n <line x1="1" y1="1" x2="13" y2="13" />\n <line x1="13" y1="1" x2="1" y2="13" />\n </svg>\n <svg class="${re}" width="18" height="18" viewBox="0 0 24 24" fill="none">\n <path d="M7 7.03882L17 16.9611" />\n <path d="M7.03968 17L16.9619 7" />\n </svg>\n `,t.addEventListener("click",()=>this.handleCloseRequest(t)),this.container.appendChild(t)}this.iframe=document.createElement("iframe"),this.iframe.className=ae,this.iframe.setAttribute("allow",me),this.iframe.setAttribute("title",e.ariaLabelModal),this.iframe.addEventListener("load",()=>this.handleIframeLoad()),this.confirmOverlay=document.createElement("div"),this.confirmOverlay.className=ue,this.confirmOverlay.innerHTML=`\n <div class="${he}" role="dialog" aria-modal="true" tabindex="-1"\n aria-labelledby="${this.modalId}-exit-title" aria-describedby="${this.modalId}-exit-message">\n <h3 id="${this.modalId}-exit-title">${e.exitTitle}</h3>\n <p id="${this.modalId}-exit-message">${e.exitMessage}</p>\n <div class="didit-confirm-actions">\n <button type="button" data-action="continue">${e.continueButton}</button>\n <button type="button" data-action="exit">${e.exitButton}</button>\n </div>\n </div>\n `,this.confirmOverlay.querySelector('[data-action="continue"]')?.addEventListener("click",()=>{this.hideConfirmation()}),this.confirmOverlay.querySelector('[data-action="exit"]')?.addEventListener("click",()=>{this.confirmExit()}),this.container.appendChild(this.loadingEl),this.container.appendChild(this.iframe),this.container.appendChild(this.confirmOverlay),this.overlay.appendChild(this.container),this.overlay.addEventListener("click",e=>{e.target===this.overlay&&this.handleCloseRequest()}),this.containerElement.appendChild(this.overlay)}createEmbeddedDOM(){this.embeddedContainer&&(this.container=document.createElement("div"),this.container.id=this.modalId,this.container.className=fe,this.loadingEl=document.createElement("div"),this.loadingEl.className=ce,this.loadingEl.innerHTML='\n <svg viewBox="0 0 24 24">\n <circle cx="12" cy="12" r="10" />\n <path d="M12 2a10 10 0 0 1 10 10" />\n </svg>\n ',this.iframe=document.createElement("iframe"),this.iframe.className=ae,this.iframe.setAttribute("allow",me),this.iframe.setAttribute("title",Se(this.language).ariaLabelModal),this.iframe.addEventListener("load",()=>this.handleIframeLoad()),this.container.appendChild(this.loadingEl),this.container.appendChild(this.iframe),this.embeddedContainer.appendChild(this.container))}setupEventListeners(){this.boundHandleMessage||this.boundHandleKeydown||(this.boundHandleMessage=this.handleMessage.bind(this),window.addEventListener("message",this.boundHandleMessage),this.boundHandleKeydown=this.handleKeydown.bind(this),document.addEventListener("keydown",this.boundHandleKeydown),this.boundHandleFocusChange=()=>{this.state.showConfirmation&&this.isTopmost()&&(null!==this.confirmationFocusTimeout&&window.clearTimeout(this.confirmationFocusTimeout),this.confirmationFocusTimeout=window.setTimeout(()=>{this.confirmationFocusTimeout=null,this.state.showConfirmation&&this.isTopmost()&&!this.confirmOverlay?.contains(document.activeElement)&&this.focusConfirmation()},0))},document.addEventListener("focusin",this.boundHandleFocusChange),document.addEventListener("focusout",this.boundHandleFocusChange),window.addEventListener("blur",this.boundHandleFocusChange))}removeEventListeners(){this.boundHandleMessage&&(window.removeEventListener("message",this.boundHandleMessage),this.boundHandleMessage=null),this.boundHandleKeydown&&(document.removeEventListener("keydown",this.boundHandleKeydown),this.boundHandleKeydown=null),this.boundHandleFocusChange&&(document.removeEventListener("focusin",this.boundHandleFocusChange),document.removeEventListener("focusout",this.boundHandleFocusChange),window.removeEventListener("blur",this.boundHandleFocusChange),this.boundHandleFocusChange=null)}pushToTop(){const e=De.openModals,t=e.indexOf(this);-1!==t&&e.splice(t,1),e.push(this)}removeFromStack(){const e=De.openModals,t=e.indexOf(this);-1!==t&&e.splice(t,1)}isTopmost(){const e=De.openModals;return e.length>0&&e[e.length-1]===this}handleMessage(e){if(!this.iframe?.src)return;if(!function(e,t){try{const i=new URL(e),n=new URL(t);return i.hostname.endsWith(".didit.me")||i.hostname===n.hostname}catch{return!1}}(e.origin,this.iframe.src))return xe.warn("Received postMessage from unallowed origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return;let t;xe.log("Received postMessage:",e.data);try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch{return void xe.warn("Failed to parse postMessage:",e.data)}if("didit:close_request"!==t.type){if("didit:layout"===t.type){const e=this.readFlowLayout(t.data);return void(e?this.applyFlowLayout(e):xe.warn("Ignoring a layout message without a positive contentHeight:",t.data))}this.callbacks.onMessage(t)}else this.handleCloseRequest()}readFlowLayout(e){const t="object"==typeof e&&null!==e?e:{},{contentHeight:i,colorScheme:n,dir:a,kind:o}=t;if("number"!=typeof i||!Number.isFinite(i)||i<=0)return null;const r=window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1;return{kind:"handoff"===o?"handoff":"step",contentHeight:Math.ceil(i),colorScheme:"light"===n||"dark"===n?n:r?"dark":"light",dir:"ltr"===a||"rtl"===a?a:(s=this.language,ye.includes(s.split("-")[0])?"rtl":"ltr")};var s}applyFlowLayout(e){if(this.embedded||!this.container)return;xe.log("Flow layout:",e),this.container.classList.add(de),this.container.dataset.diditTheme=e.colorScheme,this.container.dataset.diditDir=e.dir;const t=this.container.offsetHeight;this.container.style.setProperty("--didit-content-height",`${e.contentHeight}px`),this.matchPageBackground(e.colorScheme),this.setModalKind(e.kind,"handoff"===e.kind&&this.handoffHeight(e)===t)}isPhoneWindow(){return window.matchMedia?.("(max-width: 540px)").matches??!1}handoffHeight(e){const t=.9*window.innerHeight;return Math.round(Math.min(window.innerWidth>=1e3?660:e.contentHeight,t))}setModalKind(e,t=!1){if(!this.container)return;const i=this.container.dataset.diditKind;if(i===e)return;null!==this.firstLayoutTimeout&&"pending"!==e&&(window.clearTimeout(this.firstLayoutTimeout),this.firstLayoutTimeout=null);void 0===i||"pending"===i&&"handoff"===e&&t||this.animateSizeOnce(),this.container.dataset.diditKind=e,"pending"!==i||this.state.isLoading||this.loadingEl?.classList.add("hidden")}animateSizeOnce(){this.container?.classList.add(le),null!==this.sizeTimeout&&window.clearTimeout(this.sizeTimeout),this.sizeTimeout=window.setTimeout(()=>{this.sizeTimeout=null,this.container?.classList.remove(le)},300)}waitForFirstLayout(){this.container&&(this.container.classList.add(de),this.container.dataset.diditTheme=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",this.setModalKind("pending"),this.firstLayoutTimeout=window.setTimeout(()=>{this.firstLayoutTimeout=null,this.container?.classList.remove(de),delete this.container?.dataset.diditTheme,this.setModalKind("step")},3e3))}matchPageBackground(e){if(!window.matchMedia?.("(max-width: 540px)").matches)return;const t=document.documentElement;this.pageBackground??(this.pageBackground={root:t.style.backgroundColor,body:document.body.style.backgroundColor});const i="dark"===e?"#0b0b0d":"#ffffff";t.style.backgroundColor=i,document.body.style.backgroundColor=i}restorePageBackground(){this.pageBackground&&(document.documentElement.style.backgroundColor=this.pageBackground.root,document.body.style.backgroundColor=this.pageBackground.body,this.pageBackground=null)}resetFlowLayout(){!this.embedded&&this.container&&(this.restorePageBackground(),this.container.classList.remove(de,le),delete this.container.dataset.diditTheme,delete this.container.dataset.diditDir,delete this.container.dataset.diditKind,this.container.style.removeProperty("--didit-content-height"),null!==this.firstLayoutTimeout&&(window.clearTimeout(this.firstLayoutTimeout),this.firstLayoutTimeout=null),null!==this.sizeTimeout&&(window.clearTimeout(this.sizeTimeout),this.sizeTimeout=null))}handleKeydown(e){if(this.state.isOpen&&this.isTopmost()){if("Tab"===e.key&&this.state.showConfirmation){const t=Array.from(this.confirmOverlay?.querySelectorAll("button")??[]);if(t.length){e.preventDefault();const i=t.findIndex(e=>e===document.activeElement);t[e.shiftKey?i<=0?t.length-1:i-1:(i+1)%t.length].focus()}return}"Escape"===e.key&&(e.preventDefault(),this.state.showConfirmation?this.hideConfirmation():this.handleCloseRequest())}}handleIframeLoad(){this.iframe?.src&&"about:blank"!==this.iframe.src&&(this.state.isLoading=!1,"pending"!==this.container?.dataset.diditKind&&this.loadingEl?.classList.add("hidden"),this.callbacks.onIframeLoad())}handleCloseRequest(e){this.config.showExitConfirmation?this.showConfirmation(e):this.callbacks.onCloseConfirmed()}showConfirmation(e){if(!this.confirmOverlay||this.state.showConfirmation)return;const t=document.activeElement;this.confirmationTrigger=e??(t instanceof HTMLElement&&t!==document.body?t:this.container?.querySelector(`.${oe}`)??this.iframe),this.state.showConfirmation=!0,this.confirmOverlay.classList.add("active"),this.iframe&&(this.iframe.inert=!0);const i=this.container?.querySelector(`.${oe}`);i&&(i.inert=!0),this.confirmOverlay.scrollTop=0,this.isTopmost()&&this.focusConfirmation(),this.callbacks.onClose()}focusConfirmation(){this.confirmOverlay?.querySelector(`.${he}`)?.focus({preventScroll:!0})}hideConfirmation(e=!0){if(null!==this.confirmationFocusTimeout&&(window.clearTimeout(this.confirmationFocusTimeout),this.confirmationFocusTimeout=null),!this.state.showConfirmation)return;this.state.showConfirmation=!1,this.confirmOverlay?.classList.remove("active"),this.iframe&&(this.iframe.inert=!1);const t=this.container?.querySelector(`.${oe}`);t&&(t.inert=!1);const i=this.confirmationTrigger;this.confirmationTrigger=null,e&&this.isTopmost()&&i?.isConnected&&(i===this.iframe?this.confirmationFocusTimeout=window.setTimeout(()=>{this.confirmationFocusTimeout=null,this.state.isOpen&&!this.state.showConfirmation&&this.isTopmost()&&i.isConnected&&i.focus({preventScroll:!0})},0):i.focus({preventScroll:!0}))}confirmExit(){this.hideConfirmation(),this.callbacks.onCloseConfirmed()}open(e){const t=this.state.isOpen;this.language=function(e){try{const{pathname:t}=new URL(e),i=t.split("/").filter(Boolean)[0];if(i&&we.includes(i))return i}catch{}const t=navigator.language;if(we.includes(t))return t;const i=t.split("-")[0];return we.includes(i)?i:"en"}(e),this.overlay||this.container||this.createDOM(),this.setupEventListeners(),xe.log("Opening with URL:",e),this.state.isLoading=!0,this.hideConfirmation(),this.loadingEl?.classList.remove("hidden"),this.resetFlowLayout(),this.embedded||this.isPhoneWindow()||this.waitForFirstLayout(),this.iframe&&(this.iframe.src=e),this.state.isOpen=!0,this.pushToTop(),this.embedded||(this.overlay?.classList.add("active"),t||(this.previousBodyOverflow=document.body.style.overflow),document.body.style.overflow="hidden")}close(){xe.log("Closing"),this.hideConfirmation(!1),this.state.isOpen=!1,this.state.isLoading=!0,this.state.showConfirmation=!1,this.removeFromStack(),this.removeEventListeners(),this.resetFlowLayout(),this.iframe&&(this.iframe.src="about:blank"),this.embedded||(this.overlay?.classList.remove("active"),document.body.style.overflow=this.previousBodyOverflow??"",this.previousBodyOverflow=null)}destroy(){xe.log("Destroying"),this.close(),this.removeEventListeners(),this.embedded&&this.container&&this.container.parentNode?this.container.parentNode.removeChild(this.container):this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.container=null,this.iframe=null,this.loadingEl=null,this.confirmOverlay=null}isOpen(){return this.state.isOpen}isLoading(){return this.state.isLoading}}De.openModals=[];const Ee="https://verification.didit.me",Ie={invalid_token:"The transaction token is invalid.",expired_token:"The transaction token has expired.",validation:"The transaction payload failed validation.",network:"A network error occurred while contacting the Didit API."};class $e extends Error{constructor(e,t,i){super(t||Ie[e]),this.name="DiditTransactionError",this.type=e,this.status=i?.status,this.fieldErrors=i?.fieldErrors}}function ze(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function je(e){const t={};for(const[i,n]of Object.entries(e))void 0!==n&&(t[i]=n);return t}function Ae(e){if(e)return je({type:e.type,externalUserId:e.externalUserId,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,dob:e.dob,address:e.address,institutionInfo:e.institutionInfo,device:e.device,paymentMethod:e.paymentMethod?je({type:e.paymentMethod.type,accountId:e.paymentMethod.accountId,issuingCountry:e.paymentMethod.issuingCountry}):void 0})}function Oe(e){if(e)return je({status:e.status,protocol:e.protocol,required:e.required,obligationsCount:e.obligationsCount,originatorData:e.originatorData,beneficiaryData:e.beneficiaryData,metadata:e.metadata})}function Fe(e,...t){for(const i of t){const t=e[i];if("string"==typeof t&&t)return t}}function Pe(e){const t=Fe(e,"uuid","transaction_id","transactionId"),i=Fe(e,"status");if(!t||!i)throw new $e("network","Unexpected response shape from the Didit API: missing transaction id or status.");const n={transactionId:t,status:i},a=function(e){const t=e.travel_rule??e.travelRule;if(ze(t)){const e=Fe(t,"status");if(e)return e}const i=e.props;if(ze(i)){const e=Fe(i,"travel_rule_status","travelRuleStatus");if(e)return e}return Fe(e,"travel_rule_status","travelRuleStatus")}(e);a&&(n.travelRuleStatus=a);const o=function(e){if(!ze(e))return;const t=Fe(e,"type"),i=Fe(e,"url");if(!t||!i)return;const n={type:t,url:i},a=Fe(e,"session_id","sessionId");a&&(n.sessionId=a);const o=Fe(e,"session_token","sessionToken");o&&(n.sessionToken=o);const r=Fe(e,"status");r&&(n.status=r);const s=Fe(e,"widget_session_id","widgetSessionId");s&&(n.widgetSessionId=s);const d=Fe(e,"expires_at","expiresAt");return d&&(n.expiresAt=d),n}(e.action_required??e.actionRequired);return o&&(n.actionRequired=o),n}function He(e,t){const i=function(e){if(ze(e))return Fe(e,"detail","message","error")}(t);if(401===e||403===e){const n=`${i??""} ${Fe(ze(t)?t:{},"code")??""}`;return/expired/i.test(n)?new $e("expired_token",i,{status:e}):new $e("invalid_token",i,{status:e})}return 400===e||422===e?new $e("validation",i,{status:e,fieldErrors:ze(t)?t:void 0}):new $e("network",`Request failed with status ${e}.`,{status:e})}async function qe(e,t){if("function"!=typeof fetch)throw new $e("network","fetch is not available in this environment.");let i;try{i=await fetch(e,t)}catch{throw new $e("network")}const n=await async function(e){try{return await e.json()}catch{return null}}(i);if(!i.ok)throw He(i.status,n);if(!ze(n))throw new $e("network","Unexpected empty response from the Didit API.",{status:i.status});return Pe(n)}async function Ve(e){const t=await b().catch(()=>null),i=je({txnId:(n=e.transaction).txnId,txnDate:n.txnDate,zoneId:n.zoneId,type:n.category,info:(a=n.details,je({direction:a.direction,amount:a.amount,currency:a.currency,currencyType:a.currencyType,amountInDefaultCurrency:a.amountInDefaultCurrency,defaultCurrencyCode:a.defaultCurrencyCode,paymentDetails:a.paymentDetails,paymentTxnId:a.paymentTxnId,type:a.actionType,cryptoParams:a.cryptoParams})),subject:Ae(n.subject),counterparty:Ae(n.counterparty),props:n.customProperties,travelRule:Oe(n.travelRule),includeCryptoScreening:n.includeCryptoScreening});var n,a;return t&&(i.fingerprint_v2=t),qe(`${e.baseUrl}/v1/transactions/`,{method:"POST",headers:{"Content-Type":"application/json","X-Transaction-Token":e.transactionToken,...y(t)},body:JSON.stringify(i)})}async function Ne(e){return qe(`${e.baseUrl}/v1/transactions/${e.transactionId}/`,{method:"GET",headers:{"X-Transaction-Token":e.transactionToken}})}function Re(e){return new Promise(t=>setTimeout(t,e))}function Ue(e){return e instanceof $e&&("invalid_token"===e.type||"expired_token"===e.type)}class Ke{static get shared(){return Ke._instance||(Ke._instance=new Ke),Ke._instance}static reset(){Ke._instance&&(Ke._instance.destroy(),Ke._instance=null)}get state(){return this._state}get configuration(){return this._configuration}get isPresented(){return this._modal?.isOpen()??!1}get isActionModalPresented(){return this._actionModal?.isOpen()??!1}get errorMessage(){return this._errorMessage}constructor(){this._state="idle",this._modal=null,this._actionModal=null,this._actionModalSettle=null,this._actionGeneration=0,xe.log("DiditSdk initialized")}async startVerification(e){const t=e.configuration;this._configuration=t,xe.isEnabled=t?.loggingEnabled??te,xe.log("Starting verification with options:",e),this._modal&&(this._modal.destroy(),this._modal=null),this._errorMessage=void 0;try{const{url:i}=e;if(!i||"string"!=typeof i)throw new Error("Invalid options: url is required");!function(e){if(!e?.embedded)return;const t=e.embeddedContainerId;if(!t)throw new Error("Embedded mode requires embeddedContainerId: the id of the element that hosts the verification.");if("undefined"==typeof document||!document.getElementById(t))throw new Error(`Embedded container "#${t}" was not found in the page.`)}(t),this._modal=new De(t,{onClose:()=>this.handleModalClose(),onCloseConfirmed:()=>this.handleModalCloseConfirmed(),onMessage:e=>this.handleVerificationEvent(e),onIframeLoad:()=>this.handleIframeLoad()}),this._url=Te(i,t),this.setState("loading"),this.emitInternalEvent("didit:started",{}),this._modal?.open(this._url)}catch(e){this.handleError(e)}}async submitTransaction(e){if(!e?.transactionToken||"string"!=typeof e.transactionToken)throw new $e("invalid_token","transactionToken is required.");if(!e.transaction||"object"!=typeof e.transaction)throw new $e("validation","transaction payload is required.");if(!e.transaction.txnId||"string"!=typeof e.transaction.txnId)throw new $e("validation","transaction.txnId is required.");if(!e.transaction.details||"object"!=typeof e.transaction.details)throw new $e("validation","transaction.details is required.");const t=(e.baseUrl??Ee).replace(/\/+$/,"");xe.log("Submitting transaction:",e.transaction.txnId);const i=await Ve({baseUrl:t,transactionToken:e.transactionToken,transaction:e.transaction});xe.log("Transaction submitted:",i);return(e.autoLaunchAction??!0)&&"wallet_ownership"===i.actionRequired?.type&&i.actionRequired.url&&this.runTransactionAction(t,e.transactionToken,i,e.onActionCompleted),i}submitEvent(e){return xe.log("Submitting event:",e?.event?.category,e?.event?.actionType),X(e)}close(){xe.log("Closing verification programmatically"),this._actionModalSettle?.("aborted"),this.handleModalCloseConfirmed()}destroy(){xe.log("Destroying SDK instance"),this._actionGeneration++,this._actionModalSettle?.("aborted"),this._modal?.destroy(),this._modal=null,this.reset(),this.setState("idle")}async runTransactionAction(e,t,i,n){const a=this._actionGeneration;let o=!1;const r=(e,t)=>{if(!o&&a===this._actionGeneration){o=!0;try{n?.(e,t)}catch(e){xe.error("onActionCompleted callback threw:",e)}}};try{if("aborted"===await this.presentTransactionActionModal(i.actionRequired.url)||a!==this._actionGeneration)return;if(!i.transactionId)return void r(i);let n,o=null;try{o=await async function(e){const t=e.intervalMs??1500,i=Math.max(1,e.maxAttempts??10);let n=null;for(let a=0;a<i;a++){if(e.isAborted?.())return n;if(a>0&&await Re(t),e.isAborted?.())return n;try{n=await Ne(e);const t=!n.actionRequired,i=void 0!==e.initialStatus&&n.status!==e.initialStatus;if(t||i)return n}catch(e){if(Ue(e))throw e}}return n}({baseUrl:e,transactionToken:t,transactionId:i.transactionId,initialStatus:i.status,isAborted:()=>a!==this._actionGeneration})}catch(e){if(!(e instanceof $e))throw e;n=e}if(n)return void r(i,{type:n.type,message:n.message});r(o??i)}catch(e){xe.error("Transaction action follow-up failed:",e),r(i)}}presentTransactionActionModal(e){return this._actionModalSettle?.("aborted"),new Promise(t=>{let i=!1;const n=e=>{if(i)return;i=!0;const n=this._actionModal;this._actionModal=null,this._actionModalSettle=null,n?.destroy(),t(e)};let a;try{a=new De(void 0,{onClose:()=>{},onCloseConfirmed:()=>n("finished"),onMessage:e=>{this.onEvent?.(e),"didit:completed"!==e.type&&"didit:cancelled"!==e.type||n("finished")},onIframeLoad:()=>{}}),xe.log("Launching required transaction action:",e),a.open(e)}catch(e){throw this._actionModal=null,this._actionModalSettle=null,e}this._actionModal=a,this._actionModalSettle=n})}handleModalClose(){xe.log("Modal close requested")}handleModalCloseConfirmed(){xe.log("Modal close confirmed");const e=this.buildSessionData();this._modal?.close(),this.reset(),this.setState("idle");const t={type:"cancelled",session:e};this.onComplete?.(t)}handleIframeLoad(){xe.log("Iframe loaded")}emitInternalEvent(e,t){const i={type:e,data:t,timestamp:Date.now()};xe.log("Emitting internal event:",i),this.onEvent?.(i)}handleVerificationEvent(e){switch(xe.log("Verification event:",e),e.data?.sessionId&&(this._sessionId=e.data.sessionId),this.onEvent?.(e),e.type){case"didit:ready":xe.log("Verification iframe ready");break;case"didit:started":xe.log("User started verification");break;case"didit:step_started":xe.log("Step started:",e.data?.step);break;case"didit:step_completed":xe.log("Step completed:",e.data?.step,"-> next:",e.data?.nextStep);break;case"didit:media_started":xe.log("Media started:",e.data?.mediaType,"for step:",e.data?.step);break;case"didit:media_captured":xe.log("Media captured for step:",e.data?.step,"isAuto:",e.data?.isAuto);break;case"didit:document_selected":xe.log("Document selected:",e.data?.documentType,"country:",e.data?.country);break;case"didit:verification_submitted":xe.log("Verification submitted for step:",e.data?.step);break;case"didit:code_sent":xe.log("Code sent via:",e.data?.channel,"codeSize:",e.data?.codeSize);break;case"didit:code_verified":xe.log("Code verified via:",e.data?.channel);break;case"didit:status_updated":xe.log("Status updated:",e.data?.status,"step:",e.data?.step);break;case"didit:completed":this.handleVerificationCompleted(e);break;case"didit:cancelled":this.handleVerificationCancelled(e);break;case"didit:error":this.handleVerificationError(e);break;case"didit:step_changed":xe.log("Step changed:",e.data?.step)}}handleVerificationCompleted(e){xe.log("Verification completed:",e.data);const t=this.buildSessionData(e.data);this._configuration?.closeModalOnComplete&&(this._modal?.close(),this.reset(),this.setState("idle"));const i={type:"completed",session:t};this.onComplete?.(i)}handleVerificationCancelled(e){xe.log("Verification cancelled:",e.data);const t=this.buildSessionData(e.data);this._modal?.close(),this.reset(),this.setState("idle");const i={type:"cancelled",session:t};this.onComplete?.(i)}handleVerificationError(e){xe.log("Verification error:",e.data)}handleError(e){let t;xe.error("SDK error:",e),t=e instanceof Error?ke("unknown",e.message):ke("unknown","An unknown error occurred"),this._modal?.close(),this._modal=null,this.reset(),this._errorMessage=t.message,this.setState("error");const i={type:"failed",error:t};this.onComplete?.(i)}setState(e){const t=this._state;this._state=e,t!==e&&(xe.log("State changed:",t,"->",e),this.onStateChange?.(e,this._errorMessage))}reset(){this._sessionId=void 0,this._url=void 0,this._errorMessage=void 0,this._configuration=void 0}buildSessionData(e){const t=e?.sessionId||this._sessionId;if(t)return{sessionId:t,status:e?.status||"Pending"}}}Ke._instance=null,e.DEFAULT_EVENTS_BASE_URL=w,e.DEFAULT_TRANSACTION_BASE_URL=Ee,e.DiditEventError=C,e.DiditSdk=Ke,e.DiditTransactionError=$e,e.SDK_VERSION="0.5.3",e.buildFingerprintHeaders=y,e.configureEvents=function(e){const t={...L,...z({...e})};t.baseUrl=t.baseUrl.replace(/\/+$/,""),t.batchSize=Math.min(Math.max(1,Math.floor(t.batchSize)),500),t.flushIntervalMs=Math.max(0,t.flushIntervalMs),t.maxQueueSize=Math.max(1,Math.floor(t.maxQueueSize)),L=t},e.default=Ke,e.flush=G,e.getDeviceFingerprintPayload=b,e.submitEvent=X,Object.defineProperty(e,"__esModule",{value:!0})});
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DiditSDK={})}(this,function(e){"use strict";function t(e){const t=[],i=e.userAgent;let n=0;return"undefined"!=typeof navigator&&navigator.webdriver&&(t.push("webdriver"),n=.9),/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(i)&&(t.push("headless-ua"),n=.9),!1===e.uaDataMobile&&/Android|iPhone|iPad/i.test(i)&&(t.push("ua-mobile-mismatch"),n=n||.3),{score:n,flags:t}}const i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function n(e){let t="",n=0;for(;n+2<e.length;n+=3){const a=e[n]<<16|e[n+1]<<8|e[n+2];t+=i[a>>18&63],t+=i[a>>12&63],t+=i[a>>6&63],t+=i[63&a]}if(n<e.length){const a=e.length-n,o=e[n]<<16|(a>1?e[n+1]:0)<<8;t+=i[o>>18&63],t+=i[o>>12&63],a>1&&(t+=i[o>>6&63])}return t}async function a(e){if("undefined"==typeof crypto||!crypto.subtle)throw new Error("WebCrypto SubtleCrypto is not available");const t=function(e){return"string"==typeof e?(new TextEncoder).encode(e):e}(e),i=new Uint8Array(t.byteLength);i.set(t);const n=await crypto.subtle.digest("SHA-256",i);return new Uint8Array(n)}function o(e){return n(function(e){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){const t=new Uint8Array(e);return crypto.getRandomValues(t),t}const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=Math.floor(256*Math.random());return t}(e))}function r(e){if(null==e)return JSON.stringify(e??null);if(Array.isArray(e))return`[${e.map(e=>r(e)).join(",")}]`;if("object"==typeof e){return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${r(e[t])}`).join(",")}}`}return JSON.stringify(e)}function s(e){const t=e.lastIndexOf(":");return t<0?e:e.slice(0,t)}function d(e){const t=[e.screenWidth,e.screenHeight].sort((e,t)=>(e??0)-(t??0));return{ua:(n=e.userAgent,n.replace(/\/[\w.]+/g,"").replace(/\d+(?:[._]\d+)+/g,"").replace(/\bAndroid \d+/g,"Android")),platform:e.platform,lang:e.language.split("-")[0],languages:[...e.languages].sort(),concurrency:e.hardwareConcurrencyQuantized,memory:e.deviceMemory,maxTouch:e.maxTouchPoints,dpr:e.devicePixelRatio,screen:t,colorDepth:e.colorDepth,timeZone:e.timeZone,uaDataPlatform:e.uaDataPlatform,uaDataBrands:(i=e.uaDataBrands,i.map(s).filter(e=>!function(e){const t=e.toLowerCase(),i=t.indexOf("not");return i>=0&&t.indexOf("brand",i+3)>=0}(e)).sort())};var i,n}async function l(e){try{return await async function(e){return n((await a(e)).slice(0,16))}(r(e))}catch{return""}}function c(e,t){try{const i=e();return void 0===i?t:i}catch{return t}}const u="didit-pid-v1",h="didit_pid";let f=null;function m(e){return"string"==typeof e&&/^[A-Za-z0-9_-]{20,32}$/.test(e)}const p=[{source:"localStorage",read(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(u);return m(e)?e:null}catch{return null}},write(e){try{return"undefined"!=typeof localStorage&&(localStorage.setItem(u,e),!0)}catch{return!1}}},{source:"cookie",read(){try{if("undefined"==typeof document||!document.cookie)return null;const e=`${h}=`;for(const t of document.cookie.split(";")){const i=t.trim();if(i.startsWith(e)){const t=decodeURIComponent(i.substring(e.length));return m(t)?t:null}}return null}catch{return null}},write(e){try{if("undefined"==typeof document)return!1;const t="undefined"!=typeof location&&"https:"===location.protocol,i=[`${h}=${encodeURIComponent(e)}`,"Path=/","Max-Age=63072000","SameSite=Lax"];return t&&i.push("Secure"),document.cookie=i.join("; "),!0}catch{return!1}}}];function g(e,t,i){const n=[];if(t.forEach((t,i)=>{t&&n.push({id:t,source:e[i].source})}),!n.length&&m(i))return{result:{id:i,sources:["embedder"],wasCreated:!1},stale:[]};let a;if(!n.length&&f&&m(f)&&n.push({id:f,source:"memory"}),n.length){const e=function(e){const t=new Map;for(const{id:i,source:n}of e){const e=t.get(i);e?e.push(n):t.set(i,[n])}let i=e[0].id,n=0;for(const[e,a]of t)a.length>n&&(n=a.length,i=e);return{id:i,sources:t.get(i)||[]}}(n);a={id:e.id,sources:e.sources,wasCreated:!1}}else a={id:o(16),sources:["fresh"],wasCreated:!0};return f=a.id,{result:a,stale:e.filter((e,i)=>t[i]!==a.id)}}let v=null,b=null,y=null,w=null,x=0;async function k(){const e=function(){const e=p,{result:t,stale:i}=g(e,e.map(e=>e.read()));return i.forEach(e=>e.write(t.id)),t}(),i=function(){const e="undefined"!=typeof navigator,t=e?navigator:{},i=c(()=>t.userAgent||"",""),n=c(()=>t.hardwareConcurrency??null,null),a=c(()=>t.connection||t.mozConnection||t.webkitConnection||null,null),o=e&&"undefined"!=typeof screen?screen:null,r=c(()=>t.userAgentData,void 0);return{userAgent:i,userAgentNormalized:(d=i,d.replace(/(\d+)(\.\d+)+/g,"$1")),platform:c(()=>t.platform||"",""),language:c(()=>t.language||"",""),languages:c(()=>t.languages?[...t.languages]:[],[]),hardwareConcurrency:n,hardwareConcurrencyQuantized:(s=n,null===s?null:s<=1?1:s<=2?2:s<=4?4:s<=6?6:s<=8?8:s<=12?12:s<=16?16:20),deviceMemory:c(()=>t.deviceMemory??null,null),maxTouchPoints:c(()=>t.maxTouchPoints??null,null),devicePixelRatio:c(()=>e&&"undefined"!=typeof window?window.devicePixelRatio??null:null,null),screenWidth:o?.width??null,screenHeight:o?.height??null,availWidth:o?.availWidth??null,availHeight:o?.availHeight??null,colorDepth:o?.colorDepth??null,pixelDepth:o?.pixelDepth??null,orientation:o&&"orientation"in o?o.orientation?.type??null:null,timeZone:c(()=>e&&"undefined"!=typeof Intl&&Intl.DateTimeFormat&&Intl.DateTimeFormat().resolvedOptions().timeZone||"",""),connectionEffectiveType:a?.effectiveType??null,connectionDownlink:a?.downlink??null,uaDataMobile:r?.mobile??null,uaDataPlatform:r?.platform??null,uaDataBrands:r?.brands?r.brands.map(e=>`${e.brand}:${e.version}`).sort():[],cookieEnabled:c(()=>t.cookieEnabled??null,null),doNotTrack:c(()=>t.doNotTrack??null,null)};var s,d}(),n=function(e){if(!e)return{kind:"browser",hostAppVersion:null,isStandaloneBrowser:!0};const t=e,i=t.match(/WA(?:4[A]|4iOS)\/([\d.]+)/);if(i)return{kind:"whatsapp",hostAppVersion:i[1],isStandaloneBrowser:!1};const n=t.match(/GSA\/([\d.]+)/);if(n)return{kind:"gsa",hostAppVersion:n[1],isStandaloneBrowser:!1};const a=t.match(/Instagram\s+([\d.]+)/);if(a)return{kind:"instagram",hostAppVersion:a[1],isStandaloneBrowser:!1};if(/FBAN|FBAV/.test(t)){const e=t.match(/FBAV\/([\d.]+)/);return{kind:"facebook",hostAppVersion:e?.[1]??null,isStandaloneBrowser:!1}}if(/MessengerLiteForiOS|MessengerForiOS|FB_IAB\/Messenger/.test(t))return{kind:"messenger",hostAppVersion:null,isStandaloneBrowser:!1};const o=t.match(/(?:musical_ly|TikTok|trill)_(\d+)/i);if(o)return{kind:"tiktok",hostAppVersion:o[1],isStandaloneBrowser:!1};const r=t.match(/Line\/([\d.]+)/);if(r)return{kind:"line",hostAppVersion:r[1],isStandaloneBrowser:!1};if(/MicroMessenger/.test(t)){const e=t.match(/MicroMessenger\/([\d.]+)/);return{kind:"wechat",hostAppVersion:e?.[1]??null,isStandaloneBrowser:!1}}return/Telegram/i.test(t)?{kind:"telegram",hostAppVersion:null,isStandaloneBrowser:!1}:/Twitter|TwitterAndroid/i.test(t)?{kind:"twitter",hostAppVersion:null,isStandaloneBrowser:!1}:/LinkedInApp/i.test(t)?{kind:"linkedin",hostAppVersion:null,isStandaloneBrowser:!1}:/Snapchat/i.test(t)?{kind:"snapchat",hostAppVersion:null,isStandaloneBrowser:!1}:/\bwv\)|\bWebView\b/i.test(t)?{kind:"generic-wv",hostAppVersion:null,isStandaloneBrowser:!1}:{kind:"browser",hostAppVersion:null,isStandaloneBrowser:!0}}(i.userAgent),a={version:2,schema:"didit-fp-v2",platform:"web",collectedAt:(new Date).toISOString(),persistentId:e.id,persistentIdSources:e.sources,persistentIdWasCreated:e.wasCreated,signals:{platform:"web",tier:"lite",compositeHashVersion:4,navigator:i,webview:n},bot:t(i),compositeHash:""};y=a;const o=await l({navigator:d(i),webview:n.kind});return{...a,compositeHash:o}}async function C(){if("undefined"==typeof window||"undefined"==typeof navigator||"undefined"==typeof document)return null;if(b)return b;if(!w){const e=x;w=(v?v.get():k()).then(t=>e!==x?C():(b=t,t),t=>{if(e!==x)return C();throw w=null,t})}return w}const M=function(e){if(!e)return{};const t={"X-Didit-FP-V2":"1"};return e.persistentId&&(t["X-Didit-PID"]=e.persistentId),e.compositeHash&&(t["X-Didit-FP-Hash"]=e.compositeHash),e.legacyCompatibilityHash&&(t["X-Didit-FP-Legacy"]=e.legacyCompatibilityHash),e.signals?.webview?.kind&&(t["X-Didit-FP-Webview"]=e.signals.webview.kind),e.bot?.score&&(t["X-Didit-FP-Bot-Score"]=e.bot.score.toFixed(2)),t},L=function(){for(const e of p){const t=e.read();if(t)return t}return null},T="https://verification.didit.me",S=/^(security|payment|dispute|responsible_gambling)\.|^gameplay\.(bet_placed|bet_settled|p2p_settlement)$/,B=/^session\.(page_view|sdk_heartbeat|sdk_loaded|device_seen|bot_signal_observed)$|^bonus\.promotion_viewed$|^affiliate\.referral_clicked$/,_=/^[\t\x20-\x7e\x80-\xff]+$/;class D extends Error{constructor(e,t,i){super(t),this.name="DiditEventError",this.type=e,this.status=i?.status,this.eventIds=i?.eventIds??[],this.errors=i?.errors}}let E,I={...{baseUrl:T,batchSize:25,flushIntervalMs:5e3,maxQueueSize:1e3}},$=[],z=0,A=0,j=Promise.resolve(),O=!1,F=!1,P=0;function V(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return e.slice(0,t)}function H(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function N(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function q(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||void 0}catch{return}}function R(e){try{I.onError?.(e)}catch{}}function U(){return $.filter(e=>!e.sending)}function K(){void 0!==E&&clearTimeout(E),E=void 0}function W(){var e;!A&&U().length&&(e=z?Math.min(Math.max(1e3,I.flushIntervalMs)*2**z,6e4):I.flushIntervalMs,void 0===E&&(E=setTimeout(()=>{E=void 0,oe().catch(()=>{})},e)))}function Z(e=1/0,t=0){const i=[];let n=t;for(const t of $){if(i.length===I.batchSize)break;t.sending||n+t.bytes+(i.length?1:0)>e||(!i.length||t.token===i[0].token&&t.url===i[0].url)&&(n+=t.bytes+(i.length?1:0),i.push(t))}return i}function J(e,t,i){const n=function(e){return H(e)&&"string"==typeof e.detail?e.detail:void 0}(t),a=H(t)&&"string"==typeof t.code?t.code:"";let o="validation";return"event_monitoring_disabled"===a?o="monitoring_disabled":401!==e&&403!==e||(o=/expired/i.test(`${n} ${a}`)?"expired_token":"invalid_token"),new D(o,n??`Didit refused the events with status ${e}.`,{status:e,eventIds:i,errors:"validation"===o&&H(t)?t:void 0})}function X(e){return encodeURIComponent(e).replace(/%[\dA-F]{2}/g,"-").length}function Q(e,t){const i=t?`,"fingerprint_v2":${JSON.stringify(t)}`:"";return`{"events":[${e.map(e=>e.json).join(",")}]${i}}`}async function G(e,t,i,n=!1){const a=Q(e,i),o=n?X(a):0,r=new Set,s=[],d=(e,i)=>{t.results.push({eventId:e.id,outcome:"rejected",error:i}),t.rejectedCount++,r.add(e)};for(const t of e)t.sending=!0;P+=o;try{const o=await fetch(e[0].url,{method:"POST",redirect:"error",keepalive:n,headers:{"Content-Type":"application/json","X-Monitoring-Token":e[0].token,...M(i)},body:a}),c=await async function(e){try{return await e.json()}catch{return null}}(o);if(408===(l=o.status)||429===l||l>=500||!H(c))return!1;if(!o.ok){const t=J(o.status,c,e.map(e=>e.id));for(const i of e)d(i,t);return s.push(t),!0}const u=H(c)&&Array.isArray(c.results)?c.results:[];return e.forEach((e,i)=>{const n=u.filter(e=>H(e)&&e.index===i),a=n[0];if(1===n.length&&H(a))if("accepted"===a.outcome||"replayed"===a.outcome){if("string"!=typeof a.event_uuid||!a.event_uuid)return;const i={eventId:e.id,outcome:a.outcome,eventUuid:a.event_uuid};"string"==typeof a.status&&(i.status=a.status),"number"!=typeof a.score&&null!==a.score||(i.score=a.score),t.results.push(i),t["accepted"===a.outcome?"acceptedCount":"replayedCount"]++,r.add(e)}else if("rejected"===a.outcome&&H(a.errors)){const t=new D("validation","Didit rejected the event; see errors for the details.",{status:o.status,eventIds:[e.id],errors:a.errors});d(e,t),s.push(t)}}),r.size===e.length}catch{return!1}finally{P-=o,$=$.filter(e=>!r.has(e));for(const t of e)t.sending=!1;z=r.size===e.length?0:z+1,n&&W(),s.forEach(R)}var l}function Y(){return{acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[]}}async function ee(){const e={acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[]},t=await C().catch(()=>null);let i;for(K();(i=Z()).length&&await G(i,e,t););return e.pendingCount=$.length,e}async function te(){if(!F){F=!0,K();try{const e=b??(v?v.peek():y),t=X(Q([],e));let i;for(;(i=Z(65536-P,t)).length;)G(i,Y(),e,!0).catch(()=>{})}finally{F=!1,W()}}}function ie(){te().catch(()=>{})}function ne(){"hidden"===document.visibilityState&&ie()}function ae(e){const t="string"==typeof e?.monitoringToken?e.monitoringToken.trim():"",i=e?.event;if(!t)throw new D("invalid_token","monitoringToken is required.");if(!_.test(t))throw new D("invalid_token","monitoringToken is not a value a header can carry.");if(!H(i)||!i.category||"string"!=typeof i.actionType||!i.actionType.trim())throw new D("validation","event.category and event.actionType are required.");if(i.occurredAt instanceof Date&&Number.isNaN(i.occurredAt.getTime()))throw new D("validation","event.occurredAt must be a valid date.");if("function"!=typeof fetch)throw new D("network","fetch is not available in this environment.");const n=i.eventId||("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():o(16)),a=JSON.stringify(function(e,t){const{session:i,transactionContext:n,subject:a,occurredAt:o}=e;return N({event_id:t,event_category:e.category,action_type:e.actionType,occurred_at:o instanceof Date?o.toISOString():o??(new Date).toISOString(),time_zone:e.timeZone??q(),subject:a&&N({full_name:a.fullName,email:a.email,phone:a.phone,country:a.country}),business:e.business,session:i&&N({session_id:i.sessionId,sequence:i.sequence,page_url:i.pageUrl,referrer:i.referrer}),transaction_context:n&&N({amount:n.amount,currency:n.currency,direction:n.direction,payment_reference_id:n.paymentReferenceId}),payload:e.payload,custom_values:e.customValues})}(i,n)),r=`${i.category}.${i.actionType}`;return function(e){let t;if($.length>=I.maxQueueSize){for(const e of U())(!t||e.priority<t.priority)&&(t=e);(!t||e.priority<t.priority)&&(t=e),2===t.priority&&(t=void 0)}t&&t!==e&&$.splice($.indexOf(t),1),t!==e&&$.push(e),t&&R(new D("dropped","The event queue is full, so the event was dropped before it was sent.",{eventIds:[t.id]}))}({id:n,json:a,bytes:X(a),token:t,url:`${V(e.baseUrl??I.baseUrl)}/v1/events/batch/`,priority:S.test(r)?2:B.test(r)?0:1,sending:!1}),O||"undefined"==typeof window||"undefined"==typeof document||(O=!0,window.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ne)),C().catch(()=>null),!A&&!z&&U().length>=I.batchSize?oe().catch(()=>{}):W(),n}function oe(){A++;const e=j.then(ee).catch(()=>({acceptedCount:0,replayedCount:0,rejectedCount:0,pendingCount:0,results:[],pendingCount:$.length})).finally(()=>{A--,W()});return j=e,e}const re=9999,se=!0,de=!0,le=!1,ce="didit-modal-overlay",ue="didit-modal-container",he="didit-verification-iframe",fe="didit-close-button",me="didit-close-icon",pe="didit-close-icon-legacy",ge="didit-flow-sized",ve="didit-size-animated",be="didit-loading",ye="didit-confirm-overlay",we="didit-confirm-box",xe="didit-embedded",ke="didit-modal-curtain",Ce="camera; microphone; fullscreen; autoplay; encrypted-media; geolocation; clipboard-write; digital-credentials-get",Me={defaultDocumentCamera:"document_camera",defaultLivenessCamera:"liveness_camera",showDocumentCameraSwitchButton:"document_camera_switch",showLivenessCameraSwitchButton:"liveness_camera_switch"},Le=["front","back"],Te="sdk_presentation",Se="sdk_close_button",Be=["ar","fa","he"],_e=["ar","bg","bn","ca","cnr","cs","da","de","el","en","es","et","fa","fi","fr","he","hi","hr","hu","hy","id","it","ja","ka","ko","lt","lv","mk","mn","ms","nl","no","pl","pt-BR","pt","ro","ru","sk","sl","so","sr","sv","th","tr","uk","uz","vi","zh-CN","zh-TW","zh"];class De{static get isEnabled(){return this._enabled}static set isEnabled(e){this._enabled=e}static log(...e){this._enabled&&console.log("[DiditSDK]",...e)}static warn(...e){this._enabled&&console.warn("[DiditSDK]",...e)}static error(...e){this._enabled&&console.error("[DiditSDK]",...e)}}function Ee(e,t){return{type:e,message:t||{sessionExpired:"Your verification session has expired.",networkError:"A network error occurred. Please try again.",cameraAccessDenied:"Camera access is required for verification.",unknown:t||"An unknown error occurred."}[e]}}function Ie(e){return Le.includes(e)}De._enabled=!1;const $e=["defaultDocumentCamera","defaultLivenessCamera"],ze=["showDocumentCameraSwitchButton","showLivenessCameraSwitchButton"];function Ae(e,t={},i=null){const n=function(e){if(e.embedded)return[[Te,"embedded"]];const t=e.showCloseButton??se;return[[Te,"modal"],[Se,t?"true":"false"]]}(t);i&&n.push(["sdk_device_id",i]);for(const e of $e){const i=t[e];void 0!==i&&(Ie(i)?n.push([Me[e],i]):De.warn(`Ignoring ${e}: expected "front" or "back", got`,i))}for(const e of ze){const i=t[e];void 0!==i&&("boolean"==typeof i?n.push([Me[e],i?"true":"false"]):De.warn(`Ignoring ${e}: expected a boolean, got`,i))}try{const t=new URL(e);return n.forEach(([e,i])=>t.searchParams.set(e,i)),t.toString()}catch{return e}}const je={exitTitle:"Exit verification?",exitMessage:"Exiting will end your verification process. Are you sure?",continueButton:"Continue",exitButton:"Exit",ariaLabelModal:"Didit Verification",ariaLabelClose:"Close verification"},Oe={ar:{exitTitle:"الخروج من التحقق؟",exitMessage:"سيؤدي الخروج إلى إنهاء عملية التحقق الخاصة بك. هل أنت متأكد؟",continueButton:"متابعة",exitButton:"خروج",ariaLabelModal:"التحقق من Didit",ariaLabelClose:"إغلاق التحقق"},bg:{exitTitle:"Излизане от верификацията?",exitMessage:"Излизането ще прекрати процеса на верификация. Сигурни ли сте?",continueButton:"Продължи",exitButton:"Изход",ariaLabelModal:"Верификация Didit",ariaLabelClose:"Затваряне на верификацията"},bn:{exitTitle:"যাচাইকরণ থেকে বের হবেন?",exitMessage:"বের হলে আপনার যাচাইকরণ প্রক্রিয়া শেষ হয়ে যাবে। আপনি কি নিশ্চিত?",continueButton:"চালিয়ে যান",exitButton:"বের হন",ariaLabelModal:"Didit যাচাইকরণ",ariaLabelClose:"যাচাইকরণ বন্ধ করুন"},bs:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},ca:{exitTitle:"Sortir de la verificació?",exitMessage:"Sortir finalitzarà el procés de verificació. N'esteu segur?",continueButton:"Continua",exitButton:"Sortir",ariaLabelModal:"Verificació Didit",ariaLabelClose:"Tancar verificació"},cnr:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},cs:{exitTitle:"Opravdu chcete odejít?",exitMessage:"Když odejdete, proces ověření se přeruší. Opravdu chcete skončit?",continueButton:"Zůstat",exitButton:"Odejít",ariaLabelModal:"Ověření Didit",ariaLabelClose:"Zavřít ověření"},da:{exitTitle:"Forlad verifikation?",exitMessage:"Hvis du forlader, afsluttes din verifikationsproces. Er du sikker?",continueButton:"Fortsæt",exitButton:"Forlad",ariaLabelModal:"Didit-verifikation",ariaLabelClose:"Luk verifikation"},de:{exitTitle:"Verifizierung verlassen?",exitMessage:"Das Verlassen beendet Ihren Verifizierungsprozess. Sind Sie sicher?",continueButton:"Fortfahren",exitButton:"Verlassen",ariaLabelModal:"Didit-Verifizierung",ariaLabelClose:"Verifizierung schließen"},el:{exitTitle:"Έξοδος από την επαλήθευση;",exitMessage:"Η έξοδος θα τερματίσει τη διαδικασία επαλήθευσης. Είστε σίγουροι;",continueButton:"Συνέχεια",exitButton:"Έξοδος",ariaLabelModal:"Επαλήθευση Didit",ariaLabelClose:"Κλείσιμο επαλήθευσης"},en:je,es:{exitTitle:"¿Salir de la verificación?",exitMessage:"Salir terminará tu proceso de verificación. ¿Estás seguro?",continueButton:"Continuar",exitButton:"Salir",ariaLabelModal:"Verificación Didit",ariaLabelClose:"Cerrar verificación"},et:{exitTitle:"Lahkuda kinnitamisest?",exitMessage:"Lahkumine lõpetab teie kinnitamisprotsessi. Kas olete kindel?",continueButton:"Jätka",exitButton:"Lahku",ariaLabelModal:"Didit kinnitus",ariaLabelClose:"Sulge kinnitus"},fa:{exitTitle:"خروج از تأیید هویت؟",exitMessage:"خروج باعث پایان فرآیند تأیید هویت شما می‌شود. آیا مطمئن هستید؟",continueButton:"ادامه",exitButton:"خروج",ariaLabelModal:"تأیید هویت Didit",ariaLabelClose:"بستن تأیید هویت"},fi:{exitTitle:"Poistu vahvistuksesta?",exitMessage:"Poistuminen päättää vahvistusprosessisi. Oletko varma?",continueButton:"Jatka",exitButton:"Poistu",ariaLabelModal:"Didit-vahvistus",ariaLabelClose:"Sulje vahvistus"},fr:{exitTitle:"Quitter la vérification ?",exitMessage:"Quitter mettra fin à votre processus de vérification. Êtes-vous sûr ?",continueButton:"Continuer",exitButton:"Quitter",ariaLabelModal:"Vérification Didit",ariaLabelClose:"Fermer la vérification"},he:{exitTitle:"לצאת מהאימות?",exitMessage:"יציאה תסיים את תהליך האימות שלך. האם אתה בטוח?",continueButton:"המשך",exitButton:"יציאה",ariaLabelModal:"אימות Didit",ariaLabelClose:"סגירת אימות"},hi:{exitTitle:"सत्यापन से बाहर निकलें?",exitMessage:"बाहर निकलने से आपकी सत्यापन प्रक्रिया समाप्त हो जाएगी। क्या आप सुनिश्चित हैं?",continueButton:"जारी रखें",exitButton:"बाहर निकलें",ariaLabelModal:"Didit सत्यापन",ariaLabelClose:"सत्यापन बंद करें"},hr:{exitTitle:"Izaći iz verifikacije?",exitMessage:"Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",continueButton:"Nastavi",exitButton:"Izađi",ariaLabelModal:"Didit verifikacija",ariaLabelClose:"Zatvori verifikaciju"},hu:{exitTitle:"Kilépés az ellenőrzésből?",exitMessage:"A kilépés befejezi az ellenőrzési folyamatot. Biztos benne?",continueButton:"Folytatás",exitButton:"Kilépés",ariaLabelModal:"Didit ellenőrzés",ariaLabelClose:"Ellenőrzés bezárása"},hy:{exitTitle:"Դուրս գա՞լ ստուգումից",exitMessage:"Դուրս գալը կավարտի ձեր ստուգման գործընթացը։ Համոզված ե՞ք?",continueButton:"Շարունակել",exitButton:"Դուրս գալ",ariaLabelModal:"Didit ստուգում",ariaLabelClose:"Փակել ստուգումը"},id:{exitTitle:"Keluar dari verifikasi?",exitMessage:"Keluar akan mengakhiri proses verifikasi Anda. Apakah Anda yakin?",continueButton:"Lanjutkan",exitButton:"Keluar",ariaLabelModal:"Verifikasi Didit",ariaLabelClose:"Tutup verifikasi"},it:{exitTitle:"Uscire dalla verifica?",exitMessage:"L'uscita terminerà il processo di verifica. Sei sicuro?",continueButton:"Continua",exitButton:"Esci",ariaLabelModal:"Verifica Didit",ariaLabelClose:"Chiudi verifica"},ja:{exitTitle:"認証を終了しますか?",exitMessage:"終了すると認証プロセスが中断されます。よろしいですか?",continueButton:"続ける",exitButton:"終了",ariaLabelModal:"Didit 認証",ariaLabelClose:"認証を閉じる"},ka:{exitTitle:"გამოსვლა შემოწმებიდან?",exitMessage:"გამოსვლა დაასრულებს თქვენს შემოწმების პროცესს. დარწმუნებული ხართ?",continueButton:"გაგრძელება",exitButton:"გამოსვლა",ariaLabelModal:"Didit შემოწმება",ariaLabelClose:"შემოწმების დახურვა"},kk:{exitTitle:"Растаудан шығасыз ба?",exitMessage:"Шығу растау процесін аяқтайды. Сенімдісіз бе?",continueButton:"Жалғастыру",exitButton:"Шығу",ariaLabelModal:"Didit растауы",ariaLabelClose:"Растауды жабу"},ko:{exitTitle:"인증을 종료하시겠습니까?",exitMessage:"종료하면 인증 절차가 중단됩니다. 확실하십니까?",continueButton:"계속",exitButton:"종료",ariaLabelModal:"Didit 인증",ariaLabelClose:"인증 닫기"},ky:{exitTitle:"Текшерүүдөн чыгасызбы?",exitMessage:"Чыгуу текшерүү процессин токтотот. Ишенесизби?",continueButton:"Улантуу",exitButton:"Чыгуу",ariaLabelModal:"Didit текшерүүсү",ariaLabelClose:"Текшерүүнү жабуу"},lt:{exitTitle:"Išeiti iš patvirtinimo?",exitMessage:"Išėjimas nutrauks jūsų patvirtinimo procesą. Ar esate tikri?",continueButton:"Tęsti",exitButton:"Išeiti",ariaLabelModal:"Didit patvirtinimas",ariaLabelClose:"Uždaryti patvirtinimą"},lv:{exitTitle:"Iziet no verifikācijas?",exitMessage:"Iziešana pārtrauks jūsu verifikācijas procesu. Vai esat pārliecināts?",continueButton:"Turpināt",exitButton:"Iziet",ariaLabelModal:"Didit verifikācija",ariaLabelClose:"Aizvērt verifikāciju"},mk:{exitTitle:"Излези од верификацијата?",exitMessage:"Излегувањето ќе го прекине процесот на верификација. Дали сте сигурни?",continueButton:"Продолжи",exitButton:"Излези",ariaLabelModal:"Верификација Didit",ariaLabelClose:"Затвори верификација"},mn:{exitTitle:"Баталгаажуулалтаас гарах уу?",exitMessage:"Гарвал таны баталгаажуулалтын процесс дуусна. Та итгэлтэй байна уу?",continueButton:"Үргэлжлүүлэх",exitButton:"Гарах",ariaLabelModal:"Didit баталгаажуулалт",ariaLabelClose:"Баталгаажуулалтыг хаах"},ms:{exitTitle:"Keluar dari pengesahan?",exitMessage:"Keluar akan menamatkan proses pengesahan anda. Adakah anda pasti?",continueButton:"Teruskan",exitButton:"Keluar",ariaLabelModal:"Pengesahan Didit",ariaLabelClose:"Tutup pengesahan"},nl:{exitTitle:"Verificatie verlaten?",exitMessage:"Verlaten beëindigt uw verificatieproces. Weet u het zeker?",continueButton:"Doorgaan",exitButton:"Verlaten",ariaLabelModal:"Didit-verificatie",ariaLabelClose:"Verificatie sluiten"},no:{exitTitle:"Forlat verifisering?",exitMessage:"Å forlate vil avslutte verifiseringsprosessen. Er du sikker?",continueButton:"Fortsett",exitButton:"Forlat",ariaLabelModal:"Didit-verifisering",ariaLabelClose:"Lukk verifisering"},pl:{exitTitle:"Czy wyjść z weryfikacji?",exitMessage:"Wyjście zakończy proces weryfikacji. Czy na pewno?",continueButton:"Kontynuuj",exitButton:"Wyjdź",ariaLabelModal:"Weryfikacja Didit",ariaLabelClose:"Zamknij weryfikację"},"pt-BR":{exitTitle:"Sair da verificação?",exitMessage:"Sair encerrará seu processo de verificação. Tem certeza?",continueButton:"Continuar",exitButton:"Sair",ariaLabelModal:"Verificação Didit",ariaLabelClose:"Fechar verificação"},pt:{exitTitle:"Sair da verificação?",exitMessage:"Sair terminará o seu processo de verificação. Tem a certeza?",continueButton:"Continuar",exitButton:"Sair",ariaLabelModal:"Verificação Didit",ariaLabelClose:"Fechar verificação"},ro:{exitTitle:"Ieși din verificare?",exitMessage:"Ieșirea va încheia procesul de verificare. Ești sigur?",continueButton:"Continuă",exitButton:"Ieși",ariaLabelModal:"Verificare Didit",ariaLabelClose:"Închide verificarea"},ru:{exitTitle:"Выйти из верификации?",exitMessage:"Выход завершит процесс верификации. Вы уверены?",continueButton:"Продолжить",exitButton:"Выйти",ariaLabelModal:"Верификация Didit",ariaLabelClose:"Закрыть верификацию"},sk:{exitTitle:"Opustiť overenie?",exitMessage:"Odchodom ukončíte proces overenia. Ste si istí?",continueButton:"Pokračovať",exitButton:"Odísť",ariaLabelModal:"Overenie Didit",ariaLabelClose:"Zavrieť overenie"},sl:{exitTitle:"Zapustiti preverjanje?",exitMessage:"Izhod bo prekinil postopek preverjanja. Ali ste prepričani?",continueButton:"Nadaljuj",exitButton:"Izhod",ariaLabelModal:"Preverjanje Didit",ariaLabelClose:"Zapri preverjanje"},so:{exitTitle:"Ka baxdo xaqiijinta?",exitMessage:"Ka bixitaanku wuxuu dhammayn doonaa habka xaqiijintaada. Ma hubtaa?",continueButton:"Sii wad",exitButton:"Ka bax",ariaLabelModal:"Xaqiijinta Didit",ariaLabelClose:"Xir xaqiijinta"},sq:{exitTitle:"Dilni nga verifikimi?",exitMessage:"Dalja do të përfundojë procesin tuaj të verifikimit. A jeni të sigurt?",continueButton:"Vazhdo",exitButton:"Dil",ariaLabelModal:"Verifikimi Didit",ariaLabelClose:"Mbyll verifikimin"},sr:{exitTitle:"Изаћи из верификације?",exitMessage:"Изласком ћете прекинути процес верификације. Да ли сте сигурни?",continueButton:"Настави",exitButton:"Изађи",ariaLabelModal:"Верификација Didit",ariaLabelClose:"Затвори верификацију"},sv:{exitTitle:"Lämna verifiering?",exitMessage:"Att lämna avslutar din verifieringsprocess. Är du säker?",continueButton:"Fortsätt",exitButton:"Lämna",ariaLabelModal:"Didit-verifiering",ariaLabelClose:"Stäng verifiering"},th:{exitTitle:"ออกจากการยืนยันตัวตน?",exitMessage:"การออกจะสิ้นสุดกระบวนการยืนยันตัวตนของคุณ คุณแน่ใจหรือไม่?",continueButton:"ดำเนินการต่อ",exitButton:"ออก",ariaLabelModal:"การยืนยันตัวตน Didit",ariaLabelClose:"ปิดการยืนยันตัวตน"},tr:{exitTitle:"Doğrulamadan çıkmak istiyor musunuz?",exitMessage:"Çıkış, doğrulama sürecinizi sonlandıracak. Emin misiniz?",continueButton:"Devam et",exitButton:"Çıkış",ariaLabelModal:"Didit doğrulama",ariaLabelClose:"Doğrulamayı kapat"},uk:{exitTitle:"Вийти з верифікації?",exitMessage:"Вихід завершить процес верифікації. Ви впевнені?",continueButton:"Продовжити",exitButton:"Вийти",ariaLabelModal:"Верифікація Didit",ariaLabelClose:"Закрити верифікацію"},uz:{exitTitle:"Tekshiruvdan chiqasizmi?",exitMessage:"Chiqish tekshiruv jarayonini tugatadi. Ishonchingiz komilmi?",continueButton:"Davom etish",exitButton:"Chiqish",ariaLabelModal:"Didit tekshiruvi",ariaLabelClose:"Tekshiruvni yopish"},vi:{exitTitle:"Thoát khỏi xác minh?",exitMessage:"Thoát sẽ kết thúc quá trình xác minh của bạn. Bạn có chắc không?",continueButton:"Tiếp tục",exitButton:"Thoát",ariaLabelModal:"Xác minh Didit",ariaLabelClose:"Đóng xác minh"},"zh-CN":{exitTitle:"退出验证?",exitMessage:"退出将结束您的验证流程。确定要退出吗?",continueButton:"继续",exitButton:"退出",ariaLabelModal:"Didit 验证",ariaLabelClose:"关闭验证"},"zh-TW":{exitTitle:"退出驗證?",exitMessage:"退出將結束您的驗證流程。確定要退出嗎?",continueButton:"繼續",exitButton:"退出",ariaLabelModal:"Didit 驗證",ariaLabelClose:"關閉驗證"},zh:{exitTitle:"退出验证?",exitMessage:"退出将结束您的验证流程。确定要退出吗?",continueButton:"继续",exitButton:"退出",ariaLabelModal:"Didit 验证",ariaLabelClose:"关闭验证"}};function Fe(e){return Oe[e]??je}const Pe={light:"#ffffff",dark:"#0b0b0d"};class Ve{constructor(e,t){this.state={isOpen:!1,isLoading:!0,showConfirmation:!1},this.overlay=null,this.container=null,this.iframe=null,this.loadingEl=null,this.confirmOverlay=null,this.confirmationTrigger=null,this.boundHandleMessage=null,this.boundHandleKeydown=null,this.boundHandleFocusChange=null,this.confirmationFocusTimeout=null,this.firstLayoutTimeout=null,this.sizeTimeout=null,this.embedded=!1,this.embeddedContainer=null,this.language="en",this.curtain=null,this.boundPlaceCurtain=null,this.modalId=`didit-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,this.config={zIndex:e?.zIndex??re,showCloseButton:e?.showCloseButton??se,showExitConfirmation:e?.showExitConfirmation??de},this.callbacks=t,this.containerElement=e?.containerElement??document.body,this.embedded=e?.embedded??!1,this.embedded&&e?.embeddedContainerId&&(this.embeddedContainer=document.getElementById(e.embeddedContainerId))}injectStyles(){const e="didit-sdk-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent=`\n .${ce} {\n display: none;\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n z-index: ${this.config.zIndex};\n justify-content: center;\n align-items: center;\n padding: 1rem;\n opacity: 0;\n transition: opacity 0.2s ease-out;\n }\n\n .${ce}.active {\n display: flex;\n opacity: 1;\n }\n\n .${ue} {\n position: relative;\n width: 100%;\n max-width: 440px;\n height: min(860px, calc(100vh - 2rem));\n height: min(860px, calc(100dvh - 2rem));\n border-radius: 16px;\n overflow: hidden;\n background: transparent;\n }\n\n .${ce}.active .${ue} {\n transform: scale(1);\n }\n\n .${he} {\n width: 100%;\n height: 100%;\n border: none;\n display: block;\n }\n\n .${fe} {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 24px;\n height: 24px;\n background: transparent;\n border: none;\n cursor: pointer;\n padding: 0;\n z-index: 10;\n outline: none;\n }\n\n .${fe}:hover,\n .${fe}:focus {\n background: transparent;\n opacity: 0.5;\n }\n\n .${fe} svg {\n stroke: #666;\n stroke-width: 2;\n stroke-linecap: round;\n }\n\n .${be} {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n /* The flow's ground, so a phone's loader meets the ground below the viewport without a seam. */\n background: ${Pe.light};\n z-index: 5;\n }\n\n @media (prefers-color-scheme: dark) {\n .${be} {\n background: ${Pe.dark};\n }\n }\n\n .${be}.hidden {\n display: none;\n }\n\n .${be} svg {\n width: 4rem;\n height: 4rem;\n animation: didit-spin 1s linear infinite;\n }\n\n .${be} circle {\n stroke: #e5e5e5;\n stroke-width: 2.5;\n fill: none;\n }\n\n .${be} path {\n stroke: #525252;\n stroke-width: 2.5;\n stroke-linecap: round;\n fill: none;\n }\n\n @keyframes didit-spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n\n .${ye} {\n display: none;\n position: absolute;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 20;\n justify-content: center;\n align-items: center;\n opacity: 0;\n transition: opacity 0.15s ease-out;\n }\n\n .${ye}.active {\n display: flex;\n opacity: 1;\n }\n\n .${we} {\n background: #fff;\n border-radius: 12px;\n padding: 1.5rem;\n text-align: center;\n max-width: 300px;\n margin: 1rem;\n transform: scale(0.95);\n transition: transform 0.15s ease-out;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n outline: none;\n }\n\n .${ye}.active .${we} {\n transform: scale(1);\n }\n\n .${we} h3 {\n color: #1a1a2e;\n margin: 0 0 0.5rem 0;\n font-size: 1.125rem;\n font-weight: 600;\n }\n\n .${we} p {\n color: #666;\n font-size: 0.875rem;\n margin: 0 0 1.25rem 0;\n line-height: 1.5;\n }\n\n .didit-confirm-actions {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 1rem;\n }\n\n .didit-confirm-actions [data-action="continue"] {\n background: #2563eb;\n color: #fff;\n border: none;\n padding: 0.625rem 1.25rem;\n border-radius: 8px;\n font-size: 0.875rem;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease;\n }\n\n .didit-confirm-actions [data-action="continue"]:hover {\n background: #1d4ed8;\n }\n\n .didit-confirm-actions [data-action="exit"] {\n background: transparent;\n border: none;\n font-family: inherit;\n font-weight: inherit;\n line-height: inherit;\n color: #666;\n font-size: 0.875rem;\n cursor: pointer;\n padding: 0.625rem;\n transition: color 0.15s ease;\n }\n\n .didit-confirm-actions [data-action="exit"]:hover {\n color: #1a1a2e;\n }\n\n .didit-confirm-actions button:focus-visible {\n outline: 2px solid #2567ff;\n outline-offset: 2px;\n }\n\n /*\n * Steps are phone-sized (440 x 860, above). On a computer the handoff card is wider\n * (board Start-Embedded): 960 x 660 on a window of 1000px or more, never wider than the\n * window less its margin and never taller than 90% of it. In a narrower window the\n * page stacks and the height follows its content (--didit-content-height, set from the\n * flow's layout message). Until the flow reports what it shows, the modal is the handoff\n * card at its final size with the spinner inside it (the flow stays hidden and lays itself\n * out for that size): it never opens small and grows. The first change of kind (a step\n * instead of the handoff, or the person continues on this computer) animates once.\n */\n @media (min-width: 541px) {\n .${ue}[data-didit-kind="handoff"],\n .${ue}[data-didit-kind="pending"] {\n max-width: min(960px, calc(100vw - 2rem));\n height: min(var(--didit-content-height, 660px), calc(100vh * 0.9));\n height: min(var(--didit-content-height, 660px), calc(100dvh * 0.9));\n }\n\n .${ue}.${ve} {\n transition: max-width 0.25s ease, height 0.25s ease;\n }\n\n .${ue}[data-didit-kind="pending"] .${he} {\n visibility: hidden;\n }\n }\n\n /*\n * While pending the card already looks like the first screen (ground, radius, shadow and\n * close button come from the flow-sized rules below, with the device theme); the loader\n * sits inside it on the card's own ground.\n */\n .${ue}[data-didit-kind="pending"] .${be} {\n background: transparent;\n }\n\n .${ue}[data-didit-kind="pending"][data-didit-theme="dark"] .${be} circle {\n stroke: rgba(255, 255, 255, 0.16);\n }\n\n .${ue}[data-didit-kind="pending"][data-didit-theme="dark"] .${be} path {\n stroke: #f5f5f7;\n }\n\n @media (min-width: 1000px) {\n .${ue}[data-didit-kind="handoff"],\n .${ue}[data-didit-kind="pending"] {\n height: min(660px, calc(100vh * 0.9));\n height: min(660px, calc(100dvh * 0.9));\n }\n }\n\n @media (max-width: 540px) {\n .${ce} {\n padding: 0;\n }\n\n .${ue} {\n max-width: 100%;\n height: 100vh;\n height: 100dvh;\n border-radius: 0;\n }\n }\n\n /*\n * The flow's ground right below the layout viewport, in the page itself (see showCurtain):\n * on a phone, iOS browsers with their toolbars collapsed show a band of the page there,\n * below every fixed element, the full-screen modal included.\n */\n .${ke} {\n display: none;\n position: absolute;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n margin: 0;\n pointer-events: none;\n /* Under the modal where they meet for a frame while the toolbars move, above the page. */\n z-index: ${this.config.zIndex-1};\n background: ${Pe.light};\n }\n\n .${ke}[data-didit-theme="dark"] {\n background: ${Pe.dark};\n }\n\n /* The exit confirmation's dimming continues over the ground below the viewport. */\n .${ke}[data-didit-dimmed] {\n background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));\n }\n\n @media (max-width: 540px) {\n .${ke} {\n display: block;\n }\n }\n\n /*\n * The hosted flow's layout message (didit:layout) brings the modal's size\n * (see above), theme and direction. Colours are the design system tokens\n * named beside them.\n */\n .${ue}.${ge} {\n --didit-ground: #ffffff; /* site-ground */\n --didit-heading: #1a1a1a; /* c-heading */\n --didit-accent: #2567ff; /* c-accent */\n --didit-hover: rgba(120, 120, 128, 0.08); /* c-hover */\n --didit-close-fill: rgba(0, 0, 0, 0.06);\n --didit-drop: rgba(17, 24, 39, 0.35);\n --didit-ring: rgba(0, 0, 0, 0.06);\n background: var(--didit-ground);\n box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);\n }\n\n .${ue}.${ge}[data-didit-theme="dark"] {\n --didit-ground: #0b0b0d;\n --didit-heading: #f5f5f7;\n --didit-accent: #4d8bff;\n --didit-hover: rgba(255, 255, 255, 0.06);\n --didit-close-fill: rgba(255, 255, 255, 0.06);\n --didit-drop: rgba(0, 0, 0, 0.55); /* c-shadow-pop, dark */\n --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */\n }\n\n .${me} {\n display: none;\n }\n\n .${ge} .${fe} {\n top: 8px;\n right: 8px;\n width: 44px;\n height: 44px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 50%;\n background: var(--didit-close-fill);\n color: var(--didit-heading);\n }\n\n .${ge}[data-didit-dir="rtl"] .${fe} {\n right: auto;\n left: 8px;\n }\n\n .${ge} .${fe}:hover,\n .${ge} .${fe}:focus {\n background: var(--didit-close-fill);\n opacity: 1;\n }\n\n .${ge} .${fe}:hover {\n background-image: linear-gradient(var(--didit-hover), var(--didit-hover));\n }\n\n .${ge} .${fe}:focus-visible {\n outline: 2px solid var(--didit-accent);\n outline-offset: 2px;\n }\n\n .${ge} .${pe} {\n display: none;\n }\n\n .${ge} .${fe} .${me} {\n display: block;\n stroke: currentColor;\n stroke-width: 1.75;\n stroke-linejoin: round;\n }\n\n /*\n * The exit confirmation is sized in rem, so with a large text size it\n * can be taller than a short flow: it scrolls inside the modal instead\n * of being clipped, and its width and actions follow a larger text size.\n * It never grows wider than the modal: a long word wraps instead.\n */\n .${ge} .${ye} {\n padding: 1rem;\n overflow-y: auto;\n }\n\n .${ge} .${we} {\n min-width: 0;\n max-width: max(300px, 18.75rem);\n margin: auto;\n overflow-wrap: anywhere;\n /* Focusing the dialog scrolls it into view start-aligned; this keeps\n * the overlay's top padding visible so the title is never clipped. */\n scroll-margin-top: 1rem;\n }\n\n .${ge} .didit-confirm-actions {\n flex-wrap: wrap;\n }\n\n @media (max-width: 540px) {\n .${ue}.${ge} {\n max-width: 100%;\n box-shadow: none;\n }\n }\n\n .${xe} {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n .${xe} .${he} {\n width: 100%;\n height: 100%;\n max-height: none;\n }\n\n .${xe} .${be} {\n border-radius: 0;\n }\n `,document.head.appendChild(t)}createDOM(){if(this.injectStyles(),this.embedded&&this.embeddedContainer)return void this.createEmbeddedDOM();const e=Fe(this.language);if(this.overlay=document.createElement("div"),this.overlay.id=this.modalId,this.overlay.className=ce,this.overlay.setAttribute("role","dialog"),this.overlay.setAttribute("aria-modal","true"),this.overlay.setAttribute("aria-label",e.ariaLabelModal),this.container=document.createElement("div"),this.container.className=ue,this.loadingEl=document.createElement("div"),this.loadingEl.className=be,this.loadingEl.innerHTML='\n <svg viewBox="0 0 24 24">\n <circle cx="12" cy="12" r="10" />\n <path d="M12 2a10 10 0 0 1 10 10" />\n </svg>\n ',this.config.showCloseButton){const t=document.createElement("button");t.className=fe,t.setAttribute("aria-label",e.ariaLabelClose),t.innerHTML=`\n <svg class="${pe}" width="14" height="14" viewBox="0 0 14 14">\n <line x1="1" y1="1" x2="13" y2="13" />\n <line x1="13" y1="1" x2="1" y2="13" />\n </svg>\n <svg class="${me}" width="18" height="18" viewBox="0 0 24 24" fill="none">\n <path d="M7 7.03882L17 16.9611" />\n <path d="M7.03968 17L16.9619 7" />\n </svg>\n `,t.addEventListener("click",()=>this.handleCloseRequest(t)),this.container.appendChild(t)}this.iframe=document.createElement("iframe"),this.iframe.className=he,this.iframe.setAttribute("allow",Ce),this.iframe.setAttribute("title",e.ariaLabelModal),this.iframe.addEventListener("load",()=>this.handleIframeLoad()),this.confirmOverlay=document.createElement("div"),this.confirmOverlay.className=ye,this.confirmOverlay.innerHTML=`\n <div class="${we}" role="dialog" aria-modal="true" tabindex="-1"\n aria-labelledby="${this.modalId}-exit-title" aria-describedby="${this.modalId}-exit-message">\n <h3 id="${this.modalId}-exit-title">${e.exitTitle}</h3>\n <p id="${this.modalId}-exit-message">${e.exitMessage}</p>\n <div class="didit-confirm-actions">\n <button type="button" data-action="continue">${e.continueButton}</button>\n <button type="button" data-action="exit">${e.exitButton}</button>\n </div>\n </div>\n `,this.confirmOverlay.querySelector('[data-action="continue"]')?.addEventListener("click",()=>{this.hideConfirmation()}),this.confirmOverlay.querySelector('[data-action="exit"]')?.addEventListener("click",()=>{this.confirmExit()}),this.container.appendChild(this.loadingEl),this.container.appendChild(this.iframe),this.container.appendChild(this.confirmOverlay),this.overlay.appendChild(this.container),this.overlay.addEventListener("click",e=>{e.target===this.overlay&&this.handleCloseRequest()}),this.containerElement.appendChild(this.overlay)}createEmbeddedDOM(){this.embeddedContainer&&(this.container=document.createElement("div"),this.container.id=this.modalId,this.container.className=xe,this.loadingEl=document.createElement("div"),this.loadingEl.className=be,this.loadingEl.innerHTML='\n <svg viewBox="0 0 24 24">\n <circle cx="12" cy="12" r="10" />\n <path d="M12 2a10 10 0 0 1 10 10" />\n </svg>\n ',this.iframe=document.createElement("iframe"),this.iframe.className=he,this.iframe.setAttribute("allow",Ce),this.iframe.setAttribute("title",Fe(this.language).ariaLabelModal),this.iframe.addEventListener("load",()=>this.handleIframeLoad()),this.container.appendChild(this.loadingEl),this.container.appendChild(this.iframe),this.embeddedContainer.appendChild(this.container))}setupEventListeners(){this.boundHandleMessage||this.boundHandleKeydown||(this.boundHandleMessage=this.handleMessage.bind(this),window.addEventListener("message",this.boundHandleMessage),this.boundHandleKeydown=this.handleKeydown.bind(this),document.addEventListener("keydown",this.boundHandleKeydown),this.boundHandleFocusChange=()=>{this.state.showConfirmation&&this.isTopmost()&&(null!==this.confirmationFocusTimeout&&window.clearTimeout(this.confirmationFocusTimeout),this.confirmationFocusTimeout=window.setTimeout(()=>{this.confirmationFocusTimeout=null,this.state.showConfirmation&&this.isTopmost()&&!this.confirmOverlay?.contains(document.activeElement)&&this.focusConfirmation()},0))},document.addEventListener("focusin",this.boundHandleFocusChange),document.addEventListener("focusout",this.boundHandleFocusChange),window.addEventListener("blur",this.boundHandleFocusChange))}removeEventListeners(){this.boundHandleMessage&&(window.removeEventListener("message",this.boundHandleMessage),this.boundHandleMessage=null),this.boundHandleKeydown&&(document.removeEventListener("keydown",this.boundHandleKeydown),this.boundHandleKeydown=null),this.boundHandleFocusChange&&(document.removeEventListener("focusin",this.boundHandleFocusChange),document.removeEventListener("focusout",this.boundHandleFocusChange),window.removeEventListener("blur",this.boundHandleFocusChange),this.boundHandleFocusChange=null)}pushToTop(){const e=Ve.openModals,t=e.indexOf(this);-1!==t&&e.splice(t,1),e.push(this)}removeFromStack(){const e=Ve.openModals,t=e.indexOf(this);-1!==t&&e.splice(t,1)}isTopmost(){const e=Ve.openModals;return e.length>0&&e[e.length-1]===this}handleMessage(e){if(!this.iframe?.src)return;if(!function(e,t){try{const i=new URL(e),n=new URL(t);return i.hostname.endsWith(".didit.me")||i.hostname===n.hostname}catch{return!1}}(e.origin,this.iframe.src))return De.warn("Received postMessage from unallowed origin:",e.origin);if(!this.iframe||e.source!==this.iframe.contentWindow)return;let t;De.log("Received postMessage:",e.data);try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch{return void De.warn("Failed to parse postMessage:",e.data)}if("didit:close_request"!==t.type){if("didit:layout"===t.type){const e=this.readFlowLayout(t.data);return void(e?this.applyFlowLayout(e):De.warn("Ignoring a layout message without a positive contentHeight:",t.data))}this.callbacks.onMessage(t)}else this.handleCloseRequest()}readFlowLayout(e){const t="object"==typeof e&&null!==e?e:{},{contentHeight:i,colorScheme:n,dir:a,kind:o}=t;if("number"!=typeof i||!Number.isFinite(i)||i<=0)return null;const r=window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1;return{kind:"handoff"===o?"handoff":"step",contentHeight:Math.ceil(i),colorScheme:"light"===n||"dark"===n?n:r?"dark":"light",dir:"ltr"===a||"rtl"===a?a:(s=this.language,Be.includes(s.split("-")[0])?"rtl":"ltr")};var s}applyFlowLayout(e){if(this.embedded||!this.container)return;De.log("Flow layout:",e),this.container.classList.add(ge),this.container.dataset.diditTheme=e.colorScheme,this.container.dataset.diditDir=e.dir;const t=this.container.offsetHeight;this.container.style.setProperty("--didit-content-height",`${e.contentHeight}px`),this.matchPageBackground(e.colorScheme),this.curtain&&(this.curtain.dataset.diditTheme=e.colorScheme),this.setModalKind(e.kind,"handoff"===e.kind&&this.handoffHeight(e)===t)}isPhoneWindow(){return window.matchMedia?.("(max-width: 540px)").matches??!1}handoffHeight(e){const t=.9*window.innerHeight;return Math.round(Math.min(window.innerWidth>=1e3?660:e.contentHeight,t))}setModalKind(e,t=!1){if(!this.container)return;const i=this.container.dataset.diditKind;if(i===e)return;null!==this.firstLayoutTimeout&&"pending"!==e&&(window.clearTimeout(this.firstLayoutTimeout),this.firstLayoutTimeout=null);void 0===i||"pending"===i&&"handoff"===e&&t||this.animateSizeOnce(),this.container.dataset.diditKind=e,"pending"!==i||this.state.isLoading||this.loadingEl?.classList.add("hidden")}animateSizeOnce(){this.container?.classList.add(ve),null!==this.sizeTimeout&&window.clearTimeout(this.sizeTimeout),this.sizeTimeout=window.setTimeout(()=>{this.sizeTimeout=null,this.container?.classList.remove(ve)},300)}waitForFirstLayout(){this.container&&(this.container.classList.add(ge),this.container.dataset.diditTheme=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",this.setModalKind("pending"),this.firstLayoutTimeout=window.setTimeout(()=>{this.firstLayoutTimeout=null,this.container?.classList.remove(ge),delete this.container?.dataset.diditTheme,this.setModalKind("step")},3e3))}matchPageBackground(e){window.matchMedia?.("(max-width: 540px)").matches&&(Ve.pageBackground??(Ve.pageBackground={saved:{root:document.documentElement.style.backgroundColor,body:document.body.style.backgroundColor},grounds:new Map}),Ve.pageBackground.grounds.set(this,e),Ve.paintPageBackground())}restorePageBackground(){const e=Ve.pageBackground;e?.grounds.delete(this)&&(e.grounds.size>0?Ve.paintPageBackground():(Ve.pageBackground=null,document.documentElement.style.backgroundColor=e.saved.root,document.body.style.backgroundColor=e.saved.body))}static paintPageBackground(){const e=Ve.pageBackground;if(!e)return;const t=[...Ve.openModals].reverse().find(t=>e.grounds.has(t)),i=t?e.grounds.get(t):[...e.grounds.values()].pop();i&&(document.documentElement.style.backgroundColor=Pe[i],document.body.style.backgroundColor=Pe[i])}lockPageScroll(){const e=Ve.pageScrollLock;if(e)return void e.holders.add(this);const t=document.documentElement,i=document.body,n=e=>""!==e&&"visible"!==e,a=n(window.getComputedStyle(t).overflowY)&&n(window.getComputedStyle(i).overflowY);Ve.pageScrollLock={holders:new Set([this]),root:{overflow:t.style.overflow,overscrollBehavior:t.style.overscrollBehavior},body:a?{overflow:i.style.overflow}:null},t.style.overflow="hidden",t.style.overscrollBehavior="none",a&&(i.style.overflow="hidden")}unlockPageScroll(){const e=Ve.pageScrollLock;if(!e||!e.holders.delete(this)||e.holders.size>0)return;Ve.pageScrollLock=null;const t=document.documentElement;t.style.overflow=e.root.overflow,t.style.overscrollBehavior=e.root.overscrollBehavior,e.body&&(document.body.style.overflow=e.body.overflow)}showCurtain(){if(!this.curtain){const e=document.createElement("div");e.className=ke,e.setAttribute("aria-hidden","true"),document.body.appendChild(e),this.curtain=e,this.boundPlaceCurtain=()=>this.placeCurtain(),window.addEventListener("resize",this.boundPlaceCurtain),window.addEventListener("scroll",this.boundPlaceCurtain),window.visualViewport?.addEventListener("resize",this.boundPlaceCurtain)}this.curtain.dataset.diditTheme=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",this.placeCurtain()}placeCurtain(){const e=this.curtain;if(!e)return;e.style.top="0px",e.style.left="0px";const t=e.getBoundingClientRect();e.style.top=window.innerHeight-t.top+"px",e.style.left=-t.left+"px"}removeCurtain(){this.boundPlaceCurtain&&(window.removeEventListener("resize",this.boundPlaceCurtain),window.removeEventListener("scroll",this.boundPlaceCurtain),window.visualViewport?.removeEventListener("resize",this.boundPlaceCurtain),this.boundPlaceCurtain=null),this.curtain?.remove(),this.curtain=null}resetFlowLayout(){!this.embedded&&this.container&&(this.restorePageBackground(),this.container.classList.remove(ge,ve),delete this.container.dataset.diditTheme,delete this.container.dataset.diditDir,delete this.container.dataset.diditKind,this.container.style.removeProperty("--didit-content-height"),null!==this.firstLayoutTimeout&&(window.clearTimeout(this.firstLayoutTimeout),this.firstLayoutTimeout=null),null!==this.sizeTimeout&&(window.clearTimeout(this.sizeTimeout),this.sizeTimeout=null))}handleKeydown(e){if(this.state.isOpen&&this.isTopmost()){if("Tab"===e.key&&this.state.showConfirmation){const t=Array.from(this.confirmOverlay?.querySelectorAll("button")??[]);if(t.length){e.preventDefault();const i=t.findIndex(e=>e===document.activeElement);t[e.shiftKey?i<=0?t.length-1:i-1:(i+1)%t.length].focus()}return}"Escape"===e.key&&(e.preventDefault(),this.state.showConfirmation?this.hideConfirmation():this.handleCloseRequest())}}handleIframeLoad(){this.iframe?.src&&"about:blank"!==this.iframe.src&&(this.state.isLoading=!1,"pending"!==this.container?.dataset.diditKind&&this.loadingEl?.classList.add("hidden"),this.callbacks.onIframeLoad())}handleCloseRequest(e){this.config.showExitConfirmation?this.showConfirmation(e):this.callbacks.onCloseConfirmed()}showConfirmation(e){if(!this.confirmOverlay||this.state.showConfirmation)return;const t=document.activeElement;this.confirmationTrigger=e??(t instanceof HTMLElement&&t!==document.body?t:this.container?.querySelector(`.${fe}`)??this.iframe),this.state.showConfirmation=!0,this.confirmOverlay.classList.add("active"),this.curtain?.setAttribute("data-didit-dimmed",""),this.iframe&&(this.iframe.inert=!0);const i=this.container?.querySelector(`.${fe}`);i&&(i.inert=!0),this.confirmOverlay.scrollTop=0,this.isTopmost()&&this.focusConfirmation(),this.callbacks.onClose()}focusConfirmation(){this.confirmOverlay?.querySelector(`.${we}`)?.focus({preventScroll:!0})}hideConfirmation(e=!0){if(null!==this.confirmationFocusTimeout&&(window.clearTimeout(this.confirmationFocusTimeout),this.confirmationFocusTimeout=null),!this.state.showConfirmation)return;this.state.showConfirmation=!1,this.confirmOverlay?.classList.remove("active"),this.curtain?.removeAttribute("data-didit-dimmed"),this.iframe&&(this.iframe.inert=!1);const t=this.container?.querySelector(`.${fe}`);t&&(t.inert=!1);const i=this.confirmationTrigger;this.confirmationTrigger=null,e&&this.isTopmost()&&i?.isConnected&&(i===this.iframe?this.confirmationFocusTimeout=window.setTimeout(()=>{this.confirmationFocusTimeout=null,this.state.isOpen&&!this.state.showConfirmation&&this.isTopmost()&&i.isConnected&&i.focus({preventScroll:!0})},0):i.focus({preventScroll:!0}))}confirmExit(){this.hideConfirmation(),this.callbacks.onCloseConfirmed()}open(e){this.language=function(e){try{const{pathname:t}=new URL(e),i=t.split("/").filter(Boolean)[0];if(i&&_e.includes(i))return i}catch{}const t=navigator.language;if(_e.includes(t))return t;const i=t.split("-")[0];return _e.includes(i)?i:"en"}(e),this.overlay||this.container||this.createDOM(),this.setupEventListeners(),De.log("Opening with URL:",e),this.state.isLoading=!0,this.hideConfirmation(),this.loadingEl?.classList.remove("hidden"),this.resetFlowLayout(),this.embedded||this.isPhoneWindow()||this.waitForFirstLayout(),this.iframe&&(this.iframe.src=e),this.state.isOpen=!0,this.pushToTop(),this.embedded||(this.overlay?.classList.add("active"),this.lockPageScroll(),this.showCurtain())}close(){De.log("Closing"),this.hideConfirmation(!1),this.state.isOpen=!1,this.state.isLoading=!0,this.state.showConfirmation=!1,this.removeFromStack(),this.removeEventListeners(),this.resetFlowLayout(),this.iframe&&(this.iframe.src="about:blank"),this.embedded||(this.overlay?.classList.remove("active"),this.removeCurtain(),this.unlockPageScroll())}destroy(){De.log("Destroying"),this.close(),this.removeEventListeners(),this.embedded&&this.container&&this.container.parentNode?this.container.parentNode.removeChild(this.container):this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.container=null,this.iframe=null,this.loadingEl=null,this.confirmOverlay=null}isOpen(){return this.state.isOpen}isLoading(){return this.state.isLoading}}Ve.openModals=[],Ve.pageBackground=null,Ve.pageScrollLock=null;const He="https://verification.didit.me",Ne={invalid_token:"The transaction token is invalid.",expired_token:"The transaction token has expired.",validation:"The transaction payload failed validation.",network:"A network error occurred while contacting the Didit API."};class qe extends Error{constructor(e,t,i){super(t||Ne[e]),this.name="DiditTransactionError",this.type=e,this.status=i?.status,this.fieldErrors=i?.fieldErrors}}function Re(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ue(e){const t={};for(const[i,n]of Object.entries(e))void 0!==n&&(t[i]=n);return t}function Ke(e){if(e)return Ue({type:e.type,externalUserId:e.externalUserId,fullName:e.fullName,firstName:e.firstName,lastName:e.lastName,dob:e.dob,address:e.address,institutionInfo:e.institutionInfo,device:e.device,paymentMethod:e.paymentMethod?Ue({type:e.paymentMethod.type,accountId:e.paymentMethod.accountId,issuingCountry:e.paymentMethod.issuingCountry}):void 0})}function We(e){if(e)return Ue({status:e.status,protocol:e.protocol,required:e.required,obligationsCount:e.obligationsCount,originatorData:e.originatorData,beneficiaryData:e.beneficiaryData,metadata:e.metadata})}function Ze(e,...t){for(const i of t){const t=e[i];if("string"==typeof t&&t)return t}}function Je(e){const t=Ze(e,"uuid","transaction_id","transactionId"),i=Ze(e,"status");if(!t||!i)throw new qe("network","Unexpected response shape from the Didit API: missing transaction id or status.");const n={transactionId:t,status:i},a=function(e){const t=e.travel_rule??e.travelRule;if(Re(t)){const e=Ze(t,"status");if(e)return e}const i=e.props;if(Re(i)){const e=Ze(i,"travel_rule_status","travelRuleStatus");if(e)return e}return Ze(e,"travel_rule_status","travelRuleStatus")}(e);a&&(n.travelRuleStatus=a);const o=function(e){if(!Re(e))return;const t=Ze(e,"type"),i=Ze(e,"url");if(!t||!i)return;const n={type:t,url:i},a=Ze(e,"session_id","sessionId");a&&(n.sessionId=a);const o=Ze(e,"session_token","sessionToken");o&&(n.sessionToken=o);const r=Ze(e,"status");r&&(n.status=r);const s=Ze(e,"widget_session_id","widgetSessionId");s&&(n.widgetSessionId=s);const d=Ze(e,"expires_at","expiresAt");return d&&(n.expiresAt=d),n}(e.action_required??e.actionRequired);return o&&(n.actionRequired=o),n}function Xe(e,t){const i=function(e){if(Re(e))return Ze(e,"detail","message","error")}(t);if(401===e||403===e){const n=`${i??""} ${Ze(Re(t)?t:{},"code")??""}`;return/expired/i.test(n)?new qe("expired_token",i,{status:e}):new qe("invalid_token",i,{status:e})}return 400===e||422===e?new qe("validation",i,{status:e,fieldErrors:Re(t)?t:void 0}):new qe("network",`Request failed with status ${e}.`,{status:e})}async function Qe(e,t){if("function"!=typeof fetch)throw new qe("network","fetch is not available in this environment.");let i;try{i=await fetch(e,t)}catch{throw new qe("network")}const n=await async function(e){try{return await e.json()}catch{return null}}(i);if(!i.ok)throw Xe(i.status,n);if(!Re(n))throw new qe("network","Unexpected empty response from the Didit API.",{status:i.status});return Je(n)}async function Ge(e){const t=await C().catch(()=>null),i=Ue({txnId:(n=e.transaction).txnId,txnDate:n.txnDate,zoneId:n.zoneId,type:n.category,info:(a=n.details,Ue({direction:a.direction,amount:a.amount,currency:a.currency,currencyType:a.currencyType,amountInDefaultCurrency:a.amountInDefaultCurrency,defaultCurrencyCode:a.defaultCurrencyCode,paymentDetails:a.paymentDetails,paymentTxnId:a.paymentTxnId,type:a.actionType,cryptoParams:a.cryptoParams})),subject:Ke(n.subject),counterparty:Ke(n.counterparty),props:n.customProperties,travelRule:We(n.travelRule),includeCryptoScreening:n.includeCryptoScreening});var n,a;return t&&(i.fingerprint_v2=t),Qe(`${e.baseUrl}/v1/transactions/`,{method:"POST",headers:{"Content-Type":"application/json","X-Transaction-Token":e.transactionToken,...M(t)},body:JSON.stringify(i)})}async function Ye(e){return Qe(`${e.baseUrl}/v1/transactions/${e.transactionId}/`,{method:"GET",headers:{"X-Transaction-Token":e.transactionToken}})}function et(e){return new Promise(t=>setTimeout(t,e))}function tt(e){return e instanceof qe&&("invalid_token"===e.type||"expired_token"===e.type)}class it{static get shared(){return it._instance||(it._instance=new it),it._instance}static reset(){it._instance&&(it._instance.destroy(),it._instance=null)}get state(){return this._state}get configuration(){return this._configuration}get isPresented(){return this._modal?.isOpen()??!1}get isActionModalPresented(){return this._actionModal?.isOpen()??!1}get errorMessage(){return this._errorMessage}constructor(){this._state="idle",this._modal=null,this._actionModal=null,this._actionModalSettle=null,this._actionGeneration=0,De.log("DiditSdk initialized")}async startVerification(e){const t=e.configuration;this._configuration=t,De.isEnabled=t?.loggingEnabled??le,De.log("Starting verification with options:",e),this._modal&&(this._modal.destroy(),this._modal=null),this._errorMessage=void 0;try{const{url:i}=e;if(!i||"string"!=typeof i)throw new Error("Invalid options: url is required");!function(e){if(!e?.embedded)return;const t=e.embeddedContainerId;if(!t)throw new Error("Embedded mode requires embeddedContainerId: the id of the element that hosts the verification.");if("undefined"==typeof document||!document.getElementById(t))throw new Error(`Embedded container "#${t}" was not found in the page.`)}(t),this._modal=new Ve(t,{onClose:()=>this.handleModalClose(),onCloseConfirmed:()=>this.handleModalCloseConfirmed(),onMessage:e=>this.handleVerificationEvent(e),onIframeLoad:()=>this.handleIframeLoad()}),this._url=Ae(i,t,function(){try{return L()}catch{return null}}()),this.setState("loading"),this.emitInternalEvent("didit:started",{}),this._modal?.open(this._url)}catch(e){this.handleError(e)}}async submitTransaction(e){if(!e?.transactionToken||"string"!=typeof e.transactionToken)throw new qe("invalid_token","transactionToken is required.");if(!e.transaction||"object"!=typeof e.transaction)throw new qe("validation","transaction payload is required.");if(!e.transaction.txnId||"string"!=typeof e.transaction.txnId)throw new qe("validation","transaction.txnId is required.");if(!e.transaction.details||"object"!=typeof e.transaction.details)throw new qe("validation","transaction.details is required.");const t=(e.baseUrl??He).replace(/\/+$/,"");De.log("Submitting transaction:",e.transaction.txnId);const i=await Ge({baseUrl:t,transactionToken:e.transactionToken,transaction:e.transaction});De.log("Transaction submitted:",i);return(e.autoLaunchAction??!0)&&"wallet_ownership"===i.actionRequired?.type&&i.actionRequired.url&&this.runTransactionAction(t,e.transactionToken,i,e.onActionCompleted),i}submitEvent(e){return De.log("Submitting event:",e?.event?.category,e?.event?.actionType),ae(e)}close(){De.log("Closing verification programmatically"),this._actionModalSettle?.("aborted"),this.handleModalCloseConfirmed()}destroy(){De.log("Destroying SDK instance"),this._actionGeneration++,this._actionModalSettle?.("aborted"),this._modal?.destroy(),this._modal=null,this.reset(),this.setState("idle")}async runTransactionAction(e,t,i,n){const a=this._actionGeneration;let o=!1;const r=(e,t)=>{if(!o&&a===this._actionGeneration){o=!0;try{n?.(e,t)}catch(e){De.error("onActionCompleted callback threw:",e)}}};try{if("aborted"===await this.presentTransactionActionModal(i.actionRequired.url)||a!==this._actionGeneration)return;if(!i.transactionId)return void r(i);let n,o=null;try{o=await async function(e){const t=e.intervalMs??1500,i=Math.max(1,e.maxAttempts??10);let n=null;for(let a=0;a<i;a++){if(e.isAborted?.())return n;if(a>0&&await et(t),e.isAborted?.())return n;try{n=await Ye(e);const t=!n.actionRequired,i=void 0!==e.initialStatus&&n.status!==e.initialStatus;if(t||i)return n}catch(e){if(tt(e))throw e}}return n}({baseUrl:e,transactionToken:t,transactionId:i.transactionId,initialStatus:i.status,isAborted:()=>a!==this._actionGeneration})}catch(e){if(!(e instanceof qe))throw e;n=e}if(n)return void r(i,{type:n.type,message:n.message});r(o??i)}catch(e){De.error("Transaction action follow-up failed:",e),r(i)}}presentTransactionActionModal(e){return this._actionModalSettle?.("aborted"),new Promise(t=>{let i=!1;const n=e=>{if(i)return;i=!0;const n=this._actionModal;this._actionModal=null,this._actionModalSettle=null,n?.destroy(),t(e)};let a;try{a=new Ve(void 0,{onClose:()=>{},onCloseConfirmed:()=>n("finished"),onMessage:e=>{this.onEvent?.(e),"didit:completed"!==e.type&&"didit:cancelled"!==e.type||n("finished")},onIframeLoad:()=>{}}),De.log("Launching required transaction action:",e),a.open(e)}catch(e){throw this._actionModal=null,this._actionModalSettle=null,e}this._actionModal=a,this._actionModalSettle=n})}handleModalClose(){De.log("Modal close requested")}handleModalCloseConfirmed(){De.log("Modal close confirmed");const e=this.buildSessionData();this._modal?.close(),this.reset(),this.setState("idle");const t={type:"cancelled",session:e};this.onComplete?.(t)}handleIframeLoad(){De.log("Iframe loaded")}emitInternalEvent(e,t){const i={type:e,data:t,timestamp:Date.now()};De.log("Emitting internal event:",i),this.onEvent?.(i)}handleVerificationEvent(e){switch(De.log("Verification event:",e),e.data?.sessionId&&(this._sessionId=e.data.sessionId),this.onEvent?.(e),e.type){case"didit:ready":De.log("Verification iframe ready");break;case"didit:started":De.log("User started verification");break;case"didit:step_started":De.log("Step started:",e.data?.step);break;case"didit:step_completed":De.log("Step completed:",e.data?.step,"-> next:",e.data?.nextStep);break;case"didit:media_started":De.log("Media started:",e.data?.mediaType,"for step:",e.data?.step);break;case"didit:media_captured":De.log("Media captured for step:",e.data?.step,"isAuto:",e.data?.isAuto);break;case"didit:document_selected":De.log("Document selected:",e.data?.documentType,"country:",e.data?.country);break;case"didit:verification_submitted":De.log("Verification submitted for step:",e.data?.step);break;case"didit:code_sent":De.log("Code sent via:",e.data?.channel,"codeSize:",e.data?.codeSize);break;case"didit:code_verified":De.log("Code verified via:",e.data?.channel);break;case"didit:status_updated":De.log("Status updated:",e.data?.status,"step:",e.data?.step);break;case"didit:completed":this.handleVerificationCompleted(e);break;case"didit:cancelled":this.handleVerificationCancelled(e);break;case"didit:error":this.handleVerificationError(e);break;case"didit:step_changed":De.log("Step changed:",e.data?.step)}}handleVerificationCompleted(e){De.log("Verification completed:",e.data);const t=this.buildSessionData(e.data);this._configuration?.closeModalOnComplete&&(this._modal?.close(),this.reset(),this.setState("idle"));const i={type:"completed",session:t};this.onComplete?.(i)}handleVerificationCancelled(e){De.log("Verification cancelled:",e.data);const t=this.buildSessionData(e.data);this._modal?.close(),this.reset(),this.setState("idle");const i={type:"cancelled",session:t};this.onComplete?.(i)}handleVerificationError(e){De.log("Verification error:",e.data)}handleError(e){let t;De.error("SDK error:",e),t=e instanceof Error?Ee("unknown",e.message):Ee("unknown","An unknown error occurred"),this._modal?.close(),this._modal=null,this.reset(),this._errorMessage=t.message,this.setState("error");const i={type:"failed",error:t};this.onComplete?.(i)}setState(e){const t=this._state;this._state=e,t!==e&&(De.log("State changed:",t,"->",e),this.onStateChange?.(e,this._errorMessage))}reset(){this._sessionId=void 0,this._url=void 0,this._errorMessage=void 0,this._configuration=void 0}buildSessionData(e){const t=e?.sessionId||this._sessionId;if(t)return{sessionId:t,status:e?.status||"Pending"}}}it._instance=null,e.DEFAULT_EVENTS_BASE_URL=T,e.DEFAULT_TRANSACTION_BASE_URL=He,e.DiditEventError=D,e.DiditSdk=it,e.DiditTransactionError=qe,e.SDK_VERSION="0.6.0",e.buildFingerprintHeaders=M,e.configureEvents=function(e){const t={...I,...N({...e})};t.baseUrl=V(t.baseUrl),t.batchSize=Math.min(Math.max(1,Math.floor(t.batchSize)),500),t.flushIntervalMs=Math.max(0,t.flushIntervalMs),t.maxQueueSize=Math.max(1,Math.floor(t.maxQueueSize)),I=t},e.default=it,e.flush=oe,e.getDeviceFingerprintPayload=C,e.getStoredDeviceId=L,e.setDeviceSignalsProvider=function(e){v=e,x+=1,b=null,y=null,w=null},e.submitEvent=ae,Object.defineProperty(e,"__esModule",{value:!0})});
7
7
  //# sourceMappingURL=didit-sdk.umd.min.js.map