@corbado/observe 1.10.0 → 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/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var yt=0;function C(){if(yt===4294967295)throw new Error("Low-event capture sequence exhausted");return++yt}function vt(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"}}import{v7 as Wi}from"uuid";function M(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 Di={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}},Mi=1024,N=class extends Error{},Hi=["name","message","code","errors","stack"],Ni=/[^\x20-\x7E]/,B=n=>Object.prototype.toString.call(n).slice(8,-1),Bi=n=>n===null?"null":typeof n=="object"?B(n):typeof n,Ui=n=>n instanceof Error||B(n)==="Error"||B(n)==="DOMException";function wt(n){return Ni.test(n)?new TextEncoder().encode(n).byteLength:n.length}function H(n,e){let t=Di[n];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function bt(n={}){return{stack:n.stack===!0,maxStackFrames:H("maxStackFrames",n.maxStackFrames),depth:H("depth",n.depth),maxBreadth:H("maxBreadth",n.maxBreadth),maxValueLength:H("maxValueLength",n.maxValueLength),maxCauseDepth:H("maxCauseDepth",n.maxCauseDepth),maxBytes:H("maxBytes",n.maxBytes)}}function Tt(n,e={}){if(n===void 0)return;let t=bt(),i=r=>{let o=JSON.stringify(r);return o===void 0||wt(o)<=t.maxBytes};try{if(t=bt(e),t.maxBytes===0)return;let r=A(Bi(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 l={type:r,value:X(n,s,a)};if(i(l))return l}catch(l){if(!(l instanceof N))throw l}}let o={type:r,truncated:!0};return i(o)?o:void 0}catch{let r={type:"unserializable"};return i(r)?r:void 0}}function j(n,e){if(n.length>e.limits.maxBytes)throw new N;if(e.textBytes+=wt(JSON.stringify(n)),e.textBytes>e.limits.maxBytes)throw new N;return n}function X(n,e,t){if(++t.nodes>Mi)throw new N;let i=qi(n,e,t);return typeof i=="string"?j(i,t):i}function qi(n,e,t){switch(typeof n){case"string":return A(n,t.limits.maxValueLength);case"number":return Number.isFinite(n)?n:String(n);case"boolean":case"undefined":return n;case"bigint":case"symbol":return A(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`[${B(i)}]`;t.seen.add(i);try{return Ki(i,e,t)}finally{t.seen.delete(i)}}function A(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function St(n,e,t){let i=n.length>t;n=A(n,t);let r=n.split(`
1
+ var ft=0;function C(){if(ft===4294967295)throw new Error("Low-event capture sequence exhausted");return++ft}function ht(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"}}import{v7 as qi}from"uuid";function _(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 Li={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}},Ri=1024,B=class extends Error{},Fi=["name","message","code","errors","stack"],Ai=/[^\x20-\x7E]/,q=n=>Object.prototype.toString.call(n).slice(8,-1),Di=n=>n===null?"null":typeof n=="object"?q(n):typeof n,Mi=n=>n instanceof Error||q(n)==="Error"||q(n)==="DOMException";function yt(n){return Ai.test(n)?new TextEncoder().encode(n).byteLength:n.length}function H(n,e){let t=Li[n];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function gt(n={}){return{stack:n.stack===!0,maxStackFrames:H("maxStackFrames",n.maxStackFrames),depth:H("depth",n.depth),maxBreadth:H("maxBreadth",n.maxBreadth),maxValueLength:H("maxValueLength",n.maxValueLength),maxCauseDepth:H("maxCauseDepth",n.maxCauseDepth),maxBytes:H("maxBytes",n.maxBytes)}}function vt(n,e={}){if(n===void 0)return;let t=gt(),i=r=>{let o=JSON.stringify(r);return o===void 0||yt(o)<=t.maxBytes};try{if(t=gt(e),t.maxBytes===0)return;let r=A(Di(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 l={type:r,value:X(n,s,a)};if(i(l))return l}catch(l){if(!(l instanceof B))throw l}}let o={type:r,truncated:!0};return i(o)?o:void 0}catch{let r={type:"unserializable"};return i(r)?r:void 0}}function j(n,e){if(n.length>e.limits.maxBytes)throw new B;if(e.textBytes+=yt(JSON.stringify(n)),e.textBytes>e.limits.maxBytes)throw new B;return n}function X(n,e,t){if(++t.nodes>Ri)throw new B;let i=_i(n,e,t);return typeof i=="string"?j(i,t):i}function _i(n,e,t){switch(typeof n){case"string":return A(n,t.limits.maxValueLength);case"number":return Number.isFinite(n)?n:String(n);case"boolean":case"undefined":return n;case"bigint":case"symbol":return A(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`[${q(i)}]`;t.seen.add(i);try{return Hi(i,e,t)}finally{t.seen.delete(i)}}function A(n,e){return n.length>e?n.slice(0,e)+"\u2026":n}function mt(n,e,t){let i=n.length>t;n=A(n,t);let r=n.split(`
2
2
  `);if(r.length<=e+1)return A(n,t);let o=r.slice(0,e+1).join(`
3
3
  `),s=i?"[truncated]":`[+${r.length-e-1} frames]`;return A(`${o}
4
- ${s}`,t)}function Ki(n,e,t){let{limits:i}=t,r=B(n),o=p=>X(p,e-1,t);if(r==="Date")return Number.isNaN(n.getTime())?"[Invalid Date]":n.toISOString();if(r==="RegExp")return A(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 p=n,f=[];for(let m of p){if(f.length===i.maxBreadth)break;f.push(o(m))}return p.size>f.length&&f.push(`[+${p.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 p=n.slice(0,i.maxBreadth).map(o);return n.length>i.maxBreadth&&p.push(`[+${n.length-i.maxBreadth} more]`),p}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 p=n,f={type:o(p.type)};for(let m of["message","filename","lineno","colno"])m in p&&(f[m]=o(p[m]));return"error"in p&&p.error!=null&&(f.error=o(p.error)),f}let s=Object.create(null),a=n,l=Ui(n);if(l){for(let f of Hi){if(f==="stack"&&!i.stack)continue;let m=a[f];if(!(m==null||typeof m=="function")){if(f==="stack"){i.stack&&typeof m=="string"&&(s.stack=j(St(m,i.maxStackFrames,i.maxValueLength),t));continue}s[f]=o(m)}}let p=a.cause;p!=null&&typeof p!="function"&&(s.cause=Vi(p,e-1,t))}let d=0,c=Object.keys(a);for(let p of c){if(p in s||p==="stack"&&!i.stack||l&&p==="cause")continue;if(++d>i.maxBreadth){s["\u2026"]=`[+${c.length-i.maxBreadth} keys]`;break}let f=a[p];typeof f!="function"&&(s[j(p,t)]=p==="stack"&&typeof f=="string"?j(St(f,i.maxStackFrames,i.maxValueLength),t):o(f))}return!l&&r!=="Object"&&d===0?`[${r}]`:s}function Vi(n,e,t){if(typeof n!="object"||n===null)return X(n,e,t);if(t.causeBudget<=0)return j(`[${B(n)}]`,t);t.causeBudget--;try{return X(n,e,t)}finally{t.causeBudget++}}var $i=1500,h=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:C,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??C(),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,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=Wi(),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:Tt(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($i)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,d=a?.initiator??vt(this.operationName,l);t.arm(d,l==="passkey-cui"),o.start(s,d?{...a,initiator:d}: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=l=>this.captureOptions(l,i,r,o);return{start:(l,d)=>{i=this.startReference,r=this.captureSessionId,o=d?.initiator,this.subflowStepStarted(e,l,s(d),t)},finished:(l,d)=>{this.subflowStepFinished(e,l,s(d))},error:(l,d)=>{this.subflowStepError(e,{error:M(l)},s(d))},errorTyped:(l,d)=>{this.subflowStepError(e,l,s(d))}}}};function Et(n,e){if(e.explicitSpecType!==void 0)try{n.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var Z=class extends h{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:Et(e,t)})}},ee=class extends h{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:Et(e,t)})}};function ji(n){try{return decodeURIComponent(n.replace(/\+/g," "))}catch{return n}}function Gi(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 It(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)===""||Gi(ji(a),t)?o:`${a}=*`}).join("&")}`}function I(n,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function U(n){return document.visibilityState==="hidden"}function xt(n){return document.readyState==="complete"}function kt(n){return window.location.href}function Ct(n,e,t){let i=It(window.location.search,e,t);return`${window.location.pathname}${i}`}function Ot(n){return{hostname:window.location.hostname,https:window.location.protocol==="https:"}}function te(n){return typeof navigator>"u"?"":navigator.userAgent??""}async function Pt(n){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function Lt(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function Rt(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function Ft(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 At(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 _t(n){if(!(typeof navigator>"u"))return navigator.webdriver}function Dt(n){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}import{v7 as zi}from"uuid";var ze=(n,e,t)=>{let i=!1,r,o=null,s=null,a=()=>{s!==null&&(clearTimeout(s),s=null);let d=o;i=!1,o=null,d!==null&&n({...r===void 0?{}:{captureSeq:r},lowType:e,ts:d,durationMs:Date.now()-d})};return{extend:()=>{if(!i){let d=t?.();i=!0,o=Date.now(),r=d}s!==null&&clearTimeout(s),s=setTimeout(a,150)},flush:a}};function Mt(n,e,t){let i=[],r=(s,a,l)=>{let d=c=>t(a,()=>l(c));s.addEventListener(a,d),i.push(()=>s.removeEventListener(a,d))};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,l=a.from?.index,d=o.currentEntry?.index;a.navigationType==="traverse"&&typeof l=="number"&&typeof d=="number"&&l>=0&&d>=0&&d<l&&e.navigateBack()}),i}function Ht(n){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function Nt(n){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var Qi,G=()=>Qi??=zi(),ie=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=Mt(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=ze(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",C);scroll=ze(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",C);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=Ht(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=Nt(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??C(),sourceKind:"window",captureVersion:1,pageId:G()},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 Ji=(g=>(g.FlowStarted="flow_started",g.FlowDecided="flow_decided",g.FlowFinished="flow_finished",g.FlowReset="flow_reset",g.AuthMethodDecisionStarted="auth_method_decision_started",g.AuthMethodDecisionFinished="auth_method_decision_finished",g.FlowAutoFinished="flow_auto_finished",g.AuthDecisionStarted="auth_decision_started",g.AuthDecisionFinished="auth_decision_finished",g.SubflowStepStarted="subflow_step_started",g.SubflowStepFinished="subflow_step_finished",g.SubflowStepError="subflow_step_error",g.SubflowTrigger="subflow_trigger",g.SubflowError="subflow_error",g.SubflowStarted="subflow_started",g.SubflowFinished="subflow_finished",g.FlowEnriched="flow_enriched",g.Conversion="conversion",g))(Ji||{});var Qe="cbo_sdk_config",Ut="cbo_sdk_config_cache",qt="X-Corbado-Observe-Config",vo=500,bo=50,So=1e3,b={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}},Yi=1800*1e3,v={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:Yi,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 _(n,e,t){return Math.min(Math.max(n,e),t)}function D(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function R(n,e){return typeof n=="boolean"?n:e}function Bt(n,e){return typeof n=="string"?n:e}function Xi(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.length>0&&e.length<=b.flushOnFlowTypeFinished.maxNameLength).slice(0,b.flushOnFlowTypeFinished.maxEntries):[]}function Zi(n){return typeof n=="string"&&n.trim().toLowerCase()==="all"?"all":"allowlist"}function er(n){return Array.isArray(n)?n.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=b.sourcePathQueryAllow.maxKeyLength).slice(0,b.sourcePathQueryAllow.maxEntries):[]}function q(n){if(!n||typeof n!="object")return null;let e=n;return typeof e.version!="string"||e.version===""?null:Kt(e)}function Kt(n){let e=n.retry&&typeof n.retry=="object"?n.retry:{},t=_(D(e.baseDelayMs,v.retry.baseDelayMs),b.retryDelayMs.min,b.retryDelayMs.max);return{version:Bt(n.version,""),flushIntervalMs:_(D(n.flushIntervalMs,v.flushIntervalMs),b.flushIntervalMs.min,b.flushIntervalMs.max),durableOutbox:n.durableOutbox===!0,durableLowOutbox:n.durableLowOutbox===!0,beaconKeepalive:n.beaconKeepalive===!0,sessionContinuity:n.sessionContinuity===!0,sessionInactivityMs:_(D(n.sessionInactivityMs,v.sessionInactivityMs),b.sessionInactivityMs.min,b.sessionInactivityMs.max),seqLockTimeoutMs:_(D(n.seqLockTimeoutMs,v.seqLockTimeoutMs),b.seqLockTimeoutMs.min,b.seqLockTimeoutMs.max),tvc:R(n.tvc,v.tvc),tph:R(n.tph,v.tph),td:R(n.td,v.td),tlf:R(n.tlf,v.tlf),telemetry:R(n.telemetry,v.telemetry),flushOnTelemetry:n.flushOnTelemetry===!0,flushOnFlowTypeFinished:Xi(n.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:_(D(n.deviceInfoCollectorTimeoutMs,v.deviceInfoCollectorTimeoutMs),b.deviceInfoCollectorTimeoutMs.min,b.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:n.deviceInfoTiming===!0,rawErrors:R(n.rawErrors,v.rawErrors),pmd:R(n.pmd,v.pmd),aap:Bt(n.aap,""),sourcePathQuery:Zi(n.sourcePathQuery),sourcePathQueryAllow:er(n.sourcePathQueryAllow),retry:{maxAttempts:_(D(e.maxAttempts,v.retry.maxAttempts),b.retryMaxAttempts.min,b.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:_(D(e.maxDelayMs,v.retry.maxDelayMs),t,b.retryDelayMs.max)}}}function Je(n,e={}){let t=n??v,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),r=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=Kt({...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 Vt(n){try{if(!n||typeof n!="object")return;let e=n,t=e.pmd,i=typeof t=="boolean",r=e.crossOriginSession,o=r&&typeof r=="object"&&typeof r.cookieDomain=="string"?r.cookieDomain:void 0;return{pmd:i?t:!1,pmdExplicit:i,privateMode:R(e.privateMode,!0),...o!==void 0&&{crossOriginSession:{cookieDomain:o}}}}catch{return}}function re(n){let e=n.getItem(Ut),t=e&&typeof e=="object"?q(e.config):null;return t?{...e,config:t}:null}function Wt(n){return re(n)?.config??q(n.getItem(Qe))}function $t(n,e){n.setItem(Ut,e)}function ne(n,e,t){return fetch(e,t)}function jt(n){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var tr=6e4,ir=6e4,oe=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),r=typeof AbortController<"u"?new AbortController:void 0,o=r?setTimeout(()=>r.abort(),ir):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=tr,...r?{signal:r.signal}:{}},a=await ne(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 d=q(await a.json());d&&(l.config=d)}catch(d){this.options.logger.error("Failed to parse SDK config response",d),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=jt(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)}};import{v7 as ar}from"uuid";function se(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,l,d=()=>{l!==void 0&&(clearTimeout(l),l=void 0)},c=()=>(a=!0,d(),t()),p=s?r.request(e,{signal:s.signal},c):r.request(e,c);return s&&o!==void 0&&!a&&(l=setTimeout(()=>{l=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),p.catch(f=>{if(a)throw f;return t()}).finally(d)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function Gt(n){return typeof navigator<"u"&&!!navigator.locks?.request}var rr="cbo_outbox",Ye="cbo_outbox",nr=500,or=512*1024;function sr(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 K=class{constructor(e,t,i=nr,r=or,o=Ye,s=rr){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(sr);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 se(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 lr=500,dr=512*1024,zt=200,Qt=200*1024,pr=16*1024,Jt=6e4,Xe=32e3;function ae(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 le=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??v,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new K(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new K(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;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??ar()};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"||ae(i)>pr){this.probesDropped++;return}let r={...e,payload:JSON.parse(i)},o=ae(JSON.stringify(r));for(this.probeQueue.push({sessionId:t,entry:r,bytes:o,attempts:0,flushAfter:0}),this.probeBytes+=o;this.probeQueue.length>lr||this.probeBytes>dr&&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>=Qt&&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 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,r){let o=this.sessionId,s={sessionId:o,events:[],sdk:this.sdk,probes:[]};this.attachBatchMeta(s,[],t);let a=ae(JSON.stringify(s))+120,l=e>a?this.selectProbes(this.probeQueue,o,zt,e-a):[];l.length>0&&(s.probes=l.map(d=>d.entry),this.attachBatchMeta(s,l,t),r&&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(Xe,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(g=>g.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 l=r[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??s[0]?.sessionId??this.sessionId,d=r.filter(g=>g.sessionId===l).slice(0,this.batchSize),c=o.filter(g=>g.sessionId===l).slice(0,100),p=[...c.map(g=>g.event),...this.takeLows(l,100-c.length)];this.prepareEvents(d,e);let f=l===this.sessionId?this.takeTelemetry():[],m=l===this.sessionId?this.takeStandaloneDeviceInfo():void 0,y=this.selectProbes(s,l,zt,Qt),u={sessionId:l,events:d.map(g=>g.event),sdk:this.sdk};if(p.length>0&&(u.lows=p),f.length>0&&(u.telemetry=f),y.length>0&&(u.probes=y.map(g=>g.entry)),m&&(u.deviceInfo=m),a&&!m)break;this.attachBatchMeta(u,[...d,...c,...y],e),c.length&&(u.deliveryAck=!0);let w=this.shouldRequestConfig()?{[qt]:this.config.version||"1"}:void 0,T=await this.transport.send(u,w).catch(g=>(this.logger.error("Unexpected error in queue flush",g),{}));if(u.deliveryAck&&T.statusCode&&T.statusCode>=200&&T.statusCode<300&&!T.deliveryAccepted&&(T={...T,statusCode:503}),this.requestConfig&&this.handleConfigResponse(T),this.handleLowSendResult(T,c,i),this.handleProbeSendResult(T,y,i),!this.handleSendResult(T,d,i))break}e==="destroy"&&this.sendUnloadProbes(Xe,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 K(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(c=>c.id)),!0;if(!this.isRetryable(r))return this.removeEntries(t.map(c=>c.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],d=[];for(let c of t)c.attempts+=1,c.attempts>=s?l.push(c.id):(c.flushAfter=i+this.backoffForAttempt(c.attempts,a),d.push(c));return this.removeEntries(l),this.store?.update(d),!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"),U(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=I(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=I(0,"pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:kt(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(Jt-t,Xe),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(c=>c.sessionId===t),r=i.slice(0,this.batchSize),o=this.lowPending.filter(c=>c.sessionId===t).slice(0,100),s=[...o.map(c=>c.event),...this.takeLows(t,100-o.length)];this.prepareEvents(r,e);let a=this.takeTelemetry(),l=this.takeStandaloneDeviceInfo();if(r.length===0&&s.length===0&&a.length===0&&!l)return this.dirtySinceSyncFlush=!1,0;let d={sessionId:t,events:r.map(c=>c.event),sdk:this.sdk};return s.length>0&&(d.lows=s),a.length>0&&(d.telemetry=a),l&&(d.deviceInfo=l),this.attachBatchMeta(d,[...r,...o],e),o.length&&(d.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(d)||this.transport.send(d):this.transport.send(d),this.config.durableOutbox||this.removeEntries(r.map(c=>c.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>r.length,this.approximateSize(d)}approximateSize(e){try{return ae(JSON.stringify(e))}catch{return Jt}}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)}}};import{v7 as Xt}from"uuid";import cr from"detectincognitojs";async function Yt(n){return(await cr()).isPrivate}var ur=300,z=6e3,Zt="cbo_pm",fr=10080*60*1e3,ei="detectincognitojs@1.9.0",ti={timing:!1},Ze="cbo_tab_id",ii={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function O(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ri(n,e,t){return{field:n,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function et(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 de=class{constructor(e,t,i="localstorage",r,o=()=>ti,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=O(),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,d,c=a&&l===void 0&&!this.privateModeDetectionStarted?this.detectPrivateMode(i.timing).then(x=>{d=x}):void 0,p=this.startFastFields();await et(Promise.all(p.map(x=>x.promise)),ur);let f=O()-r,m=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,p);let y=()=>d?.error?[d.error]:[];this.safePublish(e,this.buildInfo(s,p,d?d.value:l,m,y()),"fast");let u=p.filter(x=>!x.settled),w=c!==void 0&&d===void 0;if(u.length===0&&!w)return;let T=O();await Promise.all([et(Promise.all(u.map(x=>x.promise)),z-(T-r)),c]);let g=u.filter(x=>!x.settled).map(x=>ri(x.field,x.source,z));g.push(...y()),i.timing&&u.length>0&&this.reportLateTiming(O()-r,u),this.safePublish(e,this.buildInfo(s,p,d?d.value:l,m,g),"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",()=>Pt(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>Ft(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>Lt(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>Rt(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>At(0)),this.startField("webdriver","navigator.webdriver",()=>_t(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>Dt(0))]}startField(e,t,i){let r=O(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:O()-r}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:O()-r,error:{field:e,source:t,error:M(s)??{message:"Unknown error"}}})).then(s=>(o.settled=s,s)),o}buildInfo(e,t,i,r,o){let s={},a=[];for(let d of t)d.settled?(d.settled.error&&a.push(d.settled.error),s[d.field]=d.settled.value,this.remember(d.field,d.settled.value)):s[d.field]=r[d.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(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(Zt);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==ei)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(Zt,{value:e,ts:Date.now(),dv:ei})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=O(),r=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:Yt(0));if(!await et(r.promise,z)||!r.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${z}ms`),{error:ri("privateMode",t,z)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(O()-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),ti}}reportFastTiming(e,t){let i=t.map(r=>`${ii[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=>`${ii[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)}}static getOsAndBrowserInfo(){return{osName:this.getOsName(),browserName:this.getBrowserName()}}static getUserAgent(){return te(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=Xt(),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(Ze);if(e)return e;let t=Xt();if(this.sessionStorage.setItem(Ze,t),this.sessionStorage.getItem(Ze)===t)return t}};function hr(){return typeof document<"u"&&U(0)}var pe=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&&hr())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 ni(n){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function oi(n){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function Q(n){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function P(n,e){return`${n}_${e}`}var ce=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(P(e,this.namespace))}setItem(e,t){this.engine.setItem(P(e,this.namespace),t)}removeItem(e){this.engine.removeItem(P(e,this.namespace))}},ue=class{constructor(e){this.logger=e}area=ni(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)}}},fe=class{constructor(e,t){this.logger=e;this.domain=t}jar=Q(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)}}},he=class{constructor(e){this.logger=e}area=oi(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 ge=1,me="cbo_storage_schema",gr=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],mr=["cbo_session_id","cbo_tab_id"],yr=["cbo_client_env_handle"];function ye(n,e,t){return n.setItem(e,t),JSON.stringify(n.getItem(e))===JSON.stringify(t)}function tt(n,e,t){let i=n.getItem(me);if(i!==null){if(i.version!==ge||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(r=>n.getItem(P(r,e))!==null))return ye(n,me,{version:ge,projectId:e,complete:!0});if(!ye(n,me,{version:ge,projectId:e,complete:!1}))return!1}for(let r of t){let o=P(r,e);if(n.getItem(o)!==null)continue;let s=n.getItem(r);if(s!==null&&!ye(n,o,s))return!1}return ye(n,me,{version:ge,projectId:e,complete:!0})}function si(n,e,t,i,r){try{if(!tt(e,n,gr))return;tt(t,n,mr),i&&tt(i,n,yr)}catch(o){r.error("Failed to migrate legacy Observe storage",o)}}var vr=10*1e3,br=60*1e3,Sr=3600*1e3,wr=300*1e3,ai=1440*60*1e3,Tr=[1e3,3e3];function Er(n){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(n?.get("Cache-Control")??"");if(!e)return Sr;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,wr),ai)}var ve=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=Wt(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"||U(0)||this.refresh()};this.removers.push(I(0,"visibilitychange",e),I(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=re(this.storage),{fetchedAt:i,expiresAt:r}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof r=="number"&&i>0&&r-i<=ai&&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<br)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(),vr):void 0;let i=!0;try{let r=await ne(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=q(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();$t(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+Er(r.headers),config:s}),re(this.storage)&&this.storage.removeItem(Qe),this.appliedVersion=s.version,this.onConfig?.(s)}catch(r){if(!this.stopped){this.logger.error("Failed to fetch SDK config",r);let o=Tr[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}};import{v7 as L}from"uuid";var V=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 be=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new V(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 W=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;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 r=this.inputBatch;if(!r){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:i};return}r.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 r=1;r<e.length;r++){let o=e[r].ts-e[r-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,r=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({...r===void 0?{}:{captureSeq:r},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect,r);return}if(s>=3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(s<=-3){this.flushInputBatch(),this.flushAutofillStreak(),this.pushLow({...r===void 0?{}:{captureSeq:r},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,r);return}let l=this.autofillTimestamps;if(l.length===0&&(this.ringEffect=this.currentEffect),l.push({ts:t,captureSeq:r}),l.length>5){let p=l.shift();this.extendInputBatch(p.ts,this.ringEffect,p.captureSeq),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let d=l[0],c=l[l.length-1];l.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:d.ts,captureSeq:d.captureSeq,lastTimestamp:c.ts,effect:this.ringEffect}}};var $=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 l=e[a],d=s.value;if(l===d)return;o=!0;let c=0;for(;c<l.length&&c<d.length&&l[c]===d[c];)c++;let p=0;for(;p<l.length-c&&p<d.length-c&&l[l.length-p-1]===d[d.length-p-1];)p++;r+=d.length-c-p}),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 Ir=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Se(n,e,t,i,r=Ir){let o=[];for(let s of r){let a=xr(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 xr(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 li(n,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function di(n,e){return e.reduce((t,i)=>t+i.value.length,0)}function we(n,e){let t=document.activeElement;return e.find(i=>i===t)}var kr=[{query:"com-1password-button",eventType:"pa-1"},{query:"com-1password-menu",eventType:"pa-2"},{query:"com-1password-notification",eventType:"pa-3"}],Cr="[data-lastpass-root], [data-lp], [data-lpignore], [data-lpfieldtype]",pi="pa-4",Or='[popover="manual"]',Pr=400,Lr=20,it="pa-5",rt="pa-6",nt=(n,e)=>{try{return Array.from(n.querySelectorAll(e))}catch{return[]}},ci=n=>{if(n.getAttribute("popover")!=="manual")return!1;let e=n.getAttribute("style")??"";return!(e.length<Pr||!/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)<Lr)},Rr=n=>{if(ci(n)||n.getAttribute("popover")!=="manual")return!1;let e=n.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))},Fr=n=>{n(document);for(let e of Array.from(document.querySelectorAll("*"))){let t=e.shadowRoot;t&&n(t)}},Ar=()=>{let n=new Set;return typeof document>"u"||Fr(e=>{for(let t of kr)n.has(t.eventType)||nt(e,t.query).length>0&&n.add(t.eventType);if(!n.has(pi)&&nt(e,Cr).length>0&&n.add(pi),!n.has(it)||!n.has(rt))for(let t of nt(e,Or)){if(!n.has(it)&&ci(t)){n.add(it);continue}!n.has(rt)&&Rr(t)&&n.add(rt)}}),n};function ui(n){return Ar()}var _r=500,Dr=250;function J(n){return li(0,n)}var E=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new W(J(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new $(0,[t],e,(r,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=J(t),this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:J(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=Se(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=I(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&we(0,[e])&&this.handleFocus(),typeof window<"u"&&(this.mountProbeTimer=setTimeout(()=>this.runEnvProbe(),_r))}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=ui(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(),Dr))}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(J(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(J(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 Te=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new W(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new $(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 r=(o,s)=>this.safe(s);for(let o of this.inputs)this.listeners.push(Se(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")},r,["input","focus","blur","click","pointerdown","pointerup","keyup"]));typeof window<"u"&&this.listeners.push(I(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&we(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 di(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 F=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 Te(this.logger,i,o):new E(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 Ee=class extends h{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 F(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 Ie=class extends h{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 F(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 Mr=["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 fi(n){if(!n)return!1;let e=n.toLowerCase();return Mr.some(t=>e.includes(t))}var ot="@corbado/observe",st="1.10.0";import{v7 as Hr}from"uuid";var at="cbo_email_link_starts";function lt(n,e){let t=n.getItem(at);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 hi(n,e){if(n)try{let t=lt(n,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),n.setItem(at,t.slice(-10))}catch{}}function gi(n,e,t=Date.now()){if(n)try{let i=lt(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 mi(n,e){if(n)try{let t=lt(n,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);n.setItem(at,t)}catch{}}var xe=class extends h{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||Hr(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,r=this.captureSession;i&&r&&hi(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:r,specType:t.explicitSpecType,startedAt:Date.now()})}},ke=class extends h{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=gi(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=I(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&&mi(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(r,o)=>i(s=>e.error(r,{...o,explicitTimestamp:s}),o)}}};var Ce=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new V(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 yi(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 Oe=class extends h{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};var Pe=class extends h{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 E(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(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 Le=class extends h{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 E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Re=class extends h{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 E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Fe=class extends h{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 Ae=class extends h{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}=Nr(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:r,actor:o})}};function Nr(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 _e=class extends h{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new F(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 h{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 Me=class extends h{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 He=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 E(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 dt=50,Br=6e4,Ur=40,qr=/^[A-Za-z0-9._-]+$/,Ne=class extends h{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(Vr(e,t),Kr(e,t)),this.inputBinding=this.createLowCollector(()=>new He(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 Kr(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>Br){Y(n,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function Vr(n,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:Y(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 Y(n,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=r.filter(s=>typeof s=="string"&&s.length<=Ur&&qr.test(s));return o.length<r.length&&Y(n,"Form: unsupported field names omitted from telemetry"),o.length>dt&&Y(n,`Form: more than ${dt} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,dt)),t}function Y(n,e){try{n.getLogger().warn(e)}catch{}}function pt(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 Be(n,e,t){return{...n,start:(i,r)=>n.start(pt(i,e,t),r),finished:(i,r)=>n.finished(pt(i,e,t),r)}}var Ue=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=vi(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{...Be(r,t,i),errorTyped:(o,s)=>{r.errorTyped(pt({code:o?.code,error:M(o?.error)},t,i),s)}}}},qe=class extends h{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=vi(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=Be(this.defineStep("get-options"),i,e),this.ceremony=Be(this.defineStep("ceremony"),i,e),this.postResponse=Be(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function vi(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 Ke=class extends h{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 E(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Wr="/inline/injected/webauthn-listeners.js",bi=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,$r=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,jr=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,Si=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,Gr=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,zr=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,Qr=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,ct=()=>Object.keys(window._sentryDebugIds??{}),ut=n=>{try{n()}catch(e){return String(e?.stack??"")}return""},wi=()=>ut(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),Jr=()=>{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]")},ft=(...n)=>{let e=navigator.credentials;return e?n.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},Yr=()=>[navigator.credentials?.get,...ft("get","_get")].some(n=>typeof n=="function"&&n.name==="getWebAuthnCredential"),Xr=()=>{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)}},Zr,en=()=>Zr??=Xr(),tn=()=>{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},rn=()=>{let n={get nodeType(){throw new Error("probe")}};return ut(()=>MutationObserver.prototype.observe.call(null,n))},nn=()=>{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},on=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...ft("get","_get","create")].some(e=>typeof e=="function"&&zr.test(Function.prototype.toString.call(e))),sn=()=>{let n=document;for(;n;){if(n.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;n=n.activeElement?.shadowRoot}return!1},an=()=>{let n=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...ft("get","_get"),n?.isConditionalMediationAvailable,n?._isConditionalMediationAvailable,n?.isUserVerifyingPlatformAuthenticatorAvailable,n?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&Qr.test(Function.prototype.toString.call(t)))},ln=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:Jr},{name:"1password",signal:"Sentry debug id",test:()=>ct().some(n=>n.includes(Wr))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:Yr},{name:"bitwarden",signal:"autofill keyframes",test:en},{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:tn},{name:"dashlane",signal:"page script stack",test:()=>bi.test(wi())||typeof HTMLDialogElement<"u"&&bi.test(ut(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>$r.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>jr.test(wi())},{name:"keeper",signal:"override source",test:on},{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:sn},{name:"nordpass",signal:"observer proxy stack",test:()=>Si.test(rn())},{name:"nordpass",signal:"observer read order",test:nn},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>ct().some(n=>Gr.test(n))},{name:"nordpass",signal:"Sentry debug id",test:()=>ct().some(n=>Si.test(n))},{name:"protonpass",signal:"WebAuthn override source",test:an},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function dn(){return typeof window>"u"||typeof document>"u"?[]:ln.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 Ti(){let n=new Map;for(let{name:e,signedIn:t,matched:i}of dn()){if(!i)continue;let r=n.get(e)??{name:e};t&&(r.signedIn=!0),n.set(e,r)}return[...n.values()]}function Ei(n){return Ti()}var Ii=3e3,pn=500,cn=6,un=1e3,Ve=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),xt(0))this.sampleAfter(Ii);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(Ii)};this.removers.push(I(0,"load",o,{once:!0}))}let r=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=cn&&r(),this.sampleAfter(pn))});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:un});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=Ei(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 fn="cbo_xs",Ci="1",hn=20;var gn=/^[A-Za-z0-9._~-]{1,128}$/,mn=1e3,yn=300*1e3,vn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bn=/^[A-Za-z0-9_-]{1,64}$/,Sn=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/,xi=/^\d{1,15}$/,wn=1e9,ki=1e3,Tn=1e5;function ht(n){return typeof n=="string"&&gn.test(n)}function En(n){let e=n.split("."),[t,i,r,o]=e;if(e.length<4||t!==Ci||!i||!vn.test(i)||!r||!xi.test(r)||!o||!xi.test(o)||Number(o)>wn)return;let s=e.length>4?e.slice(4).join("."):void 0;if(!(s!==void 0&&!ht(s)))return{sessionId:i.toLowerCase(),lastActiveAt:Number(r),seqMark:Number(o),...s!==void 0&&{context:s}}}function In(n){let e=[Ci,n.sessionId,String(Math.floor(n.lastActiveAt)),String(Math.floor(n.seqMark))];return n.context!==void 0&&e.push(n.context),e.join(".")}function xn(n,e){let t=n.trim().toLowerCase().replace(/^\./,""),i=e.toLowerCase();if(Sn.test(t))return i===t||i.endsWith(`.${t}`)?t:void 0}var We=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(!bn.test(e.projectId)){e.logger.debug("Cross-origin session off: project id is not cookie-safe");return}let t=e.scope?e.scope():Ot(0);if(!t.https){e.logger.debug("Cross-origin session off: page is not served over HTTPS");return}let i=xn(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??Q(0),o=e.jar??Q(0);return new n(`${fn}_${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 l=Math.max(t,this.highestSeen)+ki;return this.reservedMark=l+ki,this.highestSeen=this.reservedMark,l}let a=t>=this.reservedMark||s!==void 0&&s>this.reservedMark;return!a&&i-this.lastWriteAt<mn?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>Tn){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 l=t?.sessionId===i,d=l?this.plausibleMark(t.seqMark,r):void 0;d!==void 0&&(this.highestSeen=Math.max(this.highestSeen,d)),l&&!a&&(this.context=t.context);let c=r,p;s?(c=Math.max(r,d??0,this.highestSeen),p=c+hn):p=Math.max(this.reservedMark,this.highestSeen,r);let f=In({sessionId:i,lastActiveAt:o,seqMark:p,...this.context!==void 0&&{context:this.context}});return this.write(e,f),s&&(this.reservedMark=p),this.highestSeen=Math.max(this.highestSeen,p),this.lastWriteAt=o,{seq:c,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=En(o);s&&t-s.lastActiveAt<i&&s.lastActiveAt<=t+yn&&(!r||s.lastActiveAt>r.lastActiveAt)&&(r=s)}return r}};var gt={name:ot,version:st},kn=/^[0-9A-Za-z.+_-]{1,32}$/;function Cn(n,e){return n===void 0?gt:typeof n=="string"&&kn.test(n)?{...gt,integrationVersion:n}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),gt)}var mt="cbo_session_id",$e="cbo_session",k="cbo_seq",Oi="cbo_experiments",Pi="cbo_data_policy",On=255,Pn=/^[A-Za-z0-9_-]+$/,Ln=128,Rn=256,Li=1e3,Fn=/^[a-z][a-z0-9_-]{0,31}$/,Ri=/^[A-Za-z0-9_-]{1,16}$/,An=64,_n=32,Dn=50,Mn="cbo_seq",Fi=1e3,Ai=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,je=class n{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??yi({debug:this.options.debug});let t=new ue(this.logger),i=new he(this.logger),r=e.storage==="cookie",o=r?new fe(this.logger,e.cookieDomain):void 0;si(e.projectId,t,i,o,this.logger);let s=e.projectId,a=u=>new ce(u,s);this.seqLockName=P(Mn,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=Vt(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd);let l=Object.keys(v).every(u=>this.configOverrides[u]!==void 0)&&Object.keys(v.retry).every(u=>this.configOverrides.retry?.[u]!==void 0);l||(this.configManager=new ve(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let d=this.configManager?.initialConfig;this.config=Je(d,this.configOverrides),!l&&!d&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!l&&!d&&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 c=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${c}`);let p=new oe({logger:this.logger,url:c});this.crossOrigin=this.createCrossOriginSession(),this.sessionId=this.resolveSession(),this.queue=new le(this.logger,p,this.sessionId,Cn(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:P(Ye,s),getDataPolicy:()=>this.dataPolicy,getCrossOriginSession:u=>this.crossOriginSessionMeta(u),fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:u=>this.attachUndeliveredDeviceInfo(u),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((u,w)=>this.reportTelemetry(u,w));try{this.getWindowObserver()}catch(u){this.logger.error("Failed to attach page low-event observer",u)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Ve(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(u){this.logger.error("Failed to start password manager detection",u)}let f=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let u of f)this.telemetry(u.level,u.message);let m=new de(this.logger,this.storage,r?"cookie":"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(u,w)=>this.telemetry(u,w),this.fixedData?.privateMode??!0);this.deviceCollector=m;let y=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new pe(this.logger,m,Math.max(1,y),y,{timing:()=>this.config.deviceInfoTiming,emit:(u,w)=>this.telemetry(u,w)},()=>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(u=>this.handleConfig(u))}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 ie(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=Je(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<=On}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Pi);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(Pi,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<=Ln&&Pn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=Rn}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Oi);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(Oi,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:fi(te(0))}createCrossOriginSession(){let e=this.fixedData?.crossOriginSession;if(e)try{return this.isTrackingBlocked()?void 0:We.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($e);t?.id&&typeof t.lastActiveAt=="number"&&e.set(t.id,t.lastActiveAt);let i=this.sessionStorage.getItem(mt);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(k)??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(k,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=L();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($e);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(k)??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(k,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",r.id),r.id}let i=L();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(k,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem($e,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(mt);if(e){if(typeof e=="string")return Ai.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return Ai.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(mt,{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>=Fi&&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($e),o=!1;if(!r?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(r?.id)i-this.lastActivityWriteAt>=Fi&&this.persistContinuitySession(r.id,i),r.id!==this.sessionId&&(this.sessionId=r.id,this.queue.setSessionId(r.id),o=!0);else{let l=L();this.persistContinuitySession(l,i),this.persistentStorage.setItem(k,0),this.sessionId=l,this.queue.setSessionId(l),this.seq=0,o=!0}let s=this.persistentStorage.getItem(k);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(k,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!Gt(0)?e():se(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 Ct(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,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 d=s??Date.now(),c=l?.id??L(),p=l?.sessionId??this.sessionId,f=this.nextSeq(),m=typeof f=="number"?f:await f,y=this.resolveTrackingSourcePath(),u={type:"predefined",name:e,id:c,timestamp:d,seq:m,data:t,user:i,contexts:o,tags:r,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:G(),initiator:l?.initiator,trackingSourcePath:y??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},w=this.deviceInfoManager.getForEvent();w&&(u.deviceInfo=w),this.logger.debug(`Track: ${e}`,JSON.stringify(u,null,2));let T=this.passwordManagerSampler?.takeReport(p);T&&(u.passwordManagers=T),this.queue.enqueue(u,p)}catch(d){this.logger.error(`Failed to process event "${e}" before enqueue`,d),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,r,o){try{let s=L(),a=this.sessionId,l={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,l,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,l={userId:r,identifier:o,crossEnvironmentTransactionID:s},d={...this.options.defaultTags,...this.applicationTag(),...t};this.track("conversion",a,l,d,void 0,void 0,i)}flowFinished(e,t,i){try{let{userId:r,identifier:o,...s}=e,a={userId:r,identifier:o},l=L(),d=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:d}),this.flowHandle(l,d)}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??C(),captureVersion:1,pageId:e.pageId??G()},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:L(),level:e,message:i.length>Li?i.slice(0,Li):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"||!Fn.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"&&Ri.test(e.pageId)?e.pageId:this.defaultProbePageId(),r={id:L(),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"&&Ri.test(e.cfg)&&(r.cfg=e.cfg);let o=Bn(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??=Nn()}nextProbeSeq(e){let t=this.probeSeqs.get(e)??0;if(this.probeSeqs.delete(e),this.probeSeqs.set(e,t+1),this.probeSeqs.size>_n){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=G(),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>=Dn)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 be(this,e)}passkeyEnrollmentFullOperation(e){return new Ce(this,e)}passkeyDeletionOperationFull(e){return new Oe(this,e)}passwordLoginFullOperation(e){return new Pe(this,e)}passwordEnrollmentFullOperation(e){return new Le(this,e)}emailLinkOperationFull(e){return new xe(this,e)}continueEmailLinkOperation(e){return new ke(this,e)}emailOtpOperationFull(e){return new Ee(this,e)}smsOtpOperationFull(e){return new Ie(this,e)}totpOperationFull(e){return new _e(this,e)}provideIdentifierOperationFull(e){return new Re(this,e)}provideDataOperationFull(e){return new Ke(this,e)}formOperationFull(e){return new Ne(this,e)}socialLoginOperationFull(e){return new Fe(this,e)}ssoLoginOperationFull(e){return new Ae(this,e)}appConfirmationOperationFull(e){return new De(this,e)}keySigningOperationFull(e){return new Z(this,e)}keyRegistrationOperationFull(e){return new ee(this,e)}captchaOperationFull(e){return new Me(this,e)}trustedDeviceCheckOperationFull(e){return new Ue(this,e)}trustedDeviceEnrollmentOperationFull(e){return new qe(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&&!ht(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(k)??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(k,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=L();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(k,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}},Hn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function Nn(){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+=Hn[n[t]&63];return e}function Bn(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,An))}return Object.keys(e).length>0?e:void 0}var Un=["none","presence","size","class","format","partial","enum","computed","token","pseudonym","redacted","raw"];var qn={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function Kn(n,e){return Ge(n,"creationOptions",e)}function Vn(n,e){return Ge(n,"creationResponse",e)}function Wn(n){return Ge(n,"requestOptions")}function $n(n,e){return Ge(n,"assertionResponse",e)}function Ge(n,e,t={}){try{let i=typeof n=="string"?JSON.parse(n):n;if(!jn(i))return;let r=new Set(qn[e]),o=new Set,s=(a,l,d=0)=>{if(!r.has(l)){if(e==="creationOptions"&&l==="/user/id"||(e==="creationResponse"||e==="assertionResponse")&&l==="/response/userHandle"){if(a===null)return null;if(!t.userId)return;let c=typeof a=="string"?a:a instanceof ArrayBuffer||ArrayBuffer.isView(a)?_i(a):void 0;if(c===void 0)return;try{let p=t.userId(c);return typeof p=="string"||p===null?p:void 0}catch{return}}if(a===null||typeof a=="string"||typeof a=="boolean")return a;if(typeof a=="number")return Number.isFinite(a)?a:null;if(typeof a=="object"){if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))return _i(a);if(d>64||o.has(a))throw new TypeError("Invalid telemetry payload");o.add(a);try{if(Array.isArray(a))return a.map((m,y)=>s(m,`${l}/${y}`,d+1));let c=Object.create(null);for(let m in a){let y=`${l}/${m.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(r.has(y)||m==="toJSON")continue;let u=s(a[m],y,d+1);u!==void 0&&(c[m]=u)}let p=a,f=(m,y)=>{if(c[y]!==void 0||typeof p[m]!="function")return;let u=`${l}/${y}`,w=s(Reflect.apply(p[m],a,[]),u,d+1);w!==void 0&&(c[y]=w)};return l===""&&(e==="creationResponse"||e==="assertionResponse")&&f("getClientExtensionResults","clientExtensionResults"),l==="/response"&&e==="creationResponse"&&(f("getTransports","transports"),f("getAuthenticatorData","authenticatorData"),f("getPublicKey","publicKey"),f("getPublicKeyAlgorithm","publicKeyAlgorithm")),c}finally{o.delete(a)}}}};return JSON.stringify(s(i,""))}catch{return}}function jn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)}function _i(n){let e=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var S;function Ll(n){let e=new je(n);return S=e,e}function Rl(){return S}function Fl(){return S?.resetSession()}function Al(){return S?.getSessionId()}function _l(n){S?.setUser(n)}function Dl(n,e){S?.setFlowTags(n,e)}function Ml(n,e){S?.setExperiment(n,e)}function Hl(n){S?.setExperiments(n)}function Nl(n){S?.clearExperiment(n)}function Bl(){S?.clearExperiments()}function Ul(){return S?.getExperiments()??{}}function ql(n,e){S?.telemetry(n,e)}function Kl(n){S?.logInfo(n)}function Vl(n){S?.logError(n)}async function Wl(){S&&(await S.destroy(),S=void 0)}export{De as AppConfirmationOperationFull,Ji as AuthEventName,$i as CEREMONY_LOW_EVENT_TAIL_MS,b as CONFIG_BOUNDS,Ut as CONFIG_CACHE_STORAGE_KEY,qt as CONFIG_REQUEST_HEADER,Qe as CONFIG_STORAGE_KEY,Me as CaptchaOperationFull,fe as CookieStorage,je as CorbadoTracker,So as DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS,vo as DEFAULT_FLUSH_INTERVAL_MS,nr as DEFAULT_MAX_ENTRIES,or as DEFAULT_MAX_SERIALIZED_LENGTH,v as DEFAULT_RELIABILITY_CONFIG,bo as DEFAULT_SEQ_LOCK_TIMEOUT_MS,Yi as DEFAULT_SESSION_INACTIVITY_MS,ke as EmailLinkContinuationOperation,xe as EmailLinkOperationFull,Ee as EmailOtpOperationFull,K as EventStore,Ne as FormOperationFull,ee as KeyRegistrationOperationFull,Z as KeySigningOperationFull,ue as LocalStorage,ce as NamespacedStorage,Ye as OUTBOX_LOCK_NAME,rr as OUTBOX_STORAGE_KEY,h as OperationFull,Re as OperationFullProvideIdentifierWithCUI,Qt as PROBE_BATCH_MAX_BYTES,zt as PROBE_BATCH_MAX_ITEMS,pr as PROBE_PAYLOAD_MAX_BYTES,dr as PROBE_QUEUE_MAX_BYTES,lr as PROBE_QUEUE_MAX_ITEMS,Oe as PasskeyDeletionOperationFull,Ce as PasskeyEnrollmentOperationFull,be as PasskeyLoginOperationFull,Le as PasswordEnrollmentOperationFull,Pe as PasswordLoginOperationFull,Ke as ProvideDataOperationFull,Di as RAW_ERROR_BOUNDS,Un as READER_EXPOSURES,le as RequestQueue,ot as SDK_NAME,st as SDK_VERSION,he as SessionStorage,Ie as SmsOtpOperationFull,Fe as SocialLoginOperationFull,Ae as SsoLoginOperationFull,_e as TotpOperationFull,Ue as TrustedDeviceCheckOperationFull,qe as TrustedDeviceEnrollmentOperationFull,Jt as UNLOAD_BUDGET_BYTES,Xe as UNLOAD_PROBE_MAX_BYTES,$t as cacheConfigRecord,Nl as clearExperiment,Bl as clearExperiments,yi as createLogger,Wl as destroy,Ti as detectPasswordManagerExtensions,Ul as getExperiments,Al as getSessionId,Rl as getTracker,Ll as init,Wt as loadCachedConfig,re as loadConfigRecord,Vl as logError,Kl as logInfo,P as namespacedKey,q as parseReliabilityConfig,Fl as resetSession,Vt as resolveFixedDataConfig,bt as resolveRawErrorLimits,Je as resolveReliabilityConfig,$n as sanitizeAssertionResponse,Kn as sanitizeCreationOptions,Vn as sanitizeCreationResponse,Wn as sanitizeRequestOptions,Tt as serializeRawError,Ml as setExperiment,Hl as setExperiments,Dl as setFlowTags,_l as setUser,ql as telemetry,ae as utf8Length};
4
+ ${s}`,t)}function Hi(n,e,t){let{limits:i}=t,r=q(n),o=c=>X(c,e-1,t);if(r==="Date")return Number.isNaN(n.getTime())?"[Invalid Date]":n.toISOString();if(r==="RegExp")return A(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 c=n,f=[];for(let m of c){if(f.length===i.maxBreadth)break;f.push(o(m))}return c.size>f.length&&f.push(`[+${c.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 c=n.slice(0,i.maxBreadth).map(o);return n.length>i.maxBreadth&&c.push(`[+${n.length-i.maxBreadth} more]`),c}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 c=n,f={type:o(c.type)};for(let m of["message","filename","lineno","colno"])m in c&&(f[m]=o(c[m]));return"error"in c&&c.error!=null&&(f.error=o(c.error)),f}let s=Object.create(null),a=n,l=Mi(n);if(l){for(let f of Fi){if(f==="stack"&&!i.stack)continue;let m=a[f];if(!(m==null||typeof m=="function")){if(f==="stack"){i.stack&&typeof m=="string"&&(s.stack=j(mt(m,i.maxStackFrames,i.maxValueLength),t));continue}s[f]=o(m)}}let c=a.cause;c!=null&&typeof c!="function"&&(s.cause=Bi(c,e-1,t))}let p=0,d=Object.keys(a);for(let c of d){if(c in s||c==="stack"&&!i.stack||l&&c==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${d.length-i.maxBreadth} keys]`;break}let f=a[c];typeof f!="function"&&(s[j(c,t)]=c==="stack"&&typeof f=="string"?j(mt(f,i.maxStackFrames,i.maxValueLength),t):o(f))}return!l&&r!=="Object"&&p===0?`[${r}]`:s}function Bi(n,e,t){if(typeof n!="object"||n===null)return X(n,e,t);if(t.causeBudget<=0)return j(`[${q(n)}]`,t);t.causeBudget--;try{return X(n,e,t)}finally{t.causeBudget++}}var Ni=1500,h=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:C,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??C(),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=qi(),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:vt(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(Ni)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??ht(this.operationName,l);t.arm(p,l==="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=l=>this.captureOptions(l,i,r,o);return{start:(l,p)=>{i=this.startReference,r=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:_(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function St(n,e){if(e.explicitSpecType!==void 0)try{n.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var Z=class extends h{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:St(e,t)})}},ee=class extends h{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:St(e,t)})}};function Ui(n){try{return decodeURIComponent(n.replace(/\+/g," "))}catch{return n}}function Ki(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 bt(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)===""||Ki(Ui(a),t)?o:`${a}=*`}).join("&")}`}function I(n,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function N(n){return document.visibilityState==="hidden"}function wt(n){return document.readyState==="complete"}function Tt(n){return window.location.href}function Et(n,e,t){let i=bt(window.location.search,e,t);return`${window.location.pathname}${i}`}function It(n){return{hostname:window.location.hostname,https:window.location.protocol==="https:"}}function xt(n){return typeof navigator>"u"?"":navigator.userAgent??""}async function kt(n){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function Ct(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function Ot(n){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function Pt(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 Lt(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 Rt(n){if(!(typeof navigator>"u"))return navigator.webdriver}function Ft(n){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}import{v7 as Vi}from"uuid";var Ge=(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 At(n,e,t){let i=[],r=(s,a,l)=>{let p=d=>t(a,()=>l(d));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,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 Dt(n){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function Mt(n){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var Wi,G=()=>Wi??=Vi(),te=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=At(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=Ge(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",C);scroll=Ge(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",C);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=Dt(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=Mt(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??C(),sourceKind:"window",captureVersion:1,pageId:G()},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 $i=(g=>(g.FlowStarted="flow_started",g.FlowDecided="flow_decided",g.FlowFinished="flow_finished",g.FlowReset="flow_reset",g.AuthMethodDecisionStarted="auth_method_decision_started",g.AuthMethodDecisionFinished="auth_method_decision_finished",g.FlowAutoFinished="flow_auto_finished",g.AuthDecisionStarted="auth_decision_started",g.AuthDecisionFinished="auth_decision_finished",g.SubflowStepStarted="subflow_step_started",g.SubflowStepFinished="subflow_step_finished",g.SubflowStepError="subflow_step_error",g.SubflowTrigger="subflow_trigger",g.SubflowError="subflow_error",g.SubflowStarted="subflow_started",g.SubflowFinished="subflow_finished",g.FlowEnriched="flow_enriched",g.Conversion="conversion",g))($i||{});var ze="cbo_sdk_config",Ht="cbo_sdk_config_cache",Bt="X-Corbado-Observe-Config",ro=500,no=50,oo=1e3,S={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}},ji=1800*1e3,v={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:ji,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 D(n,e,t){return Math.min(Math.max(n,e),t)}function M(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function O(n,e){return typeof n=="boolean"?n:e}function _t(n,e){return typeof n=="string"?n:e}function Gi(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.length>0&&e.length<=S.flushOnFlowTypeFinished.maxNameLength).slice(0,S.flushOnFlowTypeFinished.maxEntries):[]}function zi(n){return typeof n=="string"&&n.trim().toLowerCase()==="all"?"all":"allowlist"}function Qi(n){return Array.isArray(n)?n.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=S.sourcePathQueryAllow.maxKeyLength).slice(0,S.sourcePathQueryAllow.maxEntries):[]}function U(n){if(!n||typeof n!="object")return null;let e=n;return typeof e.version!="string"||e.version===""?null:qt(e)}function qt(n){let e=n.retry&&typeof n.retry=="object"?n.retry:{},t=D(M(e.baseDelayMs,v.retry.baseDelayMs),S.retryDelayMs.min,S.retryDelayMs.max);return{version:_t(n.version,""),flushIntervalMs:D(M(n.flushIntervalMs,v.flushIntervalMs),S.flushIntervalMs.min,S.flushIntervalMs.max),durableOutbox:n.durableOutbox===!0,durableLowOutbox:n.durableLowOutbox===!0,beaconKeepalive:n.beaconKeepalive===!0,sessionContinuity:n.sessionContinuity===!0,sessionInactivityMs:D(M(n.sessionInactivityMs,v.sessionInactivityMs),S.sessionInactivityMs.min,S.sessionInactivityMs.max),seqLockTimeoutMs:D(M(n.seqLockTimeoutMs,v.seqLockTimeoutMs),S.seqLockTimeoutMs.min,S.seqLockTimeoutMs.max),tvc:O(n.tvc,v.tvc),tph:O(n.tph,v.tph),td:O(n.td,v.td),tlf:O(n.tlf,v.tlf),telemetry:O(n.telemetry,v.telemetry),flushOnTelemetry:n.flushOnTelemetry===!0,flushOnFlowTypeFinished:Gi(n.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:D(M(n.deviceInfoCollectorTimeoutMs,v.deviceInfoCollectorTimeoutMs),S.deviceInfoCollectorTimeoutMs.min,S.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:n.deviceInfoTiming===!0,rawErrors:O(n.rawErrors,v.rawErrors),pmd:O(n.pmd,v.pmd),aap:_t(n.aap,""),sourcePathQuery:zi(n.sourcePathQuery),sourcePathQueryAllow:Qi(n.sourcePathQueryAllow),retry:{maxAttempts:D(M(e.maxAttempts,v.retry.maxAttempts),S.retryMaxAttempts.min,S.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:D(M(e.maxDelayMs,v.retry.maxDelayMs),t,S.retryDelayMs.max)}}}function Qe(n,e={}){let t=n??v,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),r=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=qt({...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 Nt(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:O(e.pmd,!1),privateMode:O(e.privateMode,!0),...i!==void 0&&{crossOriginSession:{cookieDomain:i}}}}catch{return}}function ie(n){let e=n.getItem(Ht),t=e&&typeof e=="object"?U(e.config):null;return t?{...e,config:t}:null}function Ut(n){return ie(n)?.config??U(n.getItem(ze))}function Kt(n,e){n.setItem(Ht,e)}var Ji=new Set;function Vt(n){Ji.add(n)}function re(n,e,t){return fetch(e,t)}function Wt(n){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var Yi=6e4,Xi=6e4,ne=class{constructor(e){this.options=e;Vt(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(),Xi):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=Yi,...r?{signal:r.signal}:{}},a=await re(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=U(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=Wt(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)}};import{v7 as rr}from"uuid";function oe(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,l,p=()=>{l!==void 0&&(clearTimeout(l),l=void 0)},d=()=>(a=!0,p(),t()),c=s?r.request(e,{signal:s.signal},d):r.request(e,d);return s&&o!==void 0&&!a&&(l=setTimeout(()=>{l=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),c.catch(f=>{if(a)throw f;return t()}).finally(p)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function $t(n){return typeof navigator<"u"&&!!navigator.locks?.request}var Zi="cbo_outbox",Je="cbo_outbox",er=500,tr=512*1024;function ir(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 K=class{constructor(e,t,i=er,r=tr,o=Je,s=Zi){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(ir);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 oe(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 nr=500,or=512*1024,jt=200,Gt=200*1024,sr=16*1024,zt=6e4,Ye=32e3;function se(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 ae=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??v,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new K(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){this.lowStore=new K(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;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??rr()};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"||se(i)>sr){this.probesDropped++;return}let r={...e,payload:JSON.parse(i)},o=se(JSON.stringify(r));for(this.probeQueue.push({sessionId:t,entry:r,bytes:o,attempts:0,flushAfter:0}),this.probeBytes+=o;this.probeQueue.length>nr||this.probeBytes>or&&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>=Gt&&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 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,r){let o=this.sessionId,s={sessionId:o,events:[],sdk:this.sdk,probes:[]};this.attachBatchMeta(s,[],t);let a=se(JSON.stringify(s))+120,l=e>a?this.selectProbes(this.probeQueue,o,jt,e-a):[];l.length>0&&(s.probes=l.map(p=>p.entry),this.attachBatchMeta(s,l,t),r&&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(Ye,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(g=>g.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 l=r[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??s[0]?.sessionId??this.sessionId,p=r.filter(g=>g.sessionId===l).slice(0,this.batchSize),d=o.filter(g=>g.sessionId===l).slice(0,100),c=[...d.map(g=>g.event),...this.takeLows(l,100-d.length)];this.prepareEvents(p,e);let f=l===this.sessionId?this.takeTelemetry():[],m=l===this.sessionId?this.takeStandaloneDeviceInfo():void 0,y=this.selectProbes(s,l,jt,Gt),u={sessionId:l,events:p.map(g=>g.event),sdk:this.sdk};if(c.length>0&&(u.lows=c),f.length>0&&(u.telemetry=f),y.length>0&&(u.probes=y.map(g=>g.entry)),m&&(u.deviceInfo=m),a&&!m)break;this.attachBatchMeta(u,[...p,...d,...y],e),d.length&&(u.deliveryAck=!0);let w=this.shouldRequestConfig()?{[Bt]:this.config.version||"1"}:void 0,T=await this.transport.send(u,w).catch(g=>(this.logger.error("Unexpected error in queue flush",g),{}));if(u.deliveryAck&&T.statusCode&&T.statusCode>=200&&T.statusCode<300&&!T.deliveryAccepted&&(T={...T,statusCode:503}),this.requestConfig&&this.handleConfigResponse(T),this.handleLowSendResult(T,d,i),this.handleProbeSendResult(T,y,i),!this.handleSendResult(T,p,i))break}e==="destroy"&&this.sendUnloadProbes(Ye,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 K(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(d=>d.id)),!0;if(!this.isRetryable(r))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,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"),N(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=I(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=I(0,"pagehide",this.onPageHide))}writeLifecycleDebugOutput(e){if(!this.debug||!this.storage)return;let t={last_executed:Date.now(),url:Tt(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(zt-t,Ye),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(d=>d.sessionId===t),r=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(r,e);let a=this.takeTelemetry(),l=this.takeStandaloneDeviceInfo();if(r.length===0&&s.length===0&&a.length===0&&!l)return this.dirtySinceSyncFlush=!1,0;let p={sessionId:t,events:r.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,[...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(d=>d.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>r.length,this.approximateSize(p)}approximateSize(e){try{return se(JSON.stringify(e))}catch{return zt}}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)}}};import{v7 as Jt}from"uuid";import ar from"detectincognitojs";async function Qt(n){return(await ar()).isPrivate}var lr=300,z=6e3,Yt="cbo_pm",pr=10080*60*1e3,Xt="detectincognitojs@1.9.0",Zt={timing:!1},Xe="cbo_tab_id",ei={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 ti(n,e,t){return{field:n,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function Ze(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 le=class{constructor(e,t,i="localstorage",r,o=()=>Zt,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=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(x=>{p=x}):void 0,c=this.startFastFields();await Ze(Promise.all(c.map(x=>x.promise)),lr);let f=P()-r,m=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,c);let y=()=>p?.error?[p.error]:[];this.safePublish(e,this.buildInfo(s,c,p?p.value:l,m,y()),"fast");let u=c.filter(x=>!x.settled),w=d!==void 0&&p===void 0;if(u.length===0&&!w)return;let T=P();await Promise.all([Ze(Promise.all(u.map(x=>x.promise)),z-(T-r)),d]);let g=u.filter(x=>!x.settled).map(x=>ti(x.field,x.source,z));g.push(...y()),i.timing&&u.length>0&&this.reportLateTiming(P()-r,u),this.safePublish(e,this.buildInfo(s,c,p?p.value:l,m,g),"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",()=>kt(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>Pt(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>Ct(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>Ot(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>Lt(0)),this.startField("webdriver","navigator.webdriver",()=>Rt(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>Ft(0))]}startField(e,t,i){let r=P(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:P()-r}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:P()-r,error:{field:e,source:t,error:_(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 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(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(Yt);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==Xt)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(Yt,{value:e,ts:Date.now(),dv:Xt})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=P(),r=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:Qt(0));if(!await Ze(r.promise,z)||!r.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${z}ms`),{error:ti("privateMode",t,z)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(P()-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),Zt}}reportFastTiming(e,t){let i=t.map(r=>`${ei[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=>`${ei[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=Jt(),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(Xe);if(e)return e;let t=Jt();if(this.sessionStorage.setItem(Xe,t),this.sessionStorage.getItem(Xe)===t)return t}};function dr(){return typeof document<"u"&&N(0)}var pe=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&&dr())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 ii(n){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function ri(n){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function Q(n){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function L(n,e){return`${n}_${e}`}var de=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))}},ce=class{constructor(e){this.logger=e}area=ii(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)}}},ue=class{constructor(e,t){this.logger=e;this.domain=t}jar=Q(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)}}},fe=class{constructor(e){this.logger=e}area=ri(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 he=1,ge="cbo_storage_schema",cr=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],ur=["cbo_session_id","cbo_tab_id"],fr=["cbo_client_env_handle"];function me(n,e,t){return n.setItem(e,t),JSON.stringify(n.getItem(e))===JSON.stringify(t)}function et(n,e,t){let i=n.getItem(ge);if(i!==null){if(i.version!==he||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(r=>n.getItem(L(r,e))!==null))return me(n,ge,{version:he,projectId:e,complete:!0});if(!me(n,ge,{version:he,projectId:e,complete:!1}))return!1}for(let r of t){let o=L(r,e);if(n.getItem(o)!==null)continue;let s=n.getItem(r);if(s!==null&&!me(n,o,s))return!1}return me(n,ge,{version:he,projectId:e,complete:!0})}function ni(n,e,t,i,r){try{if(!et(e,n,cr))return;et(t,n,ur),i&&et(i,n,fr)}catch(o){r.error("Failed to migrate legacy Observe storage",o)}}var hr=10*1e3,gr=60*1e3,mr=3600*1e3,yr=300*1e3,oi=1440*60*1e3,vr=[1e3,3e3];function Sr(n){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(n?.get("Cache-Control")??"");if(!e)return mr;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,yr),oi)}var ye=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=Ut(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"||N(0)||this.refresh()};this.removers.push(I(0,"visibilitychange",e),I(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=ie(this.storage),{fetchedAt:i,expiresAt:r}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof r=="number"&&i>0&&r-i<=oi&&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<gr)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(),hr):void 0;let i=!0;try{let r=await re(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=U(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();Kt(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+Sr(r.headers),config:s}),ie(this.storage)&&this.storage.removeItem(ze),this.appliedVersion=s.version,this.onConfig?.(s)}catch(r){if(!this.stopped){this.logger.error("Failed to fetch SDK config",r);let o=vr[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}};import{v7 as R}from"uuid";var V=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 ve=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-login"),this.lowEventTracker=new V(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 W=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 d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},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 d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(o<=-3){this.flushInputBatch(),this.flushAutofillStreak();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},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 d=a.shift();this.extendInputBatch(d,this.ringEffect),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let l=a[0],p=a[a.length-1];a.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:l,captureSeq:this.takeSeq(),lastTimestamp:p,effect:this.ringEffect}}};var $=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 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 c=0;for(;c<l.length-d&&c<p.length-d&&l[l.length-c-1]===p[p.length-c-1];)c++;r+=p.length-d-c}),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 br=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Se(n,e,t,i,r=br){let o=[];for(let s of r){let a=wr(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 wr(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 si(n,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function ai(n,e){return e.reduce((t,i)=>t+i.value.length,0)}function be(n,e){let t=document.activeElement;return e.find(i=>i===t)}function J(n){return si(0,n)}var E=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new W(J(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new $(0,[t],e,(r,o,s)=>{this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=J(t),this.pushLow({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:r,inputEffect:J(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=Se(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=I(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&be(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(J(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(J(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 we=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new W(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new $(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 r=(o,s)=>this.safe(s);for(let o of this.inputs)this.listeners.push(Se(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(I(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&be(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 ai(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 F=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 we(this.logger,i,o):new E(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 Te=class extends h{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 F(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 Ee=class extends h{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 F(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 Tr=["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 li(n){if(!n)return!1;let e=n.toLowerCase();return Tr.some(t=>e.includes(t))}var tt="@corbado/observe",it="1.10.1";import{v7 as Er}from"uuid";var rt="cbo_email_link_starts";function nt(n,e){let t=n.getItem(rt);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 pi(n,e){if(n)try{let t=nt(n,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),n.setItem(rt,t.slice(-10))}catch{}}function di(n,e,t=Date.now()){if(n)try{let i=nt(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 ci(n,e){if(n)try{let t=nt(n,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);n.setItem(rt,t)}catch{}}var Ie=class extends h{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||Er(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,r=this.captureSession;i&&r&&pi(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:r,specType:t.explicitSpecType,startedAt:Date.now()})}},xe=class extends h{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=di(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=I(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&&ci(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(r,o)=>i(s=>e.error(r,{...o,explicitTimestamp:s}),o)}}};var ke=class extends h{getOptions;ceremony;postResponse;lowEventTracker;constructor(e,t){super(e,"passkey-enrollment"),this.lowEventTracker=new V(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 ui(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 Ce=class extends h{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};var Oe=class extends h{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 E(e.getLogger(),t.identifierInputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.identifierLowEventTracker?.flushPending())),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(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 Pe=class extends h{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 E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Le=class extends h{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 E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Re=class extends h{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 Fe=class extends h{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}=Ir(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:r,actor:o})}};function Ir(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 Ae=class extends h{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new F(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 h{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 Me=class extends h{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,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 E(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 ot=50,xr=6e4,kr=40,Cr=/^[A-Za-z0-9._-]+$/,He=class extends h{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(Pr(e,t),Or(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 Or(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>xr){Y(n,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function Pr(n,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:Y(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 Y(n,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=r.filter(s=>typeof s=="string"&&s.length<=kr&&Cr.test(s));return o.length<r.length&&Y(n,"Form: unsupported field names omitted from telemetry"),o.length>ot&&Y(n,`Form: more than ${ot} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,ot)),t}function Y(n,e){try{n.getLogger().warn(e)}catch{}}function st(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 Be(n,e,t){return{...n,start:(i,r)=>n.start(st(i,e,t),r),finished:(i,r)=>n.finished(st(i,e,t),r)}}var qe=class extends h{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{...Be(r,t,i),errorTyped:(o,s)=>{r.errorTyped(st({code:o?.code,error:_(o?.error)},t,i),s)}}}},Ne=class extends h{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=Be(this.defineStep("get-options"),i,e),this.ceremony=Be(this.defineStep("ceremony"),i,e),this.postResponse=Be(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 Ue=class extends h{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 E(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};var Lr="/inline/injected/webauthn-listeners.js",hi=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,Rr=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,Fr=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,gi=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,Ar=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,Dr=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,Mr=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,at=()=>Object.keys(window._sentryDebugIds??{}),lt=n=>{try{n()}catch(e){return String(e?.stack??"")}return""},mi=()=>lt(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),_r=()=>{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]")},pt=(...n)=>{let e=navigator.credentials;return e?n.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},Hr=()=>[navigator.credentials?.get,...pt("get","_get")].some(n=>typeof n=="function"&&n.name==="getWebAuthnCredential"),Br=()=>{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)}},qr,Nr=()=>qr??=Br(),Ur=()=>{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},Kr=()=>{let n={get nodeType(){throw new Error("probe")}};return lt(()=>MutationObserver.prototype.observe.call(null,n))},Vr=()=>{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},Wr=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...pt("get","_get","create")].some(e=>typeof e=="function"&&Dr.test(Function.prototype.toString.call(e))),$r=()=>{let n=document;for(;n;){if(n.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;n=n.activeElement?.shadowRoot}return!1},jr=()=>{let n=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...pt("get","_get"),n?.isConditionalMediationAvailable,n?._isConditionalMediationAvailable,n?.isUserVerifyingPlatformAuthenticatorAvailable,n?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&Mr.test(Function.prototype.toString.call(t)))},Gr=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:_r},{name:"1password",signal:"Sentry debug id",test:()=>at().some(n=>n.includes(Lr))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:Hr},{name:"bitwarden",signal:"autofill keyframes",test:Nr},{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:Ur},{name:"dashlane",signal:"page script stack",test:()=>hi.test(mi())||typeof HTMLDialogElement<"u"&&hi.test(lt(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>Rr.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>Fr.test(mi())},{name:"keeper",signal:"override source",test:Wr},{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:$r},{name:"nordpass",signal:"observer proxy stack",test:()=>gi.test(Kr())},{name:"nordpass",signal:"observer read order",test:Vr},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>at().some(n=>Ar.test(n))},{name:"nordpass",signal:"Sentry debug id",test:()=>at().some(n=>gi.test(n))},{name:"protonpass",signal:"WebAuthn override source",test:jr},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function zr(){return typeof window>"u"||typeof document>"u"?[]:Gr.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 yi(){let n=new Map;for(let{name:e,signedIn:t,matched:i}of zr()){if(!i)continue;let r=n.get(e)??{name:e};t&&(r.signedIn=!0),n.set(e,r)}return[...n.values()]}function vi(n){return yi()}var Si=3e3,Qr=500,Jr=6,Yr=1e3,Ke=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),wt(0))this.sampleAfter(Si);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(Si)};this.removers.push(I(0,"load",o,{once:!0}))}let r=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=Jr&&r(),this.sampleAfter(Qr))});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:Yr});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=vi(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 Xr="cbo_xs",Ti="1",Zr=20;var en=/^[A-Za-z0-9._~-]{1,128}$/,tn=1e3,rn=300*1e3,nn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,on=/^[A-Za-z0-9_-]{1,64}$/,sn=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/,bi=/^\d{1,15}$/,an=1e9,wi=1e3,ln=1e5;function dt(n){return typeof n=="string"&&en.test(n)}function pn(n){let e=n.split("."),[t,i,r,o]=e;if(e.length<4||t!==Ti||!i||!nn.test(i)||!r||!bi.test(r)||!o||!bi.test(o)||Number(o)>an)return;let s=e.length>4?e.slice(4).join("."):void 0;if(!(s!==void 0&&!dt(s)))return{sessionId:i.toLowerCase(),lastActiveAt:Number(r),seqMark:Number(o),...s!==void 0&&{context:s}}}function dn(n){let e=[Ti,n.sessionId,String(Math.floor(n.lastActiveAt)),String(Math.floor(n.seqMark))];return n.context!==void 0&&e.push(n.context),e.join(".")}function cn(n,e){let t=n.trim().toLowerCase().replace(/^\./,""),i=e.toLowerCase();if(sn.test(t))return i===t||i.endsWith(`.${t}`)?t:void 0}var Ve=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(!on.test(e.projectId)){e.logger.debug("Cross-origin session off: project id is not cookie-safe");return}let t=e.scope?e.scope():It(0);if(!t.https){e.logger.debug("Cross-origin session off: page is not served over HTTPS");return}let i=cn(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??Q(0),o=e.jar??Q(0);return new n(`${Xr}_${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 l=Math.max(t,this.highestSeen)+wi;return this.reservedMark=l+wi,this.highestSeen=this.reservedMark,l}let a=t>=this.reservedMark||s!==void 0&&s>this.reservedMark;return!a&&i-this.lastWriteAt<tn?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 l=t?.sessionId===i,p=l?this.plausibleMark(t.seqMark,r):void 0;p!==void 0&&(this.highestSeen=Math.max(this.highestSeen,p)),l&&!a&&(this.context=t.context);let d=r,c;s?(d=Math.max(r,p??0,this.highestSeen),c=d+Zr):c=Math.max(this.reservedMark,this.highestSeen,r);let f=dn({sessionId:i,lastActiveAt:o,seqMark:c,...this.context!==void 0&&{context:this.context}});return this.write(e,f),s&&(this.reservedMark=c),this.highestSeen=Math.max(this.highestSeen,c),this.lastWriteAt=o,{seq:d,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=pn(o);s&&t-s.lastActiveAt<i&&s.lastActiveAt<=t+rn&&(!r||s.lastActiveAt>r.lastActiveAt)&&(r=s)}return r}};var ct={name:tt,version:it},un=/^[0-9A-Za-z.+_-]{1,32}$/;function fn(n,e){return n===void 0?ct:typeof n=="string"&&un.test(n)?{...ct,integrationVersion:n}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),ct)}var ut="cbo_session_id",We="cbo_session",k="cbo_seq",Ei="cbo_experiments",Ii="cbo_data_policy",hn=255,gn=/^[A-Za-z0-9_-]+$/,mn=128,yn=256,xi=1e3,vn=/^[a-z][a-z0-9_-]{0,31}$/,ki=/^[A-Za-z0-9_-]{1,16}$/,Sn=64,bn=32,wn=50,Tn="cbo_seq",Ci=1e3,Oi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$e=class n{constructor(e){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??ui({debug:this.options.debug});let t=new ce(this.logger),i=new fe(this.logger),r=e.storage==="cookie",o=r?new ue(this.logger,e.cookieDomain):void 0;ni(e.projectId,t,i,o,this.logger);let s=e.projectId,a=u=>new de(u,s);this.seqLockName=L(Tn,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=Nt(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd);let l=Object.keys(v).every(u=>this.configOverrides[u]!==void 0)&&Object.keys(v.retry).every(u=>this.configOverrides.retry?.[u]!==void 0);l||(this.configManager=new ye(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let p=this.configManager?.initialConfig;this.config=Qe(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 c=new ne({logger:this.logger,url:d});this.crossOrigin=this.createCrossOriginSession(),this.sessionId=this.resolveSession(),this.queue=new ae(this.logger,c,this.sessionId,fn(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:L(Je,s),getDataPolicy:()=>this.dataPolicy,getCrossOriginSession:u=>this.crossOriginSessionMeta(u),fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:u=>this.attachUndeliveredDeviceInfo(u),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((u,w)=>this.reportTelemetry(u,w));try{this.getWindowObserver()}catch(u){this.logger.error("Failed to attach page low-event observer",u)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Ke(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(u){this.logger.error("Failed to start password manager detection",u)}let f=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let u of f)this.telemetry(u.level,u.message);let m=new le(this.logger,this.storage,r?"cookie":"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(u,w)=>this.telemetry(u,w),this.fixedData?.privateMode??!0);this.deviceCollector=m;let y=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new pe(this.logger,m,Math.max(1,y),y,{timing:()=>this.config.deviceInfoTiming,emit:(u,w)=>this.telemetry(u,w)},()=>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(u=>this.handleConfig(u))}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 te(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}handleConfig(e){let t=Qe(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<=hn}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Ii);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(Ii,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<=mn&&gn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=yn}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Ei);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(Ei,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:li(xt(0))}createCrossOriginSession(){let e=this.fixedData?.crossOriginSession;if(e)try{return this.isTrackingBlocked()?void 0:Ve.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(We);t?.id&&typeof t.lastActiveAt=="number"&&e.set(t.id,t.lastActiveAt);let i=this.sessionStorage.getItem(ut);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(k)??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(k,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=R();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(We);if(t?.id&&e-t.lastActiveAt<this.config.sessionInactivityMs)return this.persistContinuitySession(t.id,e),this.seq=this.persistentStorage.getItem(k)??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(k,0),this.seq=0,this.logger.debug("Adopted per-tab session id as continuity session",r.id),r.id}let i=R();return this.persistContinuitySession(i,e),this.persistentStorage.setItem(k,0),this.seq=0,this.logger.debug("Created continuity session id",i),i}persistContinuitySession(e,t){this.lastActivityWriteAt=t,this.persistentStorage.setItem(We,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(ut);if(e){if(typeof e=="string")return Oi.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return Oi.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(ut,{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>=Ci&&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(We),o=!1;if(!r?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(r?.id)i-this.lastActivityWriteAt>=Ci&&this.persistContinuitySession(r.id,i),r.id!==this.sessionId&&(this.sessionId=r.id,this.queue.setSessionId(r.id),o=!0);else{let l=R();this.persistContinuitySession(l,i),this.persistentStorage.setItem(k,0),this.sessionId=l,this.queue.setSessionId(l),this.seq=0,o=!0}let s=this.persistentStorage.getItem(k);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(k,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!$t(0)?e():oe(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 Et(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,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??R(),c=l?.sessionId??this.sessionId,f=this.nextSeq(),m=typeof f=="number"?f:await f,y=this.resolveTrackingSourcePath(),u={type:"predefined",name:e,id:d,timestamp:p,seq:m,data:t,user:i,contexts:o,tags:r,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:G(),initiator:l?.initiator,trackingSourcePath:y??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},w=this.deviceInfoManager.getForEvent();w&&(u.deviceInfo=w),this.logger.debug(`Track: ${e}`,JSON.stringify(u,null,2));let T=this.passwordManagerSampler?.takeReport(c);T&&(u.passwordManagers=T),this.queue.enqueue(u,c)}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=R(),a=this.sessionId,l={...this.options.defaultTags,...this.applicationTag(),...t};return this.track("flow_started",e,void 0,l,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,l={userId:r,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:r,identifier:o,...s}=e,a={userId:r,identifier:o},l=R(),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(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??C(),captureVersion:1,pageId:e.pageId??G()},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:R(),level:e,message:i.length>xi?i.slice(0,xi):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"||!vn.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:R(),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=xn(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??=In()}nextProbeSeq(e){let t=this.probeSeqs.get(e)??0;if(this.probeSeqs.delete(e),this.probeSeqs.set(e,t+1),this.probeSeqs.size>bn){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=G(),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>=wn)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 ve(this,e)}passkeyEnrollmentFullOperation(e){return new ke(this,e)}passkeyDeletionOperationFull(e){return new Ce(this,e)}passwordLoginFullOperation(e){return new Oe(this,e)}passwordEnrollmentFullOperation(e){return new Pe(this,e)}emailLinkOperationFull(e){return new Ie(this,e)}continueEmailLinkOperation(e){return new xe(this,e)}emailOtpOperationFull(e){return new Te(this,e)}smsOtpOperationFull(e){return new Ee(this,e)}totpOperationFull(e){return new Ae(this,e)}provideIdentifierOperationFull(e){return new Le(this,e)}provideDataOperationFull(e){return new Ue(this,e)}formOperationFull(e){return new He(this,e)}socialLoginOperationFull(e){return new Re(this,e)}ssoLoginOperationFull(e){return new Fe(this,e)}appConfirmationOperationFull(e){return new De(this,e)}keySigningOperationFull(e){return new Z(this,e)}keyRegistrationOperationFull(e){return new ee(this,e)}captchaOperationFull(e){return new Me(this,e)}trustedDeviceCheckOperationFull(e){return new qe(this,e)}trustedDeviceEnrollmentOperationFull(e){return new Ne(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&&!dt(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(k)??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(k,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=R();return this.config.sessionContinuity?(this.persistContinuitySession(e,Date.now()),this.persistentStorage.setItem(k,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}},En="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function In(){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+=En[n[t]&63];return e}function xn(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,Sn))}return Object.keys(e).length>0?e:void 0}var kn=["none","presence","size","class","format","partial","enum","computed","token","pseudonym","redacted","raw"];var Cn={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function On(n,e){return je(n,"creationOptions",e)}function Pn(n,e){return je(n,"creationResponse",e)}function Ln(n){return je(n,"requestOptions")}function Rn(n,e){return je(n,"assertionResponse",e)}function je(n,e,t={}){try{let i=typeof n=="string"?JSON.parse(n):n;if(!Fn(i))return;let r=new Set(Cn[e]),o=new Set,s=(a,l,p=0)=>{if(!r.has(l)){if(e==="creationOptions"&&l==="/user/id"||(e==="creationResponse"||e==="assertionResponse")&&l==="/response/userHandle"){if(a===null)return null;if(!t.userId)return;let d=typeof a=="string"?a:a instanceof ArrayBuffer||ArrayBuffer.isView(a)?Pi(a):void 0;if(d===void 0)return;try{let c=t.userId(d);return typeof c=="string"||c===null?c:void 0}catch{return}}if(a===null||typeof a=="string"||typeof a=="boolean")return a;if(typeof a=="number")return Number.isFinite(a)?a:null;if(typeof a=="object"){if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))return Pi(a);if(p>64||o.has(a))throw new TypeError("Invalid telemetry payload");o.add(a);try{if(Array.isArray(a))return a.map((m,y)=>s(m,`${l}/${y}`,p+1));let d=Object.create(null);for(let m in a){let y=`${l}/${m.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(r.has(y)||m==="toJSON")continue;let u=s(a[m],y,p+1);u!==void 0&&(d[m]=u)}let c=a,f=(m,y)=>{if(d[y]!==void 0||typeof c[m]!="function")return;let u=`${l}/${y}`,w=s(Reflect.apply(c[m],a,[]),u,p+1);w!==void 0&&(d[y]=w)};return l===""&&(e==="creationResponse"||e==="assertionResponse")&&f("getClientExtensionResults","clientExtensionResults"),l==="/response"&&e==="creationResponse"&&(f("getTransports","transports"),f("getAuthenticatorData","authenticatorData"),f("getPublicKey","publicKey"),f("getPublicKeyAlgorithm","publicKeyAlgorithm")),d}finally{o.delete(a)}}}};return JSON.stringify(s(i,""))}catch{return}}function Fn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)}function Pi(n){let e=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength),t="";for(let i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var b;function hl(n){let e=new $e(n);return b=e,e}function gl(){return b}function ml(){return b?.resetSession()}function yl(){return b?.getSessionId()}function vl(n){b?.setUser(n)}function Sl(n,e){b?.setFlowTags(n,e)}function bl(n,e){b?.setExperiment(n,e)}function wl(n){b?.setExperiments(n)}function Tl(n){b?.clearExperiment(n)}function El(){b?.clearExperiments()}function Il(){return b?.getExperiments()??{}}function xl(n,e){b?.telemetry(n,e)}function kl(n){b?.logInfo(n)}function Cl(n){b?.logError(n)}async function Ol(){b&&(await b.destroy(),b=void 0)}export{De as AppConfirmationOperationFull,$i as AuthEventName,Ni as CEREMONY_LOW_EVENT_TAIL_MS,S as CONFIG_BOUNDS,Ht as CONFIG_CACHE_STORAGE_KEY,Bt as CONFIG_REQUEST_HEADER,ze as CONFIG_STORAGE_KEY,Me as CaptchaOperationFull,ue as CookieStorage,$e as CorbadoTracker,oo as DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS,ro as DEFAULT_FLUSH_INTERVAL_MS,er as DEFAULT_MAX_ENTRIES,tr as DEFAULT_MAX_SERIALIZED_LENGTH,v as DEFAULT_RELIABILITY_CONFIG,no as DEFAULT_SEQ_LOCK_TIMEOUT_MS,ji as DEFAULT_SESSION_INACTIVITY_MS,xe as EmailLinkContinuationOperation,Ie as EmailLinkOperationFull,Te as EmailOtpOperationFull,K as EventStore,He as FormOperationFull,ee as KeyRegistrationOperationFull,Z as KeySigningOperationFull,ce as LocalStorage,de as NamespacedStorage,Je as OUTBOX_LOCK_NAME,Zi as OUTBOX_STORAGE_KEY,h as OperationFull,Le as OperationFullProvideIdentifierWithCUI,Gt as PROBE_BATCH_MAX_BYTES,jt as PROBE_BATCH_MAX_ITEMS,sr as PROBE_PAYLOAD_MAX_BYTES,or as PROBE_QUEUE_MAX_BYTES,nr as PROBE_QUEUE_MAX_ITEMS,Ce as PasskeyDeletionOperationFull,ke as PasskeyEnrollmentOperationFull,ve as PasskeyLoginOperationFull,Pe as PasswordEnrollmentOperationFull,Oe as PasswordLoginOperationFull,Ue as ProvideDataOperationFull,Li as RAW_ERROR_BOUNDS,kn as READER_EXPOSURES,ae as RequestQueue,tt as SDK_NAME,it as SDK_VERSION,fe as SessionStorage,Ee as SmsOtpOperationFull,Re as SocialLoginOperationFull,Fe as SsoLoginOperationFull,Ae as TotpOperationFull,qe as TrustedDeviceCheckOperationFull,Ne as TrustedDeviceEnrollmentOperationFull,zt as UNLOAD_BUDGET_BYTES,Ye as UNLOAD_PROBE_MAX_BYTES,Kt as cacheConfigRecord,Tl as clearExperiment,El as clearExperiments,ui as createLogger,Ol as destroy,yi as detectPasswordManagerExtensions,Il as getExperiments,yl as getSessionId,gl as getTracker,hl as init,Ut as loadCachedConfig,ie as loadConfigRecord,Cl as logError,kl as logInfo,L as namespacedKey,U as parseReliabilityConfig,ml as resetSession,Nt as resolveFixedDataConfig,gt as resolveRawErrorLimits,Qe as resolveReliabilityConfig,Rn as sanitizeAssertionResponse,On as sanitizeCreationOptions,Pn as sanitizeCreationResponse,Ln as sanitizeRequestOptions,vt as serializeRawError,bl as setExperiment,wl as setExperiments,Sl as setFlowTags,vl as setUser,xl as telemetry,se as utf8Length};