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