@corbado/observe 1.9.1 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/analysis/client.mjs +183 -14
- package/dist/analysis/config.mjs +5 -5
- package/dist/analysis/cross-origin-session.mjs +422 -0
- package/dist/analysis/device.mjs +0 -79
- package/dist/analysis/low-events/grouped-input-tracker.mjs +2 -3
- package/dist/analysis/low-events/input-change-recorder.mjs +35 -12
- package/dist/analysis/low-events/input-tracker.mjs +0 -58
- package/dist/analysis/queue.mjs +9 -0
- package/dist/analysis/readers/network.mjs +5 -0
- package/dist/analysis/readers/page.mjs +4 -0
- package/dist/analysis/transports/fetch.mjs +16 -1
- package/dist/analysis/utils/operation-full.mjs +0 -1
- package/dist/analysis/version.mjs +1 -1
- package/dist/cdn/script.global.js +4 -4
- package/dist/index.d.mts +130 -30
- package/dist/index.d.ts +130 -30
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/package.json +1 -1
- package/dist/analysis/readers/password-manager-dom.mjs +0 -112
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";(()=>{var
|
|
2
|
-
`);if(
|
|
3
|
-
`),s=i?"[truncated]":`[+${
|
|
4
|
-
${s}`,t)}function lr(r,e,t){let{limits:i}=t,n=K(r),o=u=>ae(u,e-1,t);if(n==="Date")return Number.isNaN(r.getTime())?"[Invalid Date]":r.toISOString();if(n==="RegExp")return A(String(r),i.maxValueLength);if(n==="ArrayBuffer")return`[ArrayBuffer(${r.byteLength})]`;if(ArrayBuffer.isView(r))return`[${n}(${r.byteLength})]`;if(n==="Map"||n==="Set"){let u=r,f=[];for(let h of u){if(f.length===i.maxBreadth)break;f.push(o(h))}return u.size>f.length&&f.push(`[+${u.size-f.length} more]`),f}if(n==="Promise"||n==="WeakMap"||n==="WeakSet"||n==="Window")return`[${n}]`;if(typeof Node<"u"&&r instanceof Node)return`[${n}]`;if(Array.isArray(r)){let u=r.slice(0,i.maxBreadth).map(o);return r.length>i.maxBreadth&&u.push(`[+${r.length-i.maxBreadth} more]`),u}if(typeof Response<"u"&&r instanceof Response)return{status:o(r.status),statusText:o(r.statusText),url:o(r.url),redirected:o(r.redirected)};if(typeof Event<"u"&&r instanceof Event){let u=r,f={type:o(u.type)};for(let h of["message","filename","lineno","colno"])h in u&&(f[h]=o(u[h]));return"error"in u&&u.error!=null&&(f.error=o(u.error)),f}let s=Object.create(null),a=r,l=sr(r);if(l){for(let f of rr){if(f==="stack"&&!i.stack)continue;let h=a[f];if(!(h==null||typeof h=="function")){if(f==="stack"){i.stack&&typeof h=="string"&&(s.stack=te(Ft(h,i.maxStackFrames,i.maxValueLength),t));continue}s[f]=o(h)}}let u=a.cause;u!=null&&typeof u!="function"&&(s.cause=dr(u,e-1,t))}let p=0,d=Object.keys(a);for(let u of d){if(u in s||u==="stack"&&!i.stack||l&&u==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${d.length-i.maxBreadth} keys]`;break}let f=a[u];typeof f!="function"&&(s[te(u,t)]=u==="stack"&&typeof f=="string"?te(Ft(f,i.maxStackFrames,i.maxValueLength),t):o(f))}return!l&&n!=="Object"&&p===0?`[${n}]`:s}function dr(r,e,t){if(typeof r!="object"||r===null)return ae(r,e,t);if(t.causeBudget<=0)return te(`[${K(r)}]`,t);t.causeBudget--;try{return ae(r,e,t)}finally{t.causeBudget++}}var pr=1500,g=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:O,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??O(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),passwordManagerDomScan:()=>this.tracker.isPasswordManagerDomScanEnabled(),registerInputs:(i,n)=>this.tracker.getWindowObserver().registerInputs(i,()=>({subflowStartEventId:this.startReference,fieldRole:t,initiator:t?`input-${t}`:"unknown",sessionId:this.captureSessionId}),n),beginCeremony:i=>this.tracker.getWindowObserver().beginCeremony({subflowStartEventId:this.startReference,initiator:i??"unknown",sessionId:this.captureSessionId})}}createLowCollector(e){try{let t=e();return this.lowPrefillCapturers.push(i=>t.capturePrefill(i)),t}catch(t){this.tracker.getLogger().error("Failed to attach low-event collector",t);return}}registerLowFlusher(e){this.lowFlushers.push(e)}captureOptions(e,t=this.startReference,i=this.captureSessionId,n){if(!t&&!n)return e;let o={};return t&&(o.subflowStartEventId=e?.subflowStartEventId??t,o.captureSessionId=e?.captureSessionId??i),n&&(o.initiator=e?.initiator??n),Object.defineProperties({},{...Object.getOwnPropertyDescriptors(e??{}),...Object.getOwnPropertyDescriptors(o)})}get captureReference(){return this.startReference}get captureSession(){return this.captureSessionId}adoptCapture(e,t,i){this.startReference=e,this.captureSessionId=t,this.captureSpecType=i}subflowStart(e,t){try{for(let i of this.lowFlushers)try{i()}catch(n){this.tracker.getLogger().error("Failed to flush previous low-event context",n)}this.captureSpecType=e?.explicitSpecType,this.startReference=S(),this.captureSessionId=this.tracker.getSessionId(),this.tracker.trackSubflowStarted(this.operationName,e,this.captureOptions(t),this.startReference),this.captureInputPrefills(!0)}catch(i){this.tracker.getLogger().error("Failed to start low-event capture context",i)}}capturePrefill(){this.captureInputPrefills(!1)}captureInputPrefills(e){for(let t of this.lowPrefillCapturers)try{t(e)}catch(i){this.tracker.getLogger().error("Failed to capture input prefill",i)}}trigger(e,t){this.tracker.trackSubflowTrigger(this.operationName,e,this.captureOptions(t))}customStep(e){return this.defineStep(e)}subflowStepStarted(e,t,i,n){this.captureSpecType=t?.explicitSpecType??this.captureSpecType,this.tracker.trackSubflowStepStarted(this.operationName,e,t,this.captureOptions(i),n)}subflowStepFinished(e,t,i){(!i?.subflowStartEventId||i.subflowStartEventId===this.startReference)&&(this.captureSpecType=t?.explicitSpecType??this.captureSpecType),this.tracker.trackSubflowStepFinished(this.operationName,e,t,this.captureOptions(i))}subflowStepError(e,t,i){let n=t;try{let o=this.tracker.getSdkConfig().rawErrors?i?.rawError:void 0;o!==void 0&&(n={...t,rawError:Dt(o,i?.rawErrorLimits)})}catch{}this.tracker.trackSubflowStepError(this.operationName,e,n,this.captureOptions(i))}withWindowLowEvents(e,t){let i,n=s=>{s?.subflowStartEventId&&s.subflowStartEventId!==i||t.scheduleDisarm(pr)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??Ct(this.operationName,l);t.arm(p,l==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),n(a)},error:(s,a)=>{o.error(s,a),n(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),n(a)}}}defineStep(e,t){let i,n,o,s=l=>this.captureOptions(l,i,n,o);return{start:(l,p)=>{i=this.startReference,n=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,l,s(p),t)},finished:(l,p)=>{this.subflowStepFinished(e,l,s(p))},error:(l,p)=>{this.subflowStepError(e,{error:U(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function _t(r,e){if(e.explicitSpecType!==void 0)try{r.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var le=class extends g{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:_t(e,t)})}},de=class extends g{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:_t(e,t)})}};function ur(r){try{return decodeURIComponent(r.replace(/\+/g," "))}catch{return r}}function cr(r,e){let t=r.toLowerCase();return e.some(i=>{let n=i.toLowerCase();return n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n})}function At(r,e,t){return e!=="allowlist"||r===""||r==="?"?r:`?${(r.startsWith("?")?r.slice(1):r).split("&").map(o=>{let s=o.indexOf("=");if(s===-1)return o;let a=o.slice(0,s);return o.slice(s+1)===""||cr(ur(a),t)?o:`${a}=*`}).join("&")}`}function x(r,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function W(r){return document.visibilityState==="hidden"}function Mt(r){return document.readyState==="complete"}function Ht(r){return window.location.href}function Bt(r,e,t){let i=At(window.location.search,e,t);return`${window.location.pathname}${i}`}function pe(r){return typeof navigator>"u"?"":navigator.userAgent??""}async function Nt(r){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function Ut(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function qt(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function Vt(r){if(typeof PublicKeyCredential>"u"||!PublicKeyCredential.getClientCapabilities)return;let e=await PublicKeyCredential.getClientCapabilities();return Object.fromEntries(Object.entries(e).map(([t,i])=>[t,i.toString()]))}async function Kt(r){if(typeof navigator>"u"||!navigator.userAgentData)return;let e=await navigator.userAgentData.getHighEntropyValues(["platformVersion","model"]),t=e.platform,i=e.mobile,n=e.platformVersion,o=e.model||void 0;if(!(!t||i===void 0||!n))return{platform:t,mobile:i,platformVersion:n,model:o}}function Wt(r){if(!(typeof navigator>"u"))return navigator.webdriver}function Gt(r){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}var rt=(r,e,t)=>{let i=!1,n,o=null,s=null,a=()=>{s!==null&&(clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&r({...n===void 0?{}:{captureSeq:n},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),n=p}s!==null&&clearTimeout(s),s=setTimeout(a,150)},flush:a}};function $t(r,e,t){let i=[],n=(s,a,l)=>{let p=d=>t(a,()=>l(d));s.addEventListener(a,p),i.push(()=>s.removeEventListener(a,p))};n(window,"blur",()=>e.blur()),n(window,"focus",()=>e.focus()),n(document,"visibilitychange",()=>e.visibilityChange(document.visibilityState==="hidden")),n(document,"focusout",s=>e.focusOut(s.target,!!s.relatedTarget)),n(document,"focusin",s=>e.focusIn(()=>s.composedPath())),n(document,"pointerdown",s=>e.pointerDown(s.target)),window.visualViewport&&(n(window.visualViewport,"resize",()=>e.viewportResize()),n(window.visualViewport,"scroll",()=>e.viewportScroll())),n(window,"pagehide",()=>e.pageHide());let o=window.navigation;return o&&n(o,"currententrychange",s=>{let a=s,l=a.from?.index,p=o.currentEntry?.index;a.navigationType==="traverse"&&typeof l=="number"&&typeof p=="number"&&l>=0&&p>=0&&p<l&&e.navigateBack()}),i}function Qt(r){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function jt(r){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var fr,ie=()=>fr??=S(),ue=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=$t(0,{blur:()=>{this.flushInputs(),this.bracket=this.context(),this.emit({lowType:"window-blur",ts:Date.now()},this.bracket)},focus:()=>{this.flushInputs(),this.emit({lowType:"window-focus",ts:Date.now()},this.bracket??this.context()),this.bracket=void 0},visibilityChange:n=>{this.flushInputs(),this.emit({lowType:`document-visibilitychange-${n?"hidden":"visible"}`,ts:Date.now()})},focusOut:(n,o)=>{let s=this.findInput(n);this.lastBlur=s&&!o&&Date.now()-this.unrelatedPointerAt>250?{registration:s,ts:Date.now()}:void 0},focusIn:n=>{this.lastBlur=void 0;let o=this.inputFocusListeners.size>0&&n().find(s=>this.findInput(s));o&&this.notifyInputFocus(o)},pointerDown:n=>{this.findInput(n)?this.unrelatedPointerAt=-1/0:(this.lastBlur=void 0,this.unrelatedPointerAt=Date.now())},viewportResize:()=>this.extendViewport("resize"),viewportScroll:()=>this.extendViewport("scroll"),pageHide:()=>{this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.flushKeepalive()},navigateBack:()=>{this.flushInputs(),this.emit({lowType:"window-navigate-back",ts:Date.now()})}},(n,o)=>{try{o()}catch(s){this.logger.error(`Failed to observe window ${n}`,s)}}))}inputs=new Set;inputFocusListeners=new Set;ceremonies=new Set;removers=[];lastBlur;bracket;unrelatedPointerAt=-1/0;destroyed=!1;viewportContext={};resize=rt(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",O);scroll=rt(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",O);registerInputs(e,t,i){if(this.destroyed)return()=>{};let n={fields:e,context:t,flush:i};if(this.inputs.add(n),this.inputFocusListeners.size>0&&typeof document<"u"){let o=Qt(0),s=e.find(a=>o.includes(a));s&&this.notifyInputFocus(s)}return()=>{this.inputs.delete(n),this.lastBlur?.registration===n&&(this.lastBlur=void 0)}}beginCeremony(e){let t={context:e,settled:!1};this.destroyed||(this.flushInputs(),this.ceremonies.add(t));let i=()=>{t.timer&&clearTimeout(t.timer),this.ceremonies.delete(t),this.bracket===t.context&&(this.bracket=void 0)};return{settle:n=>{t.settled=!0,t.timer&&clearTimeout(t.timer),t.timer=setTimeout(i,n)},destroy:i}}onInputFocus(e){return this.destroyed?()=>{}:(this.inputFocusListeners.add(e),()=>this.inputFocusListeners.delete(e))}notifyInputFocus(e){for(let t of this.inputFocusListeners)try{t(e)}catch(i){this.logger.error("Failed to notify registered input focus",i)}}context(){let e=[...this.ceremonies].filter(o=>!o.settled);if(e.length===1)return e[0].context;if(e.length>1)return;let t=jt(0),i=this.findInput(t.active);if(i)return i.context();let n=this.lastBlur;if(n&&Date.now()-n.ts<=250&&t.idle)return n.registration.context()}findInput(e){return[...this.inputs].find(t=>t.fields.some(i=>i===e))}flushInputs(){for(let e of this.inputs)try{e.flush()}catch(t){this.logger.error("Failed to flush window input context",t)}}emit(e,t){if(this.destroyed)return;let{sessionId:i,...n}=t??{};this.enqueue({...e,...n,captureSeq:e.captureSeq??O(),sourceKind:"window",captureVersion:1,pageId:ie()},i)}extendViewport(e){let t=this.context(),i=this.viewportContext[e];(i?.subflowStartEventId!==t?.subflowStartEventId||i?.fieldRole!==t?.fieldRole||i?.sessionId!==t?.sessionId)&&this[e].flush(),this.viewportContext[e]=t,this[e].extend()}destroy(){if(!this.destroyed){this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.destroyed=!0;for(let e of this.removers)e();for(let e of this.ceremonies)e.timer&&clearTimeout(e.timer);this.ceremonies.clear(),this.inputs.clear(),this.inputFocusListeners.clear()}}};var nt="cbo_sdk_config",Yt="cbo_sdk_config_cache",Xt="X-Corbado-Observe-Config";var I={flushIntervalMs:{min:100,max:6e4},retryMaxAttempts:{min:1,max:10},retryDelayMs:{min:50,max:12e4},sessionInactivityMs:{min:6e4,max:864e5},seqLockTimeoutMs:{min:0,max:250},deviceInfoCollectorTimeoutMs:{min:10,max:1e4},flushOnFlowTypeFinished:{maxEntries:20,maxNameLength:100},sourcePathQueryAllow:{maxEntries:50,maxKeyLength:64}},hr=1800*1e3,b={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:hr,seqLockTimeoutMs:50,tvc:!0,tph:!0,td:!0,tlf:!0,telemetry:!0,flushOnTelemetry:!1,flushOnFlowTypeFinished:[],deviceInfoCollectorTimeoutMs:1e3,deviceInfoTiming:!1,rawErrors:!0,pmd:!0,retry:{maxAttempts:1,baseDelayMs:0,maxDelayMs:0},aap:"",sourcePathQuery:"allowlist",sourcePathQueryAllow:[]};function M(r,e,t){return Math.min(Math.max(r,e),t)}function H(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function R(r,e){return typeof r=="boolean"?r:e}function zt(r,e){return typeof r=="string"?r:e}function gr(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0&&e.length<=I.flushOnFlowTypeFinished.maxNameLength).slice(0,I.flushOnFlowTypeFinished.maxEntries):[]}function mr(r){return typeof r=="string"&&r.trim().toLowerCase()==="all"?"all":"allowlist"}function yr(r){return Array.isArray(r)?r.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=I.sourcePathQueryAllow.maxKeyLength).slice(0,I.sourcePathQueryAllow.maxEntries):[]}function G(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.version!="string"||e.version===""?null:Jt(e)}function Jt(r){let e=r.retry&&typeof r.retry=="object"?r.retry:{},t=M(H(e.baseDelayMs,b.retry.baseDelayMs),I.retryDelayMs.min,I.retryDelayMs.max);return{version:zt(r.version,""),flushIntervalMs:M(H(r.flushIntervalMs,b.flushIntervalMs),I.flushIntervalMs.min,I.flushIntervalMs.max),durableOutbox:r.durableOutbox===!0,durableLowOutbox:r.durableLowOutbox===!0,beaconKeepalive:r.beaconKeepalive===!0,sessionContinuity:r.sessionContinuity===!0,sessionInactivityMs:M(H(r.sessionInactivityMs,b.sessionInactivityMs),I.sessionInactivityMs.min,I.sessionInactivityMs.max),seqLockTimeoutMs:M(H(r.seqLockTimeoutMs,b.seqLockTimeoutMs),I.seqLockTimeoutMs.min,I.seqLockTimeoutMs.max),tvc:R(r.tvc,b.tvc),tph:R(r.tph,b.tph),td:R(r.td,b.td),tlf:R(r.tlf,b.tlf),telemetry:R(r.telemetry,b.telemetry),flushOnTelemetry:r.flushOnTelemetry===!0,flushOnFlowTypeFinished:gr(r.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:M(H(r.deviceInfoCollectorTimeoutMs,b.deviceInfoCollectorTimeoutMs),I.deviceInfoCollectorTimeoutMs.min,I.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:r.deviceInfoTiming===!0,rawErrors:R(r.rawErrors,b.rawErrors),pmd:R(r.pmd,b.pmd),aap:zt(r.aap,""),sourcePathQuery:mr(r.sourcePathQuery),sourcePathQueryAllow:yr(r.sourcePathQueryAllow),retry:{maxAttempts:M(H(e.maxAttempts,b.retry.maxAttempts),I.retryMaxAttempts.min,I.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:M(H(e.maxDelayMs,b.retry.maxDelayMs),t,I.retryDelayMs.max)}}}function ot(r,e={}){let t=r??b,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),n=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=Jt({...t,...i,retry:{...t.retry,...n}});return o.retry={...t.retry,...Object.fromEntries(Object.keys(n).map(s=>[s,o.retry[s]]))},o.retry.maxDelayMs=Math.max(o.retry.baseDelayMs,o.retry.maxDelayMs),o}function Zt(r){try{if(!r||typeof r!="object")return;let e=r,t=e.pmd,i=typeof t=="boolean";return{pmd:i?t:!1,pmdExplicit:i,privateMode:R(e.privateMode,!0)}}catch{return}}function ce(r){let e=r.getItem(Yt),t=e&&typeof e=="object"?G(e.config):null;return t?{...e,config:t}:null}function ei(r){return ce(r)?.config??G(r.getItem(nt))}function ti(r,e){r.setItem(Yt,e)}function fe(r,e,t){return fetch(e,t)}function ii(r){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var vr=6e4,Sr=6e4,he=class{constructor(e){this.options=e}async send(e,t){try{e.meta={...e.meta,sent:Date.now(),transport:"fetch"};let i=JSON.stringify(e),n=typeof AbortController<"u"?new AbortController:void 0,o=n?setTimeout(()=>n.abort(),Sr):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=vr,...n?{signal:n.signal}:{}},a=await fe(0,this.options.url,s),l={statusCode:a.status,headers:{"retry-after":a.headers.get("Retry-After")}};if(a.headers.get("X-Corbado-Observe-Accepted")==="1"&&(l.deliveryAccepted=!0),a.status===200)try{let p=G(await a.json());p&&(l.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return l}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{this.options.logger.debug(`Sending ${e.events.length} events via beacon`);let t=ii(0);if(!t)return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let i=new Blob([JSON.stringify(e)],{type:"text/plain"});return t(this.options.url,i)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};function ge(r,e,t,i={}){let n=typeof navigator<"u"?navigator.locks:void 0;if(n?.request){let o=i.timeoutMs,s=o!==void 0&&typeof AbortController<"u"?new AbortController:null;if(o!==void 0&&!s)return Promise.resolve().then(t);try{let a=!1,l,p=()=>{l!==void 0&&(clearTimeout(l),l=void 0)},d=()=>(a=!0,p(),t()),u=s?n.request(e,{signal:s.signal},d):n.request(e,d);return s&&o!==void 0&&!a&&(l=setTimeout(()=>{l=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),u.catch(f=>{if(a)throw f;return t()}).finally(p)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function ri(r){return typeof navigator<"u"&&!!navigator.locks?.request}var br="cbo_outbox",st="cbo_outbox",wr=500,Tr=512*1024;function Er(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.id=="string"&&e.id!==""&&typeof e.sessionId=="string"&&typeof e.flushAfter=="number"&&Number.isFinite(e.flushAfter)&&typeof e.attempts=="number"&&Number.isFinite(e.attempts)&&typeof e.event=="object"&&e.event!==null}var $=class{constructor(e,t,i=wr,n=Tr,o=st,s=br){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=n;this.lockName=o;this.storageKey=s;this.entries=this.read()}entries=[];reportedMalformed=!1;read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(Er);return t.length<e.length&&!this.reportedMalformed&&(this.reportedMalformed=!0,this.logger.error(`EventStore dropped ${e.length-t.length} malformed outbox entries`),this.logger.reportTelemetry?.("error","event store dropped malformed outbox entries")),t}mutate(e){return ge(0,this.lockName,()=>{try{let t=e(this.read());if(t.length>this.maxEntries){let i=t.length-this.maxEntries;t=t.slice(t.length-this.maxEntries),this.logger.error(`EventStore evicted ${i} oldest entries (cap ${this.maxEntries})`),this.logger.reportTelemetry?.("error","event store evicted entries (cap)")}t=this.enforceSizeBudget(t),this.entries=t,this.storage.setItem(this.storageKey,t)}catch(t){this.logger.error("Failed to mutate event store",t),this.logger.reportTelemetry?.("error","failed to mutate event store")}})}enforceSizeBudget(e){let t=e.map(o=>JSON.stringify(o).length),i=t.reduce((o,s)=>o+s,e.length+1),n=0;for(;i>this.maxSerializedLength&&n<e.length;)i-=t[n]+1,n++;return n===0?e:(this.logger.error(`EventStore evicted ${n} oldest entries (size budget ${this.maxSerializedLength})`),this.logger.reportTelemetry?.("error","event store evicted entries (size budget)"),e.slice(n))}add(e){return this.mutate(t=>t.some(i=>i.id===e.id)?t:[...t,e])}all(){return this.entries=this.read(),this.entries}getDue(e){return this.all().filter(t=>t.flushAfter<=e)}remove(e){if(e.length===0)return Promise.resolve();let t=new Set(e);return this.mutate(i=>i.filter(n=>!t.has(n.id)))}update(e){if(e.length===0)return Promise.resolve();let t=new Map(e.map(i=>[i.id,i]));return this.mutate(i=>i.map(n=>t.get(n.id)??n))}size(){return this.all().length}};var Ir=500,kr=512*1024,ni=200,oi=200*1024,xr=16*1024,si=6e4,at=32e3;function me(r){let e=0;for(let t=0;t<r.length;t++){let i=r.charCodeAt(t);i<128?e+=1:i<2048?e+=2:i>=55296&&i<=56319&&t+1<r.length?(e+=4,t++):e+=3}return e}var ye=class{constructor(e,t,i,n,o={},s){this.logger=e;this.transport=t;this.sessionId=i;this.sdk=n;this.storage=s;if(this.batchSize=o.batchSize||50,this.flushIntervalOverride=o.flushInterval,this.debug=o.debug??!1,this.requestConfig=o.requestConfig??!0,this.onConfigReceived=o.onConfigReceived,this.getDataPolicy=o.getDataPolicy,this.fixedData=o.fixedData===!0,this.beforeEventBatchSend=o.beforeEventBatchSend,this.standaloneDeviceInfo=o.standaloneDeviceInfo,this.config=o.config??b,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new $(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new $(this.storage,this.logger,1e3,256*1024,`${this.outboxLockName??"cbo_outbox"}:lows`,"cbo_low_outbox_v1");let a=this.lowStore.all();this.lowPending=a.filter(l=>this.validPendingLow(l)),this.lowStore.remove(a.filter(l=>!this.validPendingLow(l)).map(l=>l.id))}this.setupLifecycleHooks(),(this.pending.length>0||this.lowPending.length>0)&&(this.dirtySinceSyncFlush=!0,this.scheduleFlush(0,"recovery"))}pending=[];lowsQueue=[];lowPending=[];lowStore;telemetryQueue=[];probeQueue=[];probeBytes=0;probesDropped=0;timer=null;isFlushing=!1;flushingDone;destroyed=!1;dirtySinceSyncFlush=!1;onVisibilityChange=null;onPageHide=null;removeVisibilityChange=null;removePageHide=null;batchSize;flushIntervalOverride;debug;requestConfig;onConfigReceived;getDataPolicy;fixedData;beforeEventBatchSend;standaloneDeviceInfo;config;priorityFlowTypes;outboxLockName;store;configResolved=!1;setSessionId(e){this.sessionId=e}flushInterval(){return this.flushIntervalOverride??this.config.flushIntervalMs}enqueue(e,t=this.sessionId){try{let i={id:e.id,sessionId:t,flushAfter:0,attempts:0,event:e};this.pending.push(i),this.store?.add(i),this.scheduleAfterEnqueue(e)}catch(i){this.logger.error("Failed to enqueue event",i)}}enqueueLow(e,t=this.sessionId){try{let i={...e,id:e.id??S()};if(this.config.durableLowOutbox){let n={id:i.id,sessionId:t,event:i,attempts:0,flushAfter:0};this.lowPending.push(n),this.lowPending=this.lowPending.slice(-1e3),this.lowStore?.add(n)}else this.lowsQueue.push({sessionId:t,event:i});this.scheduleAfterEnqueue()}catch(i){this.logger.error("Failed to enqueue low event",i)}}notifyDeviceInfo(){try{this.dirtySinceSyncFlush=!0,this.scheduleFlush(this.flushInterval(),"timer")}catch(e){this.logger.error("Failed to schedule device info flush",e)}}enqueueTelemetry(e){try{if(!this.config.telemetry)return;this.telemetryQueue.push(e),this.dirtySinceSyncFlush=!0,this.config.flushOnTelemetry&&this.flush("telemetry")}catch(t){this.logger.error("Failed to enqueue telemetry",t)}}enqueueProbe(e,t=this.sessionId){try{if(this.destroyed)return;let i=JSON.stringify(e.payload);if(typeof i!="string"||me(i)>xr){this.probesDropped++;return}let n={...e,payload:JSON.parse(i)},o=me(JSON.stringify(n));for(this.probeQueue.push({sessionId:t,entry:n,bytes:o,attempts:0,flushAfter:0}),this.probeBytes+=o;this.probeQueue.length>Ir||this.probeBytes>kr&&this.probeQueue.length>1;){let s=this.probeQueue.shift();this.probeBytes-=s.bytes,this.probesDropped++}this.scheduleFlush(this.flushInterval(),"timer")}catch(i){this.logger.error("Failed to enqueue probe",i)}}droppedProbeCount(){return this.probesDropped}dueProbes(e){return this.probeQueue.filter(t=>t.flushAfter<=e)}selectProbes(e,t,i,n){let o=[],s=0;for(let a of e){if(o.length>=i)break;if(a.sessionId===t){if(s+a.bytes>n){o.length===0&&n>=oi&&o.push(a);break}s+=a.bytes,o.push(a)}}return o}removeProbes(e){if(e.length===0)return;let t=new Set(e);this.probeQueue=this.probeQueue.filter(i=>!t.has(i));for(let i of e)this.probeBytes-=i.bytes}dropProbes(e){this.removeProbes(e),this.probesDropped+=e.length}handleProbeSendResult(e,t,i){if(t.length===0)return;let n=e.statusCode;if(typeof n=="number"&&n>=200&&n<300){this.removeProbes(t);return}if(!this.isRetryable(n)){this.dropProbes(t);return}let o=Math.max(1,this.config.retry.maxAttempts),s=this.parseRetryAfter(e),a=[];for(let l of t)l.attempts+=1,l.attempts>=o?a.push(l):l.flushAfter=i+this.backoffForAttempt(l.attempts,s);this.dropProbes(a)}sendUnloadProbes(e,t,i,n){let o=this.sessionId,s={sessionId:o,events:[],sdk:this.sdk,probes:[]};this.attachBatchMeta(s,[],t);let a=me(JSON.stringify(s))+120,l=e>a?this.selectProbes(this.probeQueue,o,ni,e-a):[];l.length>0&&(s.probes=l.map(p=>p.entry),this.attachBatchMeta(s,l,t),n&&this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(s):Promise.resolve(this.transport.send(s)).catch(()=>{}),this.removeProbes(l)),i&&this.dropProbes(this.probeQueue.slice())}scheduleAfterEnqueue(e){if(this.dirtySinceSyncFlush=!0,e!==void 0&&this.isPriorityEvent(e)){this.flush("flow-finished");return}this.scheduleFlush(this.flushInterval(),"timer")}isPriorityEvent(e){if(e.type!=="predefined"||e.name!=="flow_finished"&&e.name!=="flow_auto_finished")return!1;let t=e.data?.flowName;return typeof t=="string"&&this.priorityFlowTypes.has(t)}scheduleFlush(e,t){this.destroyed||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush(t)},e))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(e="timer"){if(this.destroyed)return;if(this.isFlushing){if(e==="destroy"){await this.flushingDone;try{this.sendUnloadProbes(at,e,!0,!1)}catch(i){this.logger.error("Unexpected error in queue flush",i)}}return}this.isFlushing=!0;let t;this.flushingDone=new Promise(i=>{t=i});try{for(this.clearTimer();;){let i=Date.now(),n=this.getDuePending(i),o=this.lowPending.filter(w=>w.flushAfter<=i),s=e==="destroy"?[]:this.dueProbes(i),a=n.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0&&s.length===0;if(a&&!this.hasStandaloneDeviceInfo())break;let l=n[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??s[0]?.sessionId??this.sessionId,p=n.filter(w=>w.sessionId===l).slice(0,this.batchSize),d=o.filter(w=>w.sessionId===l).slice(0,100),u=[...d.map(w=>w.event),...this.takeLows(l,100-d.length)];this.prepareEvents(p,e);let f=l===this.sessionId?this.takeTelemetry():[],h=l===this.sessionId?this.takeStandaloneDeviceInfo():void 0,m=this.selectProbes(s,l,ni,oi),c={sessionId:l,events:p.map(w=>w.event),sdk:this.sdk};if(u.length>0&&(c.lows=u),f.length>0&&(c.telemetry=f),m.length>0&&(c.probes=m.map(w=>w.entry)),h&&(c.deviceInfo=h),a&&!h)break;this.attachBatchMeta(c,[...p,...d,...m],e),d.length&&(c.deliveryAck=!0);let v=this.shouldRequestConfig()?{[Xt]:this.config.version||"1"}:void 0,y=await this.transport.send(c,v).catch(w=>(this.logger.error("Unexpected error in queue flush",w),{}));if(c.deliveryAck&&y.statusCode&&y.statusCode>=200&&y.statusCode<300&&!y.deliveryAccepted&&(y={...y,statusCode:503}),this.requestConfig&&this.handleConfigResponse(y),this.handleLowSendResult(y,d,i),this.handleProbeSendResult(y,m,i),!this.handleSendResult(y,p,i))break}e==="destroy"&&this.sendUnloadProbes(at,e,!0,!1)}catch(i){this.logger.error("Unexpected error in queue flush",i)}finally{this.isFlushing=!1,t(),this.flushingDone=void 0,this.rescheduleIfPending()}}attachBatchMeta(e,t,i){e.meta={...e.meta,flushReason:i};let n=this.readDataPolicy();n!==void 0&&(e.meta={...e.meta,dataPolicy:n}),this.config.version&&(e.meta={...e.meta,configVersion:this.config.version}),this.fixedData&&(e.meta={...e.meta,fixedData:!0});let o=t.reduce((s,a)=>Math.max(s,a.attempts),0);o>0&&(e.meta={...e.meta,retryCount:o})}prepareEvents(e,t){if(!(!this.beforeEventBatchSend||e.length===0))try{this.beforeEventBatchSend(e.map(i=>i.event),t)}catch(i){this.logger.error("Failed to prepare events for sending",i)}}readDataPolicy(){try{return this.getDataPolicy?.()}catch(e){this.logger.debug("Failed to read data policy for batch meta",e);return}}getDuePending(e){return this.pending.filter(t=>t.flushAfter<=e)}takeLows(e=this.sessionId,t=100){let i=this.lowsQueue.filter(o=>o.sessionId===e).slice(0,t),n=new Set(i);return this.lowsQueue=this.lowsQueue.filter(o=>!n.has(o)),i.map(o=>o.event)}validPendingLow(e){return typeof e.event?.lowType=="string"&&e.event.id===e.id&&Number.isFinite(e.event.ts)&&e.event.ts>Date.now()-7*864e5}removeLowEntries(e){let t=new Set(e);this.lowPending=this.lowPending.filter(i=>!t.has(i.id)),this.lowStore?.remove(e)}handleLowSendResult(e,t,i){let n=e.statusCode;if(n!==void 0&&n>=200&&n<300){e.deliveryAccepted?this.removeLowEntries(t.map(o=>o.id)):this.deferLowEntries(t,i);return}if(!this.isRetryable(n)){this.removeLowEntries(t.map(o=>o.id)),this.logger.reportTelemetry?.("error","low events rejected by ingestion");return}this.deferLowEntries(t,i,this.parseRetryAfter(e))}deferLowEntries(e,t,i=null){let n=[];for(let o of e){if(!this.validPendingLow(o)){n.push(o.id);continue}o.attempts=Math.min(o.attempts+1,16),o.flushAfter=t+Math.max(Math.min(6e4,1e3*2**Math.min(o.attempts,6)),this.backoffForAttempt(o.attempts,i))}this.removeLowEntries(n),this.lowStore?.update(e.filter(o=>!n.includes(o.id)))}hasStandaloneDeviceInfo(){try{return this.standaloneDeviceInfo?.has()??!1}catch(e){return this.logger.error("Failed to read device info for batch",e),!1}}takeStandaloneDeviceInfo(){try{return this.standaloneDeviceInfo?.take()}catch(e){this.logger.error("Failed to read device info for batch",e);return}}takeTelemetry(){let e=this.telemetryQueue;return this.telemetryQueue=[],e}shouldRequestConfig(){return this.requestConfig&&!this.configResolved}handleConfigResponse(e){let t=e.statusCode;typeof t=="number"&&t>=200&&t<300&&(this.configResolved=!0),e.config&&(this.config.version||this.updateConfig(e.config),this.onConfigReceived?.(e.config))}updateConfig(e){if(this.destroyed)return;let t=this.config.flushIntervalMs!==e.flushIntervalMs;if(this.config={...e,durableOutbox:this.config.durableOutbox||e.durableOutbox},this.priorityFlowTypes=new Set(e.flushOnFlowTypeFinished),e.durableLowOutbox&&this.lowsQueue.length){let n=this.lowsQueue;this.lowsQueue=[];for(let{event:o,sessionId:s}of n)this.enqueueLow(o,s)}let i=!1;if(this.config.durableOutbox&&this.storage&&!this.store){this.store=new $(this.storage,this.logger,void 0,void 0,this.outboxLockName);let n=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!n.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let n=e.statusCode,o=typeof n=="number"&&n>=200&&n<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(d=>d.id)),!0;if(!this.isRetryable(n))return this.removeEntries(t.map(d=>d.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],p=[];for(let d of t)d.attempts+=1,d.attempts>=s?l.push(d.id):(d.flushAfter=i+this.backoffForAttempt(d.attempts,a),p.push(d));return this.removeEntries(l),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,n=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(n=Math.min(n,i.maxDelayMs));let o=Math.round(n/2+Math.random()*(n/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer||this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0&&this.probeQueue.length===0)return;let e=Date.now();if(this.getDuePending(e).length>0||this.lowPending.some(i=>i.flushAfter<=e)||this.lowsQueue.length>0||this.probeQueue.some(i=>i.flushAfter<=e)){this.scheduleFlush(this.flushInterval(),"timer");return}let t=Math.min(...[...this.pending,...this.lowPending,...this.probeQueue].map(i=>i.flushAfter));this.scheduleFlush(Math.max(0,t-e),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{this.writeLifecycleDebugOutput("cbo_visibility_change_debug"),W(0)&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.writeLifecycleDebugOutput("cbo_pagehide_debug"),this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.removeVisibilityChange=x(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=x(0,"pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:Ht(0)};this.storage.setItem(e,t)}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){let t=this.flushSyncEvents(e);e==="pagehide"&&this.probeQueue.length>0&&this.sendUnloadProbes(Math.min(si-t,at),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(d=>d.sessionId===t),n=i.slice(0,this.batchSize),o=this.lowPending.filter(d=>d.sessionId===t).slice(0,100),s=[...o.map(d=>d.event),...this.takeLows(t,100-o.length)];this.prepareEvents(n,e);let a=this.takeTelemetry(),l=this.takeStandaloneDeviceInfo();if(n.length===0&&s.length===0&&a.length===0&&!l)return this.dirtySinceSyncFlush=!1,0;let p={sessionId:t,events:n.map(d=>d.event),sdk:this.sdk};return s.length>0&&(p.lows=s),a.length>0&&(p.telemetry=a),l&&(p.deviceInfo=l),this.attachBatchMeta(p,[...n,...o],e),o.length&&(p.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(p)||this.transport.send(p):this.transport.send(p),this.config.durableOutbox||this.removeEntries(n.map(d=>d.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>n.length,this.approximateSize(p)}approximateSize(e){try{return me(JSON.stringify(e))}catch{return si}}destroy(){try{this.destroyed=!0,this.clearTimer(),this.dropProbes(this.probeQueue.slice()),typeof window<"u"&&(this.removeVisibilityChange&&this.removeVisibilityChange(),this.removePageHide&&this.removePageHide())}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};var lt={d:(r,e)=>{for(var t in e)lt.o(e,t)&&!lt.o(r,t)&&Object.defineProperty(r,t,{enumerable:!0,get:e[t]})},o:(r,e)=>Object.prototype.hasOwnProperty.call(r,e)},dt={};lt.d(dt,{A:()=>Cr,k:()=>ai});var Q=function(r,e,t,i){return new(t||(t=Promise))(function(n,o){function s(p){try{l(i.next(p))}catch(d){o(d)}}function a(p){try{l(i.throw(p))}catch(d){o(d)}}function l(p){var d;p.done?n(p.value):(d=p.value,d instanceof t?d:new t(function(u){u(d)})).then(s,a)}l((i=i.apply(r,e||[])).next())})},j=function(r,e){var t,i,n,o,s={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(p){return(function(d){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,d[0]&&(s=0)),s;)try{if(t=1,i&&(n=2&d[0]?i.return:d[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,d[1])).done)return n;switch(i=0,n&&(d=[2&d[0],n.value]),d[0]){case 0:case 1:n=d;break;case 4:return s.label++,{value:d[1],done:!1};case 5:s.label++,i=d[1],d=[0];continue;case 7:d=s.ops.pop(),s.trys.pop();continue;default:if(n=s.trys,!((n=n.length>0&&n[n.length-1])||d[0]!==6&&d[0]!==2)){s=0;continue}if(d[0]===3&&(!n||d[1]>n[0]&&d[1]<n[3])){s.label=d[1];break}if(d[0]===6&&s.label<n[1]){s.label=n[1],n=d;break}if(n&&s.label<n[2]){s.label=n[2],s.ops.push(d);break}n[2]&&s.ops.pop(),s.trys.pop();continue}d=e.call(r,s)}catch(u){d=[6,u],i=0}finally{t=n=0}if(5&d[0])throw d[1];return{value:d[0]?d[1]:void 0,done:!0}})([l,p])}}};function ai(){return Q(this,void 0,Promise,function(){return j(this,function(r){switch(r.label){case 0:return[4,new Promise(function(e,t){var i="Unknown",n=!1;function o(d){n||(n=!0,e({isPrivate:d,browserName:i}))}function s(){var d=0,u=parseInt("-1");try{u.toFixed(u)}catch(f){d=f.message.length}return d}function a(){return Q(this,void 0,void 0,function(){var d,u;return j(this,function(f){switch(f.label){case 0:return f.trys.push([0,2,,3]),[4,navigator.storage.getDirectory()];case 1:return f.sent(),o(!1),[3,3];case 2:return d=f.sent(),u=d instanceof Error&&typeof d.message=="string"?d.message:String(d),o(u.includes("unknown transient reason")),[3,3];case 3:return[2]}})})}function l(){var d;return Q(this,void 0,Promise,function(){return j(this,function(u){switch(u.label){case 0:return typeof((d=navigator.storage)===null||d===void 0?void 0:d.getDirectory)!="function"?[3,2]:[4,a()];case 1:return u.sent(),[3,3];case 2:navigator.maxTouchPoints!==void 0?(function(){var f=String(Math.random());try{var h=indexedDB.open(f,1);h.onupgradeneeded=function(m){var c=m.target.result,v=function(y){o(y)};try{c.createObjectStore("t",{autoIncrement:!0}).put(new Blob),v(!1)}catch(y){(y instanceof Error&&typeof y.message=="string"?y.message:String(y)).includes("are not yet supported")?v(!0):v(!1)}finally{c.close(),indexedDB.deleteDatabase(f)}},h.onerror=function(){return o(!1)}}catch{o(!1)}})():(function(){var f=window.openDatabase,h=window.localStorage;try{f(null,null,null,null)}catch{return void o(!0)}try{h.setItem("test","1"),h.removeItem("test")}catch{return void o(!0)}o(!1)})(),u.label=3;case 3:return[2]}})})}function p(){var d;return Q(this,void 0,Promise,function(){var u,f,h;return j(this,function(m){switch(m.label){case 0:if(typeof((d=navigator.storage)===null||d===void 0?void 0:d.getDirectory)!="function")return[3,5];m.label=1;case 1:return m.trys.push([1,3,,4]),[4,navigator.storage.getDirectory()];case 2:return m.sent(),o(!1),[3,4];case 3:return u=m.sent(),f=u instanceof Error&&typeof u.message=="string"?u.message:String(u),o(f.includes("Security error")),[2];case 4:return[3,6];case 5:(h=indexedDB.open("inPrivate")).onerror=function(c){if(h.error&&h.error.name==="InvalidStateError")return c.preventDefault(),void o(!0);o(!1)},h.onsuccess=function(){indexedDB.deleteDatabase("inPrivate"),o(!1)},m.label=6;case 6:return[2]}})})}(function(){return Q(this,void 0,Promise,function(){return j(this,function(d){switch(d.label){case 0:return s()!==44&&s()!==43?[3,2]:(i="Safari",[4,l()]);case 1:return d.sent(),[3,6];case 2:return s()!==51?[3,3]:(u=navigator.userAgent,i=u.match(/Chrome/)?navigator.brave!==void 0?"Brave":u.match(/Edg/)?"Edge":u.match(/OPR/)?"Opera":"Chrome":"Chromium",(function(){var f=this,h="__di_"+Math.random().toString(36).slice(2),m=new Uint8Array(16384),c=indexedDB.open(h,1);c.onupgradeneeded=function(){c.result.createObjectStore("s")},c.onerror=function(){indexedDB.deleteDatabase(h),o(!1)},c.onsuccess=function(){var v=c.result,y=!1;try{var w=v.transaction("s","readwrite",{durability:"strict"});y=w.durability==="strict",w.abort()}catch{}if(!y)return v.close(),indexedDB.deleteDatabase(h),void o(!1);var T=function(J){return new Promise(function(F,Z){var ee=performance.now(),N=0,C=function(){if(N!==15){var _=v.transaction("s","readwrite",{durability:J});_.objectStore("s").put(m,N),N++,_.oncomplete=C,_.onerror=_.onabort=function(){return Z(_.error)}}else F(performance.now()-ee)};C()})};Q(f,void 0,void 0,function(){var J,F,Z,ee,N;return j(this,function(C){switch(C.label){case 0:return J=performance.now(),[4,T("relaxed")];case 1:return C.sent(),[4,T("strict")];case 2:C.sent(),F=[],Z=0,C.label=3;case 3:return Z<15?[4,T("relaxed")]:[3,7];case 4:return ee=C.sent(),[4,T("strict")];case 5:if(N=C.sent(),F.push(ee>0?N/ee:1/0),F.length>=7&&performance.now()-J>=1e3)return[3,7];C.label=6;case 6:return Z++,[3,3];case 7:return F.sort(function(_,Xi){return _-Xi}),v.close(),indexedDB.deleteDatabase(h),o(F[F.length>>1]<1.3),[2]}})}).catch(function(){v.close(),indexedDB.deleteDatabase(h),o(!1)})}})(),[3,6]);case 3:return s()!==25?[3,5]:(i="Firefox",[4,p()]);case 4:return d.sent(),[3,6];case 5:navigator.msSaveBlob!==void 0?(i="Internet Explorer",o(window.indexedDB===void 0)):t(new Error("detectIncognito cannot determine the browser")),d.label=6;case 6:return[2]}var u})})})().catch(t)})];case 1:return[2,r.sent()]}})})}var Cr=ai,li=dt.A,Mo=dt.k;async function di(r){return(await li()).isPrivate}var Or=300,re=6e3,pi="cbo_pm",Pr=10080*60*1e3,ui="detectincognitojs@1.9.0",ci={timing:!1},pt="cbo_tab_id",fi={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function P(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function hi(r,e,t){return{field:r,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function ut(r,e){let t;try{return await Promise.race([r.then(()=>!0,()=>!0),new Promise(i=>{t=setTimeout(()=>i(!1),Math.max(0,e))})])}finally{t&&clearTimeout(t)}}var ve=class{constructor(e,t,i="localstorage",n,o=()=>ci,s,a=!0){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=n;this.settings=o;this.emitTelemetry=s;this.privateModeEnabled=a}pagePrivateMode;privateModeDetectionStarted=!1;lastKnown={};async collect(e,t={}){try{let i=this.resolveSettings(),n=P(),o=this.getClientEnvHandle(),s={type:"web",clientEnvHandle:o.value,clientEnvHandleMeta:{timestamp:o.timestamp,source:o.source},tabId:this.getTabId()},a=typeof __CBO_DATA_PRIVATE_MODE__=="boolean"?__CBO_DATA_PRIVATE_MODE__:this.privateModeEnabled,l=a?this.knownPrivateMode(i.timing):void 0,p,d=a&&l===void 0&&!this.privateModeDetectionStarted?this.detectPrivateMode(i.timing).then(T=>{p=T}):void 0,u=this.startFastFields();await ut(Promise.all(u.map(T=>T.promise)),Or);let f=P()-n,h=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,u);let m=()=>p?.error?[p.error]:[];this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,m()),"fast");let c=u.filter(T=>!T.settled),v=d!==void 0&&p===void 0;if(c.length===0&&!v)return;let y=P();await Promise.all([ut(Promise.all(c.map(T=>T.promise)),re-(y-n)),d]);let w=c.filter(T=>!T.settled).map(T=>hi(T.field,T.source,re));w.push(...m()),i.timing&&c.length>0&&this.reportLateTiming(P()-n,c),this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,w),"update")}catch(i){this.logger.error("Failed to collect device info",i)}}async getInfo(){let e;return await this.collect(t=>{e=t}),e??{}}startFastFields(){return[this.startField("bluetoothAvailable","navigator.bluetooth.getAvailability",()=>Nt(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>Vt(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>Ut(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>qt(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>Kt(0)),this.startField("webdriver","navigator.webdriver",()=>Wt(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>Gt(0))]}startField(e,t,i){let n=P(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:P()-n}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:P()-n,error:{field:e,source:t,error:U(s)??{message:"Unknown error"}}})).then(s=>(o.settled=s,s)),o}buildInfo(e,t,i,n,o){let s={},a=[];for(let p of t)p.settled?(p.settled.error&&a.push(p.settled.error),s[p.field]=p.settled.value,this.remember(p.field,p.settled.value)):s[p.field]=n[p.field];s.privateMode=i,a.push(...o);let l={...e,data:{bluetoothAvailable:s.bluetoothAvailable,javaScriptHighEntropy:s.javaScriptHighEntropy,privateMode:s.privateMode,webdriver:s.webdriver,conditionalMediationAvailable:s.conditionalMediationAvailable,userVerifyingPlatformAuthenticatorAvailable:s.userVerifyingPlatformAuthenticatorAvailable,clientCapabilities:s.clientCapabilities,maxTouchPoints:s.maxTouchPoints}};return a.length>0&&(l.collectionErrors=a),l}remember(e,t){t!==void 0&&(this.lastKnown[e]=t)}safePublish(e,t,i){try{e(t,i)}catch(n){this.logger.error("Failed to publish device info",n)}}knownPrivateMode(e){if(this.pagePrivateMode!==void 0)return this.pagePrivateMode;let t=this.readPrivateModeCache();return t&&(this.pagePrivateMode=t.value,e&&this.reportTelemetry(`device info privateMode from cache, age ${Math.round((Date.now()-t.ts)/1e3)}s`)),this.pagePrivateMode}canCachePrivateMode(){return this.storageSource==="localstorage"}readPrivateModeCache(){if(this.canCachePrivateMode())try{let e=this.storage.getItem(pi);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==ui)return;let t=Date.now()-e.ts;return t<0||t>=Pr?void 0:e}catch(e){this.logger.debug("Failed to read cached privateMode",e);return}}writePrivateModeCache(e){if(this.canCachePrivateMode())try{this.storage.setItem(pi,{value:e,ts:Date.now(),dv:ui})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=P(),n=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:di(0));if(!await ut(n.promise,re)||!n.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${re}ms`),{error:hi("privateMode",t,re)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(P()-i)}ms`),n.settled.error)return{error:n.settled.error};let s=n.settled.value;return typeof s!="boolean"?{value:void 0}:(this.pagePrivateMode=s,this.writePrivateModeCache(s),{value:s})}resolveSettings(){try{return{timing:this.settings()?.timing===!0}}catch(e){return this.logger.error("Failed to resolve device info collector settings",e),ci}}reportFastTiming(e,t){let i=t.map(n=>`${fi[n.field]}=${Math.round(n.settled?.durationMs??e)}`).join(",");this.reportTelemetry(`device info collected in ${Math.round(e)}ms (${i})`)}reportLateTiming(e,t){let i=t.map(n=>`${fi[n.field]}=${n.settled?Math.round(n.settled.durationMs):"timeout"}`).join(",");this.reportTelemetry(`device info late fields done in ${Math.round(e)}ms (${i})`)}reportTelemetry(e){if(this.emitTelemetry)try{this.emitTelemetry("info",e)}catch(t){this.logger.error("Failed to report device info timing",t)}}static getOsAndBrowserInfo(){return{osName:this.getOsName(),browserName:this.getBrowserName()}}static getUserAgent(){return pe(0)}static getOsName(){let e=this.getUserAgent();return e.includes("iOS")?"iOS":e.includes("Android")?"Android":e.includes("Windows")?"Windows":e.includes("Macintosh")?"macOS":e.includes("Linux")?"Linux":e.includes("ChromeOS")?"ChromeOS":"other"}static getBrowserName(){let e=this.getUserAgent();return e.includes("Chrome")?"Chrome":e.includes("Firefox")?"Firefox":e.includes("Safari")?"Safari":e.includes("Edge")?"Edge":e.includes("Opera")?"Opera":e.includes("IE")?"IE":"other"}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle");if(e)return e;let t=S(),i={timestamp:Date.now(),source:this.storageSource,value:t};return this.storage.setItem("cbo_client_env_handle",i),i}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(pt);if(e)return e;let t=S();if(this.sessionStorage.setItem(pt,t),this.sessionStorage.getItem(pt)===t)return t}};function Lr(){return typeof document<"u"&&W(0)}var Se=class{constructor(e,t,i,n,o,s){this.logger=e;this.source=t;this.refreshInterval=i;this.attachInterval=n;this.diagnostics=o;this.onUndelivered=s}snapshot;snapshotPhase;publishedAt=0;version=0;deliveredVersion=0;refreshedAt=0;lastAttachedAt=null;eventsSeen=!1;refreshPromise;timer;destroyed=!1;start(){this.refresh()}getForEvent(){if(this.eventsSeen=!0,Date.now()-this.refreshedAt>=this.refreshInterval&&this.refresh(),!!this.snapshot){if(this.version!==this.deliveredVersion)return this.markDelivered("event");if(!(this.lastAttachedAt!==null&&Date.now()-this.lastAttachedAt<this.attachInterval))return this.lastAttachedAt=Date.now(),this.snapshot}}hasUndelivered(){return this.snapshot!==void 0&&this.version!==this.deliveredVersion}takeUndelivered(){if(this.hasUndelivered())return this.markDelivered("flush")}hasStandalone(){return this.eventsSeen&&this.hasUndelivered()}takeStandalone(){if(this.hasStandalone())return this.markDelivered("request")}destroy(){this.destroyed=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}markDelivered(e){return this.deliveredVersion=this.version,this.lastAttachedAt=Date.now(),this.snapshotPhase==="update"&&this.report(`device info update delivered via ${e} after ${Math.max(0,Date.now()-this.publishedAt)}ms`),this.snapshot}publish(e,t){if(t==="fast"&&(this.refreshedAt=Date.now()),!(this.snapshot&&JSON.stringify(this.snapshot)===JSON.stringify(e))&&(this.snapshot=e,this.snapshotPhase=t,this.publishedAt=Date.now(),this.version++,this.eventsSeen&&this.onUndelivered))try{this.onUndelivered()}catch(i){this.logger.error("Failed to announce undelivered device info",i)}}report(e){if(this.diagnostics)try{this.diagnostics.timing()&&this.diagnostics.emit("info",e)}catch(t){this.logger.error("Failed to report device info delivery",t)}}scheduleRefresh(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.refresh()},this.refreshInterval)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.snapshot&&Lr())return this.destroyed||this.scheduleRefresh(),Promise.resolve();let e=this.snapshot!==void 0;return this.refreshPromise=Promise.resolve().then(()=>this.source.collect((t,i)=>this.publish(t,i),{refresh:e})).catch(t=>this.logger.error("Failed to refresh device info",t)).finally(()=>{this.refreshPromise=void 0,this.destroyed||this.scheduleRefresh()}),this.refreshPromise}};function gi(r){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function mi(r){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function yi(r){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function L(r,e){return`${r}_${e}`}var be=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(L(e,this.namespace))}setItem(e,t){this.engine.setItem(L(e,this.namespace),t)}removeItem(e){this.engine.removeItem(L(e,this.namespace))}},we=class{constructor(e){this.logger=e}area=gi(0);getItem(e){try{if(typeof localStorage>"u")return null;let t=this.area.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`LocalStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof localStorage>"u")return;this.area.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`LocalStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`localStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof localStorage>"u")return;this.area.removeItem(e)}catch(t){this.logger.error(`LocalStorage.removeItem failed for key "${e}"`,t)}}},Te=class{constructor(e,t){this.logger=e;this.domain=t}jar=yi(0);getItem(e){try{if(typeof document>"u")return null;let t=e+"=",i=this.jar.read().split(";");for(let n=0;n<i.length;n++){let o=i[n].trim();if(o.indexOf(t)===0){let s=o.substring(t.length);return JSON.parse(decodeURIComponent(s))}}return null}catch(t){return this.logger.error(`CookieStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof document>"u")return;let i=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; SameSite=Lax`;this.domain&&(i+=`; domain=${this.domain}`),this.jar.write(i)}catch(i){this.logger.error(`CookieStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`cookie.setItem failed: ${e}`)}}removeItem(e){try{if(typeof document>"u")return;let t=`${e}=; Max-Age=-99999999; path=/`;this.domain&&(t+=`; domain=${this.domain}`),this.jar.write(t)}catch(t){this.logger.error(`CookieStorage.removeItem failed for key "${e}"`,t)}}},Ee=class{constructor(e){this.logger=e}area=mi(0);getItem(e){try{if(typeof sessionStorage>"u")return null;let t=this.area.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`SessionStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof sessionStorage>"u")return;this.area.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`SessionStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`sessionStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof sessionStorage>"u")return;this.area.removeItem(e)}catch(t){this.logger.error(`SessionStorage.removeItem failed for key "${e}"`,t)}}};var Ie=1,ke="cbo_storage_schema",Fr=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],Rr=["cbo_session_id","cbo_tab_id"],Dr=["cbo_client_env_handle"];function xe(r,e,t){return r.setItem(e,t),JSON.stringify(r.getItem(e))===JSON.stringify(t)}function ct(r,e,t){let i=r.getItem(ke);if(i!==null){if(i.version!==Ie||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(n=>r.getItem(L(n,e))!==null))return xe(r,ke,{version:Ie,projectId:e,complete:!0});if(!xe(r,ke,{version:Ie,projectId:e,complete:!1}))return!1}for(let n of t){let o=L(n,e);if(r.getItem(o)!==null)continue;let s=r.getItem(n);if(s!==null&&!xe(r,o,s))return!1}return xe(r,ke,{version:Ie,projectId:e,complete:!0})}function vi(r,e,t,i,n){try{if(!ct(e,r,Fr))return;ct(t,r,Rr),i&&ct(i,r,Dr)}catch(o){n.error("Failed to migrate legacy Observe storage",o)}}var _r=10*1e3,Ar=60*1e3,Mr=3600*1e3,Hr=300*1e3,Si=1440*60*1e3,Br=[1e3,3e3];function Nr(r){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(r?.get("Cache-Control")??"");if(!e)return Mr;let t=Number(r?.get("Age")??0),i=(Number(e[1])-(Number.isFinite(t)&&t>0?t:0))*1e3;return Math.min(Math.max(i,Hr),Si)}var Ce=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=ei(t)??void 0,this.appliedVersion=this.initialConfig?.version}initialConfig;requestTimer;retryTimer;controller;removers=[];fetching=!1;stopped=!1;lastAttemptAt;appliedVersion;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.listen(),this.refresh())}listen(){if(typeof window>"u")return;let e=()=>{typeof document>"u"||W(0)||this.refresh()};this.removers.push(x(0,"visibilitychange",e),x(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=ce(this.storage),{fetchedAt:i,expiresAt:n}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof n=="number"&&i>0&&n-i<=Si&&i<=e&&e<n){t.config.version!==this.appliedVersion&&(this.appliedVersion=t.config.version,this.onConfig?.(t.config));return}let o=this.lastAttemptAt===void 0?1/0:e-this.lastAttemptAt;if(o>=0&&o<Ar)return;this.lastAttemptAt=e,clearTimeout(this.retryTimer),this.fetchConfig()}catch(e){this.logger.error("Unexpected error in SDK config refresh",e)}}async fetchConfig(e=0){if(this.stopped||this.fetching)return;this.fetching=!0;let t=typeof AbortController<"u"?new AbortController:void 0;this.controller=t,this.requestTimer=t?setTimeout(()=>t.abort(),_r):void 0;let i=!0;try{let n=await fe(0,this.url,{method:"GET",cache:"no-cache",...t?{signal:t.signal}:{}});if(!n.ok)throw i=(n.status===408||n.status===429||n.status>=500)&&!n.headers.has("Retry-After"),new Error(`SDK config request failed (${n.status})`);let o=await n.json();i=!1;let s=G(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();ti(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+Nr(n.headers),config:s}),ce(this.storage)&&this.storage.removeItem(nt),this.appliedVersion=s.version,this.onConfig?.(s)}catch(n){if(!this.stopped){this.logger.error("Failed to fetch SDK config",n);let o=Br[e];(i&&!(n instanceof SyntaxError)||t?.signal.aborted)&&o!==void 0&&(this.retryTimer=setTimeout(()=>{this.fetchConfig(e+1)},o))}}finally{clearTimeout(this.requestTimer),this.requestTimer=void 0,this.controller=void 0,this.fetching=!1}}destroy(){this.stopped=!0,this.removers.splice(0).forEach(e=>e()),clearTimeout(this.requestTimer),clearTimeout(this.retryTimer),this.controller?.abort(),this.onConfig=void 0}};var z=class{constructor(e,t){this.logger=e;this.sink=t}lease;destroyed=!1;arm(e,t=!1){if(this.disarm(),!(this.destroyed||t))try{this.lease=this.sink.beginCeremony?.(e)}catch(i){this.logger.error("Failed to register ceremony low-event context",i)}}scheduleDisarm(e){try{this.lease?.settle(e)}catch(t){this.logger.error("Failed to settle ceremony low-event context",t)}}disarm(){try{this.lease?.destroy()}catch(e){this.logger.error("Failed to release ceremony low-event context",e)}this.lease=void 0}destroy(){this.disarm(),this.destroyed=!0}};var Oe=class extends g{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new z(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType})}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker.destroy()}};var Y=class{constructor(e,t,i,n){this.previousLength=e;this.pushLow=t;this.logger=i;this.reserveCaptureSeq=n}prefillSettled=!1;inputBatch=null;currentEffect="modify";ringEffect="modify";autofillTimestamps=[];autofillStreak=null;idleTimer=null;markInputObserved(){this.prefillSettled=!0}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect,i){let n=this.inputBatch;if(!n){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:i};return}n.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e.ts,this.ringEffect,e.captureSeq);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let n=1;n<e.length;n++){let o=e[n].ts-e[n-1].ts;if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1,n=this.reserveCaptureSeq?.()){this.markInputObserved(),this.scheduleIdle();let o=this.previousLength;this.currentEffect=e===0?"clear":o===0?"fill":"modify";let s=e-o;if(this.previousLength=e,e===0&&o>0){this.flush(),this.pushLow({...n===void 0?{}:{captureSeq:n},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,n);return}if(s>=3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...n===void 0?{}:{captureSeq:n},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(s<=-3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...n===void 0?{}:{captureSeq:n},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let a=this.autofillStreak;if(a){if(s===1&&t-a.lastTimestamp<=80){a.lastTimestamp=t;return}this.flushAutofillStreak()}if(s!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,n);return}let l=this.autofillTimestamps;if(l.length===0&&(this.ringEffect=this.currentEffect),l.push({ts:t,captureSeq:n}),l.length>5){let u=l.shift();this.extendInputBatch(u.ts,this.ringEffect,u.captureSeq),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let p=l[0],d=l[l.length-1];l.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:p.ts,captureSeq:p.captureSeq,lastTimestamp:d.ts,effect:this.ringEffect}}};var X=class{constructor(e,t,i,n,o){this.inputs=t;this.logger=i;this.changed=n;this.reserveCaptureSeq=o;for(let s of t)s.addEventListener("paste",this.onPaste,!0),s.addEventListener("beforeinput",this.onBeforeInput,!0)}before=null;timestamp=0;captureSeq;pasteEvent;timer=null;onPaste=e=>this.begin(e);onBeforeInput=e=>{e.inputType==="insertFromPaste"?this.begin(e):this.flush()};handlesInput(e){if(!this.before)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?!0:(this.clear(),!1)}get pending(){return this.before!==null}begin(e){if(!(!e.isTrusted||this.before))try{this.before=this.inputs.map(t=>t.value),this.pasteEvent=e,this.timestamp=Date.now(),this.captureSeq=this.reserveCaptureSeq?.(),this.timer=setTimeout(()=>this.flush(),0)}catch(t){this.logger.error("Failed to observe paste",t),this.clear()}}flush(){let e=this.before;if(!e)return;let t=this.timestamp,i=this.captureSeq;this.clear();try{let n=0,o=!1;this.inputs.forEach((s,a)=>{let l=e[a],p=s.value;if(l===p)return;o=!0;let d=0;for(;d<l.length&&d<p.length&&l[d]===p[d];)d++;let u=0;for(;u<l.length-d&&u<p.length-d&&l[l.length-u-1]===p[p.length-u-1];)u++;n+=p.length-d-u}),o&&this.changed(t,n,i)}catch(n){this.logger.error("Failed to finish paste observation",n)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.before=null,this.pasteEvent=void 0}destroy(){this.flush();for(let e of this.inputs)e.removeEventListener("paste",this.onPaste,!0),e.removeEventListener("beforeinput",this.onBeforeInput,!0)}};var Ur=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Pe(r,e,t,i,n=Ur){let o=[];for(let s of n){let a=qr(s,t,i);a&&o.push([s,a])}for(let[s,a]of o)e.addEventListener(s,a);return()=>{for(let[s,a]of o)e.removeEventListener(s,a)}}function qr(r,e,t){switch(r){case"focus":case"blur":{let i=e[r];return i&&(n=>t(r,()=>i(n.relatedTarget)))}case"pointerdown":case"pointerup":case"click":{let i=e[r];return i&&(()=>t(r,()=>i()))}case"input":{let i=e.input;return i&&(n=>t("input",()=>i(n.isComposing||n.inputType==="insertCompositionText",n)))}case"keyup":{let i=e.keyupEscape;return i&&(n=>t("keyup",()=>{n.key==="Escape"&&i()}))}}}function bi(r,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function wi(r,e){return e.reduce((t,i)=>t+i.value.length,0)}function Le(r,e){let t=document.activeElement;return e.find(i=>i===t)}var Vr=[{query:"com-1password-button",eventType:"pa-1"},{query:"com-1password-menu",eventType:"pa-2"},{query:"com-1password-notification",eventType:"pa-3"}],Kr="[data-lastpass-root], [data-lp], [data-lpignore], [data-lpfieldtype]",Ti="pa-4",Wr='[popover="manual"]',Gr=400,$r=20,ft="pa-5",ht="pa-6",gt=(r,e)=>{try{return Array.from(r.querySelectorAll(e))}catch{return[]}},Ei=r=>{if(r.getAttribute("popover")!=="manual")return!1;let e=r.getAttribute("style")??"";return!(e.length<Gr||!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/display:\s*block\b/i.test(e)||(e.match(/initial\s*!important/gi)?.length??0)<$r)},Qr=r=>{if(Ei(r)||r.getAttribute("popover")!=="manual")return!1;let e=r.getAttribute("style")??"";return!(!/z-index:\s*2147483647\b/i.test(e)||!/position:\s*fixed\b/i.test(e)||!/backdrop-filter:\s*[^;]*blur\(\s*20px\s*\)/i.test(e)||!/background-color:\s*rgba\(\s*35\s*,\s*35\s*,\s*35\s*,/i.test(e))},jr=r=>{r(document);for(let e of Array.from(document.querySelectorAll("*"))){let t=e.shadowRoot;t&&r(t)}},zr=()=>{let r=new Set;return typeof document>"u"||jr(e=>{for(let t of Vr)r.has(t.eventType)||gt(e,t.query).length>0&&r.add(t.eventType);if(!r.has(Ti)&>(e,Kr).length>0&&r.add(Ti),!r.has(ft)||!r.has(ht))for(let t of gt(e,Wr)){if(!r.has(ft)&&Ei(t)){r.add(ft);continue}!r.has(ht)&&Qr(t)&&r.add(ht)}}),r};function Ii(r){return zr()}var Yr=500,Xr=250;function ne(r){return bi(0,r)}var k=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new Y(ne(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new X(0,[t],e,(n,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=ne(t),this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:n,inputEffect:ne(t)===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;removeFieldListeners;removePageHide;changes;pasteObserver;emittedSignals=new Set;firstFocusHandled=!1;mountProbeTimer=null;focusProbeTimer=null;destroyed=!1;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.mountProbeTimer!==null&&(clearTimeout(this.mountProbeTimer),this.mountProbeTimer=null),this.focusProbeTimer!==null&&(clearTimeout(this.focusProbeTimer),this.focusProbeTimer=null),this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;this.removeFieldListeners=Pe(0,e,{focus:()=>this.handleFocus(),blur:()=>this.handleBlur(),pointerdown:()=>this.enqueueNonInputEvent("pointerdown"),pointerup:()=>this.enqueueNonInputEvent("pointerup"),click:()=>this.enqueueNonInputEvent("click"),input:(t,i)=>this.handleInput(i,t),keyupEscape:()=>this.enqueueNonInputEvent("keyup-escape")},(t,i)=>{try{i()}catch(n){t==="input"?this.logger.error("Failed to observe input",n):this.logger.error(`Failed to handle low event "${t}"`,n)}}),typeof window<"u"&&(this.removePageHide=x(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&Le(0,[e])&&this.handleFocus(),typeof window<"u"&&(this.mountProbeTimer=setTimeout(()=>this.runEnvProbe(),Yr))}detach(){this.removeFieldListeners?.(),typeof window<"u"&&this.removePageHide?.()}pushLow=e=>{this.sink.enqueueLowEvent(e)};runEnvProbe(){try{if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.sink.passwordManagerDomScan?.()!==!1){let e=Ii(0),t=Date.now();for(let i of e)this.emittedSignals.has(i)||(this.emittedSignals.add(i),this.pushLow({lowType:i,ts:t}))}}catch(e){this.logger.error("Failed to run input env probe",e)}}scheduleFocusProbe(){this.firstFocusHandled||(this.firstFocusHandled=!0,this.focusProbeTimer=setTimeout(()=>this.runEnvProbe(),Xr))}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(ne(this.inputField),e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.scheduleFocusProbe(),this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e,t){this.pasteObserver.handlesInput(e)||this.changes.record(ne(this.inputField),Date.now(),t)}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}};var Fe=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new Y(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new X(0,this.inputs,e,(o,s,a)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let l=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...a===void 0?{}:{captureSeq:a},lowType:"input-paste",ts:o,inputEffect:this.length()===0?"clear":l===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.(this.inputs,()=>this.flushPending()),this.capturePrefill();let n=(o,s)=>this.safe(s);for(let o of this.inputs)this.listeners.push(Pe(0,o,{input:(s,a)=>{this.paste.handlesInput(a)||(this.composing||=s,this.changeTimer===null&&(this.changeTime=Date.now(),this.changeSeq=i.reserveCaptureSeq?.(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))},focus:s=>{this.contains(s)||this.emit("focus")},blur:s=>{this.contains(s)||(this.flushPending(),this.emit("blur"))},click:()=>this.emit("click"),pointerdown:()=>this.emit("pointerdown"),pointerup:()=>this.emit("pointerup"),keyupEscape:()=>this.emit("keyup-escape")},n,["input","focus","blur","click","pointerdown","pointerup","keyup"]));typeof window<"u"&&this.listeners.push(x(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&Le(0,this.inputs)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;changeSeq;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return wi(0,this.inputs)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing,this.changeSeq),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var D=class{constructor(e,t,i){this.logger=e;this.inputSink=t;this.groupSink=i}collector;fields=[];grouped=!1;destroyed=!1;prefillClaimed=!1;setFields(e,t=!0){try{if(this.destroyed)return;let i=[...new Set(e)];if(t===this.grouped&&i.length===this.fields.length&&i.every((s,a)=>s===this.fields[a])||(this.collector?.destroy(),this.collector=void 0,this.fields=[],this.grouped=t,i.length===0))return;let n=t?this.groupSink:this.inputSink,o={...n,enqueueLowEvent:s=>this.enqueue(n,s)};this.collector=t?new Fe(this.logger,i,o):new k(this.logger,i[0],o),this.fields=i}catch(i){this.logger.error("Failed to bind OTP inputs",i)}}enqueue(e,t){if(t.lowType==="input-prefill"){if(this.prefillClaimed)return;this.prefillClaimed=!0}else["input","input-idle","input-clear","input-paste","big-input-paste","big-input-add","big-input-rem"].includes(t.lowType)&&(this.prefillClaimed=!0);e.enqueueLowEvent(t)}capturePrefill(e=!1){e&&(this.prefillClaimed=!1),this.collector?.capturePrefill(e)}flushPending(){this.collector?.flushPending()}destroy(){this.destroyed=!0,this.collector?.destroy(),this.collector=void 0,this.fields=[]}};var Re=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new D(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var De=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new D(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var Jr=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];function ki(r){if(!r)return!1;let e=r.toLowerCase();return Jr.some(t=>e.includes(t))}var xi="@corbado/observe",Ci="1.9.1";var mt="cbo_email_link_starts";function yt(r,e){let t=r.getItem(mt);return Array.isArray(t)?t.filter(i=>!!i&&typeof i=="object"&&typeof i.transactionId=="string"&&typeof i.anchor=="string"&&typeof i.sessionId=="string"&&typeof i.startedAt=="number"&&e-i.startedAt<864e5):[]}function Oi(r,e){if(r)try{let t=yt(r,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),r.setItem(mt,t.slice(-10))}catch{}}function Pi(r,e,t=Date.now()){if(r)try{let i=yt(r,t);if(e.transactionId)return i.find(o=>o.transactionId===e.transactionId);let n=i.filter(o=>!o.continued&&(!e.specType||!o.specType||o.specType===e.specType));return n[n.length-1]}catch{return}}function Li(r,e){if(r)try{let t=yt(r,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);r.setItem(mt,t)}catch{}}var _e=class extends g{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||S(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,n=this.captureSession;i&&n&&Oi(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:n,specType:t.explicitSpecType,startedAt:Date.now()})}},Ae=class extends g{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();removePageHide;constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),n=Pi(i,{transactionId:t.transactionId,specType:t.explicitSpecType});if(n&&n.sessionId===e.getSessionId()){this.mode="attached",this.transaction=t.transactionId??n.transactionId,this.adoptCapture(n.anchor,n.sessionId,n.specType??t.explicitSpecType),this.started=!0;return}this.mode="detached",this.transaction?this.startDetached(this.createdAt):typeof window<"u"&&(this.removePageHide=x(0,"pagehide",this.onPageHide))}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&this.removePageHide?.()}deferrable(e,t=!1){let i=(n,o)=>{if(this.started){n(o?.explicitTimestamp??Date.now());return}this.deferred.push({at:o?.explicitTimestamp??Date.now(),run:n})};return{start:(n,o)=>i(s=>e.start(n,{...o,explicitTimestamp:s}),o),finished:(n,o)=>{i(s=>e.finished(n,{...o,explicitTimestamp:s}),o),t&&this.transaction&&Li(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(n,o)=>i(s=>e.error(n,{...o,explicitTimestamp:s}),o)}}};var Me=class extends g{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new z(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType,...t?.ignoreAsInteraction?{ignoreAsInteraction:!0}:{}})}destroy(){this.lowEventTracker.destroy()}};function Fi(r){let e=r.debug,t,i=(n,o)=>`[Corbado Observe SDK ${n}] ${o}`;return{reportTelemetry(n,o){if(t)try{t(n,o)}catch{}},setTelemetrySink(n){t=n},debug(n,...o){e&&console.log(i("DEBUG",n),...o)},info(n,...o){e&&console.log(i("INFO",n),...o)},warn(n,...o){e&&console.warn(i("WARN",n),...o)},error(n,...o){e&&console.error(i("ERROR",n),...o)},critical(n,...o){console.error(i("CRITICAL",n),...o)}}}var He=class extends g{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};var Be=class extends g{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker?.destroy(),this.identifierLowEventTracker?.destroy()}};var Ne=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Ue=class extends g{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,n)=>{this.trigger(i,n)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,n)=>{this.trigger(i,n)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var qe=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType,entry:t.entry})}};var Ve=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:n,actor:o}=Zr(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:n,actor:o})}};function Zr(r,e){let t={...r},i=o=>{try{e.getLogger().warn(`SSO login: unsupported ${o}; omitted from telemetry`)}catch{}},n=t.organizationDomain;return n!==void 0&&(typeof n!="string"||n.includes("@")||n.length>253)&&(delete t.organizationDomain,i("organizationDomain")),t.actor!==void 0&&t.actor!=="user"&&t.actor!=="system"&&(delete t.actor,i("actor")),t}var Ke=class extends g{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new D(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var We=class extends g{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var Ge=class extends g{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var $e=class{constructor(e,t){this.logger=e;this.sink=t}trackers=new Map;destroyed=!1;setFields(e){if(this.destroyed)return;let t=new Set(e);for(let[i,n]of this.trackers)t.has(i)||(this.safe(()=>n.destroy()),this.trackers.delete(i));for(let i of t)this.trackers.has(i)||this.safe(()=>this.trackers.set(i,new k(this.logger,i,this.sink())))}capturePrefill(e=!1){for(let t of this.trackers.values())this.safe(()=>t.capturePrefill(e))}flushPending(){for(let e of this.trackers.values())this.safe(()=>e.flushPending())}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.trackers.values())this.safe(()=>e.destroy());this.trackers.clear()}}safe(e){try{e()}catch(t){this.logger.error("Form input binding failed",t)}}};var vt=50,en=6e4,tn=40,rn=/^[A-Za-z0-9._-]+$/,Qe=class extends g{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(on(e,t),nn(e,t)),this.inputBinding=this.createLowCollector(()=>new $e(e.getLogger(),()=>this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.inputBinding?.flushPending()),t?.inputHtmlFields?.length&&this.setInputFields(t.inputHtmlFields)}setInputFields(e){this.inputBinding?.setFields(e)}destroy(){this.inputBinding?.destroy()}};function nn(r,e){let t=e?.startedAt;if(t===void 0)return;let i=Date.now();if(typeof t!="number"||!Number.isFinite(t)||t>i||i-t>en){oe(r,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function on(r,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:oe(r,"Form: missing name; the form will not be counted");let n=e?.fields;if(n===void 0)return t;if(!Array.isArray(n))return oe(r,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=n.filter(s=>typeof s=="string"&&s.length<=tn&&rn.test(s));return o.length<n.length&&oe(r,"Form: unsupported field names omitted from telemetry"),o.length>vt&&oe(r,`Form: more than ${vt} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,vt)),t}function oe(r,e){try{r.getLogger().warn(e)}catch{}}function St(r,e,t){if(r===null||typeof r!="object")return r;try{let i={...r};i.purpose===void 0&&e.purpose!==void 0&&(i.purpose=e.purpose),i.storage===void 0&&e.storage!==void 0&&(i.storage=e.storage),i.trustName===void 0&&e.trustName!==void 0&&(i.trustName=e.trustName);for(let[n,o]of[["bindingReference",255],["trustName",128]])if(typeof i[n]=="string"&&[...i[n]].length>o){delete i[n];try{t.getLogger().debug(`Trusted device: omitted ${n} exceeding ${o} characters`)}catch{}}return i}catch{return r}}function je(r,e,t){return{...r,start:(i,n)=>r.start(St(i,e,t),n),finished:(i,n)=>r.finished(St(i,e,t),n)}}var ze=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=Ri(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=this.checkStep("get-options",i,e),this.ceremony=this.checkStep("ceremony",i,e),this.postResponse=this.checkStep("post-response",i,e),this.subflowStart({explicitSpecType:t.explicitSpecType,actor:"system",ignoreAsInteraction:!0})}checkStep(e,t,i){let n=this.defineStep(e,!0);return{...je(n,t,i),errorTyped:(o,s)=>{n.errorTyped(St({code:o?.code,error:U(o?.error)},t,i),s)}}}},Ye=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=Ri(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=je(this.defineStep("get-options"),i,e),this.ceremony=je(this.defineStep("ceremony"),i,e),this.postResponse=je(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Ri(r,e){let t={...r},i=n=>{try{e.getLogger().warn(`Trusted device: missing or unsupported ${n}; omitted from telemetry`)}catch{}};return t.purpose!=="additional-verification"&&t.purpose!=="mfa-exemption"&&(delete t.purpose,i("purpose")),["cookie","indexeddb","localstore","sessionstore"].includes(t.storage)||(delete t.storage,i("storage")),t}var Xe=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...n}=t;this.subflowStart(n),i&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var sn="/inline/injected/webauthn-listeners.js",Di=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,an=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,ln=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,_i=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,dn=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,pn=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,un=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,bt=()=>Object.keys(window._sentryDebugIds??{}),wt=r=>{try{r()}catch(e){return String(e?.stack??"")}return""},Ai=()=>wt(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),cn=()=>{let r=Object.getOwnPropertyDescriptor(navigator.credentials??{},"get");if(!r?.get||!r.set||r.configurable)return!1;let e=()=>{},t=r.get.call({_get:e});return t===e||typeof t=="function"&&t===r.get.call({})&&!Function.prototype.toString.call(t).includes("[native code]")},Tt=(...r)=>{let e=navigator.credentials;return e?r.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},fn=()=>[navigator.credentials?.get,...Tt("get","_get")].some(r=>typeof r=="function"&&r.name==="getWebAuthnCredential"),hn=()=>{let r=document.documentElement,e=document.adoptedStyleSheets;if(!r||typeof r.getAnimations!="function"||typeof e?.push!="function"||r.getAnimations().length>0)return!1;let t=new CSSStyleSheet;t.replaceSync(":where(:root){animation:bitwardenfill 1s 1000s paused}"),e.push(t);try{let i=r.getAnimations().filter(n=>n.animationName==="bitwardenfill");return i.forEach(n=>n.cancel()),i.length>0}finally{let i=e.indexOf(t);i>=0&&e.splice(i,1)}},gn,mn=()=>gn??=hn(),yn=()=>{let r=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;if(typeof r!="function"||!Object.prototype.hasOwnProperty.call(r,Symbol.hasInstance))return!1;let e=r[Symbol.hasInstance]({});return e instanceof Promise?(e.catch(()=>{}),!0):!1},vn=()=>{let r={get nodeType(){throw new Error("probe")}};return wt(()=>MutationObserver.prototype.observe.call(null,r))},Sn=()=>{let r=new Error("probe"),e=[],t={get nodeType(){return e.push("nodeType"),1},get ownerDocument(){throw e.push("ownerDocument"),r}};try{MutationObserver.prototype.observe.call(null,t)}catch(i){return i===r&&e.join()==="nodeType,ownerDocument"}return!1},bn=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...Tt("get","_get","create")].some(e=>typeof e=="function"&&pn.test(Function.prototype.toString.call(e))),wn=()=>{let r=document;for(;r;){if(r.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;r=r.activeElement?.shadowRoot}return!1},Tn=()=>{let r=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...Tt("get","_get"),r?.isConditionalMediationAvailable,r?._isConditionalMediationAvailable,r?.isUserVerifyingPlatformAuthenticatorAvailable,r?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&un.test(Function.prototype.toString.call(t)))},En=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:cn},{name:"1password",signal:"Sentry debug id",test:()=>bt().some(r=>r.includes(sn))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:fn},{name:"bitwarden",signal:"autofill keyframes",test:mn},{name:"dashlane",signal:"injected script tag",test:()=>document.querySelector('script[src*="-extension://"][src*="/dashlane-"][src$="-page-script.js"]')!==null},{name:"dashlane",signal:"PublicKeyCredential hasInstance trap",test:yn},{name:"dashlane",signal:"page script stack",test:()=>Di.test(Ai())||typeof HTMLDialogElement<"u"&&Di.test(wt(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>an.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>ln.test(Ai())},{name:"keeper",signal:"override source",test:bn},{name:"keeper",signal:"field lock",test:()=>document.querySelector("[data-keeper-lock-id]")!==null},{name:"lastpass",signal:"passkey override",signedIn:!0,test:()=>typeof window.__nativeCredentialsGet=="function"},{name:"lastpass",signal:"icon root",test:wn},{name:"nordpass",signal:"observer proxy stack",test:()=>_i.test(vn())},{name:"nordpass",signal:"observer read order",test:Sn},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>bt().some(r=>dn.test(r))},{name:"nordpass",signal:"Sentry debug id",test:()=>bt().some(r=>_i.test(r))},{name:"protonpass",signal:"WebAuthn override source",test:Tn},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function In(){return typeof window>"u"||typeof document>"u"?[]:En.map(({name:r,signal:e,signedIn:t,test:i})=>{try{return{name:r,signal:e,signedIn:t,matched:i()}}catch(n){return{name:r,signal:e,signedIn:t,matched:!1,error:n}}})}function kn(){let r=new Map;for(let{name:e,signedIn:t,matched:i}of In()){if(!i)continue;let n=r.get(e)??{name:e};t&&(n.signedIn=!0),r.set(e,n)}return[...r.values()]}function Mi(r){return kn()}var Hi=3e3,xn=500,Cn=6,On=1e3,Je=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),Mt(0))this.sampleAfter(Hi);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(Hi)};this.removers.push(x(0,"load",o,{once:!0}))}let n=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=Cn&&n(),this.sampleAfter(xn))});this.removers.push(n)}detected=new Map;timers=new Set;idleCallbacks=new Set;sampledFields=new WeakSet;focusSamples=0;removers=[];destroyed=!1;reportedCounts=new Map;getDetected(){return[...this.detected.values()]}takeReport(e){if(!(!this.isEnabled()||this.detected.size<=(this.reportedCounts.get(e)??0)))return this.reportedCounts.set(e,this.detected.size),this.getDetected().map(({name:t})=>({name:t}))}destroy(){this.destroyed=!0;for(let e of this.removers)e();for(let e of this.timers)clearTimeout(e);this.timers.clear();for(let e of this.idleCallbacks)cancelIdleCallback(e);this.idleCallbacks.clear()}sampleAfter(e){let t=setTimeout(()=>{this.timers.delete(t),this.sampleWhenIdle()},e);this.timers.add(t)}sampleWhenIdle(){if(typeof requestIdleCallback!="function"){this.sample();return}let e=requestIdleCallback(()=>{this.idleCallbacks.delete(e),this.sample()},{timeout:On});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=Mi(0);for(let t of e){let i=this.detected.get(t.name);(!i||t.signedIn&&!i.signedIn)&&this.detected.set(t.name,t)}}catch(e){this.logger.error("Failed to detect password manager extensions",e)}}};var Et={name:xi,version:Ci},Pn=/^[0-9A-Za-z.+_-]{1,32}$/;function Ln(r,e){return r===void 0?Et:typeof r=="string"&&Pn.test(r)?{...Et,integrationVersion:r}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),Et)}var Bi="cbo_session_id",It="cbo_session",B="cbo_seq",Ni="cbo_experiments",Ui="cbo_data_policy",Fn=255,Rn=/^[A-Za-z0-9_-]+$/,Dn=128,_n=256,qi=1e3,An=/^[a-z][a-z0-9_-]{0,31}$/,Vi=/^[A-Za-z0-9_-]{1,16}$/,Mn=64,Hn=32,Bn=50,Nn="cbo_seq",Ki=1e3,Wi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ze=class r{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Fi({debug:this.options.debug});let t=new we(this.logger),i=new Ee(this.logger),n=e.storage==="cookie",o=n?new Te(this.logger,e.cookieDomain):void 0;vi(e.projectId,t,i,o,this.logger);let s=e.projectId,a=c=>new be(c,s);this.seqLockName=L(Nn,s),this.sessionStorage=a(i),this.persistentStorage=a(t),this.storage=a(o??t),this.configOverrides={...e.sdkConfig,...e.sdkConfig?.retry&&{retry:{...e.sdkConfig.retry}},...e.sdkConfig?.flushOnFlowTypeFinished&&{flushOnFlowTypeFinished:[...e.sdkConfig.flushOnFlowTypeFinished]},...e.sdkConfig?.sourcePathQueryAllow&&{sourcePathQueryAllow:[...e.sdkConfig.sourcePathQueryAllow]}},this.fixedData=Zt(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd);let l=Object.keys(b).every(c=>this.configOverrides[c]!==void 0)&&Object.keys(b.retry).every(c=>this.configOverrides.retry?.[c]!==void 0);l||(this.configManager=new Ce(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let p=this.configManager?.initialConfig;this.config=ot(p,this.configOverrides),!l&&!p&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!l&&!p&&e.deviceInfoCollectorTimeout!=null&&this.configOverrides.deviceInfoCollectorTimeoutMs===void 0&&(this.config={...this.config,deviceInfoCollectorTimeoutMs:e.deviceInfoCollectorTimeout}),e.apiBaseUrl!==""&&(/^https?:\/\//.test(e.apiBaseUrl)||(this.logger.critical(`Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: missing http(s) scheme")),e.apiBaseUrl.endsWith("/")&&(this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: trailing slash")));let d=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${d}`);let u=new he({logger:this.logger,url:d});this.sessionId=this.resolveSessionId(),this.queue=new ye(this.logger,u,this.sessionId,Ln(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:L(st,s),getDataPolicy:()=>this.dataPolicy,fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:c=>this.attachUndeliveredDeviceInfo(c),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((c,v)=>this.reportTelemetry(c,v));try{this.getWindowObserver()}catch(c){this.logger.error("Failed to attach page low-event observer",c)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Je(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(c){this.logger.error("Failed to start password manager detection",c)}let f=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let c of f)this.telemetry(c.level,c.message);let h=new ve(this.logger,this.storage,n?"cookie":"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(c,v)=>this.telemetry(c,v),this.fixedData?.privateMode??!0);this.deviceCollector=h;let m=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new Se(this.logger,h,Math.max(1,m),m,{timing:()=>this.config.deviceInfoTiming,emit:(c,v)=>this.telemetry(c,v)},()=>this.queue.notifyDeviceInfo()),this.deviceInfoManager.start(),this.experiments=this.loadPersistedExperiments(),e.experiments&&this.setExperiments(e.experiments),this.dataPolicy=this.loadPersistedDataPolicy(),e.dataPolicy!==void 0&&this.setDataPolicy(e.dataPolicy),this.configManager?.start(c=>this.handleConfig(c))}logger;queue;sessionId;storage;sessionStorage;persistentStorage;seqLockName;config;configManager;configOverrides;fixedData;deviceInfoManager;deviceCollector;eventTabId;seq=0;lastActivityWriteAt=0;experiments={};dataPolicy;telemetryReporting=!1;telemetryReady=!1;reportedTelemetryKeys=new Set;pendingSelfTelemetry=[];probePageId;probeSeqs=new Map;windowObserver;passwordManagerSampler;getWindowObserver(){return this.windowObserver??=new ue(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=ot(e,this.configOverrides);t.sessionContinuity||=this.config.sessionContinuity,t.durableOutbox||=this.config.durableOutbox,this.config=t,this.queue.updateConfig(this.config)}getLogger(){return this.logger}applicationTag(){return this.options.applicationId?{applicationId:this.options.applicationId.toLowerCase()}:{}}setExperiment(e,t){this.setExperiments({[e]:t})}setExperiments(e){try{if(!e||typeof e!="object")return;let t=!1;for(let[i,n]of Object.entries(e)){if(!r.isValidExperimentKey(i)||!r.isValidExperimentVariant(n)){this.logger.debug(`Ignoring invalid experiment assignment "${String(i)}"`);continue}this.experiments[i]!==n&&(this.experiments[i]=n,t=!0)}t&&this.persistExperiments()}catch(t){this.logger.error("Failed to set experiments",t)}}clearExperiment(e){try{Object.prototype.hasOwnProperty.call(this.experiments,e)&&(delete this.experiments[e],this.persistExperiments())}catch(t){this.logger.error("Failed to clear experiment",t)}}clearExperiments(){try{if(Object.keys(this.experiments).length===0)return;this.experiments={},this.persistExperiments()}catch(e){this.logger.error("Failed to clear experiments",e)}}getExperiments(){return{...this.experiments}}getPersistentStorage(){return this.persistentStorage}getSdkConfig(){return Object.freeze({version:this.config.version,aap:this.config.aap,rawErrors:this.config.rawErrors})}setDataPolicy(e){try{if(!r.isValidDataPolicy(e)){this.logger.debug(`Ignoring invalid data policy code "${String(e)}"`);return}this.dataPolicy!==e&&(this.dataPolicy=e,this.persistDataPolicy())}catch(t){this.logger.error("Failed to set data policy",t)}}getDataPolicy(){return this.dataPolicy}static isValidDataPolicy(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=Fn}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Ui);return r.isValidDataPolicy(e)?e:void 0}catch(e){this.logger.debug("Failed to load persisted data policy",e);return}}persistDataPolicy(){try{if(this.dataPolicy===void 0)return;this.persistentStorage.setItem(Ui,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Dn&&Rn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=_n}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Ni);if(!e||typeof e!="object")return{};let t={};for(let[i,n]of Object.entries(e))r.isValidExperimentKey(i)&&r.isValidExperimentVariant(n)&&(t[i]=n);return t}catch(e){return this.logger.debug("Failed to load persisted experiments",e),{}}}persistExperiments(){try{this.persistentStorage.setItem(Ni,this.experiments)}catch(e){this.logger.debug("Failed to persist experiments",e)}}resolveExperiments(e){let t={...this.experiments};if(e&&typeof e=="object")for(let[i,n]of Object.entries(e))r.isValidExperimentKey(i)&&r.isValidExperimentVariant(n)&&(t[i]=n);return Object.keys(t).length>0?t:void 0}isTrackingBlocked(){return typeof navigator>"u"?!1:ki(pe(0))}resolveSessionId(){try{if(this.config.sessionContinuity)return this.getContinuitySessionId();let e=Date.now(),t=this.readPerTabSession();if(t&&e-t.lastActiveAt<this.perTabInactivityMs(t))return this.persistPerTabSession(t.id,e),this.seq=0,t.id;let i=S();return this.persistPerTabSession(i,e),this.seq=0,this.logger.debug("Created session id",i),i}catch(e){return this.logger.error("Failed to get session id",e),this.reportTelemetry("error","failed to get session id"),""}}getContinuitySessionId(){let e=Date.now(),t=this.persistentStorage.getItem(It);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(B)??0,t.id;if(!t?.id){let n=this.readPerTabSession();if(n&&e-n.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(n.id,e),this.persistentStorage.setItem(B,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",n.id),n.id}let i=S();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(B,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem(It,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(Bi);if(e){if(typeof e=="string")return Wi.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return Wi.test(e.id)?e:void 0}}persistPerTabSession(e,t){this.lastActivityWriteAt=t;let i=this.configOverrides.sessionInactivityMs!==void 0||this.config.version?this.config.sessionInactivityMs:this.readPerTabSession()?.inactivityMs;this.sessionStorage.setItem(Bi,{id:e,lastActiveAt:t,...i===void 0?{}:{inactivityMs:i}})}perTabInactivityMs(e){return this.configOverrides.sessionInactivityMs!==void 0?this.config.sessionInactivityMs:e.inactivityMs??this.config.sessionInactivityMs}nextSeq(){if(!this.config.sessionContinuity){let i=Date.now();return this.sessionId&&i-this.lastActivityWriteAt>=Ki&&this.persistPerTabSession(this.sessionId,i),this.seq++}let e=()=>{let i=Date.now(),n=this.persistentStorage.getItem(It),o=!1;if(!n?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(n?.id)i-this.lastActivityWriteAt>=Ki&&this.persistContinuitySession(n.id,i),n.id!==this.sessionId&&(this.sessionId=n.id,this.queue.setSessionId(n.id),o=!0);else{let l=S();this.persistContinuitySession(l,i),this.persistentStorage.setItem(B,0),this.sessionId=l,this.queue.setSessionId(l),this.seq=0,o=!0}let s=this.persistentStorage.getItem(B);o&&(this.seq=typeof s=="number"?s:0);let a=typeof s=="number"&&s>this.seq?s:this.seq;return this.seq=a+1,this.persistentStorage.setItem(B,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!ri(0)?e():ge(0,this.seqLockName,e,{timeoutMs:t,onTimeout:()=>{this.logger.warn(`Sequence Web Lock acquisition timed out after ${t}ms; using fallback`),this.reportTelemetry("info",`seq web lock timeout; using fallback, ${t}ms`)}})}resolveTrackingSourcePath(){if(!(typeof window>"u"))return Bt(0,this.config.sourcePathQuery,this.config.sourcePathQueryAllow)}resolveEventTabId(){return this.eventTabId===void 0&&(this.eventTabId=this.deviceCollector.getTabId()),this.eventTabId}trackSubflowStarted(e,t,i,n){let o={subflowType:e,...t};this.track("subflow_started",o,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{id:n,subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowTrigger(e,t,i){let n={subflowType:e,...t};this.track("subflow_trigger",n,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowStepStarted(e,t,i,n,o){let s={subflowType:e,stepName:t,stepData:i,identifier:n?.identifier,ignoreAsInteraction:o};this.track("subflow_step_started",s,n?.userReference,void 0,void 0,n?.explicitTimestamp,n?.experiments,{subflowStartEventId:n?.subflowStartEventId,sessionId:n?.captureSessionId,initiator:n?.initiator})}trackSubflowStepFinished(e,t,i,n){let o={subflowType:e,stepName:t,stepData:i,identifier:n?.identifier};this.track("subflow_step_finished",o,n?.userReference,void 0,void 0,n?.explicitTimestamp,n?.experiments,{subflowStartEventId:n?.subflowStartEventId,sessionId:n?.captureSessionId,initiator:n?.initiator})}trackSubflowStepError(e,t,i,n){let o={subflowType:e,stepName:t,stepData:i,identifier:n?.identifier};this.track("subflow_step_error",o,n?.userReference,void 0,void 0,n?.explicitTimestamp,n?.experiments,{subflowStartEventId:n?.subflowStartEventId,sessionId:n?.captureSessionId,initiator:n?.initiator})}trackSubflowError(e,t,i){let n={subflowType:e,stepData:t};this.track("subflow_error",n,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}async track(e,t,i,n,o,s,a,l){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=s??Date.now(),d=l?.id??S(),u=l?.sessionId??this.sessionId,f=this.nextSeq(),h=typeof f=="number"?f:await f,m=this.resolveTrackingSourcePath(),c={type:"predefined",name:e,id:d,timestamp:p,seq:h,data:t,user:i,contexts:o,tags:n,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:ie(),initiator:l?.initiator,trackingSourcePath:m??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},v=this.deviceInfoManager.getForEvent();v&&(c.deviceInfo=v),this.logger.debug(`Track: ${e}`,JSON.stringify(c,null,2));let y=this.passwordManagerSampler?.takeReport(u);y&&(c.passwordManagers=y),this.queue.enqueue(c,u)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,n,o){try{let s=S(),a=this.sessionId,l={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,l,n,o?.explicitTimestamp,i,{id:s,sessionId:a}),this.flowHandle(s,a)}catch(s){return this.logger.warn("Failed to start flow",s),{enrich:async()=>{}}}}flowDecided(e,t,i){this.track("flow_decided",e,void 0,t,void 0,void 0,i)}conversion(e,t,i){let{userId:n,identifier:o,crossEnvironmentTransactionID:s,...a}=e,l={userId:n,identifier:o,crossEnvironmentTransactionID:s},p={...this.options.defaultTags,...this.applicationTag(),...t};this.track("conversion",a,l,p,void 0,void 0,i)}flowFinished(e,t,i){try{let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o},l=S(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:p}),this.flowHandle(l,p)}catch(n){return this.logger.warn("Failed to finish flow",n),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(n){this.logger.warn("Failed to enrich flow",n)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}setUser(e){this.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}setFlowTags(e,t){try{if(!e||typeof e!="object"){this.logger.warn("setFlowTags: ignoring non-object tags");return}let i={};for(let[o,s]of Object.entries(e)){if(o===""||typeof s!="string"){this.logger.warn(`setFlowTags: ignoring invalid tag "${o}"`);continue}i[o]=s}if(Object.keys(i).length===0)return;let n={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(n.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(n.expFol=t.expandToFollowing),this.track("flow_enriched",n,void 0,i)}catch(i){this.logger.warn("Failed to set flow tags",i)}}authMethodsDecisionStarted(e,t,i,n){this.track("auth_method_decision_started",e,void 0,t,void 0,n?.explicitTimestamp,i)}authMethodsDecisionFinished(e,t,i){this.track("auth_method_decision_finished",e,void 0,t,void 0,void 0,i)}authDecisionStarted(e,t,i){this.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}authDecisionFinished(e,t,i){this.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}enqueueLowEvent(e,t){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping low event "${e.lowType}" for blocked user agent.`);return}this.queue.enqueueLow({...e,captureSeq:e.captureSeq??O(),captureVersion:1,pageId:e.pageId??ie()},t)}catch(i){this.logger.error(`Failed to process low event "${e.lowType}" before enqueue`,i)}}telemetry(e,t){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping telemetry for blocked user agent.");return}let i=typeof t=="string"?t:String(t);if(i.length===0)return;let n={id:S(),level:e,message:i.length>qi?i.slice(0,qi):i,ts:Date.now()};this.queue.enqueueTelemetry(n)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}probe(e){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping probe for blocked user agent.");return}if(!e||typeof e!="object"||typeof e.kind!="string"||!An.test(e.kind)){this.logger.debug("Dropping probe with an invalid kind.");return}let t=e.payload;if(!t||typeof t!="object"){this.logger.debug(`Dropping probe "${e.kind}" without an object payload.`);return}let i=typeof e.pageId=="string"&&Vi.test(e.pageId)?e.pageId:this.defaultProbePageId(),n={id:S(),kind:e.kind,ts:typeof e.ts=="number"&&Number.isFinite(e.ts)?Math.round(e.ts):Date.now(),pageId:i,seq:this.nextProbeSeq(i),payload:t};typeof e.cfg=="string"&&Vi.test(e.cfg)&&(n.cfg=e.cfg);let o=Vn(e.ctx);o&&(n.ctx=o),this.queue.enqueueProbe(n)}catch(t){this.logger.error("Failed to process probe before enqueue",t)}}defaultProbePageId(){return this.probePageId??=qn()}nextProbeSeq(e){let t=this.probeSeqs.get(e)??0;if(this.probeSeqs.delete(e),this.probeSeqs.set(e,t+1),this.probeSeqs.size>Hn){let i=this.probeSeqs.keys().next().value;i!==void 0&&this.probeSeqs.delete(i)}return t}logInfo(e){this.telemetry("info",e)}logError(e){this.telemetry("error",e)}attachUndeliveredDeviceInfo(e){try{let t=this.deviceInfoManager;if(!t?.hasUndelivered())return;let i=ie(),n=e.find(o=>o.meta?.pageId===i&&!o.deviceInfo);n&&(n.deviceInfo=t.takeUndelivered())}catch(t){this.logger.error("Failed to attach device info to batch",t)}}reportTelemetry(e,t){if(!this.telemetryReporting){this.telemetryReporting=!0;try{if(this.reportedTelemetryKeys.has(t)||this.reportedTelemetryKeys.size>=Bn)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}isPasswordManagerDomScanEnabled(){return this.fixedData?.pmdExplicit?this.fixedData.pmd:!0}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}passkeyLoginFullOperation(e){return new Oe(this,e)}passkeyEnrollmentFullOperation(e){return new Me(this,e)}passkeyDeletionOperationFull(e){return new He(this,e)}passwordLoginFullOperation(e){return new Be(this,e)}passwordEnrollmentFullOperation(e){return new Ne(this,e)}emailLinkOperationFull(e){return new _e(this,e)}continueEmailLinkOperation(e){return new Ae(this,e)}emailOtpOperationFull(e){return new Re(this,e)}smsOtpOperationFull(e){return new De(this,e)}totpOperationFull(e){return new Ke(this,e)}provideIdentifierOperationFull(e){return new Ue(this,e)}provideDataOperationFull(e){return new Xe(this,e)}formOperationFull(e){return new Qe(this,e)}socialLoginOperationFull(e){return new qe(this,e)}ssoLoginOperationFull(e){return new Ve(this,e)}appConfirmationOperationFull(e){return new We(this,e)}keySigningOperationFull(e){return new le(this,e)}keyRegistrationOperationFull(e){return new de(this,e)}captchaOperationFull(e){return new Ge(this,e)}trustedDeviceCheckOperationFull(e){return new ze(this,e)}trustedDeviceEnrollmentOperationFull(e){return new Ye(this,e)}async destroy(){if(this.configManager?.destroy(),this.passwordManagerSampler?.destroy(),this.windowObserver?.destroy(),this.deviceInfoManager.destroy(),this.config.td)try{await this.queue.flush("destroy")}catch(e){this.logger.error("Failed to flush queue during destroy",e)}this.queue.destroy()}getSessionId(){if(!this.sessionId){let e=this.resolveSessionId();e&&(this.sessionId=e,this.queue.setSessionId(e))}return this.sessionId||void 0}resetSession(){let e=S();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(B,0)):this.persistPerTabSession(e,Date.now()),this.sessionId=e,this.seq=0,this.queue.setSessionId(e),this.logger.debug(`Session reset: ${e}`),e}},Un="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function qn(){let r=new Uint8Array(16);try{crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t++)r[t]=Math.floor(Math.random()*256)}let e="";for(let t=0;t<r.length;t++)e+=Un[r[t]&63];return e}function Vn(r){if(!r||typeof r!="object")return;let e={};for(let t of["state","flowType","step"]){let i=r[t];typeof i=="string"&&i.length>0&&(e[t]=i.slice(0,Mn))}return Object.keys(e).length>0?e:void 0}function et(r,e,t){let i=window.Corbado;i?.[e]&&(t(i[e]),delete window.Corbado[e])}function Gi(r,e){window.Corbado=e}var kt={};function $i(r,e="default"){kt[e]=new Ze(r)}function Qi(r="default"){if(!kt[r])throw new Error(`Tracker ${r} not initialized (call Corbado.init() first)`);return kt[r]}function Kn(r){for(let e of r)$i(e[0],e[1])}var ji={};function zi(r,e,t=[],i){let n=Qi(r),o=n[e];if(typeof o!="function")return;let s=o.apply(n,t);i&&s&&typeof s=="object"&&(ji[i]=s)}function Yi(r,e,t=[]){let i=ji[r];if(!i)return;let n=e.split("."),o=i;for(let a=0;a<n.length-1;a++)if(o=o?.[n[a]],!o)return;let s=o[n[n.length-1]];typeof s=="function"&&s.apply(o,t)}function Wn(r){for(let e of r)zi(e[0],e[1],Array.isArray(e[2])?e[2]:[],e[3])}function Gn(r){for(let e of r)Yi(e[0],e[1],Array.isArray(e[2])?e[2]:[])}typeof window<"u"&&(et(0,"IQ",Kn),et(0,"MQ",Wn),et(0,"OQ",Gn),Gi(0,{init:$i,get:Qi,__dispatchMethod:zi,__dispatchOp:Yi}));})();
|
|
1
|
+
"use strict";(()=>{var Ct=0;function P(){if(Ct===4294967295)throw new Error("Low-event capture sequence exhausted");return++Ct}function xt(n,e){if(n==="passkey-login")switch(e){case"passkey-known-identifier":case"passkey-no-identifier":return"passkey-button";case"passkey-known-identifier-auto":case"passkey-no-identifier-auto":case"passkey-immediate":return"automatic"}else if(n==="passkey-enrollment")switch(e){case"manual":return"passkey-button";case"auto":case"conditional":return"automatic"}}var E=[];for(let n=0;n<256;++n)E.push((n+256).toString(16).slice(1));function Ot(n,e=0){return(E[n[e+0]]+E[n[e+1]]+E[n[e+2]]+E[n[e+3]]+"-"+E[n[e+4]]+E[n[e+5]]+"-"+E[n[e+6]]+E[n[e+7]]+"-"+E[n[e+8]]+E[n[e+9]]+"-"+E[n[e+10]]+E[n[e+11]]+E[n[e+12]]+E[n[e+13]]+E[n[e+14]]+E[n[e+15]]).toLowerCase()}var rt,Zi=new Uint8Array(16);function ae(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(Zi)}var nt={};function er(n,e,t){let i;if(n)i=Pt(n.random??n.rng?.()??ae(),n.msecs,n.seq,e,t);else{let r=Date.now(),o=ae();tr(nt,r,o),i=Pt(o,nt.msecs,nt.seq,e,t)}return e??Ot(i)}function tr(n,e,t){return n.msecs??=-1/0,n.seq??=0,e>n.msecs?(n.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],n.msecs=e):(n.seq=n.seq+1|0,n.seq===0&&n.msecs++),n}function Pt(n,e,t,i,r=0){if(n.length<16)throw new Error("Random bytes length must be >= 16");if(!i)i=new Uint8Array(16),r=0;else if(r<0||r+16>i.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);return e??=Date.now(),t??=n[6]*127<<24|n[7]<<16|n[8]<<8|n[9],i[r++]=e/1099511627776&255,i[r++]=e/4294967296&255,i[r++]=e/16777216&255,i[r++]=e/65536&255,i[r++]=e/256&255,i[r++]=e&255,i[r++]=112|t>>>28&15,i[r++]=t>>>20&255,i[r++]=128|t>>>14&63,i[r++]=t>>>6&255,i[r++]=t<<2&255|n[10]&3,i[r++]=n[11],i[r++]=n[12],i[r++]=n[13],i[r++]=n[14],i[r++]=n[15],i}var S=er;function N(n){if(n!=null){if(n instanceof Error)return{name:n.name,message:n.message};if(typeof n=="string")return{message:n};if(typeof n=="object"){let e=n;if(typeof e.message=="string"||typeof e.code=="string")return{name:typeof e.name=="string"?e.name:void 0,message:typeof e.message=="string"?e.message:void 0,code:typeof e.code=="string"?e.code:void 0}}return{message:String(n)}}}var ir={maxStackFrames:{min:1,max:100,default:50},depth:{min:0,max:10,default:3},maxBreadth:{min:1,max:1e3,default:30},maxValueLength:{min:1,max:1e4,default:1024},maxCauseDepth:{min:0,max:10,default:3},maxBytes:{min:0,max:65536,default:32768}},rr=1024,V=class extends Error{},nr=["name","message","code","errors","stack"],or=/[^\x20-\x7E]/,K=n=>Object.prototype.toString.call(n).slice(8,-1),sr=n=>n===null?"null":typeof n=="object"?K(n):typeof n,ar=n=>n instanceof Error||K(n)==="Error"||K(n)==="DOMException";function Rt(n){return or.test(n)?new TextEncoder().encode(n).byteLength:n.length}function U(n,e){let t=ir[n];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function Lt(n={}){return{stack:n.stack===!0,maxStackFrames:U("maxStackFrames",n.maxStackFrames),depth:U("depth",n.depth),maxBreadth:U("maxBreadth",n.maxBreadth),maxValueLength:U("maxValueLength",n.maxValueLength),maxCauseDepth:U("maxCauseDepth",n.maxCauseDepth),maxBytes:U("maxBytes",n.maxBytes)}}function Dt(n,e={}){if(n===void 0)return;let t=Lt(),i=r=>{let o=JSON.stringify(r);return o===void 0||Rt(o)<=t.maxBytes};try{if(t=Lt(e),t.maxBytes===0)return;let r=_(sr(n),1024);for(let s=t.depth;s>=0;s--){let a={limits:t,causeBudget:t.maxCauseDepth,seen:new Set,nodes:0,textBytes:0};try{let d={type:r,value:le(n,s,a)};if(i(d))return d}catch(d){if(!(d instanceof V))throw d}}let o={type:r,truncated:!0};return i(o)?o:void 0}catch{let r={type:"unserializable"};return i(r)?r:void 0}}function te(n,e){if(n.length>e.limits.maxBytes)throw new V;if(e.textBytes+=Rt(JSON.stringify(n)),e.textBytes>e.limits.maxBytes)throw new V;return n}function le(n,e,t){if(++t.nodes>rr)throw new V;let i=lr(n,e,t);return typeof i=="string"?te(i,t):i}function lr(n,e,t){switch(typeof n){case"string":return _(n,t.limits.maxValueLength);case"number":return Number.isFinite(n)?n:String(n);case"boolean":case"undefined":return n;case"bigint":case"symbol":return _(String(n),t.limits.maxValueLength);case"function":return`[Function: ${n.name||"anonymous"}]`}if(n===null)return null;let i=n;if(t.seen.has(i))return"[Circular]";if(e<0)return`[${K(i)}]`;t.seen.add(i);try{return dr(i,e,t)}finally{t.seen.delete(i)}}function _(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function Ft(n,e,t){let i=n.length>t;n=_(n,t);let r=n.split(`
|
|
2
|
+
`);if(r.length<=e+1)return _(n,t);let o=r.slice(0,e+1).join(`
|
|
3
|
+
`),s=i?"[truncated]":`[+${r.length-e-1} frames]`;return _(`${o}
|
|
4
|
+
${s}`,t)}function dr(n,e,t){let{limits:i}=t,r=K(n),o=u=>le(u,e-1,t);if(r==="Date")return Number.isNaN(n.getTime())?"[Invalid Date]":n.toISOString();if(r==="RegExp")return _(String(n),i.maxValueLength);if(r==="ArrayBuffer")return`[ArrayBuffer(${n.byteLength})]`;if(ArrayBuffer.isView(n))return`[${r}(${n.byteLength})]`;if(r==="Map"||r==="Set"){let u=n,f=[];for(let h of u){if(f.length===i.maxBreadth)break;f.push(o(h))}return u.size>f.length&&f.push(`[+${u.size-f.length} more]`),f}if(r==="Promise"||r==="WeakMap"||r==="WeakSet"||r==="Window")return`[${r}]`;if(typeof Node<"u"&&n instanceof Node)return`[${r}]`;if(Array.isArray(n)){let u=n.slice(0,i.maxBreadth).map(o);return n.length>i.maxBreadth&&u.push(`[+${n.length-i.maxBreadth} more]`),u}if(typeof Response<"u"&&n instanceof Response)return{status:o(n.status),statusText:o(n.statusText),url:o(n.url),redirected:o(n.redirected)};if(typeof Event<"u"&&n instanceof Event){let u=n,f={type:o(u.type)};for(let h of["message","filename","lineno","colno"])h in u&&(f[h]=o(u[h]));return"error"in u&&u.error!=null&&(f.error=o(u.error)),f}let s=Object.create(null),a=n,d=ar(n);if(d){for(let f of nr){if(f==="stack"&&!i.stack)continue;let h=a[f];if(!(h==null||typeof h=="function")){if(f==="stack"){i.stack&&typeof h=="string"&&(s.stack=te(Ft(h,i.maxStackFrames,i.maxValueLength),t));continue}s[f]=o(h)}}let u=a.cause;u!=null&&typeof u!="function"&&(s.cause=pr(u,e-1,t))}let p=0,l=Object.keys(a);for(let u of l){if(u in s||u==="stack"&&!i.stack||d&&u==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${l.length-i.maxBreadth} keys]`;break}let f=a[u];typeof f!="function"&&(s[te(u,t)]=u==="stack"&&typeof f=="string"?te(Ft(f,i.maxStackFrames,i.maxValueLength),t):o(f))}return!d&&r!=="Object"&&p===0?`[${r}]`:s}function pr(n,e,t){if(typeof n!="object"||n===null)return le(n,e,t);if(t.causeBudget<=0)return te(`[${K(n)}]`,t);t.causeBudget--;try{return le(n,e,t)}finally{t.causeBudget++}}var ur=1500,g=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:P,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??P(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),registerInputs:(i,r)=>this.tracker.getWindowObserver().registerInputs(i,()=>({subflowStartEventId:this.startReference,fieldRole:t,initiator:t?`input-${t}`:"unknown",sessionId:this.captureSessionId}),r),beginCeremony:i=>this.tracker.getWindowObserver().beginCeremony({subflowStartEventId:this.startReference,initiator:i??"unknown",sessionId:this.captureSessionId})}}createLowCollector(e){try{let t=e();return this.lowPrefillCapturers.push(i=>t.capturePrefill(i)),t}catch(t){this.tracker.getLogger().error("Failed to attach low-event collector",t);return}}registerLowFlusher(e){this.lowFlushers.push(e)}captureOptions(e,t=this.startReference,i=this.captureSessionId,r){if(!t&&!r)return e;let o={};return t&&(o.subflowStartEventId=e?.subflowStartEventId??t,o.captureSessionId=e?.captureSessionId??i),r&&(o.initiator=e?.initiator??r),Object.defineProperties({},{...Object.getOwnPropertyDescriptors(e??{}),...Object.getOwnPropertyDescriptors(o)})}get captureReference(){return this.startReference}get captureSession(){return this.captureSessionId}adoptCapture(e,t,i){this.startReference=e,this.captureSessionId=t,this.captureSpecType=i}subflowStart(e,t){try{for(let i of this.lowFlushers)try{i()}catch(r){this.tracker.getLogger().error("Failed to flush previous low-event context",r)}this.captureSpecType=e?.explicitSpecType,this.startReference=S(),this.captureSessionId=this.tracker.getSessionId(),this.tracker.trackSubflowStarted(this.operationName,e,this.captureOptions(t),this.startReference),this.captureInputPrefills(!0)}catch(i){this.tracker.getLogger().error("Failed to start low-event capture context",i)}}capturePrefill(){this.captureInputPrefills(!1)}captureInputPrefills(e){for(let t of this.lowPrefillCapturers)try{t(e)}catch(i){this.tracker.getLogger().error("Failed to capture input prefill",i)}}trigger(e,t){this.tracker.trackSubflowTrigger(this.operationName,e,this.captureOptions(t))}customStep(e){return this.defineStep(e)}subflowStepStarted(e,t,i,r){this.captureSpecType=t?.explicitSpecType??this.captureSpecType,this.tracker.trackSubflowStepStarted(this.operationName,e,t,this.captureOptions(i),r)}subflowStepFinished(e,t,i){(!i?.subflowStartEventId||i.subflowStartEventId===this.startReference)&&(this.captureSpecType=t?.explicitSpecType??this.captureSpecType),this.tracker.trackSubflowStepFinished(this.operationName,e,t,this.captureOptions(i))}subflowStepError(e,t,i){let r=t;try{let o=this.tracker.getSdkConfig().rawErrors?i?.rawError:void 0;o!==void 0&&(r={...t,rawError:Dt(o,i?.rawErrorLimits)})}catch{}this.tracker.trackSubflowStepError(this.operationName,e,r,this.captureOptions(i))}withWindowLowEvents(e,t){let i,r=s=>{s?.subflowStartEventId&&s.subflowStartEventId!==i||t.scheduleDisarm(ur)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let d=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??xt(this.operationName,d);t.arm(p,d==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),r(a)},error:(s,a)=>{o.error(s,a),r(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),r(a)}}}defineStep(e,t){let i,r,o,s=d=>this.captureOptions(d,i,r,o);return{start:(d,p)=>{i=this.startReference,r=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,d,s(p),t)},finished:(d,p)=>{this.subflowStepFinished(e,d,s(p))},error:(d,p)=>{this.subflowStepError(e,{error:N(d)},s(p))},errorTyped:(d,p)=>{this.subflowStepError(e,d,s(p))}}}};function At(n,e){if(e.explicitSpecType!==void 0)try{n.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var de=class extends g{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:At(e,t)})}},pe=class extends g{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:At(e,t)})}};function cr(n){try{return decodeURIComponent(n.replace(/\+/g," "))}catch{return n}}function fr(n,e){let t=n.toLowerCase();return e.some(i=>{let r=i.toLowerCase();return r.endsWith("*")?t.startsWith(r.slice(0,-1)):t===r})}function Mt(n,e,t){return e!=="allowlist"||n===""||n==="?"?n:`?${(n.startsWith("?")?n.slice(1):n).split("&").map(o=>{let s=o.indexOf("=");if(s===-1)return o;let a=o.slice(0,s);return o.slice(s+1)===""||fr(cr(a),t)?o:`${a}=*`}).join("&")}`}function C(n,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function W(n){return document.visibilityState==="hidden"}function _t(n){return document.readyState==="complete"}function Ht(n){return window.location.href}function Bt(n,e,t){let i=Mt(window.location.search,e,t);return`${window.location.pathname}${i}`}function qt(n){return{hostname:window.location.hostname,https:window.location.protocol==="https:"}}function Nt(n){return typeof navigator>"u"?"":navigator.userAgent??""}async function Ut(n){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function Vt(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function Kt(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function Wt(n){if(typeof PublicKeyCredential>"u"||!PublicKeyCredential.getClientCapabilities)return;let e=await PublicKeyCredential.getClientCapabilities();return Object.fromEntries(Object.entries(e).map(([t,i])=>[t,i.toString()]))}async function $t(n){if(typeof navigator>"u"||!navigator.userAgentData)return;let e=await navigator.userAgentData.getHighEntropyValues(["platformVersion","model"]),t=e.platform,i=e.mobile,r=e.platformVersion,o=e.model||void 0;if(!(!t||i===void 0||!r))return{platform:t,mobile:i,platformVersion:r,model:o}}function Gt(n){if(!(typeof navigator>"u"))return navigator.webdriver}function Qt(n){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}var ot=(n,e,t)=>{let i=!1,r,o=null,s=null,a=()=>{s!==null&&(clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&n({...r===void 0?{}:{captureSeq:r},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),r=p}s!==null&&clearTimeout(s),s=setTimeout(a,150)},flush:a}};function jt(n,e,t){let i=[],r=(s,a,d)=>{let p=l=>t(a,()=>d(l));s.addEventListener(a,p),i.push(()=>s.removeEventListener(a,p))};r(window,"blur",()=>e.blur()),r(window,"focus",()=>e.focus()),r(document,"visibilitychange",()=>e.visibilityChange(document.visibilityState==="hidden")),r(document,"focusout",s=>e.focusOut(s.target,!!s.relatedTarget)),r(document,"focusin",s=>e.focusIn(()=>s.composedPath())),r(document,"pointerdown",s=>e.pointerDown(s.target)),window.visualViewport&&(r(window.visualViewport,"resize",()=>e.viewportResize()),r(window.visualViewport,"scroll",()=>e.viewportScroll())),r(window,"pagehide",()=>e.pageHide());let o=window.navigation;return o&&r(o,"currententrychange",s=>{let a=s,d=a.from?.index,p=o.currentEntry?.index;a.navigationType==="traverse"&&typeof d=="number"&&typeof p=="number"&&d>=0&&p>=0&&p<d&&e.navigateBack()}),i}function zt(n){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function Yt(n){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var hr,ie=()=>hr??=S(),ue=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=jt(0,{blur:()=>{this.flushInputs(),this.bracket=this.context(),this.emit({lowType:"window-blur",ts:Date.now()},this.bracket)},focus:()=>{this.flushInputs(),this.emit({lowType:"window-focus",ts:Date.now()},this.bracket??this.context()),this.bracket=void 0},visibilityChange:r=>{this.flushInputs(),this.emit({lowType:`document-visibilitychange-${r?"hidden":"visible"}`,ts:Date.now()})},focusOut:(r,o)=>{let s=this.findInput(r);this.lastBlur=s&&!o&&Date.now()-this.unrelatedPointerAt>250?{registration:s,ts:Date.now()}:void 0},focusIn:r=>{this.lastBlur=void 0;let o=this.inputFocusListeners.size>0&&r().find(s=>this.findInput(s));o&&this.notifyInputFocus(o)},pointerDown:r=>{this.findInput(r)?this.unrelatedPointerAt=-1/0:(this.lastBlur=void 0,this.unrelatedPointerAt=Date.now())},viewportResize:()=>this.extendViewport("resize"),viewportScroll:()=>this.extendViewport("scroll"),pageHide:()=>{this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.flushKeepalive()},navigateBack:()=>{this.flushInputs(),this.emit({lowType:"window-navigate-back",ts:Date.now()})}},(r,o)=>{try{o()}catch(s){this.logger.error(`Failed to observe window ${r}`,s)}}))}inputs=new Set;inputFocusListeners=new Set;ceremonies=new Set;removers=[];lastBlur;bracket;unrelatedPointerAt=-1/0;destroyed=!1;viewportContext={};resize=ot(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",P);scroll=ot(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",P);registerInputs(e,t,i){if(this.destroyed)return()=>{};let r={fields:e,context:t,flush:i};if(this.inputs.add(r),this.inputFocusListeners.size>0&&typeof document<"u"){let o=zt(0),s=e.find(a=>o.includes(a));s&&this.notifyInputFocus(s)}return()=>{this.inputs.delete(r),this.lastBlur?.registration===r&&(this.lastBlur=void 0)}}beginCeremony(e){let t={context:e,settled:!1};this.destroyed||(this.flushInputs(),this.ceremonies.add(t));let i=()=>{t.timer&&clearTimeout(t.timer),this.ceremonies.delete(t),this.bracket===t.context&&(this.bracket=void 0)};return{settle:r=>{t.settled=!0,t.timer&&clearTimeout(t.timer),t.timer=setTimeout(i,r)},destroy:i}}onInputFocus(e){return this.destroyed?()=>{}:(this.inputFocusListeners.add(e),()=>this.inputFocusListeners.delete(e))}notifyInputFocus(e){for(let t of this.inputFocusListeners)try{t(e)}catch(i){this.logger.error("Failed to notify registered input focus",i)}}context(){let e=[...this.ceremonies].filter(o=>!o.settled);if(e.length===1)return e[0].context;if(e.length>1)return;let t=Yt(0),i=this.findInput(t.active);if(i)return i.context();let r=this.lastBlur;if(r&&Date.now()-r.ts<=250&&t.idle)return r.registration.context()}findInput(e){return[...this.inputs].find(t=>t.fields.some(i=>i===e))}flushInputs(){for(let e of this.inputs)try{e.flush()}catch(t){this.logger.error("Failed to flush window input context",t)}}emit(e,t){if(this.destroyed)return;let{sessionId:i,...r}=t??{};this.enqueue({...e,...r,captureSeq:e.captureSeq??P(),sourceKind:"window",captureVersion:1,pageId:ie()},i)}extendViewport(e){let t=this.context(),i=this.viewportContext[e];(i?.subflowStartEventId!==t?.subflowStartEventId||i?.fieldRole!==t?.fieldRole||i?.sessionId!==t?.sessionId)&&this[e].flush(),this.viewportContext[e]=t,this[e].extend()}destroy(){if(!this.destroyed){this.flushInputs(),this.resize.flush(),this.scroll.flush(),this.destroyed=!0;for(let e of this.removers)e();for(let e of this.ceremonies)e.timer&&clearTimeout(e.timer);this.ceremonies.clear(),this.inputs.clear(),this.inputFocusListeners.clear()}}};var st="cbo_sdk_config",Xt="cbo_sdk_config_cache",Zt="X-Corbado-Observe-Config";var I={flushIntervalMs:{min:100,max:6e4},retryMaxAttempts:{min:1,max:10},retryDelayMs:{min:50,max:12e4},sessionInactivityMs:{min:6e4,max:864e5},seqLockTimeoutMs:{min:0,max:250},deviceInfoCollectorTimeoutMs:{min:10,max:1e4},flushOnFlowTypeFinished:{maxEntries:20,maxNameLength:100},sourcePathQueryAllow:{maxEntries:50,maxKeyLength:64}},gr=1800*1e3,b={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:gr,seqLockTimeoutMs:50,tvc:!0,tph:!0,td:!0,tlf:!0,telemetry:!0,flushOnTelemetry:!1,flushOnFlowTypeFinished:[],deviceInfoCollectorTimeoutMs:1e3,deviceInfoTiming:!1,rawErrors:!0,pmd:!0,retry:{maxAttempts:1,baseDelayMs:0,maxDelayMs:0},aap:"",sourcePathQuery:"allowlist",sourcePathQueryAllow:[]};function H(n,e,t){return Math.min(Math.max(n,e),t)}function B(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function L(n,e){return typeof n=="boolean"?n:e}function Jt(n,e){return typeof n=="string"?n:e}function mr(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.length>0&&e.length<=I.flushOnFlowTypeFinished.maxNameLength).slice(0,I.flushOnFlowTypeFinished.maxEntries):[]}function yr(n){return typeof n=="string"&&n.trim().toLowerCase()==="all"?"all":"allowlist"}function vr(n){return Array.isArray(n)?n.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=I.sourcePathQueryAllow.maxKeyLength).slice(0,I.sourcePathQueryAllow.maxEntries):[]}function $(n){if(!n||typeof n!="object")return null;let e=n;return typeof e.version!="string"||e.version===""?null:ei(e)}function ei(n){let e=n.retry&&typeof n.retry=="object"?n.retry:{},t=H(B(e.baseDelayMs,b.retry.baseDelayMs),I.retryDelayMs.min,I.retryDelayMs.max);return{version:Jt(n.version,""),flushIntervalMs:H(B(n.flushIntervalMs,b.flushIntervalMs),I.flushIntervalMs.min,I.flushIntervalMs.max),durableOutbox:n.durableOutbox===!0,durableLowOutbox:n.durableLowOutbox===!0,beaconKeepalive:n.beaconKeepalive===!0,sessionContinuity:n.sessionContinuity===!0,sessionInactivityMs:H(B(n.sessionInactivityMs,b.sessionInactivityMs),I.sessionInactivityMs.min,I.sessionInactivityMs.max),seqLockTimeoutMs:H(B(n.seqLockTimeoutMs,b.seqLockTimeoutMs),I.seqLockTimeoutMs.min,I.seqLockTimeoutMs.max),tvc:L(n.tvc,b.tvc),tph:L(n.tph,b.tph),td:L(n.td,b.td),tlf:L(n.tlf,b.tlf),telemetry:L(n.telemetry,b.telemetry),flushOnTelemetry:n.flushOnTelemetry===!0,flushOnFlowTypeFinished:mr(n.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:H(B(n.deviceInfoCollectorTimeoutMs,b.deviceInfoCollectorTimeoutMs),I.deviceInfoCollectorTimeoutMs.min,I.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:n.deviceInfoTiming===!0,rawErrors:L(n.rawErrors,b.rawErrors),pmd:L(n.pmd,b.pmd),aap:Jt(n.aap,""),sourcePathQuery:yr(n.sourcePathQuery),sourcePathQueryAllow:vr(n.sourcePathQueryAllow),retry:{maxAttempts:H(B(e.maxAttempts,b.retry.maxAttempts),I.retryMaxAttempts.min,I.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:H(B(e.maxDelayMs,b.retry.maxDelayMs),t,I.retryDelayMs.max)}}}function at(n,e={}){let t=n??b,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),r=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=ei({...t,...i,retry:{...t.retry,...r}});return o.retry={...t.retry,...Object.fromEntries(Object.keys(r).map(s=>[s,o.retry[s]]))},o.retry.maxDelayMs=Math.max(o.retry.baseDelayMs,o.retry.maxDelayMs),o}function ti(n){try{if(!n||typeof n!="object")return;let e=n,t=e.crossOriginSession,i=t&&typeof t=="object"&&typeof t.cookieDomain=="string"?t.cookieDomain:void 0;return{pmd:L(e.pmd,!1),privateMode:L(e.privateMode,!0),...i!==void 0&&{crossOriginSession:{cookieDomain:i}}}}catch{return}}function ce(n){let e=n.getItem(Xt),t=e&&typeof e=="object"?$(e.config):null;return t?{...e,config:t}:null}function ii(n){return ce(n)?.config??$(n.getItem(st))}function ri(n,e){n.setItem(Xt,e)}var Sr=new Set;function ni(n){Sr.add(n)}function fe(n,e,t){return fetch(e,t)}function oi(n){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var br=6e4,wr=6e4,he=class{constructor(e){this.options=e;ni(0)}async send(e,t){try{e.meta={...e.meta,sent:Date.now(),transport:"fetch"};let i=JSON.stringify(e),r=typeof AbortController<"u"?new AbortController:void 0,o=r?setTimeout(()=>r.abort(),wr):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=br,...r?{signal:r.signal}:{}},a=await fe(0,this.options.url,s),d={statusCode:a.status,headers:{"retry-after":a.headers.get("Retry-After")}};if(a.headers.get("X-Corbado-Observe-Accepted")==="1"&&(d.deliveryAccepted=!0),a.status===200)try{let p=$(await a.json());p&&(d.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return d}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{this.options.logger.debug(`Sending ${e.events.length} events via beacon`);let t=oi(0);if(!t)return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let i=new Blob([JSON.stringify(e)],{type:"text/plain"});return t(this.options.url,i)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};function ge(n,e,t,i={}){let r=typeof navigator<"u"?navigator.locks:void 0;if(r?.request){let o=i.timeoutMs,s=o!==void 0&&typeof AbortController<"u"?new AbortController:null;if(o!==void 0&&!s)return Promise.resolve().then(t);try{let a=!1,d,p=()=>{d!==void 0&&(clearTimeout(d),d=void 0)},l=()=>(a=!0,p(),t()),u=s?r.request(e,{signal:s.signal},l):r.request(e,l);return s&&o!==void 0&&!a&&(d=setTimeout(()=>{d=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),u.catch(f=>{if(a)throw f;return t()}).finally(p)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function si(n){return typeof navigator<"u"&&!!navigator.locks?.request}var Tr="cbo_outbox",lt="cbo_outbox",Er=500,Ir=512*1024;function kr(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&e.id!==""&&typeof e.sessionId=="string"&&typeof e.flushAfter=="number"&&Number.isFinite(e.flushAfter)&&typeof e.attempts=="number"&&Number.isFinite(e.attempts)&&typeof e.event=="object"&&e.event!==null}var G=class{constructor(e,t,i=Er,r=Ir,o=lt,s=Tr){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=r;this.lockName=o;this.storageKey=s;this.entries=this.read()}entries=[];reportedMalformed=!1;read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(kr);return t.length<e.length&&!this.reportedMalformed&&(this.reportedMalformed=!0,this.logger.error(`EventStore dropped ${e.length-t.length} malformed outbox entries`),this.logger.reportTelemetry?.("error","event store dropped malformed outbox entries")),t}mutate(e){return ge(0,this.lockName,()=>{try{let t=e(this.read());if(t.length>this.maxEntries){let i=t.length-this.maxEntries;t=t.slice(t.length-this.maxEntries),this.logger.error(`EventStore evicted ${i} oldest entries (cap ${this.maxEntries})`),this.logger.reportTelemetry?.("error","event store evicted entries (cap)")}t=this.enforceSizeBudget(t),this.entries=t,this.storage.setItem(this.storageKey,t)}catch(t){this.logger.error("Failed to mutate event store",t),this.logger.reportTelemetry?.("error","failed to mutate event store")}})}enforceSizeBudget(e){let t=e.map(o=>JSON.stringify(o).length),i=t.reduce((o,s)=>o+s,e.length+1),r=0;for(;i>this.maxSerializedLength&&r<e.length;)i-=t[r]+1,r++;return r===0?e:(this.logger.error(`EventStore evicted ${r} oldest entries (size budget ${this.maxSerializedLength})`),this.logger.reportTelemetry?.("error","event store evicted entries (size budget)"),e.slice(r))}add(e){return this.mutate(t=>t.some(i=>i.id===e.id)?t:[...t,e])}all(){return this.entries=this.read(),this.entries}getDue(e){return this.all().filter(t=>t.flushAfter<=e)}remove(e){if(e.length===0)return Promise.resolve();let t=new Set(e);return this.mutate(i=>i.filter(r=>!t.has(r.id)))}update(e){if(e.length===0)return Promise.resolve();let t=new Map(e.map(i=>[i.id,i]));return this.mutate(i=>i.map(r=>t.get(r.id)??r))}size(){return this.all().length}};var Cr=500,xr=512*1024,ai=200,li=200*1024,Or=16*1024,di=6e4,dt=32e3;function me(n){let e=0;for(let t=0;t<n.length;t++){let i=n.charCodeAt(t);i<128?e+=1:i<2048?e+=2:i>=55296&&i<=56319&&t+1<n.length?(e+=4,t++):e+=3}return e}var ye=class{constructor(e,t,i,r,o={},s){this.logger=e;this.transport=t;this.sessionId=i;this.sdk=r;this.storage=s;if(this.batchSize=o.batchSize||50,this.flushIntervalOverride=o.flushInterval,this.debug=o.debug??!1,this.requestConfig=o.requestConfig??!0,this.onConfigReceived=o.onConfigReceived,this.getDataPolicy=o.getDataPolicy,this.getCrossOriginSession=o.getCrossOriginSession,this.fixedData=o.fixedData===!0,this.beforeEventBatchSend=o.beforeEventBatchSend,this.standaloneDeviceInfo=o.standaloneDeviceInfo,this.config=o.config??b,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new G(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new G(this.storage,this.logger,1e3,256*1024,`${this.outboxLockName??"cbo_outbox"}:lows`,"cbo_low_outbox_v1");let a=this.lowStore.all();this.lowPending=a.filter(d=>this.validPendingLow(d)),this.lowStore.remove(a.filter(d=>!this.validPendingLow(d)).map(d=>d.id))}this.setupLifecycleHooks(),(this.pending.length>0||this.lowPending.length>0)&&(this.dirtySinceSyncFlush=!0,this.scheduleFlush(0,"recovery"))}pending=[];lowsQueue=[];lowPending=[];lowStore;telemetryQueue=[];probeQueue=[];probeBytes=0;probesDropped=0;timer=null;isFlushing=!1;flushingDone;destroyed=!1;dirtySinceSyncFlush=!1;onVisibilityChange=null;onPageHide=null;removeVisibilityChange=null;removePageHide=null;batchSize;flushIntervalOverride;debug;requestConfig;onConfigReceived;getDataPolicy;getCrossOriginSession;fixedData;beforeEventBatchSend;standaloneDeviceInfo;config;priorityFlowTypes;outboxLockName;store;configResolved=!1;setSessionId(e){this.sessionId=e}flushInterval(){return this.flushIntervalOverride??this.config.flushIntervalMs}enqueue(e,t=this.sessionId){try{let i={id:e.id,sessionId:t,flushAfter:0,attempts:0,event:e};this.pending.push(i),this.store?.add(i),this.scheduleAfterEnqueue(e)}catch(i){this.logger.error("Failed to enqueue event",i)}}enqueueLow(e,t=this.sessionId){try{let i={...e,id:e.id??S()};if(this.config.durableLowOutbox){let r={id:i.id,sessionId:t,event:i,attempts:0,flushAfter:0};this.lowPending.push(r),this.lowPending=this.lowPending.slice(-1e3),this.lowStore?.add(r)}else this.lowsQueue.push({sessionId:t,event:i});this.scheduleAfterEnqueue()}catch(i){this.logger.error("Failed to enqueue low event",i)}}notifyDeviceInfo(){try{this.dirtySinceSyncFlush=!0,this.scheduleFlush(this.flushInterval(),"timer")}catch(e){this.logger.error("Failed to schedule device info flush",e)}}enqueueTelemetry(e){try{if(!this.config.telemetry)return;this.telemetryQueue.push(e),this.dirtySinceSyncFlush=!0,this.config.flushOnTelemetry&&this.flush("telemetry")}catch(t){this.logger.error("Failed to enqueue telemetry",t)}}enqueueProbe(e,t=this.sessionId){try{if(this.destroyed)return;let i=JSON.stringify(e.payload);if(typeof i!="string"||me(i)>Or){this.probesDropped++;return}let r={...e,payload:JSON.parse(i)},o=me(JSON.stringify(r));for(this.probeQueue.push({sessionId:t,entry:r,bytes:o,attempts:0,flushAfter:0}),this.probeBytes+=o;this.probeQueue.length>Cr||this.probeBytes>xr&&this.probeQueue.length>1;){let s=this.probeQueue.shift();this.probeBytes-=s.bytes,this.probesDropped++}this.scheduleFlush(this.flushInterval(),"timer")}catch(i){this.logger.error("Failed to enqueue probe",i)}}droppedProbeCount(){return this.probesDropped}dueProbes(e){return this.probeQueue.filter(t=>t.flushAfter<=e)}selectProbes(e,t,i,r){let o=[],s=0;for(let a of e){if(o.length>=i)break;if(a.sessionId===t){if(s+a.bytes>r){o.length===0&&r>=li&&o.push(a);break}s+=a.bytes,o.push(a)}}return o}removeProbes(e){if(e.length===0)return;let t=new Set(e);this.probeQueue=this.probeQueue.filter(i=>!t.has(i));for(let i of e)this.probeBytes-=i.bytes}dropProbes(e){this.removeProbes(e),this.probesDropped+=e.length}handleProbeSendResult(e,t,i){if(t.length===0)return;let r=e.statusCode;if(typeof r=="number"&&r>=200&&r<300){this.removeProbes(t);return}if(!this.isRetryable(r)){this.dropProbes(t);return}let o=Math.max(1,this.config.retry.maxAttempts),s=this.parseRetryAfter(e),a=[];for(let d of t)d.attempts+=1,d.attempts>=o?a.push(d):d.flushAfter=i+this.backoffForAttempt(d.attempts,s);this.dropProbes(a)}sendUnloadProbes(e,t,i,r){let o=this.sessionId,s={sessionId:o,events:[],sdk:this.sdk,probes:[]};this.attachBatchMeta(s,[],t);let a=me(JSON.stringify(s))+120,d=e>a?this.selectProbes(this.probeQueue,o,ai,e-a):[];d.length>0&&(s.probes=d.map(p=>p.entry),this.attachBatchMeta(s,d,t),r&&this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(s):Promise.resolve(this.transport.send(s)).catch(()=>{}),this.removeProbes(d)),i&&this.dropProbes(this.probeQueue.slice())}scheduleAfterEnqueue(e){if(this.dirtySinceSyncFlush=!0,e!==void 0&&this.isPriorityEvent(e)){this.flush("flow-finished");return}this.scheduleFlush(this.flushInterval(),"timer")}isPriorityEvent(e){if(e.type!=="predefined"||e.name!=="flow_finished"&&e.name!=="flow_auto_finished")return!1;let t=e.data?.flowName;return typeof t=="string"&&this.priorityFlowTypes.has(t)}scheduleFlush(e,t){this.destroyed||this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.flush(t)},e))}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}async flush(e="timer"){if(this.destroyed)return;if(this.isFlushing){if(e==="destroy"){await this.flushingDone;try{this.sendUnloadProbes(dt,e,!0,!1)}catch(i){this.logger.error("Unexpected error in queue flush",i)}}return}this.isFlushing=!0;let t;this.flushingDone=new Promise(i=>{t=i});try{for(this.clearTimer();;){let i=Date.now(),r=this.getDuePending(i),o=this.lowPending.filter(w=>w.flushAfter<=i),s=e==="destroy"?[]:this.dueProbes(i),a=r.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0&&s.length===0;if(a&&!this.hasStandaloneDeviceInfo())break;let d=r[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??s[0]?.sessionId??this.sessionId,p=r.filter(w=>w.sessionId===d).slice(0,this.batchSize),l=o.filter(w=>w.sessionId===d).slice(0,100),u=[...l.map(w=>w.event),...this.takeLows(d,100-l.length)];this.prepareEvents(p,e);let f=d===this.sessionId?this.takeTelemetry():[],h=d===this.sessionId?this.takeStandaloneDeviceInfo():void 0,m=this.selectProbes(s,d,ai,li),c={sessionId:d,events:p.map(w=>w.event),sdk:this.sdk};if(u.length>0&&(c.lows=u),f.length>0&&(c.telemetry=f),m.length>0&&(c.probes=m.map(w=>w.entry)),h&&(c.deviceInfo=h),a&&!h)break;this.attachBatchMeta(c,[...p,...l,...m],e),l.length&&(c.deliveryAck=!0);let v=this.shouldRequestConfig()?{[Zt]:this.config.version||"1"}:void 0,y=await this.transport.send(c,v).catch(w=>(this.logger.error("Unexpected error in queue flush",w),{}));if(c.deliveryAck&&y.statusCode&&y.statusCode>=200&&y.statusCode<300&&!y.deliveryAccepted&&(y={...y,statusCode:503}),this.requestConfig&&this.handleConfigResponse(y),this.handleLowSendResult(y,l,i),this.handleProbeSendResult(y,m,i),!this.handleSendResult(y,p,i))break}e==="destroy"&&this.sendUnloadProbes(dt,e,!0,!1)}catch(i){this.logger.error("Unexpected error in queue flush",i)}finally{this.isFlushing=!1,t(),this.flushingDone=void 0,this.rescheduleIfPending()}}attachBatchMeta(e,t,i){e.meta={...e.meta,flushReason:i};let r=this.readDataPolicy();r!==void 0&&(e.meta={...e.meta,dataPolicy:r}),this.config.version&&(e.meta={...e.meta,configVersion:this.config.version}),this.fixedData&&(e.meta={...e.meta,fixedData:!0});try{let s=this.getCrossOriginSession?.(e.sessionId);s&&(e.meta={...e.meta,crossOriginSession:s})}catch{}let o=t.reduce((s,a)=>Math.max(s,a.attempts),0);o>0&&(e.meta={...e.meta,retryCount:o})}prepareEvents(e,t){if(!(!this.beforeEventBatchSend||e.length===0))try{this.beforeEventBatchSend(e.map(i=>i.event),t)}catch(i){this.logger.error("Failed to prepare events for sending",i)}}readDataPolicy(){try{return this.getDataPolicy?.()}catch(e){this.logger.debug("Failed to read data policy for batch meta",e);return}}getDuePending(e){return this.pending.filter(t=>t.flushAfter<=e)}takeLows(e=this.sessionId,t=100){let i=this.lowsQueue.filter(o=>o.sessionId===e).slice(0,t),r=new Set(i);return this.lowsQueue=this.lowsQueue.filter(o=>!r.has(o)),i.map(o=>o.event)}validPendingLow(e){return typeof e.event?.lowType=="string"&&e.event.id===e.id&&Number.isFinite(e.event.ts)&&e.event.ts>Date.now()-7*864e5}removeLowEntries(e){let t=new Set(e);this.lowPending=this.lowPending.filter(i=>!t.has(i.id)),this.lowStore?.remove(e)}handleLowSendResult(e,t,i){let r=e.statusCode;if(r!==void 0&&r>=200&&r<300){e.deliveryAccepted?this.removeLowEntries(t.map(o=>o.id)):this.deferLowEntries(t,i);return}if(!this.isRetryable(r)){this.removeLowEntries(t.map(o=>o.id)),this.logger.reportTelemetry?.("error","low events rejected by ingestion");return}this.deferLowEntries(t,i,this.parseRetryAfter(e))}deferLowEntries(e,t,i=null){let r=[];for(let o of e){if(!this.validPendingLow(o)){r.push(o.id);continue}o.attempts=Math.min(o.attempts+1,16),o.flushAfter=t+Math.max(Math.min(6e4,1e3*2**Math.min(o.attempts,6)),this.backoffForAttempt(o.attempts,i))}this.removeLowEntries(r),this.lowStore?.update(e.filter(o=>!r.includes(o.id)))}hasStandaloneDeviceInfo(){try{return this.standaloneDeviceInfo?.has()??!1}catch(e){return this.logger.error("Failed to read device info for batch",e),!1}}takeStandaloneDeviceInfo(){try{return this.standaloneDeviceInfo?.take()}catch(e){this.logger.error("Failed to read device info for batch",e);return}}takeTelemetry(){let e=this.telemetryQueue;return this.telemetryQueue=[],e}shouldRequestConfig(){return this.requestConfig&&!this.configResolved}handleConfigResponse(e){let t=e.statusCode;typeof t=="number"&&t>=200&&t<300&&(this.configResolved=!0),e.config&&(this.config.version||this.updateConfig(e.config),this.onConfigReceived?.(e.config))}updateConfig(e){if(this.destroyed)return;let t=this.config.flushIntervalMs!==e.flushIntervalMs;if(this.config={...e,durableOutbox:this.config.durableOutbox||e.durableOutbox},this.priorityFlowTypes=new Set(e.flushOnFlowTypeFinished),e.durableLowOutbox&&this.lowsQueue.length){let r=this.lowsQueue;this.lowsQueue=[];for(let{event:o,sessionId:s}of r)this.enqueueLow(o,s)}let i=!1;if(this.config.durableOutbox&&this.storage&&!this.store){this.store=new G(this.storage,this.logger,void 0,void 0,this.outboxLockName);let r=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!r.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let r=e.statusCode,o=typeof r=="number"&&r>=200&&r<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(l=>l.id)),!0;if(!this.isRetryable(r))return this.removeEntries(t.map(l=>l.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),d=[],p=[];for(let l of t)l.attempts+=1,l.attempts>=s?d.push(l.id):(l.flushAfter=i+this.backoffForAttempt(l.attempts,a),p.push(l));return this.removeEntries(d),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,r=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(r=Math.min(r,i.maxDelayMs));let o=Math.round(r/2+Math.random()*(r/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let r=Date.parse(t);return Number.isNaN(r)?null:Math.max(0,r-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer||this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0&&this.probeQueue.length===0)return;let e=Date.now();if(this.getDuePending(e).length>0||this.lowPending.some(i=>i.flushAfter<=e)||this.lowsQueue.length>0||this.probeQueue.some(i=>i.flushAfter<=e)){this.scheduleFlush(this.flushInterval(),"timer");return}let t=Math.min(...[...this.pending,...this.lowPending,...this.probeQueue].map(i=>i.flushAfter));this.scheduleFlush(Math.max(0,t-e),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{this.writeLifecycleDebugOutput("cbo_visibility_change_debug"),W(0)&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.writeLifecycleDebugOutput("cbo_pagehide_debug"),this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.removeVisibilityChange=C(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=C(0,"pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:Ht(0)};this.storage.setItem(e,t)}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){let t=this.flushSyncEvents(e);e==="pagehide"&&this.probeQueue.length>0&&this.sendUnloadProbes(Math.min(di-t,dt),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(l=>l.sessionId===t),r=i.slice(0,this.batchSize),o=this.lowPending.filter(l=>l.sessionId===t).slice(0,100),s=[...o.map(l=>l.event),...this.takeLows(t,100-o.length)];this.prepareEvents(r,e);let a=this.takeTelemetry(),d=this.takeStandaloneDeviceInfo();if(r.length===0&&s.length===0&&a.length===0&&!d)return this.dirtySinceSyncFlush=!1,0;let p={sessionId:t,events:r.map(l=>l.event),sdk:this.sdk};return s.length>0&&(p.lows=s),a.length>0&&(p.telemetry=a),d&&(p.deviceInfo=d),this.attachBatchMeta(p,[...r,...o],e),o.length&&(p.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(p)||this.transport.send(p):this.transport.send(p),this.config.durableOutbox||this.removeEntries(r.map(l=>l.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>r.length,this.approximateSize(p)}approximateSize(e){try{return me(JSON.stringify(e))}catch{return di}}destroy(){try{this.destroyed=!0,this.clearTimer(),this.dropProbes(this.probeQueue.slice()),typeof window<"u"&&(this.removeVisibilityChange&&this.removeVisibilityChange(),this.removePageHide&&this.removePageHide())}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};var pt={d:(n,e)=>{for(var t in e)pt.o(e,t)&&!pt.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:e[t]})},o:(n,e)=>Object.prototype.hasOwnProperty.call(n,e)},ut={};pt.d(ut,{A:()=>Pr,k:()=>pi});var Q=function(n,e,t,i){return new(t||(t=Promise))(function(r,o){function s(p){try{d(i.next(p))}catch(l){o(l)}}function a(p){try{d(i.throw(p))}catch(l){o(l)}}function d(p){var l;p.done?r(p.value):(l=p.value,l instanceof t?l:new t(function(u){u(l)})).then(s,a)}d((i=i.apply(n,e||[])).next())})},j=function(n,e){var t,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(d){return function(p){return(function(l){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(s=0)),s;)try{if(t=1,i&&(r=2&l[0]?i.return:l[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,l[1])).done)return r;switch(i=0,r&&(l=[2&l[0],r.value]),l[0]){case 0:case 1:r=l;break;case 4:return s.label++,{value:l[1],done:!1};case 5:s.label++,i=l[1],l=[0];continue;case 7:l=s.ops.pop(),s.trys.pop();continue;default:if(r=s.trys,!((r=r.length>0&&r[r.length-1])||l[0]!==6&&l[0]!==2)){s=0;continue}if(l[0]===3&&(!r||l[1]>r[0]&&l[1]<r[3])){s.label=l[1];break}if(l[0]===6&&s.label<r[1]){s.label=r[1],r=l;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(l);break}r[2]&&s.ops.pop(),s.trys.pop();continue}l=e.call(n,s)}catch(u){l=[6,u],i=0}finally{t=r=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}})([d,p])}}};function pi(){return Q(this,void 0,Promise,function(){return j(this,function(n){switch(n.label){case 0:return[4,new Promise(function(e,t){var i="Unknown",r=!1;function o(l){r||(r=!0,e({isPrivate:l,browserName:i}))}function s(){var l=0,u=parseInt("-1");try{u.toFixed(u)}catch(f){l=f.message.length}return l}function a(){return Q(this,void 0,void 0,function(){var l,u;return j(this,function(f){switch(f.label){case 0:return f.trys.push([0,2,,3]),[4,navigator.storage.getDirectory()];case 1:return f.sent(),o(!1),[3,3];case 2:return l=f.sent(),u=l instanceof Error&&typeof l.message=="string"?l.message:String(l),o(u.includes("unknown transient reason")),[3,3];case 3:return[2]}})})}function d(){var l;return Q(this,void 0,Promise,function(){return j(this,function(u){switch(u.label){case 0:return typeof((l=navigator.storage)===null||l===void 0?void 0:l.getDirectory)!="function"?[3,2]:[4,a()];case 1:return u.sent(),[3,3];case 2:navigator.maxTouchPoints!==void 0?(function(){var f=String(Math.random());try{var h=indexedDB.open(f,1);h.onupgradeneeded=function(m){var c=m.target.result,v=function(y){o(y)};try{c.createObjectStore("t",{autoIncrement:!0}).put(new Blob),v(!1)}catch(y){(y instanceof Error&&typeof y.message=="string"?y.message:String(y)).includes("are not yet supported")?v(!0):v(!1)}finally{c.close(),indexedDB.deleteDatabase(f)}},h.onerror=function(){return o(!1)}}catch{o(!1)}})():(function(){var f=window.openDatabase,h=window.localStorage;try{f(null,null,null,null)}catch{return void o(!0)}try{h.setItem("test","1"),h.removeItem("test")}catch{return void o(!0)}o(!1)})(),u.label=3;case 3:return[2]}})})}function p(){var l;return Q(this,void 0,Promise,function(){var u,f,h;return j(this,function(m){switch(m.label){case 0:if(typeof((l=navigator.storage)===null||l===void 0?void 0:l.getDirectory)!="function")return[3,5];m.label=1;case 1:return m.trys.push([1,3,,4]),[4,navigator.storage.getDirectory()];case 2:return m.sent(),o(!1),[3,4];case 3:return u=m.sent(),f=u instanceof Error&&typeof u.message=="string"?u.message:String(u),o(f.includes("Security error")),[2];case 4:return[3,6];case 5:(h=indexedDB.open("inPrivate")).onerror=function(c){if(h.error&&h.error.name==="InvalidStateError")return c.preventDefault(),void o(!0);o(!1)},h.onsuccess=function(){indexedDB.deleteDatabase("inPrivate"),o(!1)},m.label=6;case 6:return[2]}})})}(function(){return Q(this,void 0,Promise,function(){return j(this,function(l){switch(l.label){case 0:return s()!==44&&s()!==43?[3,2]:(i="Safari",[4,d()]);case 1:return l.sent(),[3,6];case 2:return s()!==51?[3,3]:(u=navigator.userAgent,i=u.match(/Chrome/)?navigator.brave!==void 0?"Brave":u.match(/Edg/)?"Edge":u.match(/OPR/)?"Opera":"Chrome":"Chromium",(function(){var f=this,h="__di_"+Math.random().toString(36).slice(2),m=new Uint8Array(16384),c=indexedDB.open(h,1);c.onupgradeneeded=function(){c.result.createObjectStore("s")},c.onerror=function(){indexedDB.deleteDatabase(h),o(!1)},c.onsuccess=function(){var v=c.result,y=!1;try{var w=v.transaction("s","readwrite",{durability:"strict"});y=w.durability==="strict",w.abort()}catch{}if(!y)return v.close(),indexedDB.deleteDatabase(h),void o(!1);var T=function(X){return new Promise(function(D,Z){var ee=performance.now(),q=0,O=function(){if(q!==15){var M=v.transaction("s","readwrite",{durability:X});M.objectStore("s").put(m,q),q++,M.oncomplete=O,M.onerror=M.onabort=function(){return Z(M.error)}}else D(performance.now()-ee)};O()})};Q(f,void 0,void 0,function(){var X,D,Z,ee,q;return j(this,function(O){switch(O.label){case 0:return X=performance.now(),[4,T("relaxed")];case 1:return O.sent(),[4,T("strict")];case 2:O.sent(),D=[],Z=0,O.label=3;case 3:return Z<15?[4,T("relaxed")]:[3,7];case 4:return ee=O.sent(),[4,T("strict")];case 5:if(q=O.sent(),D.push(ee>0?q/ee:1/0),D.length>=7&&performance.now()-X>=1e3)return[3,7];O.label=6;case 6:return Z++,[3,3];case 7:return D.sort(function(M,Xi){return M-Xi}),v.close(),indexedDB.deleteDatabase(h),o(D[D.length>>1]<1.3),[2]}})}).catch(function(){v.close(),indexedDB.deleteDatabase(h),o(!1)})}})(),[3,6]);case 3:return s()!==25?[3,5]:(i="Firefox",[4,p()]);case 4:return l.sent(),[3,6];case 5:navigator.msSaveBlob!==void 0?(i="Internet Explorer",o(window.indexedDB===void 0)):t(new Error("detectIncognito cannot determine the browser")),l.label=6;case 6:return[2]}var u})})})().catch(t)})];case 1:return[2,n.sent()]}})})}var Pr=pi,ui=ut.A,Uo=ut.k;async function ci(n){return(await ui()).isPrivate}var Lr=300,re=6e3,fi="cbo_pm",Fr=10080*60*1e3,hi="detectincognitojs@1.9.0",gi={timing:!1},ct="cbo_tab_id",mi={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function F(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function yi(n,e,t){return{field:n,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function ft(n,e){let t;try{return await Promise.race([n.then(()=>!0,()=>!0),new Promise(i=>{t=setTimeout(()=>i(!1),Math.max(0,e))})])}finally{t&&clearTimeout(t)}}var ve=class{constructor(e,t,i="localstorage",r,o=()=>gi,s,a=!0){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=r;this.settings=o;this.emitTelemetry=s;this.privateModeEnabled=a}pagePrivateMode;privateModeDetectionStarted=!1;lastKnown={};async collect(e,t={}){try{let i=this.resolveSettings(),r=F(),o=this.getClientEnvHandle(),s={type:"web",clientEnvHandle:o.value,clientEnvHandleMeta:{timestamp:o.timestamp,source:o.source},tabId:this.getTabId()},a=typeof __CBO_DATA_PRIVATE_MODE__=="boolean"?__CBO_DATA_PRIVATE_MODE__:this.privateModeEnabled,d=a?this.knownPrivateMode(i.timing):void 0,p,l=a&&d===void 0&&!this.privateModeDetectionStarted?this.detectPrivateMode(i.timing).then(T=>{p=T}):void 0,u=this.startFastFields();await ft(Promise.all(u.map(T=>T.promise)),Lr);let f=F()-r,h=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,u);let m=()=>p?.error?[p.error]:[];this.safePublish(e,this.buildInfo(s,u,p?p.value:d,h,m()),"fast");let c=u.filter(T=>!T.settled),v=l!==void 0&&p===void 0;if(c.length===0&&!v)return;let y=F();await Promise.all([ft(Promise.all(c.map(T=>T.promise)),re-(y-r)),l]);let w=c.filter(T=>!T.settled).map(T=>yi(T.field,T.source,re));w.push(...m()),i.timing&&c.length>0&&this.reportLateTiming(F()-r,c),this.safePublish(e,this.buildInfo(s,u,p?p.value:d,h,w),"update")}catch(i){this.logger.error("Failed to collect device info",i)}}async getInfo(){let e;return await this.collect(t=>{e=t}),e??{}}startFastFields(){return[this.startField("bluetoothAvailable","navigator.bluetooth.getAvailability",()=>Ut(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>Wt(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>Vt(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>Kt(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>$t(0)),this.startField("webdriver","navigator.webdriver",()=>Gt(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>Qt(0))]}startField(e,t,i){let r=F(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:F()-r}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:F()-r,error:{field:e,source:t,error:N(s)??{message:"Unknown error"}}})).then(s=>(o.settled=s,s)),o}buildInfo(e,t,i,r,o){let s={},a=[];for(let p of t)p.settled?(p.settled.error&&a.push(p.settled.error),s[p.field]=p.settled.value,this.remember(p.field,p.settled.value)):s[p.field]=r[p.field];s.privateMode=i,a.push(...o);let d={...e,data:{bluetoothAvailable:s.bluetoothAvailable,javaScriptHighEntropy:s.javaScriptHighEntropy,privateMode:s.privateMode,webdriver:s.webdriver,conditionalMediationAvailable:s.conditionalMediationAvailable,userVerifyingPlatformAuthenticatorAvailable:s.userVerifyingPlatformAuthenticatorAvailable,clientCapabilities:s.clientCapabilities,maxTouchPoints:s.maxTouchPoints}};return a.length>0&&(d.collectionErrors=a),d}remember(e,t){t!==void 0&&(this.lastKnown[e]=t)}safePublish(e,t,i){try{e(t,i)}catch(r){this.logger.error("Failed to publish device info",r)}}knownPrivateMode(e){if(this.pagePrivateMode!==void 0)return this.pagePrivateMode;let t=this.readPrivateModeCache();return t&&(this.pagePrivateMode=t.value,e&&this.reportTelemetry(`device info privateMode from cache, age ${Math.round((Date.now()-t.ts)/1e3)}s`)),this.pagePrivateMode}canCachePrivateMode(){return this.storageSource==="localstorage"}readPrivateModeCache(){if(this.canCachePrivateMode())try{let e=this.storage.getItem(fi);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==hi)return;let t=Date.now()-e.ts;return t<0||t>=Fr?void 0:e}catch(e){this.logger.debug("Failed to read cached privateMode",e);return}}writePrivateModeCache(e){if(this.canCachePrivateMode())try{this.storage.setItem(fi,{value:e,ts:Date.now(),dv:hi})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=F(),r=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:ci(0));if(!await ft(r.promise,re)||!r.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${re}ms`),{error:yi("privateMode",t,re)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(F()-i)}ms`),r.settled.error)return{error:r.settled.error};let s=r.settled.value;return typeof s!="boolean"?{value:void 0}:(this.pagePrivateMode=s,this.writePrivateModeCache(s),{value:s})}resolveSettings(){try{return{timing:this.settings()?.timing===!0}}catch(e){return this.logger.error("Failed to resolve device info collector settings",e),gi}}reportFastTiming(e,t){let i=t.map(r=>`${mi[r.field]}=${Math.round(r.settled?.durationMs??e)}`).join(",");this.reportTelemetry(`device info collected in ${Math.round(e)}ms (${i})`)}reportLateTiming(e,t){let i=t.map(r=>`${mi[r.field]}=${r.settled?Math.round(r.settled.durationMs):"timeout"}`).join(",");this.reportTelemetry(`device info late fields done in ${Math.round(e)}ms (${i})`)}reportTelemetry(e){if(this.emitTelemetry)try{this.emitTelemetry("info",e)}catch(t){this.logger.error("Failed to report device info timing",t)}}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle");if(e)return e;let t=S(),i={timestamp:Date.now(),source:this.storageSource,value:t};return this.storage.setItem("cbo_client_env_handle",i),i}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(ct);if(e)return e;let t=S();if(this.sessionStorage.setItem(ct,t),this.sessionStorage.getItem(ct)===t)return t}};function Rr(){return typeof document<"u"&&W(0)}var Se=class{constructor(e,t,i,r,o,s){this.logger=e;this.source=t;this.refreshInterval=i;this.attachInterval=r;this.diagnostics=o;this.onUndelivered=s}snapshot;snapshotPhase;publishedAt=0;version=0;deliveredVersion=0;refreshedAt=0;lastAttachedAt=null;eventsSeen=!1;refreshPromise;timer;destroyed=!1;start(){this.refresh()}getForEvent(){if(this.eventsSeen=!0,Date.now()-this.refreshedAt>=this.refreshInterval&&this.refresh(),!!this.snapshot){if(this.version!==this.deliveredVersion)return this.markDelivered("event");if(!(this.lastAttachedAt!==null&&Date.now()-this.lastAttachedAt<this.attachInterval))return this.lastAttachedAt=Date.now(),this.snapshot}}hasUndelivered(){return this.snapshot!==void 0&&this.version!==this.deliveredVersion}takeUndelivered(){if(this.hasUndelivered())return this.markDelivered("flush")}hasStandalone(){return this.eventsSeen&&this.hasUndelivered()}takeStandalone(){if(this.hasStandalone())return this.markDelivered("request")}destroy(){this.destroyed=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}markDelivered(e){return this.deliveredVersion=this.version,this.lastAttachedAt=Date.now(),this.snapshotPhase==="update"&&this.report(`device info update delivered via ${e} after ${Math.max(0,Date.now()-this.publishedAt)}ms`),this.snapshot}publish(e,t){if(t==="fast"&&(this.refreshedAt=Date.now()),!(this.snapshot&&JSON.stringify(this.snapshot)===JSON.stringify(e))&&(this.snapshot=e,this.snapshotPhase=t,this.publishedAt=Date.now(),this.version++,this.eventsSeen&&this.onUndelivered))try{this.onUndelivered()}catch(i){this.logger.error("Failed to announce undelivered device info",i)}}report(e){if(this.diagnostics)try{this.diagnostics.timing()&&this.diagnostics.emit("info",e)}catch(t){this.logger.error("Failed to report device info delivery",t)}}scheduleRefresh(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.refresh()},this.refreshInterval)}refresh(){if(this.refreshPromise)return this.refreshPromise;if(this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.snapshot&&Rr())return this.destroyed||this.scheduleRefresh(),Promise.resolve();let e=this.snapshot!==void 0;return this.refreshPromise=Promise.resolve().then(()=>this.source.collect((t,i)=>this.publish(t,i),{refresh:e})).catch(t=>this.logger.error("Failed to refresh device info",t)).finally(()=>{this.refreshPromise=void 0,this.destroyed||this.scheduleRefresh()}),this.refreshPromise}};function vi(n){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function Si(n){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function ne(n){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function R(n,e){return`${n}_${e}`}var be=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(R(e,this.namespace))}setItem(e,t){this.engine.setItem(R(e,this.namespace),t)}removeItem(e){this.engine.removeItem(R(e,this.namespace))}},we=class{constructor(e){this.logger=e}area=vi(0);getItem(e){try{if(typeof localStorage>"u")return null;let t=this.area.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`LocalStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof localStorage>"u")return;this.area.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`LocalStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`localStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof localStorage>"u")return;this.area.removeItem(e)}catch(t){this.logger.error(`LocalStorage.removeItem failed for key "${e}"`,t)}}},Te=class{constructor(e,t){this.logger=e;this.domain=t}jar=ne(0);getItem(e){try{if(typeof document>"u")return null;let t=e+"=",i=this.jar.read().split(";");for(let r=0;r<i.length;r++){let o=i[r].trim();if(o.indexOf(t)===0){let s=o.substring(t.length);return JSON.parse(decodeURIComponent(s))}}return null}catch(t){return this.logger.error(`CookieStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof document>"u")return;let i=`${e}=${encodeURIComponent(JSON.stringify(t))}; path=/; SameSite=Lax`;this.domain&&(i+=`; domain=${this.domain}`),this.jar.write(i)}catch(i){this.logger.error(`CookieStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`cookie.setItem failed: ${e}`)}}removeItem(e){try{if(typeof document>"u")return;let t=`${e}=; Max-Age=-99999999; path=/`;this.domain&&(t+=`; domain=${this.domain}`),this.jar.write(t)}catch(t){this.logger.error(`CookieStorage.removeItem failed for key "${e}"`,t)}}},Ee=class{constructor(e){this.logger=e}area=Si(0);getItem(e){try{if(typeof sessionStorage>"u")return null;let t=this.area.getItem(e);return t?JSON.parse(t):null}catch(t){return this.logger.error(`SessionStorage.getItem failed for key "${e}"`,t),null}}setItem(e,t){try{if(typeof sessionStorage>"u")return;this.area.setItem(e,JSON.stringify(t))}catch(i){this.logger.error(`SessionStorage.setItem failed for key "${e}"`,i),this.logger.reportTelemetry?.("error",`sessionStorage.setItem failed: ${e}`)}}removeItem(e){try{if(typeof sessionStorage>"u")return;this.area.removeItem(e)}catch(t){this.logger.error(`SessionStorage.removeItem failed for key "${e}"`,t)}}};var Ie=1,ke="cbo_storage_schema",Dr=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],Ar=["cbo_session_id","cbo_tab_id"],Mr=["cbo_client_env_handle"];function Ce(n,e,t){return n.setItem(e,t),JSON.stringify(n.getItem(e))===JSON.stringify(t)}function ht(n,e,t){let i=n.getItem(ke);if(i!==null){if(i.version!==Ie||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(r=>n.getItem(R(r,e))!==null))return Ce(n,ke,{version:Ie,projectId:e,complete:!0});if(!Ce(n,ke,{version:Ie,projectId:e,complete:!1}))return!1}for(let r of t){let o=R(r,e);if(n.getItem(o)!==null)continue;let s=n.getItem(r);if(s!==null&&!Ce(n,o,s))return!1}return Ce(n,ke,{version:Ie,projectId:e,complete:!0})}function bi(n,e,t,i,r){try{if(!ht(e,n,Dr))return;ht(t,n,Ar),i&&ht(i,n,Mr)}catch(o){r.error("Failed to migrate legacy Observe storage",o)}}var _r=10*1e3,Hr=60*1e3,Br=3600*1e3,qr=300*1e3,wi=1440*60*1e3,Nr=[1e3,3e3];function Ur(n){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(n?.get("Cache-Control")??"");if(!e)return Br;let t=Number(n?.get("Age")??0),i=(Number(e[1])-(Number.isFinite(t)&&t>0?t:0))*1e3;return Math.min(Math.max(i,qr),wi)}var xe=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=ii(t)??void 0,this.appliedVersion=this.initialConfig?.version}initialConfig;requestTimer;retryTimer;controller;removers=[];fetching=!1;stopped=!1;lastAttemptAt;appliedVersion;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.listen(),this.refresh())}listen(){if(typeof window>"u")return;let e=()=>{typeof document>"u"||W(0)||this.refresh()};this.removers.push(C(0,"visibilitychange",e),C(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=ce(this.storage),{fetchedAt:i,expiresAt:r}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof r=="number"&&i>0&&r-i<=wi&&i<=e&&e<r){t.config.version!==this.appliedVersion&&(this.appliedVersion=t.config.version,this.onConfig?.(t.config));return}let o=this.lastAttemptAt===void 0?1/0:e-this.lastAttemptAt;if(o>=0&&o<Hr)return;this.lastAttemptAt=e,clearTimeout(this.retryTimer),this.fetchConfig()}catch(e){this.logger.error("Unexpected error in SDK config refresh",e)}}async fetchConfig(e=0){if(this.stopped||this.fetching)return;this.fetching=!0;let t=typeof AbortController<"u"?new AbortController:void 0;this.controller=t,this.requestTimer=t?setTimeout(()=>t.abort(),_r):void 0;let i=!0;try{let r=await fe(0,this.url,{method:"GET",cache:"no-cache",...t?{signal:t.signal}:{}});if(!r.ok)throw i=(r.status===408||r.status===429||r.status>=500)&&!r.headers.has("Retry-After"),new Error(`SDK config request failed (${r.status})`);let o=await r.json();i=!1;let s=$(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();ri(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+Ur(r.headers),config:s}),ce(this.storage)&&this.storage.removeItem(st),this.appliedVersion=s.version,this.onConfig?.(s)}catch(r){if(!this.stopped){this.logger.error("Failed to fetch SDK config",r);let o=Nr[e];(i&&!(r instanceof SyntaxError)||t?.signal.aborted)&&o!==void 0&&(this.retryTimer=setTimeout(()=>{this.fetchConfig(e+1)},o))}}finally{clearTimeout(this.requestTimer),this.requestTimer=void 0,this.controller=void 0,this.fetching=!1}}destroy(){this.stopped=!0,this.removers.splice(0).forEach(e=>e()),clearTimeout(this.requestTimer),clearTimeout(this.retryTimer),this.controller?.abort(),this.onConfig=void 0}};var z=class{constructor(e,t){this.logger=e;this.sink=t}lease;destroyed=!1;arm(e,t=!1){if(this.disarm(),!(this.destroyed||t))try{this.lease=this.sink.beginCeremony?.(e)}catch(i){this.logger.error("Failed to register ceremony low-event context",i)}}scheduleDisarm(e){try{this.lease?.settle(e)}catch(t){this.logger.error("Failed to settle ceremony low-event context",t)}}disarm(){try{this.lease?.destroy()}catch(e){this.logger.error("Failed to release ceremony low-event context",e)}this.lease=void 0}destroy(){this.disarm(),this.destroyed=!0}};var Oe=class extends g{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new z(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType})}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker.destroy()}};var Y=class{constructor(e,t,i,r){this.previousLength=e;this.pushLow=t;this.logger=i;this.reserveCaptureSeq=r}prefillSettled=!1;inputBatch=null;currentEffect="modify";ringEffect="modify";autofillTimestamps=[];autofillStreak=null;idleTimer=null;runSeq;markInputObserved(){this.prefillSettled=!0}observe(){this.runSeq!==void 0||this.inputBatch||this.autofillTimestamps.length>0||this.autofillStreak||(this.runSeq=this.reserveCaptureSeq?.())}takeSeq(){let e=this.runSeq;return this.runSeq=void 0,e??this.reserveCaptureSeq?.()}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect){let i=this.inputBatch;if(!i){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:this.takeSeq()};return}i.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e,this.ringEffect);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let r=1;r<e.length;r++){let o=e[r]-e[r-1];if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1){this.observe(),this.markInputObserved(),this.scheduleIdle();let r=this.previousLength;this.currentEffect=e===0?"clear":r===0?"fill":"modify";let o=e-r;if(this.previousLength=e,e===0&&r>0){this.flush();let l=this.takeSeq();this.pushLow({...l===void 0?{}:{captureSeq:l},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}if(o>=3){this.flushInputBatch(),this.flushAutofillStreak();let l=this.takeSeq();this.pushLow({...l===void 0?{}:{captureSeq:l},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(o<=-3){this.flushInputBatch(),this.flushAutofillStreak();let l=this.takeSeq();this.pushLow({...l===void 0?{}:{captureSeq:l},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let s=this.autofillStreak;if(s){if(o===1&&t-s.lastTimestamp<=80){s.lastTimestamp=t;return}this.flushAutofillStreak()}if(o!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}let a=this.autofillTimestamps;if(a.length===0&&(this.ringEffect=this.currentEffect),a.push(t),a.length>5){let l=a.shift();this.extendInputBatch(l,this.ringEffect),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let d=a[0],p=a[a.length-1];a.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:d,captureSeq:this.takeSeq(),lastTimestamp:p,effect:this.ringEffect}}};var J=class{constructor(e,t,i,r,o){this.inputs=t;this.logger=i;this.changed=r;this.reserveCaptureSeq=o;for(let s of t)s.addEventListener("paste",this.onPaste,!0),s.addEventListener("beforeinput",this.onBeforeInput,!0)}before=null;timestamp=0;captureSeq;pasteEvent;timer=null;onPaste=e=>this.begin(e);onBeforeInput=e=>{e.inputType==="insertFromPaste"?this.begin(e):this.flush()};handlesInput(e){if(!this.before)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?!0:(this.clear(),!1)}get pending(){return this.before!==null}begin(e){if(!(!e.isTrusted||this.before))try{this.before=this.inputs.map(t=>t.value),this.pasteEvent=e,this.timestamp=Date.now(),this.captureSeq=this.reserveCaptureSeq?.(),this.timer=setTimeout(()=>this.flush(),0)}catch(t){this.logger.error("Failed to observe paste",t),this.clear()}}flush(){let e=this.before;if(!e)return;let t=this.timestamp,i=this.captureSeq;this.clear();try{let r=0,o=!1;this.inputs.forEach((s,a)=>{let d=e[a],p=s.value;if(d===p)return;o=!0;let l=0;for(;l<d.length&&l<p.length&&d[l]===p[l];)l++;let u=0;for(;u<d.length-l&&u<p.length-l&&d[d.length-u-1]===p[p.length-u-1];)u++;r+=p.length-l-u}),o&&this.changed(t,r,i)}catch(r){this.logger.error("Failed to finish paste observation",r)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.before=null,this.pasteEvent=void 0}destroy(){this.flush();for(let e of this.inputs)e.removeEventListener("paste",this.onPaste,!0),e.removeEventListener("beforeinput",this.onBeforeInput,!0)}};var Vr=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Pe(n,e,t,i,r=Vr){let o=[];for(let s of r){let a=Kr(s,t,i);a&&o.push([s,a])}for(let[s,a]of o)e.addEventListener(s,a);return()=>{for(let[s,a]of o)e.removeEventListener(s,a)}}function Kr(n,e,t){switch(n){case"focus":case"blur":{let i=e[n];return i&&(r=>t(n,()=>i(r.relatedTarget)))}case"pointerdown":case"pointerup":case"click":{let i=e[n];return i&&(()=>t(n,()=>i()))}case"input":{let i=e.input;return i&&(r=>t("input",()=>i(r.isComposing||r.inputType==="insertCompositionText",r)))}case"keyup":{let i=e.keyupEscape;return i&&(r=>t("keyup",()=>{r.key==="Escape"&&i()}))}}}function Ti(n,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function Ei(n,e){return e.reduce((t,i)=>t+i.value.length,0)}function Le(n,e){let t=document.activeElement;return e.find(i=>i===t)}function oe(n){return Ti(0,n)}var k=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new Y(oe(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new J(0,[t],e,(r,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=oe(t),this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:oe(t)===0?"clear":a===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;removeFieldListeners;removePageHide;changes;pasteObserver;destroyed=!1;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;this.removeFieldListeners=Pe(0,e,{focus:()=>this.handleFocus(),blur:()=>this.handleBlur(),pointerdown:()=>this.enqueueNonInputEvent("pointerdown"),pointerup:()=>this.enqueueNonInputEvent("pointerup"),click:()=>this.enqueueNonInputEvent("click"),input:(t,i)=>this.handleInput(i,t),keyupEscape:()=>this.enqueueNonInputEvent("keyup-escape")},(t,i)=>{try{i()}catch(r){t==="input"?this.logger.error("Failed to observe input",r):this.logger.error(`Failed to handle low event "${t}"`,r)}}),typeof window<"u"&&(this.removePageHide=C(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&Le(0,[e])&&this.handleFocus()}detach(){this.removeFieldListeners?.(),typeof window<"u"&&this.removePageHide?.()}pushLow=e=>{this.sink.enqueueLowEvent(e)};capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(oe(this.inputField),e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e,t){this.pasteObserver.handlesInput(e)||this.changes.record(oe(this.inputField),Date.now(),t)}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}};var Fe=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new Y(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new J(0,this.inputs,e,(o,s,a)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let d=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...a===void 0?{}:{captureSeq:a},lowType:"input-paste",ts:o,inputEffect:this.length()===0?"clear":d===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.(this.inputs,()=>this.flushPending()),this.capturePrefill();let r=(o,s)=>this.safe(s);for(let o of this.inputs)this.listeners.push(Pe(0,o,{input:(s,a)=>{this.paste.handlesInput(a)||(this.composing||=s,this.changeTimer===null&&(this.changeTime=Date.now(),this.changes.observe(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))},focus:s=>{this.contains(s)||this.emit("focus")},blur:s=>{this.contains(s)||(this.flushPending(),this.emit("blur"))},click:()=>this.emit("click"),pointerdown:()=>this.emit("pointerdown"),pointerup:()=>this.emit("pointerup"),keyupEscape:()=>this.emit("keyup-escape")},r,["input","focus","blur","click","pointerdown","pointerup","keyup"]));typeof window<"u"&&this.listeners.push(C(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&Le(0,this.inputs)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return Ei(0,this.inputs)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var A=class{constructor(e,t,i){this.logger=e;this.inputSink=t;this.groupSink=i}collector;fields=[];grouped=!1;destroyed=!1;prefillClaimed=!1;setFields(e,t=!0){try{if(this.destroyed)return;let i=[...new Set(e)];if(t===this.grouped&&i.length===this.fields.length&&i.every((s,a)=>s===this.fields[a])||(this.collector?.destroy(),this.collector=void 0,this.fields=[],this.grouped=t,i.length===0))return;let r=t?this.groupSink:this.inputSink,o={...r,enqueueLowEvent:s=>this.enqueue(r,s)};this.collector=t?new Fe(this.logger,i,o):new k(this.logger,i[0],o),this.fields=i}catch(i){this.logger.error("Failed to bind OTP inputs",i)}}enqueue(e,t){if(t.lowType==="input-prefill"){if(this.prefillClaimed)return;this.prefillClaimed=!0}else["input","input-idle","input-clear","input-paste","big-input-paste","big-input-add","big-input-rem"].includes(t.lowType)&&(this.prefillClaimed=!0);e.enqueueLowEvent(t)}capturePrefill(e=!1){e&&(this.prefillClaimed=!1),this.collector?.capturePrefill(e)}flushPending(){this.collector?.flushPending()}destroy(){this.destroyed=!0,this.collector?.destroy(),this.collector=void 0,this.fields=[]}};var Re=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new A(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var De=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new A(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var Wr=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];function Ii(n){if(!n)return!1;let e=n.toLowerCase();return Wr.some(t=>e.includes(t))}var ki="@corbado/observe",Ci="1.10.1";var gt="cbo_email_link_starts";function mt(n,e){let t=n.getItem(gt);return Array.isArray(t)?t.filter(i=>!!i&&typeof i=="object"&&typeof i.transactionId=="string"&&typeof i.anchor=="string"&&typeof i.sessionId=="string"&&typeof i.startedAt=="number"&&e-i.startedAt<864e5):[]}function xi(n,e){if(n)try{let t=mt(n,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),n.setItem(gt,t.slice(-10))}catch{}}function Oi(n,e,t=Date.now()){if(n)try{let i=mt(n,t);if(e.transactionId)return i.find(o=>o.transactionId===e.transactionId);let r=i.filter(o=>!o.continued&&(!e.specType||!o.specType||o.specType===e.specType));return r[r.length-1]}catch{return}}function Pi(n,e){if(n)try{let t=mt(n,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);n.setItem(gt,t)}catch{}}var Ae=class extends g{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||S(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,r=this.captureSession;i&&r&&xi(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:r,specType:t.explicitSpecType,startedAt:Date.now()})}},Me=class extends g{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();removePageHide;constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),r=Oi(i,{transactionId:t.transactionId,specType:t.explicitSpecType});if(r&&r.sessionId===e.getSessionId()){this.mode="attached",this.transaction=t.transactionId??r.transactionId,this.adoptCapture(r.anchor,r.sessionId,r.specType??t.explicitSpecType),this.started=!0;return}this.mode="detached",this.transaction?this.startDetached(this.createdAt):typeof window<"u"&&(this.removePageHide=C(0,"pagehide",this.onPageHide))}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&this.removePageHide?.()}deferrable(e,t=!1){let i=(r,o)=>{if(this.started){r(o?.explicitTimestamp??Date.now());return}this.deferred.push({at:o?.explicitTimestamp??Date.now(),run:r})};return{start:(r,o)=>i(s=>e.start(r,{...o,explicitTimestamp:s}),o),finished:(r,o)=>{i(s=>e.finished(r,{...o,explicitTimestamp:s}),o),t&&this.transaction&&Pi(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(r,o)=>i(s=>e.error(r,{...o,explicitTimestamp:s}),o)}}};var _e=class extends g{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new z(e.getLogger(),this.lowEventSink("ceremony")),this.registerLowFlusher(()=>this.lowEventTracker.disarm()),this.getOptions=this.defineStep("get-options"),this.ceremony=this.withWindowLowEvents(this.defineStep("ceremony"),this.lowEventTracker),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType,...t?.ignoreAsInteraction?{ignoreAsInteraction:!0}:{}})}destroy(){this.lowEventTracker.destroy()}};function Li(n){let e=n.debug,t,i=(r,o)=>`[Corbado Observe SDK ${r}] ${o}`;return{reportTelemetry(r,o){if(t)try{t(r,o)}catch{}},setTelemetrySink(r){t=r},debug(r,...o){e&&console.log(i("DEBUG",r),...o)},info(r,...o){e&&console.log(i("INFO",r),...o)},warn(r,...o){e&&console.warn(i("WARN",r),...o)},error(r,...o){e&&console.error(i("ERROR",r),...o)},critical(r,...o){console.error(i("CRITICAL",r),...o)}}}var He=class extends g{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};var Be=class extends g{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}trigger(e,t){super.trigger(e,t)}destroy(){this.lowEventTracker?.destroy(),this.identifierLowEventTracker?.destroy()}};var qe=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Ne=class extends g{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,r)=>{this.trigger(i,r)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,r)=>{this.trigger(i,r)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Ue=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType,entry:t.entry})}};var Ve=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:r,actor:o}=$r(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:r,actor:o})}};function $r(n,e){let t={...n},i=o=>{try{e.getLogger().warn(`SSO login: unsupported ${o}; omitted from telemetry`)}catch{}},r=t.organizationDomain;return r!==void 0&&(typeof r!="string"||r.includes("@")||r.length>253)&&(delete t.organizationDomain,i("organizationDomain")),t.actor!==void 0&&t.actor!=="user"&&t.actor!=="system"&&(delete t.actor,i("actor")),t}var Ke=class extends g{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new A(e.getLogger(),this.lowEventSink("input","otp"),this.lowEventSink("input-group","otp"))),t.inputHtmlFields?.length?this.setInputFields(t.inputHtmlFields):t.inputHtmlField&&this.lowEventTracker?.setFields([t.inputHtmlField],!1),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending())}setInputFields(e){this.lowEventTracker?.setFields(e)}destroy(){this.lowEventTracker?.destroy()}};var We=class extends g{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var $e=class extends g{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};var Ge=class{constructor(e,t){this.logger=e;this.sink=t}trackers=new Map;destroyed=!1;setFields(e){if(this.destroyed)return;let t=new Set(e);for(let[i,r]of this.trackers)t.has(i)||(this.safe(()=>r.destroy()),this.trackers.delete(i));for(let i of t)this.trackers.has(i)||this.safe(()=>this.trackers.set(i,new k(this.logger,i,this.sink())))}capturePrefill(e=!1){for(let t of this.trackers.values())this.safe(()=>t.capturePrefill(e))}flushPending(){for(let e of this.trackers.values())this.safe(()=>e.flushPending())}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.trackers.values())this.safe(()=>e.destroy());this.trackers.clear()}}safe(e){try{e()}catch(t){this.logger.error("Form input binding failed",t)}}};var yt=50,Gr=6e4,Qr=40,jr=/^[A-Za-z0-9._-]+$/,Qe=class extends g{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(Yr(e,t),zr(e,t)),this.inputBinding=this.createLowCollector(()=>new Ge(e.getLogger(),()=>this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.inputBinding?.flushPending()),t?.inputHtmlFields?.length&&this.setInputFields(t.inputHtmlFields)}setInputFields(e){this.inputBinding?.setFields(e)}destroy(){this.inputBinding?.destroy()}};function zr(n,e){let t=e?.startedAt;if(t===void 0)return;let i=Date.now();if(typeof t!="number"||!Number.isFinite(t)||t>i||i-t>Gr){se(n,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function Yr(n,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:se(n,"Form: missing name; the form will not be counted");let r=e?.fields;if(r===void 0)return t;if(!Array.isArray(r))return se(n,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=r.filter(s=>typeof s=="string"&&s.length<=Qr&&jr.test(s));return o.length<r.length&&se(n,"Form: unsupported field names omitted from telemetry"),o.length>yt&&se(n,`Form: more than ${yt} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,yt)),t}function se(n,e){try{n.getLogger().warn(e)}catch{}}function vt(n,e,t){if(n===null||typeof n!="object")return n;try{let i={...n};i.purpose===void 0&&e.purpose!==void 0&&(i.purpose=e.purpose),i.storage===void 0&&e.storage!==void 0&&(i.storage=e.storage),i.trustName===void 0&&e.trustName!==void 0&&(i.trustName=e.trustName);for(let[r,o]of[["bindingReference",255],["trustName",128]])if(typeof i[r]=="string"&&[...i[r]].length>o){delete i[r];try{t.getLogger().debug(`Trusted device: omitted ${r} exceeding ${o} characters`)}catch{}}return i}catch{return n}}function je(n,e,t){return{...n,start:(i,r)=>n.start(vt(i,e,t),r),finished:(i,r)=>n.finished(vt(i,e,t),r)}}var ze=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=Fi(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=this.checkStep("get-options",i,e),this.ceremony=this.checkStep("ceremony",i,e),this.postResponse=this.checkStep("post-response",i,e),this.subflowStart({explicitSpecType:t.explicitSpecType,actor:"system",ignoreAsInteraction:!0})}checkStep(e,t,i){let r=this.defineStep(e,!0);return{...je(r,t,i),errorTyped:(o,s)=>{r.errorTyped(vt({code:o?.code,error:N(o?.error)},t,i),s)}}}},Ye=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=Fi(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=je(this.defineStep("get-options"),i,e),this.ceremony=je(this.defineStep("ceremony"),i,e),this.postResponse=je(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function Fi(n,e){let t={...n},i=r=>{try{e.getLogger().warn(`Trusted device: missing or unsupported ${r}; omitted from telemetry`)}catch{}};return t.purpose!=="additional-verification"&&t.purpose!=="mfa-exemption"&&(delete t.purpose,i("purpose")),["cookie","indexeddb","localstore","sessionstore"].includes(t.storage)||(delete t.storage,i("storage")),t}var Je=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...r}=t;this.subflowStart(r),i&&(this.lowEventTracker=this.createLowCollector(()=>new k(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Jr="/inline/injected/webauthn-listeners.js",Ri=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,Xr=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,Zr=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,Di=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,en=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,tn=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,rn=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,St=()=>Object.keys(window._sentryDebugIds??{}),bt=n=>{try{n()}catch(e){return String(e?.stack??"")}return""},Ai=()=>bt(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),nn=()=>{let n=Object.getOwnPropertyDescriptor(navigator.credentials??{},"get");if(!n?.get||!n.set||n.configurable)return!1;let e=()=>{},t=n.get.call({_get:e});return t===e||typeof t=="function"&&t===n.get.call({})&&!Function.prototype.toString.call(t).includes("[native code]")},wt=(...n)=>{let e=navigator.credentials;return e?n.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},on=()=>[navigator.credentials?.get,...wt("get","_get")].some(n=>typeof n=="function"&&n.name==="getWebAuthnCredential"),sn=()=>{let n=document.documentElement,e=document.adoptedStyleSheets;if(!n||typeof n.getAnimations!="function"||typeof e?.push!="function"||n.getAnimations().length>0)return!1;let t=new CSSStyleSheet;t.replaceSync(":where(:root){animation:bitwardenfill 1s 1000s paused}"),e.push(t);try{let i=n.getAnimations().filter(r=>r.animationName==="bitwardenfill");return i.forEach(r=>r.cancel()),i.length>0}finally{let i=e.indexOf(t);i>=0&&e.splice(i,1)}},an,ln=()=>an??=sn(),dn=()=>{let n=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;if(typeof n!="function"||!Object.prototype.hasOwnProperty.call(n,Symbol.hasInstance))return!1;let e=n[Symbol.hasInstance]({});return e instanceof Promise?(e.catch(()=>{}),!0):!1},pn=()=>{let n={get nodeType(){throw new Error("probe")}};return bt(()=>MutationObserver.prototype.observe.call(null,n))},un=()=>{let n=new Error("probe"),e=[],t={get nodeType(){return e.push("nodeType"),1},get ownerDocument(){throw e.push("ownerDocument"),n}};try{MutationObserver.prototype.observe.call(null,t)}catch(i){return i===n&&e.join()==="nodeType,ownerDocument"}return!1},cn=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...wt("get","_get","create")].some(e=>typeof e=="function"&&tn.test(Function.prototype.toString.call(e))),fn=()=>{let n=document;for(;n;){if(n.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;n=n.activeElement?.shadowRoot}return!1},hn=()=>{let n=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...wt("get","_get"),n?.isConditionalMediationAvailable,n?._isConditionalMediationAvailable,n?.isUserVerifyingPlatformAuthenticatorAvailable,n?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&rn.test(Function.prototype.toString.call(t)))},gn=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:nn},{name:"1password",signal:"Sentry debug id",test:()=>St().some(n=>n.includes(Jr))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:on},{name:"bitwarden",signal:"autofill keyframes",test:ln},{name:"dashlane",signal:"injected script tag",test:()=>document.querySelector('script[src*="-extension://"][src*="/dashlane-"][src$="-page-script.js"]')!==null},{name:"dashlane",signal:"PublicKeyCredential hasInstance trap",test:dn},{name:"dashlane",signal:"page script stack",test:()=>Ri.test(Ai())||typeof HTMLDialogElement<"u"&&Ri.test(bt(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>Xr.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>Zr.test(Ai())},{name:"keeper",signal:"override source",test:cn},{name:"keeper",signal:"field lock",test:()=>document.querySelector("[data-keeper-lock-id]")!==null},{name:"lastpass",signal:"passkey override",signedIn:!0,test:()=>typeof window.__nativeCredentialsGet=="function"},{name:"lastpass",signal:"icon root",test:fn},{name:"nordpass",signal:"observer proxy stack",test:()=>Di.test(pn())},{name:"nordpass",signal:"observer read order",test:un},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>St().some(n=>en.test(n))},{name:"nordpass",signal:"Sentry debug id",test:()=>St().some(n=>Di.test(n))},{name:"protonpass",signal:"WebAuthn override source",test:hn},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function mn(){return typeof window>"u"||typeof document>"u"?[]:gn.map(({name:n,signal:e,signedIn:t,test:i})=>{try{return{name:n,signal:e,signedIn:t,matched:i()}}catch(r){return{name:n,signal:e,signedIn:t,matched:!1,error:r}}})}function yn(){let n=new Map;for(let{name:e,signedIn:t,matched:i}of mn()){if(!i)continue;let r=n.get(e)??{name:e};t&&(r.signedIn=!0),n.set(e,r)}return[...n.values()]}function Mi(n){return yn()}var _i=3e3,vn=500,Sn=6,bn=1e3,Xe=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),_t(0))this.sampleAfter(_i);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(_i)};this.removers.push(C(0,"load",o,{once:!0}))}let r=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=Sn&&r(),this.sampleAfter(vn))});this.removers.push(r)}detected=new Map;timers=new Set;idleCallbacks=new Set;sampledFields=new WeakSet;focusSamples=0;removers=[];destroyed=!1;reportedCounts=new Map;getDetected(){return[...this.detected.values()]}takeReport(e){if(!(!this.isEnabled()||this.detected.size<=(this.reportedCounts.get(e)??0)))return this.reportedCounts.set(e,this.detected.size),this.getDetected().map(({name:t})=>({name:t}))}destroy(){this.destroyed=!0;for(let e of this.removers)e();for(let e of this.timers)clearTimeout(e);this.timers.clear();for(let e of this.idleCallbacks)cancelIdleCallback(e);this.idleCallbacks.clear()}sampleAfter(e){let t=setTimeout(()=>{this.timers.delete(t),this.sampleWhenIdle()},e);this.timers.add(t)}sampleWhenIdle(){if(typeof requestIdleCallback!="function"){this.sample();return}let e=requestIdleCallback(()=>{this.idleCallbacks.delete(e),this.sample()},{timeout:bn});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=Mi(0);for(let t of e){let i=this.detected.get(t.name);(!i||t.signedIn&&!i.signedIn)&&this.detected.set(t.name,t)}}catch(e){this.logger.error("Failed to detect password manager extensions",e)}}};var wn="cbo_xs",qi="1",Tn=20;var En=/^[A-Za-z0-9._~-]{1,128}$/,In=1e3,kn=300*1e3,Cn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,xn=/^[A-Za-z0-9_-]{1,64}$/,On=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/,Hi=/^\d{1,15}$/,Pn=1e9,Bi=1e3,Ln=1e5;function Tt(n){return typeof n=="string"&&En.test(n)}function Fn(n){let e=n.split("."),[t,i,r,o]=e;if(e.length<4||t!==qi||!i||!Cn.test(i)||!r||!Hi.test(r)||!o||!Hi.test(o)||Number(o)>Pn)return;let s=e.length>4?e.slice(4).join("."):void 0;if(!(s!==void 0&&!Tt(s)))return{sessionId:i.toLowerCase(),lastActiveAt:Number(r),seqMark:Number(o),...s!==void 0&&{context:s}}}function Rn(n){let e=[qi,n.sessionId,String(Math.floor(n.lastActiveAt)),String(Math.floor(n.seqMark))];return n.context!==void 0&&e.push(n.context),e.join(".")}function Dn(n,e){let t=n.trim().toLowerCase().replace(/^\./,""),i=e.toLowerCase();if(On.test(t))return i===t||i.endsWith(`.${t}`)?t:void 0}var Ze=class n{constructor(e,t,i,r,o){this.name=e;this.domain=t;this.jar=i;this.contextJar=r;this.deps=o}enabled=!0;reservedFor;reservedMark=0;highestSeen=0;lastWriteAt=0;context;static create(e){try{if(typeof document>"u"||typeof window>"u")return;if(!xn.test(e.projectId)){e.logger.debug("Cross-origin session off: project id is not cookie-safe");return}let t=e.scope?e.scope():qt(0);if(!t.https){e.logger.debug("Cross-origin session off: page is not served over HTTPS");return}let i=Dn(e.cookieDomain,t.hostname);if(!i){e.logger.warn(`Cross-origin session off: "${e.cookieDomain}" is not the page's domain or a parent of it`),e.report("info","cross-origin session: cookieDomain does not match the page");return}let r=e.jar??ne(0),o=e.jar??ne(0);return new n(`${wn}_${e.projectId}`,i,r,o,e)}catch(t){e.logger.error("Cross-origin session setup failed",t);return}}isEnabled(){return this.enabled}stop(){this.enabled=!1}boot(e,t=Date.now()){if(this.enabled)try{let i=this.read(this.jar,t),r=e.sessionId,o=!1;i&&i.sessionId!==r&&(!r||e.lastActiveAt<=0||i.lastActiveAt>e.lastActiveAt)&&(r=i.sessionId,o=!0);let s=o?i?.seqMark??0:e.seq;if(r){let a=this.sync(this.jar,i,r,s,t,!0,!1);s=a.seq,this.isStored(a.value)||(this.enabled=!1,this.deps.logger.debug("Cross-origin session off: the cookie could not be stored"),this.deps.report("info","cross-origin session: cookie not stored"))}return{sessionId:r,seq:s,adopted:o}}catch(i){this.enabled=!1,this.deps.logger.error("Cross-origin session boot failed",i),this.deps.report("error","cross-origin session: boot failed");return}}claim(e,t,i=Date.now()){if(!this.enabled||!e)return t;try{let r=this.read(this.jar,i);this.follow(e);let o=r?.sessionId===e,s=o?this.plausibleMark(r.seqMark,t):void 0;if(s!==void 0&&(this.highestSeen=Math.max(this.highestSeen,s)),r&&!o){if(t<this.reservedMark)return t;let d=Math.max(t,this.highestSeen)+Bi;return this.reservedMark=d+Bi,this.highestSeen=this.reservedMark,d}let a=t>=this.reservedMark||s!==void 0&&s>this.reservedMark;return!a&&i-this.lastWriteAt<In?t:this.sync(this.jar,r,e,t,i,a,!1).seq}catch(r){return this.deps.logger.error("Cross-origin session cookie update failed",r),t}}reset(e,t=Date.now()){if(!(!this.enabled||!e))try{this.reservedFor=void 0,this.follow(e),this.sync(this.jar,this.read(this.jar,t),e,0,t,!0,!0)}catch(i){this.deps.logger.error("Cross-origin session cookie reset failed",i)}}setContext(e,t,i,r=Date.now()){if(!(!this.enabled||!e))try{let o=this.read(this.contextJar,r);return this.follow(e),this.context=i,this.sync(this.contextJar,o,e,t,r,t>=this.reservedMark,!0).seq}catch(o){this.deps.logger.error("Cross-origin session context update failed",o);return}}getContext(e,t=Date.now()){if(!(!this.enabled||!e)){try{let i=this.read(this.contextJar,t);if(i?.sessionId===e)return this.reservedFor===e&&(this.context=i.context),i.context}catch(i){this.deps.logger.error("Cross-origin session context read failed",i)}return this.reservedFor===e?this.context:void 0}}follow(e){this.reservedFor!==e&&(this.reservedFor=e,this.reservedMark=0,this.highestSeen=0,this.context=void 0)}plausibleMark(e,t){if(e-t>Ln){this.deps.report("info","cross-origin session: implausible seq mark ignored");return}return e}sync(e,t,i,r,o,s,a){this.follow(i);let d=t?.sessionId===i,p=d?this.plausibleMark(t.seqMark,r):void 0;p!==void 0&&(this.highestSeen=Math.max(this.highestSeen,p)),d&&!a&&(this.context=t.context);let l=r,u;s?(l=Math.max(r,p??0,this.highestSeen),u=l+Tn):u=Math.max(this.reservedMark,this.highestSeen,r);let f=Rn({sessionId:i,lastActiveAt:o,seqMark:u,...this.context!==void 0&&{context:this.context}});return this.write(e,f),s&&(this.reservedMark=u),this.highestSeen=Math.max(this.highestSeen,u),this.lastWriteAt=o,{seq:l,value:f}}maxAgeSeconds(){return Math.max(60,Math.ceil(this.deps.inactivityMs()/1e3))}write(e,t){e.write(`${this.name}=${t}; Domain=${this.domain}; Path=/; Max-Age=${this.maxAgeSeconds()}; SameSite=Lax; Secure`)}rawValues(e){let t=`${this.name}=`;return e.read().split(";").map(i=>i.trim()).filter(i=>i.startsWith(t)).map(i=>i.substring(t.length))}isStored(e){try{return this.rawValues(this.jar).includes(e)}catch{return!1}}read(e,t){let i=this.deps.inactivityMs(),r;for(let o of this.rawValues(e)){let s=Fn(o);s&&t-s.lastActiveAt<i&&s.lastActiveAt<=t+kn&&(!r||s.lastActiveAt>r.lastActiveAt)&&(r=s)}return r}};var Et={name:ki,version:Ci},An=/^[0-9A-Za-z.+_-]{1,32}$/;function Mn(n,e){return n===void 0?Et:typeof n=="string"&&An.test(n)?{...Et,integrationVersion:n}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),Et)}var It="cbo_session_id",et="cbo_session",x="cbo_seq",Ni="cbo_experiments",Ui="cbo_data_policy",_n=255,Hn=/^[A-Za-z0-9_-]+$/,Bn=128,qn=256,Vi=1e3,Nn=/^[a-z][a-z0-9_-]{0,31}$/,Ki=/^[A-Za-z0-9_-]{1,16}$/,Un=64,Vn=32,Kn=50,Wn="cbo_seq",Wi=1e3,$i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,tt=class n{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Li({debug:this.options.debug});let t=new we(this.logger),i=new Ee(this.logger),r=e.storage==="cookie",o=r?new Te(this.logger,e.cookieDomain):void 0;bi(e.projectId,t,i,o,this.logger);let s=e.projectId,a=c=>new be(c,s);this.seqLockName=R(Wn,s),this.sessionStorage=a(i),this.persistentStorage=a(t),this.storage=a(o??t),this.configOverrides={...e.sdkConfig,...e.sdkConfig?.retry&&{retry:{...e.sdkConfig.retry}},...e.sdkConfig?.flushOnFlowTypeFinished&&{flushOnFlowTypeFinished:[...e.sdkConfig.flushOnFlowTypeFinished]},...e.sdkConfig?.sourcePathQueryAllow&&{sourcePathQueryAllow:[...e.sdkConfig.sourcePathQueryAllow]}},this.fixedData=ti(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd);let d=Object.keys(b).every(c=>this.configOverrides[c]!==void 0)&&Object.keys(b.retry).every(c=>this.configOverrides.retry?.[c]!==void 0);d||(this.configManager=new xe(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let p=this.configManager?.initialConfig;this.config=at(p,this.configOverrides),!d&&!p&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!d&&!p&&e.deviceInfoCollectorTimeout!=null&&this.configOverrides.deviceInfoCollectorTimeoutMs===void 0&&(this.config={...this.config,deviceInfoCollectorTimeoutMs:e.deviceInfoCollectorTimeout}),e.apiBaseUrl!==""&&(/^https?:\/\//.test(e.apiBaseUrl)||(this.logger.critical(`Invalid apiBaseUrl: URL must start with http:// or https:// (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: missing http(s) scheme")),e.apiBaseUrl.endsWith("/")&&(this.logger.critical(`Invalid apiBaseUrl: URL must not have a trailing slash (got: "${e.apiBaseUrl}")`),this.reportTelemetry("error","invalid apiBaseUrl: trailing slash")));let l=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${l}`);let u=new he({logger:this.logger,url:l});this.crossOrigin=this.createCrossOriginSession(),this.sessionId=this.resolveSession(),this.queue=new ye(this.logger,u,this.sessionId,Mn(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:R(lt,s),getDataPolicy:()=>this.dataPolicy,getCrossOriginSession:c=>this.crossOriginSessionMeta(c),fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:c=>this.attachUndeliveredDeviceInfo(c),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((c,v)=>this.reportTelemetry(c,v));try{this.getWindowObserver()}catch(c){this.logger.error("Failed to attach page low-event observer",c)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Xe(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(c){this.logger.error("Failed to start password manager detection",c)}let f=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let c of f)this.telemetry(c.level,c.message);let h=new ve(this.logger,this.storage,r?"cookie":"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(c,v)=>this.telemetry(c,v),this.fixedData?.privateMode??!0);this.deviceCollector=h;let m=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new Se(this.logger,h,Math.max(1,m),m,{timing:()=>this.config.deviceInfoTiming,emit:(c,v)=>this.telemetry(c,v)},()=>this.queue.notifyDeviceInfo()),this.deviceInfoManager.start(),this.experiments=this.loadPersistedExperiments(),e.experiments&&this.setExperiments(e.experiments),this.dataPolicy=this.loadPersistedDataPolicy(),e.dataPolicy!==void 0&&this.setDataPolicy(e.dataPolicy),this.configManager?.start(c=>this.handleConfig(c))}logger;queue;sessionId;storage;sessionStorage;persistentStorage;seqLockName;config;configManager;configOverrides;fixedData;deviceInfoManager;deviceCollector;eventTabId;seq=0;lastActivityWriteAt=0;experiments={};dataPolicy;telemetryReporting=!1;telemetryReady=!1;reportedTelemetryKeys=new Set;pendingSelfTelemetry=[];probePageId;probeSeqs=new Map;windowObserver;passwordManagerSampler;crossOrigin;crossOriginAdoptedId;getWindowObserver(){return this.windowObserver??=new ue(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=at(e,this.configOverrides);t.sessionContinuity||=this.config.sessionContinuity,t.durableOutbox||=this.config.durableOutbox,this.config=t,this.queue.updateConfig(this.config)}getLogger(){return this.logger}applicationTag(){return this.options.applicationId?{applicationId:this.options.applicationId.toLowerCase()}:{}}setExperiment(e,t){this.setExperiments({[e]:t})}setExperiments(e){try{if(!e||typeof e!="object")return;let t=!1;for(let[i,r]of Object.entries(e)){if(!n.isValidExperimentKey(i)||!n.isValidExperimentVariant(r)){this.logger.debug(`Ignoring invalid experiment assignment "${String(i)}"`);continue}this.experiments[i]!==r&&(this.experiments[i]=r,t=!0)}t&&this.persistExperiments()}catch(t){this.logger.error("Failed to set experiments",t)}}clearExperiment(e){try{Object.prototype.hasOwnProperty.call(this.experiments,e)&&(delete this.experiments[e],this.persistExperiments())}catch(t){this.logger.error("Failed to clear experiment",t)}}clearExperiments(){try{if(Object.keys(this.experiments).length===0)return;this.experiments={},this.persistExperiments()}catch(e){this.logger.error("Failed to clear experiments",e)}}getExperiments(){return{...this.experiments}}getPersistentStorage(){return this.persistentStorage}getSdkConfig(){return Object.freeze({version:this.config.version,aap:this.config.aap,rawErrors:this.config.rawErrors})}setDataPolicy(e){try{if(!n.isValidDataPolicy(e)){this.logger.debug(`Ignoring invalid data policy code "${String(e)}"`);return}this.dataPolicy!==e&&(this.dataPolicy=e,this.persistDataPolicy())}catch(t){this.logger.error("Failed to set data policy",t)}}getDataPolicy(){return this.dataPolicy}static isValidDataPolicy(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=_n}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Ui);return n.isValidDataPolicy(e)?e:void 0}catch(e){this.logger.debug("Failed to load persisted data policy",e);return}}persistDataPolicy(){try{if(this.dataPolicy===void 0)return;this.persistentStorage.setItem(Ui,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Bn&&Hn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=qn}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Ni);if(!e||typeof e!="object")return{};let t={};for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return t}catch(e){return this.logger.debug("Failed to load persisted experiments",e),{}}}persistExperiments(){try{this.persistentStorage.setItem(Ni,this.experiments)}catch(e){this.logger.debug("Failed to persist experiments",e)}}resolveExperiments(e){let t={...this.experiments};if(e&&typeof e=="object")for(let[i,r]of Object.entries(e))n.isValidExperimentKey(i)&&n.isValidExperimentVariant(r)&&(t[i]=r);return Object.keys(t).length>0?t:void 0}isTrackingBlocked(){return typeof navigator>"u"?!1:Ii(Nt(0))}createCrossOriginSession(){let e=this.fixedData?.crossOriginSession;if(e)try{return this.isTrackingBlocked()?void 0:Ze.create({projectId:this.options.projectId,cookieDomain:e.cookieDomain,logger:this.logger,inactivityMs:()=>this.config.sessionInactivityMs,report:(t,i)=>this.reportTelemetry(t,i)})}catch(t){this.logger.error("Failed to set up the cross-origin session",t);return}}readLocalSessionActivity(){let e=new Map;try{let t=this.persistentStorage.getItem(et);t?.id&&typeof t.lastActiveAt=="number"&&e.set(t.id,t.lastActiveAt);let i=this.sessionStorage.getItem(It);i&&typeof i=="object"&&i.id&&typeof i.lastActiveAt=="number"&&e.set(i.id,Math.max(e.get(i.id)??0,i.lastActiveAt))}catch(t){this.logger.error("Failed to read local session activity",t)}return e}bootCrossOriginSession(e){try{this.crossOriginAdoptedId=void 0;let t=Date.now(),i=this.config.sessionContinuity,r=i?Math.max(this.seq,this.persistentStorage.getItem(x)??0):this.seq,o=this.crossOrigin?.boot({sessionId:this.sessionId,lastActiveAt:this.sessionId&&e.get(this.sessionId)||0,seq:r},t);if(!o||!o.sessionId)return;o.adopted&&(this.sessionId=o.sessionId,this.crossOriginAdoptedId=o.sessionId,i?this.persistContinuitySession(o.sessionId,t):this.persistPerTabSession(o.sessionId,t),this.logger.debug("Adopted cross-origin session id",o.sessionId)),this.seq=o.seq,i&&this.persistentStorage.setItem(x,o.seq)}catch(t){this.logger.error("Failed to apply the cross-origin session",t)}}resolveSession(){if(!this.crossOrigin)return this.resolveSessionId();let e=this.readLocalSessionActivity();return this.sessionId=this.resolveSessionId(),this.bootCrossOriginSession(e),this.sessionId}crossOriginSessionMeta(e){if(this.crossOrigin?.isEnabled())return e&&e===this.crossOriginAdoptedId?"adopted":"own"}resolveSessionId(){try{if(this.config.sessionContinuity)return this.getContinuitySessionId();let e=Date.now(),t=this.readPerTabSession();if(t&&e-t.lastActiveAt<this.perTabInactivityMs(t))return this.persistPerTabSession(t.id,e),this.seq=0,t.id;let i=S();return this.persistPerTabSession(i,e),this.seq=0,this.logger.debug("Created session id",i),i}catch(e){return this.logger.error("Failed to get session id",e),this.reportTelemetry("error","failed to get session id"),""}}getContinuitySessionId(){let e=Date.now(),t=this.persistentStorage.getItem(et);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(x)??0,t.id;if(!t?.id){let r=this.readPerTabSession();if(r&&e-r.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(r.id,e),this.persistentStorage.setItem(x,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",r.id),r.id}let i=S();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(x,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem(et,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(It);if(e){if(typeof e=="string")return $i.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return $i.test(e.id)?e:void 0}}persistPerTabSession(e,t){this.lastActivityWriteAt=t;let i=this.configOverrides.sessionInactivityMs!==void 0||this.config.version?this.config.sessionInactivityMs:this.readPerTabSession()?.inactivityMs;this.sessionStorage.setItem(It,{id:e,lastActiveAt:t,...i===void 0?{}:{inactivityMs:i}})}perTabInactivityMs(e){return this.configOverrides.sessionInactivityMs!==void 0?this.config.sessionInactivityMs:e.inactivityMs??this.config.sessionInactivityMs}nextSeq(){if(!this.config.sessionContinuity){let i=Date.now();this.sessionId&&i-this.lastActivityWriteAt>=Wi&&this.persistPerTabSession(this.sessionId,i);let r=this.crossOrigin?this.crossOrigin.claim(this.sessionId,this.seq,i):this.seq;return this.seq=r+1,r}let e=()=>{let i=Date.now(),r=this.persistentStorage.getItem(et),o=!1;if(!r?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(r?.id)i-this.lastActivityWriteAt>=Wi&&this.persistContinuitySession(r.id,i),r.id!==this.sessionId&&(this.sessionId=r.id,this.queue.setSessionId(r.id),o=!0);else{let d=S();this.persistContinuitySession(d,i),this.persistentStorage.setItem(x,0),this.sessionId=d,this.queue.setSessionId(d),this.seq=0,o=!0}let s=this.persistentStorage.getItem(x);o&&(this.seq=typeof s=="number"?s:0);let a=typeof s=="number"&&s>this.seq?s:this.seq;return this.crossOrigin&&(a=this.crossOrigin.claim(this.sessionId,a,i)),this.seq=a+1,this.persistentStorage.setItem(x,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!si(0)?e():ge(0,this.seqLockName,e,{timeoutMs:t,onTimeout:()=>{this.logger.warn(`Sequence Web Lock acquisition timed out after ${t}ms; using fallback`),this.reportTelemetry("info",`seq web lock timeout; using fallback, ${t}ms`)}})}resolveTrackingSourcePath(){if(!(typeof window>"u"))return Bt(0,this.config.sourcePathQuery,this.config.sourcePathQueryAllow)}resolveEventTabId(){return this.eventTabId===void 0&&(this.eventTabId=this.deviceCollector.getTabId()),this.eventTabId}trackSubflowStarted(e,t,i,r){let o={subflowType:e,...t};this.track("subflow_started",o,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{id:r,subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowTrigger(e,t,i){let r={subflowType:e,...t};this.track("subflow_trigger",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}trackSubflowStepStarted(e,t,i,r,o){let s={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier,ignoreAsInteraction:o};this.track("subflow_step_started",s,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepFinished(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier};this.track("subflow_step_finished",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowStepError(e,t,i,r){let o={subflowType:e,stepName:t,stepData:i,identifier:r?.identifier};this.track("subflow_step_error",o,r?.userReference,void 0,void 0,r?.explicitTimestamp,r?.experiments,{subflowStartEventId:r?.subflowStartEventId,sessionId:r?.captureSessionId,initiator:r?.initiator})}trackSubflowError(e,t,i){let r={subflowType:e,stepData:t};this.track("subflow_error",r,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}async track(e,t,i,r,o,s,a,d){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=s??Date.now(),l=d?.id??S(),u=d?.sessionId??this.sessionId,f=this.nextSeq(),h=typeof f=="number"?f:await f,m=this.resolveTrackingSourcePath(),c={type:"predefined",name:e,id:l,timestamp:p,seq:h,data:t,user:i,contexts:o,tags:r,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:ie(),initiator:d?.initiator,trackingSourcePath:m??"",subflowStartEventId:d?.subflowStartEventId,tabId:this.resolveEventTabId()}},v=this.deviceInfoManager.getForEvent();v&&(c.deviceInfo=v),this.logger.debug(`Track: ${e}`,JSON.stringify(c,null,2));let y=this.passwordManagerSampler?.takeReport(u);y&&(c.passwordManagers=y),this.queue.enqueue(c,u)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,r,o){try{let s=S(),a=this.sessionId,d={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,d,r,o?.explicitTimestamp,i,{id:s,sessionId:a}),this.flowHandle(s,a)}catch(s){return this.logger.warn("Failed to start flow",s),{enrich:async()=>{}}}}flowDecided(e,t,i){this.track("flow_decided",e,void 0,t,void 0,void 0,i)}conversion(e,t,i){let{userId:r,identifier:o,crossEnvironmentTransactionID:s,...a}=e,d={userId:r,identifier:o,crossEnvironmentTransactionID:s},p={...this.options.defaultTags,...this.applicationTag(),...t};this.track("conversion",a,d,p,void 0,void 0,i)}flowFinished(e,t,i){try{let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o},d=S(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:d,sessionId:p}),this.flowHandle(d,p)}catch(r){return this.logger.warn("Failed to finish flow",r),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(r){this.logger.warn("Failed to enrich flow",r)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}setUser(e){this.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}setFlowTags(e,t){try{if(!e||typeof e!="object"){this.logger.warn("setFlowTags: ignoring non-object tags");return}let i={};for(let[o,s]of Object.entries(e)){if(o===""||typeof s!="string"){this.logger.warn(`setFlowTags: ignoring invalid tag "${o}"`);continue}i[o]=s}if(Object.keys(i).length===0)return;let r={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(r.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(r.expFol=t.expandToFollowing),this.track("flow_enriched",r,void 0,i)}catch(i){this.logger.warn("Failed to set flow tags",i)}}authMethodsDecisionStarted(e,t,i,r){this.track("auth_method_decision_started",e,void 0,t,void 0,r?.explicitTimestamp,i)}authMethodsDecisionFinished(e,t,i){this.track("auth_method_decision_finished",e,void 0,t,void 0,void 0,i)}authDecisionStarted(e,t,i){this.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}authDecisionFinished(e,t,i){this.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}enqueueLowEvent(e,t){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping low event "${e.lowType}" for blocked user agent.`);return}this.queue.enqueueLow({...e,captureSeq:e.captureSeq??P(),captureVersion:1,pageId:e.pageId??ie()},t)}catch(i){this.logger.error(`Failed to process low event "${e.lowType}" before enqueue`,i)}}telemetry(e,t){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping telemetry for blocked user agent.");return}let i=typeof t=="string"?t:String(t);if(i.length===0)return;let r={id:S(),level:e,message:i.length>Vi?i.slice(0,Vi):i,ts:Date.now()};this.queue.enqueueTelemetry(r)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}probe(e){try{if(this.isTrackingBlocked()){this.logger.debug("Skipping probe for blocked user agent.");return}if(!e||typeof e!="object"||typeof e.kind!="string"||!Nn.test(e.kind)){this.logger.debug("Dropping probe with an invalid kind.");return}let t=e.payload;if(!t||typeof t!="object"){this.logger.debug(`Dropping probe "${e.kind}" without an object payload.`);return}let i=typeof e.pageId=="string"&&Ki.test(e.pageId)?e.pageId:this.defaultProbePageId(),r={id:S(),kind:e.kind,ts:typeof e.ts=="number"&&Number.isFinite(e.ts)?Math.round(e.ts):Date.now(),pageId:i,seq:this.nextProbeSeq(i),payload:t};typeof e.cfg=="string"&&Ki.test(e.cfg)&&(r.cfg=e.cfg);let o=Qn(e.ctx);o&&(r.ctx=o),this.queue.enqueueProbe(r)}catch(t){this.logger.error("Failed to process probe before enqueue",t)}}defaultProbePageId(){return this.probePageId??=Gn()}nextProbeSeq(e){let t=this.probeSeqs.get(e)??0;if(this.probeSeqs.delete(e),this.probeSeqs.set(e,t+1),this.probeSeqs.size>Vn){let i=this.probeSeqs.keys().next().value;i!==void 0&&this.probeSeqs.delete(i)}return t}logInfo(e){this.telemetry("info",e)}logError(e){this.telemetry("error",e)}attachUndeliveredDeviceInfo(e){try{let t=this.deviceInfoManager;if(!t?.hasUndelivered())return;let i=ie(),r=e.find(o=>o.meta?.pageId===i&&!o.deviceInfo);r&&(r.deviceInfo=t.takeUndelivered())}catch(t){this.logger.error("Failed to attach device info to batch",t)}}reportTelemetry(e,t){if(!this.telemetryReporting){this.telemetryReporting=!0;try{if(this.reportedTelemetryKeys.has(t)||this.reportedTelemetryKeys.size>=Kn)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}passkeyLoginFullOperation(e){return new Oe(this,e)}passkeyEnrollmentFullOperation(e){return new _e(this,e)}passkeyDeletionOperationFull(e){return new He(this,e)}passwordLoginFullOperation(e){return new Be(this,e)}passwordEnrollmentFullOperation(e){return new qe(this,e)}emailLinkOperationFull(e){return new Ae(this,e)}continueEmailLinkOperation(e){return new Me(this,e)}emailOtpOperationFull(e){return new Re(this,e)}smsOtpOperationFull(e){return new De(this,e)}totpOperationFull(e){return new Ke(this,e)}provideIdentifierOperationFull(e){return new Ne(this,e)}provideDataOperationFull(e){return new Je(this,e)}formOperationFull(e){return new Qe(this,e)}socialLoginOperationFull(e){return new Ue(this,e)}ssoLoginOperationFull(e){return new Ve(this,e)}appConfirmationOperationFull(e){return new We(this,e)}keySigningOperationFull(e){return new de(this,e)}keyRegistrationOperationFull(e){return new pe(this,e)}captchaOperationFull(e){return new $e(this,e)}trustedDeviceCheckOperationFull(e){return new ze(this,e)}trustedDeviceEnrollmentOperationFull(e){return new Ye(this,e)}async destroy(){if(this.crossOrigin?.stop(),this.configManager?.destroy(),this.passwordManagerSampler?.destroy(),this.windowObserver?.destroy(),this.deviceInfoManager.destroy(),this.config.td)try{await this.queue.flush("destroy")}catch(e){this.logger.error("Failed to flush queue during destroy",e)}this.queue.destroy()}getSessionId(){if(!this.sessionId){let e=this.resolveSession();e&&(this.sessionId=e,this.queue.setSessionId(e))}return this.sessionId||void 0}setCrossOriginContext(e){try{if(!this.crossOrigin)return!1;let t=e==null||e===""?void 0:e;if(t!==void 0&&!Tt(t))return this.logger.debug("Ignoring invalid cross-origin context (expected <= 128 chars of [A-Za-z0-9._~-])"),!1;let i=this.config.sessionContinuity?Math.max(this.seq,this.persistentStorage.getItem(x)??0):this.seq,r=this.crossOrigin.setContext(this.sessionId,i,t);return r===void 0?!1:(r>this.seq&&(this.seq=r,this.config.sessionContinuity&&this.persistentStorage.setItem(x,r)),!0)}catch(t){return this.logger.error("Failed to set the cross-origin context",t),!1}}getCrossOriginContext(){try{return this.crossOrigin?.getContext(this.sessionId)}catch(e){this.logger.error("Failed to read the cross-origin context",e);return}}resetSession(){let e=S();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(x,0)):this.persistPerTabSession(e,Date.now()),this.sessionId=e,this.seq=0,this.queue.setSessionId(e),this.crossOrigin?.reset(e),this.logger.debug(`Session reset: ${e}`),e}},$n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function Gn(){let n=new Uint8Array(16);try{crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t++)n[t]=Math.floor(Math.random()*256)}let e="";for(let t=0;t<n.length;t++)e+=$n[n[t]&63];return e}function Qn(n){if(!n||typeof n!="object")return;let e={};for(let t of["state","flowType","step"]){let i=n[t];typeof i=="string"&&i.length>0&&(e[t]=i.slice(0,Un))}return Object.keys(e).length>0?e:void 0}function it(n,e,t){let i=window.Corbado;i?.[e]&&(t(i[e]),delete window.Corbado[e])}function Gi(n,e){window.Corbado=e}var kt={};function Qi(n,e="default"){kt[e]=new tt(n)}function ji(n="default"){if(!kt[n])throw new Error(`Tracker ${n} not initialized (call Corbado.init() first)`);return kt[n]}function jn(n){for(let e of n)Qi(e[0],e[1])}var zi={};function Yi(n,e,t=[],i){let r=ji(n),o=r[e];if(typeof o!="function")return;let s=o.apply(r,t);i&&s&&typeof s=="object"&&(zi[i]=s)}function Ji(n,e,t=[]){let i=zi[n];if(!i)return;let r=e.split("."),o=i;for(let a=0;a<r.length-1;a++)if(o=o?.[r[a]],!o)return;let s=o[r[r.length-1]];typeof s=="function"&&s.apply(o,t)}function zn(n){for(let e of n)Yi(e[0],e[1],Array.isArray(e[2])?e[2]:[],e[3])}function Yn(n){for(let e of n)Ji(e[0],e[1],Array.isArray(e[2])?e[2]:[])}typeof window<"u"&&(it(0,"IQ",jn),it(0,"MQ",zn),it(0,"OQ",Yn),Gi(0,{init:Qi,get:ji,__dispatchMethod:Yi,__dispatchOp:Ji}));})();
|
|
5
5
|
/*! Bundled license information:
|
|
6
6
|
|
|
7
7
|
detectincognitojs/dist/detectIncognito.esm.js:
|