@corbado/observe 1.15.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ht=0;function x(){if(Ht===4294967295)throw new Error("Low-event capture sequence exhausted");return++Ht}function Nt(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"}}import{v7 as Oi}from"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 Ii=1500,g=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:x,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??x(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),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=Oi(),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;if(o!==void 0){let s=this.tracker.rawErrors;s&&(n={...t,rawError:s(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(Ii)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??Nt(this.operationName,l);t.arm(p,l==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),n(a)},error:(s,a)=>{o.error(s,a),n(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),n(a)}}}defineStep(e,t){let i,n,o,s=l=>this.captureOptions(l,i,n,o);return{start:(l,p)=>{i=this.startReference,n=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,l,s(p),t)},finished:(l,p)=>{this.subflowStepFinished(e,l,s(p))},error:(l,p)=>{this.subflowStepError(e,{error:N(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function Bt(r,e){if(e.explicitSpecType!==void 0)try{r.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var Q=class extends g{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:Bt(e,t)})}},X=class extends g{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:Bt(e,t)})}};function ls(r,e){return new Q(r,e)}function ps(r,e){return new X(r,e)}var ft="cbo_sdk_config",qt="cbo_sdk_config_cache",Kt="X-Corbado-Observe-Config",cs=500,us=50,fs=1e3,T={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}},Pi=1800*1e3,S={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:Pi,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 A(r,e,t){return Math.min(Math.max(r,e),t)}function _(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function O(r,e){return typeof r=="boolean"?r:e}function Ut(r,e){return typeof r=="string"?r:e}function Ri(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0&&e.length<=T.flushOnFlowTypeFinished.maxNameLength).slice(0,T.flushOnFlowTypeFinished.maxEntries):[]}function Fi(r){return typeof r=="string"&&r.trim().toLowerCase()==="all"?"all":"allowlist"}function Li(r){return Array.isArray(r)?r.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=T.sourcePathQueryAllow.maxKeyLength).slice(0,T.sourcePathQueryAllow.maxEntries):[]}function B(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.version!="string"||e.version===""?null:Wt(e)}function Wt(r){let e=r.retry&&typeof r.retry=="object"?r.retry:{},t=A(_(e.baseDelayMs,S.retry.baseDelayMs),T.retryDelayMs.min,T.retryDelayMs.max);return{version:Ut(r.version,""),flushIntervalMs:A(_(r.flushIntervalMs,S.flushIntervalMs),T.flushIntervalMs.min,T.flushIntervalMs.max),durableOutbox:r.durableOutbox===!0,durableLowOutbox:r.durableLowOutbox===!0,beaconKeepalive:r.beaconKeepalive===!0,sessionContinuity:r.sessionContinuity===!0,sessionInactivityMs:A(_(r.sessionInactivityMs,S.sessionInactivityMs),T.sessionInactivityMs.min,T.sessionInactivityMs.max),seqLockTimeoutMs:A(_(r.seqLockTimeoutMs,S.seqLockTimeoutMs),T.seqLockTimeoutMs.min,T.seqLockTimeoutMs.max),tvc:O(r.tvc,S.tvc),tph:O(r.tph,S.tph),td:O(r.td,S.td),tlf:O(r.tlf,S.tlf),telemetry:O(r.telemetry,S.telemetry),flushOnTelemetry:r.flushOnTelemetry===!0,flushOnFlowTypeFinished:Ri(r.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:A(_(r.deviceInfoCollectorTimeoutMs,S.deviceInfoCollectorTimeoutMs),T.deviceInfoCollectorTimeoutMs.min,T.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:r.deviceInfoTiming===!0,rawErrors:O(r.rawErrors,S.rawErrors),pmd:O(r.pmd,S.pmd),aap:Ut(r.aap,""),sourcePathQuery:Fi(r.sourcePathQuery),sourcePathQueryAllow:Li(r.sourcePathQueryAllow),retry:{maxAttempts:A(_(e.maxAttempts,S.retry.maxAttempts),T.retryMaxAttempts.min,T.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:A(_(e.maxDelayMs,S.retry.maxDelayMs),t,T.retryDelayMs.max)}}}function Fe(r,e={}){let t=r??S,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),n=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=Wt({...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}var Ai="static";function Vt(r,e){let t;try{t=JSON.parse(r)}catch{t=void 0}let i=!!t&&typeof t=="object"&&!Array.isArray(t),n=i?t:{};return{config:Fe(void 0,{...n,version:typeof n.version=="string"&&n.version!==""?n.version:Ai,...e!==void 0&&{pmd:e}}),valid:i}}function Le(r){try{if(!r||typeof r!="object")return;let e=r,t=e.crossOriginSession,i=t&&typeof t=="object"&&typeof t.cookieDomain=="string"?t.cookieDomain:void 0;return{pmd:O(e.pmd,!1),privateMode:O(e.privateMode,!0),...i!==void 0&&{crossOriginSession:{cookieDomain:i}}}}catch{return}}function Ae(r){let e=r.getItem(qt),t=e&&typeof e=="object"?B(e.config):null;return t?{...e,config:t}:null}function $t(r){return Ae(r)?.config??B(r.getItem(ft))}function jt(r,e){r.setItem(qt,e)}function Gt(r){try{return decodeURIComponent(r.replace(/\+/g," "))}catch{return r}}function zt(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 Jt(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)===""||zt(Gt(a),t)?o:`${a}=*`}).join("&")}`}var _i=/^[A-Za-z][A-Za-z0-9_.\-[\]]{0,63}$/;function Yt(r,e){return r===""||r==="?"?r:`?${(r.startsWith("?")?r.slice(1):r).split("&").map(n=>{if(n==="")return n;let o=n.indexOf("="),s=o===-1?n:n.slice(0,o),a=Gt(s);if(zt(a,e))return n;if(o===-1)return"*";let l=_i.test(a)?s:"*";return n.length===o+1?`${l}=`:`${l}=*`}).join("&")}`}function Qt(r){let e=String(r??"").split("/").filter(t=>t!=="");return e.length===0?"/":"/"+e.map(()=>"*").join("/")}function C(r,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function U(r){return document.visibilityState==="hidden"}function Xt(r){return document.readyState==="complete"}function Zt(r,e,t){if(typeof __CBO_DATA_PAGE_STRICT__=="boolean"&&__CBO_DATA_PAGE_STRICT__)return`${Qt(window.location.pathname)}${Yt(window.location.search,t)}`;let i=Jt(window.location.search,e,t);return`${window.location.pathname}${i}`}function er(r){return{path:window.location.pathname,search:window.location.search}}function tr(r){return{hostname:window.location.hostname,https:window.location.protocol==="https:"}}function rr(r){return typeof navigator>"u"?"":navigator.userAgent??""}async function ir(r){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function nr(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function or(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function sr(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 ar(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 lr(r){if(!(typeof navigator>"u"))return navigator.webdriver}function pr(r){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}import{v7 as Di}from"uuid";var gt=(r,e,t)=>{let i=!1,n,o=null,s=null,a=()=>{s!==null&&(clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&r({...n===void 0?{}:{captureSeq:n},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),n=p}s!==null&&clearTimeout(s),s=setTimeout(a,150)},flush:a}};function dr(r,e,t){let i=[],n=(s,a,l)=>{let p=d=>t(a,()=>l(d));s.addEventListener(a,p),i.push(()=>s.removeEventListener(a,p))};n(window,"blur",()=>e.blur()),n(window,"focus",()=>e.focus()),n(document,"visibilitychange",()=>e.visibilityChange(document.visibilityState==="hidden")),n(document,"focusout",s=>e.focusOut(s.target,!!s.relatedTarget)),n(document,"focusin",s=>e.focusIn(()=>s.composedPath())),n(document,"pointerdown",s=>e.pointerDown(s.target)),window.visualViewport&&(n(window.visualViewport,"resize",()=>e.viewportResize()),n(window.visualViewport,"scroll",()=>e.viewportScroll())),n(window,"pagehide",()=>e.pageHide());let o=window.navigation;return o&&n(o,"currententrychange",s=>{let a=s,l=a.from?.index,p=o.currentEntry?.index;a.navigationType==="traverse"&&typeof l=="number"&&typeof p=="number"&&l>=0&&p>=0&&p<l&&e.navigateBack()}),i}function cr(r){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function ur(r){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var Mi,Z=()=>Mi??=Di(),_e=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=dr(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=gt(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",x);scroll=gt(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",x);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=cr(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=ur(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??x(),sourceKind:"window",captureVersion:1,pageId:Z()},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 Hi=(m=>(m.FlowStarted="flow_started",m.FlowDecided="flow_decided",m.FlowFinished="flow_finished",m.FlowReset="flow_reset",m.AuthMethodDecisionStarted="auth_method_decision_started",m.AuthMethodDecisionFinished="auth_method_decision_finished",m.FlowAutoFinished="flow_auto_finished",m.AuthDecisionStarted="auth_decision_started",m.AuthDecisionFinished="auth_decision_finished",m.SubflowStepStarted="subflow_step_started",m.SubflowStepFinished="subflow_step_finished",m.SubflowStepError="subflow_step_error",m.SubflowTrigger="subflow_trigger",m.SubflowError="subflow_error",m.SubflowStarted="subflow_started",m.SubflowFinished="subflow_finished",m.FlowEnriched="flow_enriched",m.Conversion="conversion",m))(Hi||{});var Ni=new Set;function fr(r){Ni.add(r)}function De(r,e,t){return fetch(e,t)}function gr(r){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var Bi=6e4,Ui=6e4,Me=class{constructor(e){this.options=e;fr(0)}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(),Ui):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=Bi,...n?{signal:n.signal}:{}},a=await De(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=B(await a.json());p&&(l.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return l}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{this.options.logger.debug(`Sending ${e.events.length} events via beacon`);let t=gr(0);if(!t)return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let i=new Blob([JSON.stringify(e)],{type:"text/plain"});return t(this.options.url,i)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};import{v7 as Gi}from"uuid";function He(r,e,t,i={}){let n=typeof navigator<"u"?navigator.locks:void 0;if(n?.request){let o=i.timeoutMs,s=o!==void 0&&typeof AbortController<"u"?new AbortController:null;if(o!==void 0&&!s)return Promise.resolve().then(t);try{let a=!1,l,p=()=>{l!==void 0&&(clearTimeout(l),l=void 0)},d=()=>(a=!0,p(),t()),u=s?n.request(e,{signal:s.signal},d):n.request(e,d);return s&&o!==void 0&&!a&&(l=setTimeout(()=>{l=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),u.catch(f=>{if(a)throw f;return t()}).finally(p)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function hr(r){return typeof navigator<"u"&&!!navigator.locks?.request}var qi="cbo_outbox",ht="cbo_outbox",Ki=500,Wi=512*1024,Vi=10080*60*1e3;function $i(r){let e=r.event,t=typeof e.timestamp=="number"?e.timestamp:e.ts;if(typeof t=="number"&&Number.isFinite(t))return t;let i=/^([0-9a-f]{8})-?([0-9a-f]{4})-?7/i.exec(r.id);return i?parseInt(i[1]+i[2],16):void 0}function ji(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 q=class{constructor(e,t,i=Ki,n=Wi,o=ht,s=qi){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=n;this.lockName=o;this.storageKey=s;this.entries=this.read(),typeof __CBO_DATA_RETENTION__=="boolean"&&__CBO_DATA_RETENTION__&&this.purgeExpired(Date.now())}entries=[];reportedMalformed=!1;purgeExpired(e){let t=n=>{let o=$i(n);return o!==void 0&&e-o>Vi};if(!this.entries.some(t))return;let i=this.entries.filter(t).length;this.entries=this.entries.filter(n=>!t(n)),this.logger.debug(`EventStore deleted ${i} entries past the retention limit`),this.mutate(n=>n.filter(o=>!t(o)))}read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(ji);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 He(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 mr=6e4,mt=32e3;function ee(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 zi=["cbo_visibility_change_debug","cbo_pagehide_debug"],Ne=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??S,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new q(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){for(let l of zi)this.storage.removeItem(l);this.lowStore=new q(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=[];lane;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??Gi()};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)}}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.lane?.sendUnload(mt,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(v=>v.flushAfter<=i),s=this.lane,a=e==="destroy"||!s?[]:s.items.filter(v=>v.flushAfter<=i),l=n.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0&&a.length===0;if(l&&!this.hasStandaloneDeviceInfo())break;let p=n[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??a[0]?.sessionId??this.sessionId,d=n.filter(v=>v.sessionId===p).slice(0,this.batchSize),u=o.filter(v=>v.sessionId===p).slice(0,100),f=[...u.map(v=>v.event),...this.takeLows(p,100-u.length)];this.prepareEvents(d,e);let h=p===this.sessionId?this.takeTelemetry():[],c=p===this.sessionId?this.takeStandaloneDeviceInfo():void 0,y=s&&a.length>0?s.selectBatch(a,p):[],b={sessionId:p,events:d.map(v=>v.event),sdk:this.sdk};if(f.length>0&&(b.lows=f),h.length>0&&(b.telemetry=h),y.length>0&&(b.probes=y.map(v=>v.entry)),c&&(b.deviceInfo=c),l&&!c)break;this.attachBatchMeta(b,[...d,...u,...y],e),u.length&&(b.deliveryAck=!0);let H=this.shouldRequestConfig()?{[Kt]:this.config.version||"1"}:void 0,m=await this.transport.send(b,H).catch(v=>(this.logger.error("Unexpected error in queue flush",v),{}));if(b.deliveryAck&&m.statusCode&&m.statusCode>=200&&m.statusCode<300&&!m.deliveryAccepted&&(m={...m,statusCode:503}),this.requestConfig&&this.handleConfigResponse(m),this.handleLowSendResult(m,u,i),s?.handleResult(m,y,i),!this.handleSendResult(m,d,i))break}e==="destroy"&&this.lane?.sendUnload(mt,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 q(this.storage,this.logger,void 0,void 0,this.outboxLockName);let n=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!n.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let n=e.statusCode,o=typeof n=="number"&&n>=200&&n<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(d=>d.id)),!0;if(!this.isRetryable(n))return this.removeEntries(t.map(d=>d.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],p=[];for(let d of t)d.attempts+=1,d.attempts>=s?l.push(d.id):(d.flushAfter=i+this.backoffForAttempt(d.attempts,a),p.push(d));return this.removeEntries(l),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,n=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(n=Math.min(n,i.maxDelayMs));let o=Math.round(n/2+Math.random()*(n/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer)return;let e=this.lane?this.lane.items:[];if(this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0&&e.length===0)return;let t=Date.now();if(this.getDuePending(t).length>0||this.lowPending.some(n=>n.flushAfter<=t)||this.lowsQueue.length>0||e.some(n=>n.flushAfter<=t)){this.scheduleFlush(this.flushInterval(),"timer");return}let i=Math.min(...[...this.pending,...this.lowPending,...e].map(n=>n.flushAfter));this.scheduleFlush(Math.max(0,i-t),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{U(0)&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.removeVisibilityChange=C(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=C(0,"pagehide",this.onPageHide))}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){let t=this.flushSyncEvents(e),i=this.lane;e==="pagehide"&&i&&i.items.length>0&&i.sendUnload(Math.min(mr-t,mt),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(d=>d.sessionId===t),n=i.slice(0,this.batchSize),o=this.lowPending.filter(d=>d.sessionId===t).slice(0,100),s=[...o.map(d=>d.event),...this.takeLows(t,100-o.length)];this.prepareEvents(n,e);let a=this.takeTelemetry(),l=this.takeStandaloneDeviceInfo();if(n.length===0&&s.length===0&&a.length===0&&!l)return this.dirtySinceSyncFlush=!1,0;let p={sessionId:t,events:n.map(d=>d.event),sdk:this.sdk};return s.length>0&&(p.lows=s),a.length>0&&(p.telemetry=a),l&&(p.deviceInfo=l),this.attachBatchMeta(p,[...n,...o],e),o.length&&(p.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(p)||this.transport.send(p):this.transport.send(p),this.config.durableOutbox||this.removeEntries(n.map(d=>d.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>n.length,this.approximateSize(p)}approximateSize(e){try{return ee(JSON.stringify(e))}catch{return mr}}destroy(){try{this.destroyed=!0,this.clearTimer(),this.lane&&this.lane.drop(this.lane.items.slice()),typeof window<"u"&&(this.removeVisibilityChange&&this.removeVisibilityChange(),this.removePageHide&&this.removePageHide())}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};import{v7 as vr}from"uuid";import Ji from"detectincognitojs";async function yr(r){return(await Ji()).isPrivate}var Yi=300,te=6e3,br="cbo_pm",Qi=10080*60*1e3,Sr="detectincognitojs@1.9.0",Tr={timing:!1},yt="cbo_tab_id",wr={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function I(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Er(r,e,t){return{field:r,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function vt(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 Be=class{constructor(e,t,i="localstorage",n,o=()=>Tr,s,a=!0,l){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=n;this.settings=o;this.emitTelemetry=s;this.privateModeEnabled=a;this.deviceHandleMaxAgeMs=l}pagePrivateMode;privateModeDetectionStarted=!1;lastKnown={};async collect(e,t={}){try{let i=this.resolveSettings(),n=I(),o=this.getClientEnvHandle(),s={type:"web",clientEnvHandle:o.value,clientEnvHandleMeta:{timestamp:o.timestamp,source:o.source},tabId:this.getTabId()},a=typeof __CBO_DATA_PRIVATE_MODE__=="boolean"?__CBO_DATA_PRIVATE_MODE__:this.privateModeEnabled,l=a?this.knownPrivateMode(i.timing):void 0,p,d=a&&l===void 0&&!this.privateModeDetectionStarted?this.detectPrivateMode(i.timing).then(v=>{p=v}):void 0,u=this.startFastFields();await vt(Promise.all(u.map(v=>v.promise)),Yi);let f=I()-n,h=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,u);let c=()=>p?.error?[p.error]:[];this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,c()),"fast");let y=u.filter(v=>!v.settled),b=d!==void 0&&p===void 0;if(y.length===0&&!b)return;let H=I();await Promise.all([vt(Promise.all(y.map(v=>v.promise)),te-(H-n)),d]);let m=y.filter(v=>!v.settled).map(v=>Er(v.field,v.source,te));m.push(...c()),i.timing&&y.length>0&&this.reportLateTiming(I()-n,y),this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,m),"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",()=>ir(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>sr(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>nr(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>or(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>ar(0)),this.startField("webdriver","navigator.webdriver",()=>lr(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>pr(0))]}startField(e,t,i){let n=I(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:I()-n}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:I()-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 p of t)p.settled?(p.settled.error&&a.push(p.settled.error),s[p.field]=p.settled.value,this.remember(p.field,p.settled.value)):s[p.field]=n[p.field];s.privateMode=i,a.push(...o);let l={...e,data:{bluetoothAvailable:s.bluetoothAvailable,javaScriptHighEntropy:s.javaScriptHighEntropy,privateMode:s.privateMode,webdriver:s.webdriver,conditionalMediationAvailable:s.conditionalMediationAvailable,userVerifyingPlatformAuthenticatorAvailable:s.userVerifyingPlatformAuthenticatorAvailable,clientCapabilities:s.clientCapabilities,maxTouchPoints:s.maxTouchPoints}};return a.length>0&&(l.collectionErrors=a),l}remember(e,t){t!==void 0&&(this.lastKnown[e]=t)}safePublish(e,t,i){try{e(t,i)}catch(n){this.logger.error("Failed to publish device info",n)}}knownPrivateMode(e){if(this.pagePrivateMode!==void 0)return this.pagePrivateMode;let t=this.readPrivateModeCache();return t&&(this.pagePrivateMode=t.value,e&&this.reportTelemetry(`device info privateMode from cache, age ${Math.round((Date.now()-t.ts)/1e3)}s`)),this.pagePrivateMode}canCachePrivateMode(){return this.storageSource==="localstorage"}readPrivateModeCache(){if(this.canCachePrivateMode())try{let e=this.storage.getItem(br);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==Sr)return;let t=Date.now()-e.ts;return t<0||t>=Qi?void 0:e}catch(e){this.logger.debug("Failed to read cached privateMode",e);return}}writePrivateModeCache(e){if(this.canCachePrivateMode())try{this.storage.setItem(br,{value:e,ts:Date.now(),dv:Sr})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=I(),n=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:yr(0));if(!await vt(n.promise,te)||!n.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${te}ms`),{error:Er("privateMode",t,te)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(I()-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),Tr}}reportFastTiming(e,t){let i=t.map(n=>`${wr[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=>`${wr[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)}}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle"),t=this.deviceHandleMaxAgeMs;if(e&&!(t!==void 0&&!(Date.now()-e.timestamp<=t)))return e;let i=vr(),n={timestamp:Date.now(),source:this.storageSource,value:i};return this.storage.setItem("cbo_client_env_handle",n),n}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(yt);if(e)return e;let t=vr();if(this.sessionStorage.setItem(yt,t),this.sessionStorage.getItem(yt)===t)return t}};function Xi(){return typeof document<"u"&&U(0)}var Ue=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&&Xi())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 Cr(r){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function kr(r){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function re(r){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function P(r,e){return`${r}_${e}`}var qe=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(P(e,this.namespace))}setItem(e,t){this.engine.setItem(P(e,this.namespace),t)}removeItem(e){this.engine.removeItem(P(e,this.namespace))}},Ke=class{constructor(e){this.logger=e}area=Cr(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)}}},We=class{constructor(e,t){this.logger=e;this.domain=t}jar=re(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)}}},Ve=class{constructor(e){this.logger=e}area=kr(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 $e=1,je="cbo_storage_schema",Zi=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],en=["cbo_session_id","cbo_tab_id"],tn=["cbo_client_env_handle"];function Ge(r,e,t){return r.setItem(e,t),JSON.stringify(r.getItem(e))===JSON.stringify(t)}function bt(r,e,t){let i=r.getItem(je);if(i!==null){if(i.version!==$e||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(n=>r.getItem(P(n,e))!==null))return Ge(r,je,{version:$e,projectId:e,complete:!0});if(!Ge(r,je,{version:$e,projectId:e,complete:!1}))return!1}for(let n of t){let o=P(n,e);if(r.getItem(o)!==null)continue;let s=r.getItem(n);if(s!==null&&!Ge(r,o,s))return!1}return Ge(r,je,{version:$e,projectId:e,complete:!0})}function xr(r,e,t,i,n){try{if(!bt(e,r,Zi))return;bt(t,r,en),i&&bt(i,r,tn)}catch(o){n.error("Failed to migrate legacy Observe storage",o)}}var rn=10*1e3,nn=60*1e3,on=3600*1e3,sn=300*1e3,Or=1440*60*1e3,an=[1e3,3e3];function ln(r){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(r?.get("Cache-Control")??"");if(!e)return on;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,sn),Or)}var ze=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=$t(t)??void 0,this.appliedVersion=this.initialConfig?.version}initialConfig;requestTimer;retryTimer;controller;removers=[];fetching=!1;stopped=!1;lastAttemptAt;appliedVersion;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.listen(),this.refresh())}listen(){if(typeof window>"u")return;let e=()=>{typeof document>"u"||U(0)||this.refresh()};this.removers.push(C(0,"visibilitychange",e),C(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=Ae(this.storage),{fetchedAt:i,expiresAt:n}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof n=="number"&&i>0&&n-i<=Or&&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<nn)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(),rn):void 0;let i=!0;try{let n=await De(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=B(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();jt(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+ln(n.headers),config:s}),Ae(this.storage)&&this.storage.removeItem(ft),this.appliedVersion=s.version,this.onConfig?.(s)}catch(n){if(!this.stopped){this.logger.error("Failed to fetch SDK config",n);let o=an[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}};import{v7 as D}from"uuid";var pn=["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 Ir(r){if(!r)return!1;let e=r.toLowerCase();return pn.some(t=>e.includes(t))}var St="@corbado/observe",Tt="1.15.0";function Pr(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 dn="/inline/injected/webauthn-listeners.js",Rr=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,cn=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,un=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,Fr=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,fn=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,gn=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,hn=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,wt=()=>Object.keys(window._sentryDebugIds??{}),Et=r=>{try{r()}catch(e){return String(e?.stack??"")}return""},Lr=()=>Et(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),mn=()=>{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]")},Ct=(...r)=>{let e=navigator.credentials;return e?r.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},yn=()=>[navigator.credentials?.get,...Ct("get","_get")].some(r=>typeof r=="function"&&r.name==="getWebAuthnCredential"),vn=()=>{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)}},bn,Sn=()=>bn??=vn(),Tn=()=>{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},wn=()=>{let r={get nodeType(){throw new Error("probe")}};return Et(()=>MutationObserver.prototype.observe.call(null,r))},En=()=>{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},Cn=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...Ct("get","_get","create")].some(e=>typeof e=="function"&&gn.test(Function.prototype.toString.call(e))),kn=()=>{let r=document;for(;r;){if(r.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;r=r.activeElement?.shadowRoot}return!1},xn=()=>{let r=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...Ct("get","_get"),r?.isConditionalMediationAvailable,r?._isConditionalMediationAvailable,r?.isUserVerifyingPlatformAuthenticatorAvailable,r?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&hn.test(Function.prototype.toString.call(t)))},On=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:mn},{name:"1password",signal:"Sentry debug id",test:()=>wt().some(r=>r.includes(dn))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:yn},{name:"bitwarden",signal:"autofill keyframes",test:Sn},{name:"dashlane",signal:"injected script tag",test:()=>document.querySelector('script[src*="-extension://"][src*="/dashlane-"][src$="-page-script.js"]')!==null},{name:"dashlane",signal:"PublicKeyCredential hasInstance trap",test:Tn},{name:"dashlane",signal:"page script stack",test:()=>Rr.test(Lr())||typeof HTMLDialogElement<"u"&&Rr.test(Et(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>cn.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>un.test(Lr())},{name:"keeper",signal:"override source",test:Cn},{name:"keeper",signal:"field lock",test:()=>document.querySelector("[data-keeper-lock-id]")!==null},{name:"lastpass",signal:"passkey override",signedIn:!0,test:()=>typeof window.__nativeCredentialsGet=="function"},{name:"lastpass",signal:"icon root",test:kn},{name:"nordpass",signal:"observer proxy stack",test:()=>Fr.test(wn())},{name:"nordpass",signal:"observer read order",test:En},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>wt().some(r=>fn.test(r))},{name:"nordpass",signal:"Sentry debug id",test:()=>wt().some(r=>Fr.test(r))},{name:"protonpass",signal:"WebAuthn override source",test:xn},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function In(){return typeof window>"u"||typeof document>"u"?[]:On.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 Ar(){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 _r(r){return Ar()}var Dr=3e3,Pn=500,Rn=6,Fn=1e3,Je=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),Xt(0))this.sampleAfter(Dr);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(Dr)};this.removers.push(C(0,"load",o,{once:!0}))}let n=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=Rn&&n(),this.sampleAfter(Pn))});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:Fn});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=_r(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 ie="cbo_session_id",K="cbo_session",k="cbo_seq",kt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var xt={name:St,version:Tt},Ln=/^[0-9A-Za-z.+_-]{1,32}$/;function An(r,e){return r===void 0?xt:typeof r=="string"&&Ln.test(r)?{...xt,integrationVersion:r}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),xt)}var Mr="cbo_experiments",Hr="cbo_data_policy",_n=255,Dn=/^[A-Za-z0-9_-]+$/,Mn=128,Hn=256,Nr=1e3,Nn=50,Bn="cbo_seq",Br=1e3,W=class r{constructor(e,t=[]){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Pr({debug:this.options.debug});let i=t.concat(Array.isArray(e.plugins)?e.plugins:[]),n=new Ke(this.logger),o=new Ve(this.logger),s;this.eachPlugin(i,c=>{c.storage&&(s=c.storage(this.logger)||s)}),xr(e.projectId,n,o,s?.engine,this.logger);let a=e.projectId,l=c=>new qe(c,a);if(this.seqLockName=P(Bn,a),this.sessionStorage=l(o),this.persistentStorage=l(n),this.storage=l(s?.engine??n),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=Le(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd),typeof __CBO_SDK_CONFIG__=="string"){let c=Vt(__CBO_SDK_CONFIG__,this.fixedData?.pmd);this.config=c.config,c.valid||this.logger.error("Invalid static SDK config: running the built-in defaults")}else{let c=Object.keys(S).every(b=>this.configOverrides[b]!==void 0)&&Object.keys(S.retry).every(b=>this.configOverrides.retry?.[b]!==void 0);c||(this.configManager=new ze(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let y=this.configManager?.initialConfig;this.config=Fe(y,this.configOverrides),!c&&!y&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!c&&!y&&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 p=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${p}`);let d=new Me({logger:this.logger,url:p});this.eachPlugin(i,c=>{c.session&&(this.bridge=c.session(this)||this.bridge),c.rawErrors&&(this.rawErrors=c.rawErrors),typeof c.sourcePath=="function"&&(this.fixedSourcePath=c.sourcePath),c.eventTime&&(this.eventClock=c.eventTime),c.deviceHandleMaxAgeMs!==void 0&&(this.deviceHandleMaxAgeMs=c.deviceHandleMaxAgeMs)}),e.fixedDataConfig?.crossOriginSession&&!this.bridge&&this.logger.warn("fixedDataConfig.crossOriginSession is ignored without the crossOriginSession() plugin"),this.sessionId=this.resolveSession(),this.queue=new Ne(this.logger,d,this.sessionId,An(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:P(ht,a),getDataPolicy:()=>this.dataPolicy,getCrossOriginSession:c=>this.bridge?.meta(c),fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:c=>this.attachUndeliveredDeviceInfo(c),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((c,y)=>this.reportTelemetry(c,y));try{this.getWindowObserver()}catch(c){this.logger.error("Failed to attach page low-event observer",c)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Je(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(c){this.logger.error("Failed to start password manager detection",c)}let u=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let c of u)this.telemetry(c.level,c.message);let f=new Be(this.logger,this.storage,s?.source??"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(c,y)=>this.telemetry(c,y),this.fixedData?.privateMode??!0,this.deviceHandleMaxAgeMs);this.deviceCollector=f;let h=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new Ue(this.logger,f,Math.max(1,h),h,{timing:()=>this.config.deviceInfoTiming,emit:(c,y)=>this.telemetry(c,y)},()=>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)),this.eachPlugin(i,c=>{c.setup&&c.setup(this)})}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=[];windowObserver;passwordManagerSampler;bridge;rawErrors;fixedSourcePath;eventClock;deviceHandleMaxAgeMs;getWindowObserver(){return this.windowObserver??=new _e(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}eachPlugin(e,t){for(let i of e)try{i&&t(i)}catch(n){this.logger.error("Failed to install tracker plugin",n)}}isFullTracker(){return!1}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()}:{}}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)}}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<=_n}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Hr);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(Hr,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Mn&&Dn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=Hn}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Mr);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(Mr,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:Ir(rr(0))}resolveSession(){return this.bridge?this.bridge.resolve():this.resolveSessionId()}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=D();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(K);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=D();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(K,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(ie);if(e){if(typeof e=="string")return kt.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return kt.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(ie,{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>=Br&&this.persistPerTabSession(this.sessionId,i);let n=this.bridge?this.bridge.claim(this.sessionId,this.seq,i):this.seq;return this.seq=n+1,n}let e=()=>{let i=Date.now(),n=this.persistentStorage.getItem(K),o=!1;if(!n?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(n?.id)i-this.lastActivityWriteAt>=Br&&this.persistContinuitySession(n.id,i),n.id!==this.sessionId&&(this.sessionId=n.id,this.queue.setSessionId(n.id),o=!0);else{let l=D();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.bridge&&(a=this.bridge.claim(this.sessionId,a,i)),this.seq=a+1,this.persistentStorage.setItem(k,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!hr(0)?e():He(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")){if(this.fixedSourcePath)try{let e=this.fixedSourcePath();return typeof e=="string"?e:void 0}catch{return}return Zt(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})}async track(e,t,i,n,o,s,a,l){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=this.eventClock?.(s)??s??Date.now(),d=l?.id??D(),u=l?.sessionId??this.sessionId,f=this.nextSeq(),h=typeof f=="number"?f:await f,c=this.resolveTrackingSourcePath(),y={type:"predefined",name:e,id:d,timestamp:p,seq:h,data:t,user:i,contexts:o,tags:n,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:Z(),initiator:l?.initiator,trackingSourcePath:c??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},b=this.deviceInfoManager.getForEvent();b&&(y.deviceInfo=b),this.logger.debug(`Track: ${e}`,JSON.stringify(y,null,2));let H=this.passwordManagerSampler?.takeReport(u);H&&(y.passwordManagers=H),this.queue.enqueue(y,u)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,n,o){try{let s=D(),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)}flowFinished(e,t,i){try{let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o},l=D(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:p}),this.flowHandle(l,p)}catch(n){return this.logger.warn("Failed to finish flow",n),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(n){this.logger.warn("Failed to enrich flow",n)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}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)}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??x(),captureVersion:1,pageId:e.pageId??Z()},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:D(),level:e,message:i.length>Nr?i.slice(0,Nr):i,ts:Date.now()};this.queue.enqueueTelemetry(n)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}attachUndeliveredDeviceInfo(e){try{let t=this.deviceInfoManager;if(!t?.hasUndelivered())return;let i=Z(),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>=Nn)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}async destroy(){if(this.bridge?.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}};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 ne=class extends g{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()}};function Da(r,e){return new ne(r,e)}var $=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;runSeq;markInputObserved(){this.prefillSettled=!0}observe(){this.runSeq!==void 0||this.inputBatch||this.autofillTimestamps.length>0||this.autofillStreak||(this.runSeq=this.reserveCaptureSeq?.())}takeSeq(){let e=this.runSeq;return this.runSeq=void 0,e??this.reserveCaptureSeq?.()}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect){let i=this.inputBatch;if(!i){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:this.takeSeq()};return}i.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e,this.ringEffect);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let n=1;n<e.length;n++){let o=e[n]-e[n-1];if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1){this.observe(),this.markInputObserved(),this.scheduleIdle();let n=this.previousLength;this.currentEffect=e===0?"clear":n===0?"fill":"modify";let o=e-n;if(this.previousLength=e,e===0&&n>0){this.flush();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}if(o>=3){this.flushInputBatch(),this.flushAutofillStreak();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(o<=-3){this.flushInputBatch(),this.flushAutofillStreak();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let s=this.autofillStreak;if(s){if(o===1&&t-s.lastTimestamp<=80){s.lastTimestamp=t;return}this.flushAutofillStreak()}if(o!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}let a=this.autofillTimestamps;if(a.length===0&&(this.ringEffect=this.currentEffect),a.push(t),a.length>5){let d=a.shift();this.extendInputBatch(d,this.ringEffect),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let l=a[0],p=a[a.length-1];a.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:l,captureSeq:this.takeSeq(),lastTimestamp:p,effect:this.ringEffect}}};var j=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)}lengthsBefore=null;applied=!1;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.lengthsBefore)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?(this.applied=!0,!0):(this.clear(),!1)}get pending(){return this.lengthsBefore!==null}begin(e){if(!(!e.isTrusted||this.lengthsBefore))try{this.lengthsBefore=this.inputs.map(t=>t.value.length),this.applied=!1,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.lengthsBefore;if(!e)return;let t=this.timestamp,i=this.captureSeq,n=this.applied;this.clear();try{(n||this.inputs.some((s,a)=>s.value.length!==e[a]))&&this.changed(t,i)}catch(o){this.logger.error("Failed to finish paste observation",o)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.lengthsBefore=null,this.applied=!1,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 Un=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Ye(r,e,t,i,n=Un){let o=[];for(let s of n){let a=qn(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 qn(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 Ur(r,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function qr(r,e){return e.reduce((t,i)=>t+i.value.length,0)}function Qe(r,e){let t=document.activeElement;return e.find(i=>i===t)}function oe(r){return Ur(0,r)}var E=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new $(oe(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new j(0,[t],e,(n,o)=>{this.changes.flush(),this.changes.markInputObserved();let s=this.changes.previousLength;this.changes.previousLength=oe(t),this.pushLow({...o===void 0?{}:{captureSeq:o},lowType:"input-paste",ts:n,inputEffect:oe(t)===0?"clear":s===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;removeFieldListeners;removePageHide;changes;pasteObserver;destroyed=!1;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;this.removeFieldListeners=Ye(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=C(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&Qe(0,[e])&&this.handleFocus()}detach(){this.removeFieldListeners?.(),typeof window<"u"&&this.removePageHide?.()}pushLow=e=>{this.sink.enqueueLowEvent(e)};capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(oe(this.inputField),e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e,t){this.pasteObserver.handlesInput(e)||this.changes.record(oe(this.inputField),Date.now(),t)}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}};var Xe=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new $(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new j(0,this.inputs,e,(o,s)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:o,inputEffect:this.length()===0?"clear":a===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(Ye(0,o,{input:(s,a)=>{this.paste.handlesInput(a)||(this.composing||=s,this.changeTimer===null&&(this.changeTime=Date.now(),this.changes.observe(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))},focus:s=>{this.contains(s)||this.emit("focus")},blur:s=>{this.contains(s)||(this.flushPending(),this.emit("blur"))},click:()=>this.emit("click"),pointerdown:()=>this.emit("pointerdown"),pointerup:()=>this.emit("pointerup"),keyupEscape:()=>this.emit("keyup-escape")},n,["input","focus","blur","click","pointerdown","pointerup","keyup"]));typeof window<"u"&&this.listeners.push(C(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&Qe(0,this.inputs)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return qr(0,this.inputs)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var L=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 Xe(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 se=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function tl(r,e){return new se(r,e)}var ae=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function ol(r,e){return new ae(r,e)}import{v7 as Kn}from"uuid";var le="cbo_email_link_starts";function Ot(r,e){let t=r.getItem(le);if(!Array.isArray(t))return[];let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.transactionId=="string"&&typeof n.anchor=="string"&&typeof n.sessionId=="string"&&typeof n.startedAt=="number"&&e-n.startedAt<864e5);return typeof __CBO_DATA_RETENTION__=="boolean"&&__CBO_DATA_RETENTION__&&i.length<t.length&&(i.length===0?r.removeItem(le):r.setItem(le,i)),i}function Kr(r,e){if(r)try{let t=Ot(r,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),r.setItem(le,t.slice(-10))}catch{}}function Wr(r,e,t=Date.now()){if(r)try{let i=Ot(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 Vr(r,e){if(r)try{let t=Ot(r,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);r.setItem(le,t)}catch{}}var pe=class extends g{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||Kn(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,n=this.captureSession;i&&n&&Kr(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:n,specType:t.explicitSpecType,startedAt:Date.now()})}},de=class extends g{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();removePageHide;constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),n=Wr(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=C(0,"pagehide",this.onPageHide))}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&this.removePageHide?.()}deferrable(e,t=!1){let i=(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&&Vr(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(n,o)=>i(s=>e.error(n,{...o,explicitTimestamp:s}),o)}}};function ul(r,e){return new pe(r,e)}function fl(r,e){return new de(r,e)}var ce=class extends g{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 yl(r,e){return new ce(r,e)}var ue=class extends g{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};function Sl(r,e){return new ue(r,e)}var fe=class extends g{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new 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()}};function Cl(r,e){return new fe(r,e)}var ge=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function Il(r,e){return new ge(r,e)}var he=class extends g{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,n)=>{this.trigger(i,n)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,n)=>{this.trigger(i,n)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function Ll(r,e){return new he(r,e)}var me=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType,entry:t.entry})}};function Dl(r,e){return new me(r,e)}var ye=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:n,actor:o}=Wn(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:n,actor:o})}};function Wn(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}function Nl(r,e){return new ye(r,e)}var ve=class extends g{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function Kl(r,e){return new ve(r,e)}var be=class extends g{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function $l(r,e){return new be(r,e)}var Se=class extends g{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function zl(r,e){return new Se(r,e)}var Ze=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 It=50,Vn=6e4,$n=40,jn=/^[A-Za-z0-9._-]+$/,we=class extends g{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(zn(e,t),Gn(e,t)),this.inputBinding=this.createLowCollector(()=>new Ze(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 Gn(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>Vn){Te(r,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function zn(r,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:Te(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 Te(r,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=n.filter(s=>typeof s=="string"&&s.length<=$n&&jn.test(s));return o.length<n.length&&Te(r,"Form: unsupported field names omitted from telemetry"),o.length>It&&Te(r,`Form: more than ${It} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,It)),t}function Te(r,e){try{r.getLogger().warn(e)}catch{}}function ep(r,e){return new we(r,e)}function Pt(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 et(r,e,t){return{...r,start:(i,n)=>r.start(Pt(i,e,t),n),finished:(i,n)=>r.finished(Pt(i,e,t),n)}}var Ee=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=$r(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{...et(n,t,i),errorTyped:(o,s)=>{n.errorTyped(Pt({code:o?.code,error:N(o?.error)},t,i),s)}}}},Ce=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=$r(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=et(this.defineStep("get-options"),i,e),this.ceremony=et(this.defineStep("ceremony"),i,e),this.postResponse=et(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function $r(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}function np(r,e){return new Ee(r,e)}function op(r,e){return new Ce(r,e)}var ke=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...n}=t;this.subflowStart(n),i&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function pp(r,e){return new ke(r,e)}var jr;function tt(r){jr=r}function w(){return jr}function R(r){return!!r&&typeof r=="object"&&typeof r.track=="function"&&typeof r.enqueueLowEvent=="function"}import{v7 as Jn}from"uuid";function rt(r){let e=Jn();return r.config.sessionContinuity?(r.persistContinuitySession(e,Date.now()),r.persistentStorage.setItem(k,0)):r.persistPerTabSession(e,Date.now()),r.sessionId=e,r.seq=0,r.queue.setSessionId(e),r.bridge?.reset(e),r.getLogger().debug(`Session reset: ${e}`),e}function it(r,e){r.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}function nt(r,e,t){let i=r.getLogger();try{if(!e||typeof e!="object"){i.warn("setFlowTags: ignoring non-object tags");return}let n={};for(let[s,a]of Object.entries(e)){if(s===""||typeof a!="string"){i.warn(`setFlowTags: ignoring invalid tag "${s}"`);continue}n[s]=a}if(Object.keys(n).length===0)return;let o={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(o.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(o.expFol=t.expandToFollowing),r.track("flow_enriched",o,void 0,n)}catch(n){i.warn("Failed to set flow tags",n)}}function ot(r,e){try{Object.prototype.hasOwnProperty.call(r.experiments,e)&&(delete r.experiments[e],r.persistExperiments())}catch(t){r.getLogger().error("Failed to clear experiment",t)}}function st(r){try{if(Object.keys(r.experiments).length===0)return;r.experiments={},r.persistExperiments()}catch(e){r.getLogger().error("Failed to clear experiments",e)}}function yp(r){let e=R(r)?r:w();return e?rt(e):void 0}function vp(r,e){let[t,i]=R(r)?[r,e]:[w(),r];t&&it(t,i)}function bp(r,e,t){let i=R(r),n=i?r:w();n&&nt(n,i?e:r,i?t:e)}function Sp(r,e,t){R(r)?r.setExperiments({[e]:t}):w()?.setExperiments({[r]:e})}function Tp(r,e){let[t,i]=R(r)?[r,e]:[w(),r];t&&ot(t,i)}function wp(r){let e=R(r)?r:w();e&&st(e)}function Ep(r,e){R(r)?r.telemetry("info",e):w()?.telemetry("info",r)}function Cp(r,e){R(r)?r.telemetry("error",e):w()?.telemetry("error",r)}function Gr(r,e,t,i){let{userId:n,identifier:o,crossEnvironmentTransactionID:s,...a}=e,l={userId:n,identifier:o,crossEnvironmentTransactionID:s},p={...r.options.defaultTags,...r.applicationTag(),...t};r.track("conversion",a,l,p,void 0,void 0,i)}function zr(r,e,t,i){r.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}function Jr(r,e,t,i){r.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}function Yr(r,e,t,i){let n={subflowType:e,stepData:t};r.track("subflow_error",n,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}var Yn={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}},Qn=1024,z=class extends Error{},Xn=["name","message","code","errors","stack"],Zn=/[^\x20-\x7E]/,J=r=>Object.prototype.toString.call(r).slice(8,-1),eo=r=>r===null?"null":typeof r=="object"?J(r):typeof r,to=r=>r instanceof Error||J(r)==="Error"||J(r)==="DOMException";function Zr(r){return Zn.test(r)?new TextEncoder().encode(r).byteLength:r.length}function G(r,e){let t=Yn[r];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function Qr(r={}){return{stack:r.stack===!0,maxStackFrames:G("maxStackFrames",r.maxStackFrames),depth:G("depth",r.depth),maxBreadth:G("maxBreadth",r.maxBreadth),maxValueLength:G("maxValueLength",r.maxValueLength),maxCauseDepth:G("maxCauseDepth",r.maxCauseDepth),maxBytes:G("maxBytes",r.maxBytes)}}function ei(r,e={}){if(r===void 0)return;let t=Qr(),i=n=>{let o=JSON.stringify(n);return o===void 0||Zr(o)<=t.maxBytes};try{if(t=Qr(e),t.maxBytes===0)return;let n=M(eo(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:at(r,s,a)};if(i(l))return l}catch(l){if(!(l instanceof z))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 xe(r,e){if(r.length>e.limits.maxBytes)throw new z;if(e.textBytes+=Zr(JSON.stringify(r)),e.textBytes>e.limits.maxBytes)throw new z;return r}function at(r,e,t){if(++t.nodes>Qn)throw new z;let i=ro(r,e,t);return typeof i=="string"?xe(i,t):i}function ro(r,e,t){switch(typeof r){case"string":return M(r,t.limits.maxValueLength);case"number":return Number.isFinite(r)?r:String(r);case"boolean":case"undefined":return r;case"bigint":case"symbol":return M(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`[${J(i)}]`;t.seen.add(i);try{return io(i,e,t)}finally{t.seen.delete(i)}}function M(r,e){return r.length>e?r.slice(0,e)+"\u2026":r}function Xr(r,e,t){let i=r.length>t;r=M(r,t);let n=r.split(`
1
+ var Ht=0;function x(){if(Ht===4294967295)throw new Error("Low-event capture sequence exhausted");return++Ht}function Nt(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"}}import{v7 as Oi}from"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 Ii=1500,g=class{constructor(e,t){this.tracker=e;this.operationName=t}startReference;captureSpecType;captureSessionId;lowFlushers=[];lowPrefillCapturers=[];lowEventSink(e,t){return{reserveCaptureSeq:x,enqueueLowEvent:i=>this.tracker.enqueueLowEvent({...i,captureSeq:i.captureSeq??x(),subflowStartEventId:this.startReference,sourceKind:e,fieldRole:t,initiator:i.initiator??(t?`input-${t}`:"unknown")},this.captureSessionId),flushKeepalive:()=>this.tracker.lowEventFlushKeepalive(),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=Oi(),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;if(o!==void 0){let s=this.tracker.rawErrors;s&&(n={...t,rawError:s(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(Ii)},o=e;return{...e,start:(s,a)=>{i=a?.subflowStartEventId??this.startReference;let l=s?.explicitSpecType??this.captureSpecType,p=a?.initiator??Nt(this.operationName,l);t.arm(p,l==="passkey-cui"),o.start(s,p?{...a,initiator:p}:a)},finished:(s,a)=>{o.finished(s,a),n(a)},error:(s,a)=>{o.error(s,a),n(a)},errorTyped:(s,a)=>{o.errorTyped?.(s,a),n(a)}}}defineStep(e,t){let i,n,o,s=l=>this.captureOptions(l,i,n,o);return{start:(l,p)=>{i=this.startReference,n=this.captureSessionId,o=p?.initiator,this.subflowStepStarted(e,l,s(p),t)},finished:(l,p)=>{this.subflowStepFinished(e,l,s(p))},error:(l,p)=>{this.subflowStepError(e,{error:N(l)},s(p))},errorTyped:(l,p)=>{this.subflowStepError(e,l,s(p))}}}};function Bt(r,e){if(e.explicitSpecType!==void 0)try{r.getLogger().warn("Unsupported key operation spec type; omitting it")}catch{}}var Q=class extends g{prepare;sign;constructor(e,t={}){super(e,"key-signing"),this.prepare=this.defineStep("prepare"),this.sign=this.defineStep("sign"),this.subflowStart({actor:"system",explicitSpecType:Bt(e,t)})}},X=class extends g{prepare;postResponse;constructor(e,t={}){super(e,"key-registration"),this.prepare=this.defineStep("prepare"),this.postResponse=this.defineStep("post-response"),this.subflowStart({actor:"system",explicitSpecType:Bt(e,t)})}};function ls(r,e){return new Q(r,e)}function ps(r,e){return new X(r,e)}var ft="cbo_sdk_config",qt="cbo_sdk_config_cache",Kt="X-Corbado-Observe-Config",cs=500,us=50,fs=1e3,T={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}},Pi=1800*1e3,S={version:"",flushIntervalMs:500,durableOutbox:!1,durableLowOutbox:!1,beaconKeepalive:!1,sessionContinuity:!1,sessionInactivityMs:Pi,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 A(r,e,t){return Math.min(Math.max(r,e),t)}function _(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function O(r,e){return typeof r=="boolean"?r:e}function Ut(r,e){return typeof r=="string"?r:e}function Ri(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0&&e.length<=T.flushOnFlowTypeFinished.maxNameLength).slice(0,T.flushOnFlowTypeFinished.maxEntries):[]}function Fi(r){return typeof r=="string"&&r.trim().toLowerCase()==="all"?"all":"allowlist"}function Li(r){return Array.isArray(r)?r.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0&&e.length<=T.sourcePathQueryAllow.maxKeyLength).slice(0,T.sourcePathQueryAllow.maxEntries):[]}function B(r){if(!r||typeof r!="object")return null;let e=r;return typeof e.version!="string"||e.version===""?null:Wt(e)}function Wt(r){let e=r.retry&&typeof r.retry=="object"?r.retry:{},t=A(_(e.baseDelayMs,S.retry.baseDelayMs),T.retryDelayMs.min,T.retryDelayMs.max);return{version:Ut(r.version,""),flushIntervalMs:A(_(r.flushIntervalMs,S.flushIntervalMs),T.flushIntervalMs.min,T.flushIntervalMs.max),durableOutbox:r.durableOutbox===!0,durableLowOutbox:r.durableLowOutbox===!0,beaconKeepalive:r.beaconKeepalive===!0,sessionContinuity:r.sessionContinuity===!0,sessionInactivityMs:A(_(r.sessionInactivityMs,S.sessionInactivityMs),T.sessionInactivityMs.min,T.sessionInactivityMs.max),seqLockTimeoutMs:A(_(r.seqLockTimeoutMs,S.seqLockTimeoutMs),T.seqLockTimeoutMs.min,T.seqLockTimeoutMs.max),tvc:O(r.tvc,S.tvc),tph:O(r.tph,S.tph),td:O(r.td,S.td),tlf:O(r.tlf,S.tlf),telemetry:O(r.telemetry,S.telemetry),flushOnTelemetry:r.flushOnTelemetry===!0,flushOnFlowTypeFinished:Ri(r.flushOnFlowTypeFinished),deviceInfoCollectorTimeoutMs:A(_(r.deviceInfoCollectorTimeoutMs,S.deviceInfoCollectorTimeoutMs),T.deviceInfoCollectorTimeoutMs.min,T.deviceInfoCollectorTimeoutMs.max),deviceInfoTiming:r.deviceInfoTiming===!0,rawErrors:O(r.rawErrors,S.rawErrors),pmd:O(r.pmd,S.pmd),aap:Ut(r.aap,""),sourcePathQuery:Fi(r.sourcePathQuery),sourcePathQueryAllow:Li(r.sourcePathQueryAllow),retry:{maxAttempts:A(_(e.maxAttempts,S.retry.maxAttempts),T.retryMaxAttempts.min,T.retryMaxAttempts.max),baseDelayMs:t,maxDelayMs:A(_(e.maxDelayMs,S.retry.maxDelayMs),t,T.retryDelayMs.max)}}}function Fe(r,e={}){let t=r??S,i=Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0)),n=Object.fromEntries(Object.entries(e.retry??{}).filter(([,s])=>s!==void 0)),o=Wt({...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}var Ai="static";function Vt(r,e){let t;try{t=JSON.parse(r)}catch{t=void 0}let i=!!t&&typeof t=="object"&&!Array.isArray(t),n=i?t:{};return{config:Fe(void 0,{...n,version:typeof n.version=="string"&&n.version!==""?n.version:Ai,...e!==void 0&&{pmd:e}}),valid:i}}function Le(r){try{if(!r||typeof r!="object")return;let e=r,t=e.crossOriginSession,i=t&&typeof t=="object"&&typeof t.cookieDomain=="string"?t.cookieDomain:void 0;return{pmd:O(e.pmd,!1),privateMode:O(e.privateMode,!0),...i!==void 0&&{crossOriginSession:{cookieDomain:i}}}}catch{return}}function Ae(r){let e=r.getItem(qt),t=e&&typeof e=="object"?B(e.config):null;return t?{...e,config:t}:null}function $t(r){return Ae(r)?.config??B(r.getItem(ft))}function jt(r,e){r.setItem(qt,e)}function Gt(r){try{return decodeURIComponent(r.replace(/\+/g," "))}catch{return r}}function zt(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 Jt(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)===""||zt(Gt(a),t)?o:`${a}=*`}).join("&")}`}var _i=/^[A-Za-z][A-Za-z0-9_.\-[\]]{0,63}$/;function Yt(r,e){return r===""||r==="?"?r:`?${(r.startsWith("?")?r.slice(1):r).split("&").map(n=>{if(n==="")return n;let o=n.indexOf("="),s=o===-1?n:n.slice(0,o),a=Gt(s);if(zt(a,e))return n;if(o===-1)return"*";let l=_i.test(a)?s:"*";return n.length===o+1?`${l}=`:`${l}=*`}).join("&")}`}function Qt(r){let e=String(r??"").split("/").filter(t=>t!=="");return e.length===0?"/":"/"+e.map(()=>"*").join("/")}function C(r,e,t,i){return i===void 0?window.addEventListener(e,t):window.addEventListener(e,t,i),()=>window.removeEventListener(e,t)}function U(r){return document.visibilityState==="hidden"}function Xt(r){return document.readyState==="complete"}function Zt(r,e,t){if(typeof __CBO_DATA_PAGE_STRICT__=="boolean"&&__CBO_DATA_PAGE_STRICT__)return`${Qt(window.location.pathname)}${Yt(window.location.search,t)}`;let i=Jt(window.location.search,e,t);return`${window.location.pathname}${i}`}function er(r){return{path:window.location.pathname,search:window.location.search}}function tr(r){return{hostname:window.location.hostname,https:window.location.protocol==="https:"}}function rr(r){return typeof navigator>"u"?"":navigator.userAgent??""}async function ir(r){if(!(typeof navigator>"u"||!navigator.bluetooth))return await navigator.bluetooth.getAvailability()}async function nr(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable))return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}async function or(r){if(!(typeof PublicKeyCredential>"u"||!PublicKeyCredential.isConditionalMediationAvailable))return await PublicKeyCredential.isConditionalMediationAvailable()}async function sr(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 ar(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 lr(r){if(!(typeof navigator>"u"))return navigator.webdriver}function pr(r){if(!(typeof navigator>"u"||typeof navigator.maxTouchPoints!="number"))return navigator.maxTouchPoints}import{v7 as Di}from"uuid";var gt=(r,e,t)=>{let i=!1,n,o=null,s=null,a=()=>{s!==null&&(clearTimeout(s),s=null);let p=o;i=!1,o=null,p!==null&&r({...n===void 0?{}:{captureSeq:n},lowType:e,ts:p,durationMs:Date.now()-p})};return{extend:()=>{if(!i){let p=t?.();i=!0,o=Date.now(),n=p}s!==null&&clearTimeout(s),s=setTimeout(a,150)},flush:a}};function dr(r,e,t){let i=[],n=(s,a,l)=>{let p=d=>t(a,()=>l(d));s.addEventListener(a,p),i.push(()=>s.removeEventListener(a,p))};n(window,"blur",()=>e.blur()),n(window,"focus",()=>e.focus()),n(document,"visibilitychange",()=>e.visibilityChange(document.visibilityState==="hidden")),n(document,"focusout",s=>e.focusOut(s.target,!!s.relatedTarget)),n(document,"focusin",s=>e.focusIn(()=>s.composedPath())),n(document,"pointerdown",s=>e.pointerDown(s.target)),window.visualViewport&&(n(window.visualViewport,"resize",()=>e.viewportResize()),n(window.visualViewport,"scroll",()=>e.viewportScroll())),n(window,"pagehide",()=>e.pageHide());let o=window.navigation;return o&&n(o,"currententrychange",s=>{let a=s,l=a.from?.index,p=o.currentEntry?.index;a.navigationType==="traverse"&&typeof l=="number"&&typeof p=="number"&&l>=0&&p>=0&&p<l&&e.navigateBack()}),i}function cr(r){let e=[];for(let t=document.activeElement;t;t=t.shadowRoot?.activeElement??null)e.push(t);return e}function ur(r){let e=document.activeElement;return{active:e,idle:e===document.body||!e}}var Mi,Z=()=>Mi??=Di(),_e=class{constructor(e,t,i){this.logger=e;this.enqueue=t;this.flushKeepalive=i;typeof window>"u"||typeof document>"u"||(this.removers=dr(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=gt(e=>this.emit(e,this.viewportContext.resize),"visualviewport-resize",x);scroll=gt(e=>this.emit(e,this.viewportContext.scroll),"visualviewport-scroll",x);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=cr(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=ur(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??x(),sourceKind:"window",captureVersion:1,pageId:Z()},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 Hi=(m=>(m.FlowStarted="flow_started",m.FlowDecided="flow_decided",m.FlowFinished="flow_finished",m.FlowReset="flow_reset",m.AuthMethodDecisionStarted="auth_method_decision_started",m.AuthMethodDecisionFinished="auth_method_decision_finished",m.FlowAutoFinished="flow_auto_finished",m.AuthDecisionStarted="auth_decision_started",m.AuthDecisionFinished="auth_decision_finished",m.SubflowStepStarted="subflow_step_started",m.SubflowStepFinished="subflow_step_finished",m.SubflowStepError="subflow_step_error",m.SubflowTrigger="subflow_trigger",m.SubflowError="subflow_error",m.SubflowStarted="subflow_started",m.SubflowFinished="subflow_finished",m.FlowEnriched="flow_enriched",m.Conversion="conversion",m))(Hi||{});var Ni=new Set;function fr(r){Ni.add(r)}function De(r,e,t){return fetch(e,t)}function gr(r){if(typeof navigator?.sendBeacon=="function")return(e,t)=>navigator.sendBeacon(e,t)}var Bi=6e4,Ui=6e4,Me=class{constructor(e){this.options=e;fr(0)}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(),Ui):void 0;try{let s={method:"POST",headers:{"Content-Type":"application/json",...this.options.headers,...t},body:i,keepalive:new Blob([i]).size<=Bi,...n?{signal:n.signal}:{}},a=await De(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=B(await a.json());p&&(l.config=p)}catch(p){this.options.logger.error("Failed to parse SDK config response",p),this.options.logger.reportTelemetry?.("error","failed to parse SDK config response")}return l}finally{o&&clearTimeout(o)}}catch(i){return this.options.logger.error("Failed to send event",i),{}}}sendBeacon(e){try{this.options.logger.debug(`Sending ${e.events.length} events via beacon`);let t=gr(0);if(!t)return!1;e.meta={...e.meta,sent:Date.now(),transport:"beacon"};let i=new Blob([JSON.stringify(e)],{type:"text/plain"});return t(this.options.url,i)}catch(t){return this.options.logger.error("Failed to send event via beacon",t),!1}}flush(e){return Promise.resolve(!0)}};import{v7 as Gi}from"uuid";function He(r,e,t,i={}){let n=typeof navigator<"u"?navigator.locks:void 0;if(n?.request){let o=i.timeoutMs,s=o!==void 0&&typeof AbortController<"u"?new AbortController:null;if(o!==void 0&&!s)return Promise.resolve().then(t);try{let a=!1,l,p=()=>{l!==void 0&&(clearTimeout(l),l=void 0)},d=()=>(a=!0,p(),t()),u=s?n.request(e,{signal:s.signal},d):n.request(e,d);return s&&o!==void 0&&!a&&(l=setTimeout(()=>{l=void 0,s.abort();try{i.onTimeout?.()}catch{}},o)),u.catch(f=>{if(a)throw f;return t()}).finally(p)}catch{}}try{return Promise.resolve(t())}catch(o){return Promise.reject(o)}}function hr(r){return typeof navigator<"u"&&!!navigator.locks?.request}var qi="cbo_outbox",ht="cbo_outbox",Ki=500,Wi=512*1024,Vi=10080*60*1e3;function $i(r){let e=r.event,t=typeof e.timestamp=="number"?e.timestamp:e.ts;if(typeof t=="number"&&Number.isFinite(t))return t;let i=/^([0-9a-f]{8})-?([0-9a-f]{4})-?7/i.exec(r.id);return i?parseInt(i[1]+i[2],16):void 0}function ji(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 q=class{constructor(e,t,i=Ki,n=Wi,o=ht,s=qi){this.storage=e;this.logger=t;this.maxEntries=i;this.maxSerializedLength=n;this.lockName=o;this.storageKey=s;this.entries=this.read(),typeof __CBO_DATA_RETENTION__=="boolean"&&__CBO_DATA_RETENTION__&&this.purgeExpired(Date.now())}entries=[];reportedMalformed=!1;purgeExpired(e){let t=n=>{let o=$i(n);return o!==void 0&&e-o>Vi};if(!this.entries.some(t))return;let i=this.entries.filter(t).length;this.entries=this.entries.filter(n=>!t(n)),this.logger.debug(`EventStore deleted ${i} entries past the retention limit`),this.mutate(n=>n.filter(o=>!t(o)))}read(){let e=this.storage.getItem(this.storageKey);if(!Array.isArray(e))return[];let t=e.filter(ji);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 He(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 mr=6e4,mt=32e3;function ee(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 zi=["cbo_visibility_change_debug","cbo_pagehide_debug"],Ne=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??S,this.priorityFlowTypes=new Set(this.config.flushOnFlowTypeFinished),this.outboxLockName=o.outboxLockName,this.config.durableOutbox&&this.storage&&(this.store=new q(this.storage,this.logger,void 0,void 0,this.outboxLockName),this.pending=this.store.all()),this.storage){for(let l of zi)this.storage.removeItem(l);this.lowStore=new q(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=[];lane;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??Gi()};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)}}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.lane?.sendUnload(mt,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(v=>v.flushAfter<=i),s=this.lane,a=e==="destroy"||!s?[]:s.items.filter(v=>v.flushAfter<=i),l=n.length===0&&o.length===0&&this.lowsQueue.length===0&&this.telemetryQueue.length===0&&a.length===0;if(l&&!this.hasStandaloneDeviceInfo())break;let p=n[0]?.sessionId??o[0]?.sessionId??this.lowsQueue[0]?.sessionId??a[0]?.sessionId??this.sessionId,d=n.filter(v=>v.sessionId===p).slice(0,this.batchSize),u=o.filter(v=>v.sessionId===p).slice(0,100),f=[...u.map(v=>v.event),...this.takeLows(p,100-u.length)];this.prepareEvents(d,e);let h=p===this.sessionId?this.takeTelemetry():[],c=p===this.sessionId?this.takeStandaloneDeviceInfo():void 0,y=s&&a.length>0?s.selectBatch(a,p):[],b={sessionId:p,events:d.map(v=>v.event),sdk:this.sdk};if(f.length>0&&(b.lows=f),h.length>0&&(b.telemetry=h),y.length>0&&(b.probes=y.map(v=>v.entry)),c&&(b.deviceInfo=c),l&&!c)break;this.attachBatchMeta(b,[...d,...u,...y],e),u.length&&(b.deliveryAck=!0);let H=this.shouldRequestConfig()?{[Kt]:this.config.version||"1"}:void 0,m=await this.transport.send(b,H).catch(v=>(this.logger.error("Unexpected error in queue flush",v),{}));if(b.deliveryAck&&m.statusCode&&m.statusCode>=200&&m.statusCode<300&&!m.deliveryAccepted&&(m={...m,statusCode:503}),this.requestConfig&&this.handleConfigResponse(m),this.handleLowSendResult(m,u,i),s?.handleResult(m,y,i),!this.handleSendResult(m,d,i))break}e==="destroy"&&this.lane?.sendUnload(mt,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 q(this.storage,this.logger,void 0,void 0,this.outboxLockName);let n=new Set(this.pending.map(s=>s.id)),o=this.store.all().filter(s=>!n.has(s.id));for(let s of this.pending)this.store.add(s);this.pending=[...o,...this.pending],i=o.length>0}i?(this.dirtySinceSyncFlush=!0,this.clearTimer(),this.scheduleFlush(0,"recovery")):t&&(this.clearTimer(),this.rescheduleIfPending())}handleSendResult(e,t,i){let n=e.statusCode,o=typeof n=="number"&&n>=200&&n<300;if(t.length===0)return o;if(o)return this.removeEntries(t.map(d=>d.id)),!0;if(!this.isRetryable(n))return this.removeEntries(t.map(d=>d.id)),!1;let s=Math.max(1,this.config.retry.maxAttempts),a=this.parseRetryAfter(e),l=[],p=[];for(let d of t)d.attempts+=1,d.attempts>=s?l.push(d.id):(d.flushAfter=i+this.backoffForAttempt(d.attempts,a),p.push(d));return this.removeEntries(l),this.store?.update(p),!1}isRetryable(e){return e===void 0||e===408||e===429?!0:e>=500}backoffForAttempt(e,t){let i=this.config.retry,n=i.baseDelayMs*Math.pow(2,Math.max(0,e-1));i.maxDelayMs>0&&(n=Math.min(n,i.maxDelayMs));let o=Math.round(n/2+Math.random()*(n/2));return t!==null&&(o=Math.max(o,t)),o}parseRetryAfter(e){let t=e.headers?.["retry-after"];if(!t)return null;let i=Number(t);if(!Number.isNaN(i))return i*1e3;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,n-Date.now())}removeEntries(e){if(e.length===0)return;let t=new Set(e);this.pending=this.pending.filter(i=>!t.has(i.id)),this.store?.remove(e)}rescheduleIfPending(){try{if(this.destroyed||this.timer)return;let e=this.lane?this.lane.items:[];if(this.pending.length===0&&this.lowPending.length===0&&this.lowsQueue.length===0&&e.length===0)return;let t=Date.now();if(this.getDuePending(t).length>0||this.lowPending.some(n=>n.flushAfter<=t)||this.lowsQueue.length>0||e.some(n=>n.flushAfter<=t)){this.scheduleFlush(this.flushInterval(),"timer");return}let i=Math.min(...[...this.pending,...this.lowPending,...e].map(n=>n.flushAfter));this.scheduleFlush(Math.max(0,i-t),"backoff")}catch(e){this.logger.error("Failed to reschedule queue flush",e)}}setupLifecycleHooks(){typeof window>"u"||(this.onVisibilityChange=()=>{try{U(0)&&this.config.tvc&&this.flushSync("visibility-change")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.onPageHide=()=>{try{this.config.tph&&this.flushSync("pagehide")}catch(e){this.logger.error("Unexpected error in queue flushSync",e)}},this.removeVisibilityChange=C(0,"visibilitychange",this.onVisibilityChange),this.removePageHide=C(0,"pagehide",this.onPageHide))}flushKeepalive(e="manual"){this.flushSync(e)}flushSync(e){let t=this.flushSyncEvents(e),i=this.lane;e==="pagehide"&&i&&i.items.length>0&&i.sendUnload(Math.min(mr-t,mt),e,!0,!0)}flushSyncEvents(e){if(!this.dirtySinceSyncFlush)return 0;let t=this.sessionId,i=this.pending.filter(d=>d.sessionId===t),n=i.slice(0,this.batchSize),o=this.lowPending.filter(d=>d.sessionId===t).slice(0,100),s=[...o.map(d=>d.event),...this.takeLows(t,100-o.length)];this.prepareEvents(n,e);let a=this.takeTelemetry(),l=this.takeStandaloneDeviceInfo();if(n.length===0&&s.length===0&&a.length===0&&!l)return this.dirtySinceSyncFlush=!1,0;let p={sessionId:t,events:n.map(d=>d.event),sdk:this.sdk};return s.length>0&&(p.lows=s),a.length>0&&(p.telemetry=a),l&&(p.deviceInfo=l),this.attachBatchMeta(p,[...n,...o],e),o.length&&(p.deliveryAck=!0),this.config.beaconKeepalive&&this.transport.sendBeacon?this.transport.sendBeacon(p)||this.transport.send(p):this.transport.send(p),this.config.durableOutbox||this.removeEntries(n.map(d=>d.id)),this.dirtySinceSyncFlush=!this.config.durableOutbox&&i.length>n.length,this.approximateSize(p)}approximateSize(e){try{return ee(JSON.stringify(e))}catch{return mr}}destroy(){try{this.destroyed=!0,this.clearTimer(),this.lane&&this.lane.drop(this.lane.items.slice()),typeof window<"u"&&(this.removeVisibilityChange&&this.removeVisibilityChange(),this.removePageHide&&this.removePageHide())}catch(e){this.logger.error("Failed to destroy queue lifecycle hooks",e)}}};import{v7 as vr}from"uuid";import Ji from"detectincognitojs";async function yr(r){return(await Ji()).isPrivate}var Yi=300,te=6e3,br="cbo_pm",Qi=10080*60*1e3,Sr="detectincognitojs@1.9.0",Tr={timing:!1},yt="cbo_tab_id",wr={bluetoothAvailable:"bt",clientCapabilities:"cc",userVerifyingPlatformAuthenticatorAvailable:"uvpaa",conditionalMediationAvailable:"cm",javaScriptHighEntropy:"he",privateMode:"pm",webdriver:"wd",maxTouchPoints:"mtp"};function I(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Er(r,e,t){return{field:r,source:e,error:{name:"TimeoutError",message:`Device info collection timed out after ${t}ms`}}}async function vt(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 Be=class{constructor(e,t,i="localstorage",n,o=()=>Tr,s,a=!0,l){this.logger=e;this.storage=t;this.storageSource=i;this.sessionStorage=n;this.settings=o;this.emitTelemetry=s;this.privateModeEnabled=a;this.deviceHandleMaxAgeMs=l}pagePrivateMode;privateModeDetectionStarted=!1;lastKnown={};async collect(e,t={}){try{let i=this.resolveSettings(),n=I(),o=this.getClientEnvHandle(),s={type:"web",clientEnvHandle:o.value,clientEnvHandleMeta:{timestamp:o.timestamp,source:o.source},tabId:this.getTabId()},a=typeof __CBO_DATA_PRIVATE_MODE__=="boolean"?__CBO_DATA_PRIVATE_MODE__:this.privateModeEnabled,l=a?this.knownPrivateMode(i.timing):void 0,p,d=a&&l===void 0&&!this.privateModeDetectionStarted?this.detectPrivateMode(i.timing).then(v=>{p=v}):void 0,u=this.startFastFields();await vt(Promise.all(u.map(v=>v.promise)),Yi);let f=I()-n,h=t.refresh?this.lastKnown:{};i.timing&&this.reportFastTiming(f,u);let c=()=>p?.error?[p.error]:[];this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,c()),"fast");let y=u.filter(v=>!v.settled),b=d!==void 0&&p===void 0;if(y.length===0&&!b)return;let H=I();await Promise.all([vt(Promise.all(y.map(v=>v.promise)),te-(H-n)),d]);let m=y.filter(v=>!v.settled).map(v=>Er(v.field,v.source,te));m.push(...c()),i.timing&&y.length>0&&this.reportLateTiming(I()-n,y),this.safePublish(e,this.buildInfo(s,u,p?p.value:l,h,m),"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",()=>ir(0)),this.startField("clientCapabilities","PublicKeyCredential.getClientCapabilities",()=>sr(0)),this.startField("userVerifyingPlatformAuthenticatorAvailable","PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable",()=>nr(0)),this.startField("conditionalMediationAvailable","PublicKeyCredential.isConditionalMediationAvailable",()=>or(0)),this.startField("javaScriptHighEntropy","navigator.userAgentData.getHighEntropyValues",()=>ar(0)),this.startField("webdriver","navigator.webdriver",()=>lr(0)),this.startField("maxTouchPoints","navigator.maxTouchPoints",()=>pr(0))]}startField(e,t,i){let n=I(),o={field:e,source:t};return o.promise=Promise.resolve().then(i).then(s=>({field:e,value:s,durationMs:I()-n}),s=>(this.logger.error(`Failed to collect device info field "${e}"`,s),{field:e,durationMs:I()-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 p of t)p.settled?(p.settled.error&&a.push(p.settled.error),s[p.field]=p.settled.value,this.remember(p.field,p.settled.value)):s[p.field]=n[p.field];s.privateMode=i,a.push(...o);let l={...e,data:{bluetoothAvailable:s.bluetoothAvailable,javaScriptHighEntropy:s.javaScriptHighEntropy,privateMode:s.privateMode,webdriver:s.webdriver,conditionalMediationAvailable:s.conditionalMediationAvailable,userVerifyingPlatformAuthenticatorAvailable:s.userVerifyingPlatformAuthenticatorAvailable,clientCapabilities:s.clientCapabilities,maxTouchPoints:s.maxTouchPoints}};return a.length>0&&(l.collectionErrors=a),l}remember(e,t){t!==void 0&&(this.lastKnown[e]=t)}safePublish(e,t,i){try{e(t,i)}catch(n){this.logger.error("Failed to publish device info",n)}}knownPrivateMode(e){if(this.pagePrivateMode!==void 0)return this.pagePrivateMode;let t=this.readPrivateModeCache();return t&&(this.pagePrivateMode=t.value,e&&this.reportTelemetry(`device info privateMode from cache, age ${Math.round((Date.now()-t.ts)/1e3)}s`)),this.pagePrivateMode}canCachePrivateMode(){return this.storageSource==="localstorage"}readPrivateModeCache(){if(this.canCachePrivateMode())try{let e=this.storage.getItem(br);if(!e||typeof e!="object"||typeof e.value!="boolean"||typeof e.ts!="number"||e.dv!==Sr)return;let t=Date.now()-e.ts;return t<0||t>=Qi?void 0:e}catch(e){this.logger.debug("Failed to read cached privateMode",e);return}}writePrivateModeCache(e){if(this.canCachePrivateMode())try{this.storage.setItem(br,{value:e,ts:Date.now(),dv:Sr})}catch(t){this.logger.error("Failed to cache privateMode",t)}}async detectPrivateMode(e){this.privateModeDetectionStarted=!0;let t="detectIncognito",i=I(),n=this.startField("privateMode",t,()=>typeof __CBO_DATA_PRIVATE_MODE__=="boolean"&&!__CBO_DATA_PRIVATE_MODE__?void 0:yr(0));if(!await vt(n.promise,te)||!n.settled)return e&&this.reportTelemetry(`device info privateMode timed out after ${te}ms`),{error:Er("privateMode",t,te)};if(e&&this.reportTelemetry(`device info privateMode detected in ${Math.round(I()-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),Tr}}reportFastTiming(e,t){let i=t.map(n=>`${wr[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=>`${wr[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)}}getClientEnvHandle(){let e=this.storage.getItem("cbo_client_env_handle"),t=this.deviceHandleMaxAgeMs;if(e&&!(t!==void 0&&!(Date.now()-e.timestamp<=t)))return e;let i=vr(),n={timestamp:Date.now(),source:this.storageSource,value:i};return this.storage.setItem("cbo_client_env_handle",n),n}getTabId(){if(!this.sessionStorage)return;let e=this.sessionStorage.getItem(yt);if(e)return e;let t=vr();if(this.sessionStorage.setItem(yt,t),this.sessionStorage.getItem(yt)===t)return t}};function Xi(){return typeof document<"u"&&U(0)}var Ue=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&&Xi())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 Cr(r){return{getItem:e=>localStorage.getItem(e),setItem:(e,t)=>localStorage.setItem(e,t),removeItem:e=>localStorage.removeItem(e)}}function kr(r){return{getItem:e=>sessionStorage.getItem(e),setItem:(e,t)=>sessionStorage.setItem(e,t),removeItem:e=>sessionStorage.removeItem(e)}}function re(r){return{read:()=>document.cookie,write:e=>{document.cookie=e}}}function P(r,e){return`${r}_${e}`}var qe=class{constructor(e,t){this.engine=e;this.namespace=t}getItem(e){return this.engine.getItem(P(e,this.namespace))}setItem(e,t){this.engine.setItem(P(e,this.namespace),t)}removeItem(e){this.engine.removeItem(P(e,this.namespace))}},Ke=class{constructor(e){this.logger=e}area=Cr(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)}}},We=class{constructor(e,t){this.logger=e;this.domain=t}jar=re(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)}}},Ve=class{constructor(e){this.logger=e}area=kr(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 $e=1,je="cbo_storage_schema",Zi=["cbo_seq","cbo_sdk_config","cbo_experiments","cbo_client_env_handle","cbo_outbox","cbo_visibility_change_debug","cbo_pagehide_debug","cbo_session"],en=["cbo_session_id","cbo_tab_id"],tn=["cbo_client_env_handle"];function Ge(r,e,t){return r.setItem(e,t),JSON.stringify(r.getItem(e))===JSON.stringify(t)}function bt(r,e,t){let i=r.getItem(je);if(i!==null){if(i.version!==$e||i.projectId!==e)return!1;if(i.complete===!0)return!0;if(i.complete!==!1)return!1}else{if(t.some(n=>r.getItem(P(n,e))!==null))return Ge(r,je,{version:$e,projectId:e,complete:!0});if(!Ge(r,je,{version:$e,projectId:e,complete:!1}))return!1}for(let n of t){let o=P(n,e);if(r.getItem(o)!==null)continue;let s=r.getItem(n);if(s!==null&&!Ge(r,o,s))return!1}return Ge(r,je,{version:$e,projectId:e,complete:!0})}function xr(r,e,t,i,n){try{if(!bt(e,r,Zi))return;bt(t,r,en),i&&bt(i,r,tn)}catch(o){n.error("Failed to migrate legacy Observe storage",o)}}var rn=10*1e3,nn=60*1e3,on=3600*1e3,sn=300*1e3,Or=1440*60*1e3,an=[1e3,3e3];function ln(r){let e=/(?:^|[\s,])max-age\s*=\s*"?(\d+)"?/i.exec(r?.get("Cache-Control")??"");if(!e)return on;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,sn),Or)}var ze=class{constructor(e,t,i){this.url=e;this.storage=t;this.logger=i;this.initialConfig=$t(t)??void 0,this.appliedVersion=this.initialConfig?.version}initialConfig;requestTimer;retryTimer;controller;removers=[];fetching=!1;stopped=!1;lastAttemptAt;appliedVersion;onConfig;start(e){this.stopped||this.onConfig||(this.onConfig=e,this.listen(),this.refresh())}listen(){if(typeof window>"u")return;let e=()=>{typeof document>"u"||U(0)||this.refresh()};this.removers.push(C(0,"visibilitychange",e),C(0,"pageshow",t=>{t.persisted&&this.refresh()}))}refresh(){try{if(this.stopped||this.fetching)return;let e=Date.now(),t=Ae(this.storage),{fetchedAt:i,expiresAt:n}=t??{};if(t?.endpoint===this.url&&typeof i=="number"&&typeof n=="number"&&i>0&&n-i<=Or&&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<nn)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(),rn):void 0;let i=!0;try{let n=await De(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=B(o);if(!s)throw new Error("Invalid SDK config response");if(this.stopped||t?.signal.aborted)return;let a=Date.now();jt(this.storage,{endpoint:this.url,fetchedAt:a,expiresAt:a+ln(n.headers),config:s}),Ae(this.storage)&&this.storage.removeItem(ft),this.appliedVersion=s.version,this.onConfig?.(s)}catch(n){if(!this.stopped){this.logger.error("Failed to fetch SDK config",n);let o=an[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}};import{v7 as D}from"uuid";var pn=["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 Ir(r){if(!r)return!1;let e=r.toLowerCase();return pn.some(t=>e.includes(t))}var St="@corbado/observe",Tt="1.15.1";function Pr(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 dn="/inline/injected/webauthn-listeners.js",Rr=/\/dashlane-(?:shadow-dom|top-layer)-page-script\.js/,cn=/-extension:\/\/[^/]+\/content-scripts\/passkey_proxy\/index\.js$/,un=/-extension:\/\/[^/]+\/content_scripts\/shadow-dom\/shadowAttachNotifier\.js:/,Fr=/-extension:\/\/[^/]+\/js\/nordpass-script\.js:/,fn=/-extension:\/\/[^/]+\/js\/passkeys\.js:/,gn=/["'`](?:keeper:shadow-root-attached|webauthn-(?:get|create)-request)["'`]/,hn=/Intercept cancelled for `(?:get|create)`|["'`](?:conditionalMediationAvailable|verifyingPlatformAuthenticatorAvailable)["'`]/,wt=()=>Object.keys(window._sentryDebugIds??{}),Et=r=>{try{r()}catch(e){return String(e?.stack??"")}return""},Lr=()=>Et(()=>Element.prototype.attachShadow.call(null,{mode:"open"})),mn=()=>{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]")},Ct=(...r)=>{let e=navigator.credentials;return e?r.map(t=>Object.getOwnPropertyDescriptor(e,t)?.value):[]},yn=()=>[navigator.credentials?.get,...Ct("get","_get")].some(r=>typeof r=="function"&&r.name==="getWebAuthnCredential"),vn=()=>{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)}},bn,Sn=()=>bn??=vn(),Tn=()=>{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},wn=()=>{let r={get nodeType(){throw new Error("probe")}};return Et(()=>MutationObserver.prototype.observe.call(null,r))},En=()=>{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},Cn=()=>[Element.prototype.attachShadow,navigator.credentials?.get,navigator.credentials?.create,...Ct("get","_get","create")].some(e=>typeof e=="function"&&gn.test(Function.prototype.toString.call(e))),kn=()=>{let r=document;for(;r;){if(r.querySelector("[data-lastpass-icon-root], [data-lastpass-root]"))return!0;r=r.activeElement?.shadowRoot}return!1},xn=()=>{let r=typeof PublicKeyCredential>"u"?void 0:PublicKeyCredential;return[navigator.credentials?.get,...Ct("get","_get"),r?.isConditionalMediationAvailable,r?._isConditionalMediationAvailable,r?.isUserVerifyingPlatformAuthenticatorAvailable,r?._isUserVerifyingPlatformAuthenticatorAvailable].some(t=>typeof t=="function"&&hn.test(Function.prototype.toString.call(t)))},On=[{name:"1password",signal:"in-field button",signedIn:!0,test:()=>document.querySelector("com-1password-button")!==null},{name:"1password",signal:"credentials.get accessor",test:mn},{name:"1password",signal:"Sentry debug id",test:()=>wt().some(r=>r.includes(dn))},{name:"bitwarden",signal:"passkey override",signedIn:!0,test:yn},{name:"bitwarden",signal:"autofill keyframes",test:Sn},{name:"dashlane",signal:"injected script tag",test:()=>document.querySelector('script[src*="-extension://"][src*="/dashlane-"][src$="-page-script.js"]')!==null},{name:"dashlane",signal:"PublicKeyCredential hasInstance trap",test:Tn},{name:"dashlane",signal:"page script stack",test:()=>Rr.test(Lr())||typeof HTMLDialogElement<"u"&&Rr.test(Et(()=>HTMLDialogElement.prototype.showModal.call(null)))},{name:"kaspersky",signal:"passkey proxy flag",test:()=>window.wasKPMKeyPassProxyInited===!0},{name:"kaspersky",signal:"injected script tag",test:()=>cn.test(document.querySelector('script[src*="/content-scripts/passkey_proxy/"]')?.src??"")},{name:"keeper",signal:"attachShadow stack",test:()=>un.test(Lr())},{name:"keeper",signal:"override source",test:Cn},{name:"keeper",signal:"field lock",test:()=>document.querySelector("[data-keeper-lock-id]")!==null},{name:"lastpass",signal:"passkey override",signedIn:!0,test:()=>typeof window.__nativeCredentialsGet=="function"},{name:"lastpass",signal:"icon root",test:kn},{name:"nordpass",signal:"observer proxy stack",test:()=>Fr.test(wn())},{name:"nordpass",signal:"observer read order",test:En},{name:"nordpass",signal:"passkeys Sentry debug id",test:()=>wt().some(r=>fn.test(r))},{name:"nordpass",signal:"Sentry debug id",test:()=>wt().some(r=>Fr.test(r))},{name:"protonpass",signal:"WebAuthn override source",test:xn},{name:"protonpass",signal:"field icon",test:()=>document.querySelector("[data-protonpass-role]")!==null}];function In(){return typeof window>"u"||typeof document>"u"?[]:On.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 Ar(){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 _r(r){return Ar()}var Dr=3e3,Pn=500,Rn=6,Fn=1e3,Je=class{constructor(e,t,i){this.logger=e;this.isEnabled=t;if(typeof window>"u"||typeof document>"u")return;if(this.sample(),Xt(0))this.sampleAfter(Dr);else{let o=()=>{this.sampleWhenIdle(),this.sampleAfter(Dr)};this.removers.push(C(0,"load",o,{once:!0}))}let n=i.onInputFocus(o=>{!this.isEnabled()||this.sampledFields.has(o)||(this.sampledFields.add(o),++this.focusSamples>=Rn&&n(),this.sampleAfter(Pn))});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:Fn});this.idleCallbacks.add(e)}sample(){if(!(this.destroyed||!this.isEnabled()))try{let e=_r(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 ie="cbo_session_id",K="cbo_session",k="cbo_seq",kt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var xt={name:St,version:Tt},Ln=/^[0-9A-Za-z.+_-]{1,32}$/;function An(r,e){return r===void 0?xt:typeof r=="string"&&Ln.test(r)?{...xt,integrationVersion:r}:(e.debug("Ignoring invalid integrationVersion (expected <= 32 chars of [0-9A-Za-z.+_-])"),xt)}var Mr="cbo_experiments",Hr="cbo_data_policy",_n=255,Dn=/^[A-Za-z0-9_-]+$/,Mn=128,Hn=256,Nr=1e3,Nn=50,Bn="cbo_seq",Br=1e3,W=class r{constructor(e,t=[]){this.options=e;this.options.debug=e.debug??!1,this.logger=e.logger??Pr({debug:this.options.debug});let i=t.concat(Array.isArray(e.plugins)?e.plugins:[]),n=new Ke(this.logger),o=new Ve(this.logger),s;this.eachPlugin(i,c=>{c.storage&&(s=c.storage(this.logger)||s)}),xr(e.projectId,n,o,s?.engine,this.logger);let a=e.projectId,l=c=>new qe(c,a);if(this.seqLockName=P(Bn,a),this.sessionStorage=l(o),this.persistentStorage=l(n),this.storage=l(s?.engine??n),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=Le(e.fixedDataConfig),this.fixedData&&(this.configOverrides.pmd=this.fixedData.pmd),typeof __CBO_SDK_CONFIG__=="string"){let c=Vt(__CBO_SDK_CONFIG__,this.fixedData?.pmd);this.config=c.config,c.valid||this.logger.error("Invalid static SDK config: running the built-in defaults")}else{let c=Object.keys(S).every(b=>this.configOverrides[b]!==void 0)&&Object.keys(S.retry).every(b=>this.configOverrides.retry?.[b]!==void 0);c||(this.configManager=new ze(e.apiBaseUrl+(e.apiConfigPath??"/v1/observe/config")+"/"+e.projectId,this.persistentStorage,this.logger));let y=this.configManager?.initialConfig;this.config=Fe(y,this.configOverrides),!c&&!y&&e.flushInterval!=null&&this.configOverrides.flushIntervalMs===void 0&&(this.config={...this.config,flushIntervalMs:e.flushInterval}),!c&&!y&&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 p=e.apiBaseUrl+(e.apiEventPath??"/v1/observe/events")+"/"+e.projectId;this.logger.debug(`Using API endpoint: ${p}`);let d=new Me({logger:this.logger,url:p});this.eachPlugin(i,c=>{c.session&&(this.bridge=c.session(this)||this.bridge),c.rawErrors&&(this.rawErrors=c.rawErrors),typeof c.sourcePath=="function"&&(this.fixedSourcePath=c.sourcePath),c.eventTime&&(this.eventClock=c.eventTime),c.deviceHandleMaxAgeMs!==void 0&&(this.deviceHandleMaxAgeMs=c.deviceHandleMaxAgeMs)}),e.fixedDataConfig?.crossOriginSession&&!this.bridge&&this.logger.warn("fixedDataConfig.crossOriginSession is ignored without the crossOriginSession() plugin"),this.sessionId=this.resolveSession(),this.queue=new Ne(this.logger,d,this.sessionId,An(this.options.integrationVersion,this.logger),{debug:this.options.debug,config:this.config,requestConfig:!1,outboxLockName:P(ht,a),getDataPolicy:()=>this.dataPolicy,getCrossOriginSession:c=>this.bridge?.meta(c),fixedData:this.fixedData!==void 0||typeof __CBO_DATA_PMD__=="boolean"||typeof __CBO_DATA_PRIVATE_MODE__=="boolean",beforeEventBatchSend:c=>this.attachUndeliveredDeviceInfo(c),standaloneDeviceInfo:{has:()=>this.deviceInfoManager?.hasStandalone()??!1,take:()=>this.deviceInfoManager?.takeStandalone()}},this.persistentStorage),this.telemetryReady=!0,this.logger.setTelemetrySink?.((c,y)=>this.reportTelemetry(c,y));try{this.getWindowObserver()}catch(c){this.logger.error("Failed to attach page low-event observer",c)}if(typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.fixedData?.pmd!==!1)try{this.passwordManagerSampler=this.isTrackingBlocked()?void 0:new Je(this.logger,()=>typeof __CBO_DATA_PMD__=="boolean"?__CBO_DATA_PMD__:this.config.pmd,this.getWindowObserver())}catch(c){this.logger.error("Failed to start password manager detection",c)}let u=this.pendingSelfTelemetry;this.pendingSelfTelemetry=[];for(let c of u)this.telemetry(c.level,c.message);let f=new Be(this.logger,this.storage,s?.source??"localstorage",this.sessionStorage,()=>({timing:this.config.deviceInfoTiming}),(c,y)=>this.telemetry(c,y),this.fixedData?.privateMode??!0,this.deviceHandleMaxAgeMs);this.deviceCollector=f;let h=e.deviceInfoDebounceTime??3e4;this.deviceInfoManager=new Ue(this.logger,f,Math.max(1,h),h,{timing:()=>this.config.deviceInfoTiming,emit:(c,y)=>this.telemetry(c,y)},()=>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)),this.eachPlugin(i,c=>{c.setup&&c.setup(this)})}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=[];windowObserver;passwordManagerSampler;bridge;rawErrors;fixedSourcePath;eventClock;deviceHandleMaxAgeMs;getWindowObserver(){return this.windowObserver??=new _e(this.logger,(e,t)=>this.enqueueLowEvent(e,t),()=>this.lowEventFlushKeepalive())}eachPlugin(e,t){for(let i of e)try{i&&t(i)}catch(n){this.logger.error("Failed to install tracker plugin",n)}}isFullTracker(){return!1}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()}:{}}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)}}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<=_n}loadPersistedDataPolicy(){try{let e=this.persistentStorage.getItem(Hr);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(Hr,this.dataPolicy)}catch(e){this.logger.debug("Failed to persist data policy",e)}}static isValidExperimentKey(e){return typeof e=="string"&&e.length>0&&e.length<=Mn&&Dn.test(e)}static isValidExperimentVariant(e){return typeof e=="string"&&e.length>0&&e.length<=Hn}loadPersistedExperiments(){try{let e=this.persistentStorage.getItem(Mr);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(Mr,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:Ir(rr(0))}resolveSession(){return this.bridge?this.bridge.resolve():this.resolveSessionId()}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=D();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(K);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=D();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(K,{id:e,lastActiveAt:t})}readPerTabSession(){let e=this.sessionStorage.getItem(ie);if(e){if(typeof e=="string")return kt.test(e)?{id:e,lastActiveAt:Date.now()}:void 0;if(typeof e.lastActiveAt=="number")return kt.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(ie,{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>=Br&&this.persistPerTabSession(this.sessionId,i);let n=this.bridge?this.bridge.claim(this.sessionId,this.seq,i):this.seq;return this.seq=n+1,n}let e=()=>{let i=Date.now(),n=this.persistentStorage.getItem(K),o=!1;if(!n?.id&&this.sessionId)this.persistContinuitySession(this.sessionId,i);else if(n?.id)i-this.lastActivityWriteAt>=Br&&this.persistContinuitySession(n.id,i),n.id!==this.sessionId&&(this.sessionId=n.id,this.queue.setSessionId(n.id),o=!0);else{let l=D();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.bridge&&(a=this.bridge.claim(this.sessionId,a,i)),this.seq=a+1,this.persistentStorage.setItem(k,this.seq),a},t=this.config.seqLockTimeoutMs;return t===0||!hr(0)?e():He(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")){if(this.fixedSourcePath)try{let e=this.fixedSourcePath();return typeof e=="string"?e:void 0}catch{return}return Zt(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})}async track(e,t,i,n,o,s,a,l){try{if(this.isTrackingBlocked()){this.logger.debug(`Skipping event "${e}" for blocked user agent.`);return}(e==="flow_finished"||e==="flow_auto_finished"||e==="flow_reset")&&this.windowObserver?.flushInputs();let p=this.eventClock?.(s)??s??Date.now(),d=l?.id??D(),u=l?.sessionId??this.sessionId,f=this.nextSeq(),h=typeof f=="number"?f:await f,c=this.resolveTrackingSourcePath(),y={type:"predefined",name:e,id:d,timestamp:p,seq:h,data:t,user:i,contexts:o,tags:n,experiments:this.resolveExperiments(a),meta:{captureVersion:1,pageId:Z(),initiator:l?.initiator,trackingSourcePath:c??"",subflowStartEventId:l?.subflowStartEventId,tabId:this.resolveEventTabId()}},b=this.deviceInfoManager.getForEvent();b&&(y.deviceInfo=b),this.logger.debug(`Track: ${e}`,JSON.stringify(y,null,2));let H=this.passwordManagerSampler?.takeReport(u);H&&(y.passwordManagers=H),this.queue.enqueue(y,u)}catch(p){this.logger.error(`Failed to process event "${e}" before enqueue`,p),this.reportTelemetry("error",`failed to process event "${e}" before enqueue`)}}flowStarted(e,t,i,n,o){try{let s=D(),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)}flowFinished(e,t,i){try{let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o},l=D(),p=this.sessionId;return this.track("flow_finished",s,a,t,void 0,void 0,i,{id:l,sessionId:p}),this.flowHandle(l,p)}catch(n){return this.logger.warn("Failed to finish flow",n),{enrich:async()=>{}}}}flowHandle(e,t){return{enrich:async i=>{try{await this.track("flow_enriched",{targetEventId:e},{...i},void 0,void 0,void 0,void 0,{sessionId:t})}catch(n){this.logger.warn("Failed to enrich flow",n)}}}}flowReset(e,t,i){this.track("flow_reset",e,void 0,t,void 0,void 0,i)}flowAutoFinished(e,t,i){let{userId:n,identifier:o,...s}=e,a={userId:n,identifier:o};this.track("flow_auto_finished",s,a,t,void 0,void 0,i)}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)}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??x(),captureVersion:1,pageId:e.pageId??Z()},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:D(),level:e,message:i.length>Nr?i.slice(0,Nr):i,ts:Date.now()};this.queue.enqueueTelemetry(n)}catch(i){this.logger.error("Failed to process telemetry before enqueue",i)}}attachUndeliveredDeviceInfo(e){try{let t=this.deviceInfoManager;if(!t?.hasUndelivered())return;let i=Z(),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>=Nn)return;if(this.reportedTelemetryKeys.add(t),!this.telemetryReady){this.pendingSelfTelemetry.push({level:e,message:t});return}this.telemetry(e,t)}catch{}finally{this.telemetryReporting=!1}}}flushKeepalive(e="manual"){try{this.queue.flushKeepalive(e)}catch(t){this.logger.error("Failed to flush queue keepalive",t)}}lowEventFlushKeepalive(){this.config.tlf&&this.flushKeepalive("low-event-teardown")}async destroy(){if(this.bridge?.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}};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 ne=class extends g{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()}};function Da(r,e){return new ne(r,e)}var $=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;runSeq;markInputObserved(){this.prefillSettled=!0}observe(){this.runSeq!==void 0||this.inputBatch||this.autofillTimestamps.length>0||this.autofillStreak||(this.runSeq=this.reserveCaptureSeq?.())}takeSeq(){let e=this.runSeq;return this.runSeq=void 0,e??this.reserveCaptureSeq?.()}capturePrefill(e,t=!1){t&&(this.prefillSettled=!1),!this.prefillSettled&&(this.previousLength=e,e!==0&&(this.prefillSettled=!0,this.pushLow({lowType:"input-prefill",ts:Date.now(),initiator:"unknown"})))}flush(){this.cancelIdle(),this.flushInputBatch(),this.flushAutofillStreak()}cancelIdle(){this.idleTimer!==null&&clearTimeout(this.idleTimer),this.idleTimer=null}scheduleIdle(){this.cancelIdle(),this.idleTimer=setTimeout(()=>{this.idleTimer=null;try{this.flushInputBatch(!0),this.flushAutofillStreak()}catch(e){this.logger.error("Failed to flush idle input",e)}},3e3)}extendInputBatch(e,t=this.currentEffect){let i=this.inputBatch;if(!i){this.inputBatch={firstTimestamp:e,lastTimestamp:e,effect:t,captureSeq:this.takeSeq()};return}i.lastTimestamp=e}drainAutofillRingToBatch(){for(let e of this.autofillTimestamps)this.extendInputBatch(e,this.ringEffect);this.autofillTimestamps.length=0}flushInputBatch(e=!1){this.drainAutofillRingToBatch();let t=this.inputBatch;t&&(this.pushLow({...t.captureSeq===void 0?{}:{captureSeq:t.captureSeq},lowType:e?"input-idle":"input",ts:t.firstTimestamp,durationMs:t.lastTimestamp-t.firstTimestamp,inputEffect:t.effect}),this.inputBatch=null)}flushAutofillStreak(){let e=this.autofillStreak;e&&(this.pushLow({...e.captureSeq===void 0?{}:{captureSeq:e.captureSeq},lowType:"big-input-add",ts:e.firstTimestamp,durationMs:e.lastTimestamp-e.firstTimestamp,inputEffect:e.effect}),this.autofillStreak=null)}detectAutofillStreak(){let e=this.autofillTimestamps;if(e.length<5)return!1;let t=1/0,i=-1/0;for(let n=1;n<e.length;n++){let o=e[n]-e[n-1];if(o>80)return!1;o<t&&(t=o),o>i&&(i=o)}return i-t<=25}record(e,t=Date.now(),i=!1){this.observe(),this.markInputObserved(),this.scheduleIdle();let n=this.previousLength;this.currentEffect=e===0?"clear":n===0?"fill":"modify";let o=e-n;if(this.previousLength=e,e===0&&n>0){this.flush();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"input-clear",ts:t,inputEffect:"clear"});return}if(i){this.flushAutofillStreak(),this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}if(o>=3){this.flushInputBatch(),this.flushAutofillStreak();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"big-input-add",ts:t,inputEffect:this.currentEffect});return}if(o<=-3){this.flushInputBatch(),this.flushAutofillStreak();let d=this.takeSeq();this.pushLow({...d===void 0?{}:{captureSeq:d},lowType:"big-input-rem",ts:t,inputEffect:this.currentEffect});return}let s=this.autofillStreak;if(s){if(o===1&&t-s.lastTimestamp<=80){s.lastTimestamp=t;return}this.flushAutofillStreak()}if(o!==1){this.drainAutofillRingToBatch(),this.extendInputBatch(t,this.currentEffect);return}let a=this.autofillTimestamps;if(a.length===0&&(this.ringEffect=this.currentEffect),a.push(t),a.length>5){let d=a.shift();this.extendInputBatch(d,this.ringEffect),this.ringEffect="modify"}if(!this.detectAutofillStreak())return;let l=a[0],p=a[a.length-1];a.length=0,this.flushInputBatch(),this.autofillStreak={firstTimestamp:l,captureSeq:this.takeSeq(),lastTimestamp:p,effect:this.ringEffect}}};var j=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)}lengthsBefore=null;applied=!1;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.lengthsBefore)return!1;let t=this.pasteEvent?.type==="paste"&&(this.pasteEvent.eventPhase??0)>0;return e.inputType==="insertFromPaste"||t?(this.applied=!0,!0):(this.clear(),!1)}get pending(){return this.lengthsBefore!==null}begin(e){if(!(!e.isTrusted||this.lengthsBefore))try{this.lengthsBefore=this.inputs.map(t=>t.value.length),this.applied=!1,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.lengthsBefore;if(!e)return;let t=this.timestamp,i=this.captureSeq,n=this.applied;this.clear();try{(n||this.inputs.some((s,a)=>s.value.length!==e[a]))&&this.changed(t,i)}catch(o){this.logger.error("Failed to finish paste observation",o)}}clear(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,this.lengthsBefore=null,this.applied=!1,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 Un=["focus","blur","pointerdown","pointerup","click","input","keyup"];function Ye(r,e,t,i,n=Un){let o=[];for(let s of n){let a=qn(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 qn(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 Ur(r,e){return e.type==="checkbox"||e.type==="radio"?e.checked?1:0:e.value.length}function qr(r,e){return e.reduce((t,i)=>t+i.value.length,0)}function Qe(r,e){let t=document.activeElement;return e.find(i=>i===t)}function oe(r){return Ur(0,r)}var E=class{constructor(e,t,i){this.logger=e;this.inputField=t;this.sink=i;this.changes=new $(oe(t),this.pushLow,e,i.reserveCaptureSeq),this.pasteObserver=new j(0,[t],e,(n,o)=>{this.changes.flush(),this.changes.markInputObserved();let s=this.changes.previousLength;this.changes.previousLength=oe(t),this.pushLow({...o===void 0?{}:{captureSeq:o},lowType:"input-paste",ts:n,inputEffect:oe(t)===0?"clear":s===0?"fill":"modify"})},i.reserveCaptureSeq),this.unregisterInputs=i.registerInputs?.([t],()=>this.flushPending()),this.capturePrefill(),this.attach()}unregisterInputs;removeFieldListeners;removePageHide;changes;pasteObserver;destroyed=!1;destroy(){if(!this.destroyed){this.destroyed=!0;try{this.changes.flush(),this.unregisterInputs?.(),this.pasteObserver.destroy(),this.detach()}catch(e){this.logger.error("Failed to destroy LowEventInputTracker",e)}}}attach(){let e=this.inputField;this.removeFieldListeners=Ye(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=C(0,"pagehide",this.wrapHandler("pagehide",()=>this.flushForTeardown()))),typeof document<"u"&&Qe(0,[e])&&this.handleFocus()}detach(){this.removeFieldListeners?.(),typeof window<"u"&&this.removePageHide?.()}pushLow=e=>{this.sink.enqueueLowEvent(e)};capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(oe(this.inputField),e))}flushPending(){this.pasteObserver.flush(),this.changes.flush()}enqueueNonInputEvent(e){this.changes.flush(),this.pushLow({lowType:e,ts:Date.now()})}handleFocus(){this.enqueueNonInputEvent("focus")}handleBlur(){this.pasteObserver.flush(),this.enqueueNonInputEvent("blur")}handleInput(e,t){this.pasteObserver.handlesInput(e)||this.changes.record(oe(this.inputField),Date.now(),t)}flushForTeardown(){this.pasteObserver.flush(),this.changes.flush(),this.sink.flushKeepalive()}wrapHandler(e,t){return()=>{try{t()}catch(i){this.logger.error(`Failed to handle low event "${e}"`,i)}}}};var Xe=class{constructor(e,t,i){this.logger=e;this.sink=i;this.inputs=[...new Set(t)],this.changes=new $(this.length(),o=>i.enqueueLowEvent(o),e,i.reserveCaptureSeq),this.paste=new j(0,this.inputs,e,(o,s)=>{this.cancelChange(),this.changes.flush(),this.changes.markInputObserved();let a=this.changes.previousLength;this.changes.previousLength=this.length(),i.enqueueLowEvent({...s===void 0?{}:{captureSeq:s},lowType:"input-paste",ts:o,inputEffect:this.length()===0?"clear":a===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(Ye(0,o,{input:(s,a)=>{this.paste.handlesInput(a)||(this.composing||=s,this.changeTimer===null&&(this.changeTime=Date.now(),this.changes.observe(),this.changeTimer=setTimeout(()=>this.safe(()=>this.flushChanges()),0)))},focus:s=>{this.contains(s)||this.emit("focus")},blur:s=>{this.contains(s)||(this.flushPending(),this.emit("blur"))},click:()=>this.emit("click"),pointerdown:()=>this.emit("pointerdown"),pointerup:()=>this.emit("pointerup"),keyupEscape:()=>this.emit("keyup-escape")},n,["input","focus","blur","click","pointerdown","pointerup","keyup"]));typeof window<"u"&&this.listeners.push(C(0,"pagehide",o=>this.safe(()=>{this.flushPending(),i.flushKeepalive()}))),typeof document<"u"&&Qe(0,this.inputs)&&this.emit("focus")}inputs;changes;paste;unregisterInputs;listeners=[];changeTimer=null;changeTime=0;composing=!1;destroyed=!1;contains(e){return this.inputs.some(t=>t===e)}length(){return qr(0,this.inputs)}safe(e){try{e()}catch(t){this.logger.error("Failed to observe grouped input",t)}}cancelChange(){this.changeTimer!==null&&clearTimeout(this.changeTimer),this.changeTimer=null}flushChanges(){this.changeTimer!==null&&(this.cancelChange(),this.paste.pending||this.changes.record(this.length(),this.changeTime,this.composing),this.composing=!1)}emit(e){this.flushChanges(),this.changes.flush(),this.sink.enqueueLowEvent({lowType:e,ts:Date.now()})}capturePrefill(e=!1){this.destroyed||(this.flushPending(),this.changes.capturePrefill(this.length(),e))}flushPending(){this.paste.flush(),this.flushChanges(),this.changes.flush()}destroy(){this.destroyed||(this.destroyed=!0,this.safe(()=>{this.flushPending(),this.paste.destroy(),this.unregisterInputs?.();for(let e of this.listeners)e()}))}};var L=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 Xe(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 se=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"email-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType,emailDomain:t.emailDomain}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function tl(r,e){return new se(r,e)}var ae=class extends g{lowEventTracker;send;postResponse;resend;constructor(e,t={}){super(e,"sms-otp"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function ol(r,e){return new ae(r,e)}import{v7 as Kn}from"uuid";var le="cbo_email_link_starts";function Ot(r,e){let t=r.getItem(le);if(!Array.isArray(t))return[];let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.transactionId=="string"&&typeof n.anchor=="string"&&typeof n.sessionId=="string"&&typeof n.startedAt=="number"&&e-n.startedAt<864e5);return typeof __CBO_DATA_RETENTION__=="boolean"&&__CBO_DATA_RETENTION__&&i.length<t.length&&(i.length===0?r.removeItem(le):r.setItem(le,i)),i}function Kr(r,e){if(r)try{let t=Ot(r,e.startedAt).filter(i=>i.transactionId!==e.transactionId);t.push(e),r.setItem(le,t.slice(-10))}catch{}}function Wr(r,e,t=Date.now()){if(r)try{let i=Ot(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 Vr(r,e){if(r)try{let t=Ot(r,Date.now()).map(i=>i.transactionId===e?{...i,continued:!0}:i);r.setItem(le,t)}catch{}}var pe=class extends g{send;postResponse;resend;transactionId;constructor(e,t={}){super(e,"email-link"),this.send=this.defineStep("send"),this.postResponse=this.defineStep("post-response"),this.resend=this.defineStep("resend"),this.transactionId=t.transactionId||Kn(),this.subflowStart({explicitSpecType:t.explicitSpecType},{userReference:{crossEnvironmentTransactionIDStart:this.transactionId}});let i=this.captureReference,n=this.captureSession;i&&n&&Kr(e.getPersistentStorage(),{transactionId:this.transactionId,anchor:i,sessionId:n,specType:t.explicitSpecType,startedAt:Date.now()})}},de=class extends g{postResponse;resend;mode;continuationTracker;specType;createdAt=Date.now();transaction;started=!1;deferred=[];onPageHide=()=>this.flush();removePageHide;constructor(e,t={}){super(e,"email-link"),this.continuationTracker=e,this.specType=t.explicitSpecType,this.transaction=t.transactionId,this.postResponse=this.deferrable(this.defineStep("post-response"),!0),this.resend=this.deferrable(this.defineStep("resend"));let i=e.getPersistentStorage(),n=Wr(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=C(0,"pagehide",this.onPageHide))}get transactionId(){return this.transaction}setTransactionId(e){!e||this.transaction||(this.transaction=e,this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt()))}flush(){this.mode==="detached"&&!this.started&&this.startDetached(this.firstDeferredAt())}destroy(){this.flush(),this.removePageHideListener()}firstDeferredAt(){return this.deferred[0]?.at??this.createdAt}startDetached(e){this.started=!0,this.removePageHideListener(),this.subflowStart({explicitSpecType:this.specType,continuation:!0},{explicitTimestamp:e,...this.transaction?{userReference:{crossEnvironmentTransactionIDFinish:this.transaction}}:{}});let t=this.deferred;this.deferred=[];for(let i of t)i.run(i.at);try{this.continuationTracker.flushKeepalive()}catch{}}removePageHideListener(){typeof window<"u"&&this.removePageHide?.()}deferrable(e,t=!1){let i=(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&&Vr(this.continuationTracker.getPersistentStorage(),this.transaction)},error:(n,o)=>i(s=>e.error(n,{...o,explicitTimestamp:s}),o)}}};function ul(r,e){return new pe(r,e)}function fl(r,e){return new de(r,e)}var ce=class extends g{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 yl(r,e){return new ce(r,e)}var ue=class extends g{userConfirmation;deletion;constructor(e,t={}){super(e,"passkey-deletion"),this.userConfirmation=this.defineStep("user-confirmation"),this.deletion=this.defineStep("deletion"),this.subflowStart({})}};function Sl(r,e){return new ue(r,e)}var fe=class extends g{clientValidation;postResponse;cui;lowEventTracker;identifierLowEventTracker;constructor(e,t){super(e,"password-login"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.cui={getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.identifierInputHtmlField&&(this.identifierLowEventTracker=this.createLowCollector(()=>new 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()}};function Cl(r,e){return new fe(r,e)}var ge=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t){super(e,"password-enrollment"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","password"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function Il(r,e){return new ge(r,e)}var he=class extends g{lowEventTracker;cui;provideIdentifier;constructor(e,t){super(e,"provide-identifier"),this.cui={trigger:(i,n)=>{this.trigger(i,n)},getOptions:this.defineStep("cui-get-options",!0),ceremony:this.defineStep("cui-ceremony"),postResponse:this.defineStep("cui-post-response")},this.provideIdentifier={trigger:(i,n)=>{this.trigger(i,n)},clientValidation:this.defineStep("pi-client-validation"),postResponse:this.defineStep("pi-post-response")},this.subflowStart({explicitSpecType:t?.explicitSpecType}),t?.inputHtmlField&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),t.inputHtmlField,this.lowEventSink("input","identifier"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function Ll(r,e){return new he(r,e)}var me=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"social-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code"),this.subflowStart({explicitSpecType:t.explicitSpecType,entry:t.entry})}};function Dl(r,e){return new me(r,e)}var ye=class extends g{getRedirectUrl;exchangeCode;constructor(e,t={}){super(e,"sso-login"),this.getRedirectUrl=this.defineStep("get-redirect-url"),this.exchangeCode=this.defineStep("exchange-code");let{explicitSpecType:i,organizationDomain:n,actor:o}=Wn(t??{},e);this.subflowStart({explicitSpecType:i,organizationDomain:n,actor:o})}};function Wn(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}function Nl(r,e){return new ye(r,e)}var ve=class extends g{lowEventTracker;postResponse;constructor(e,t={}){super(e,"totp"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType}),this.lowEventTracker=this.createLowCollector(()=>new L(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()}};function Kl(r,e){return new ve(r,e)}var be=class extends g{ceremony;retry;postResponse;constructor(e,t={}){super(e,"app-confirmation"),this.ceremony=this.defineStep("ceremony"),this.retry=this.defineStep("retry"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function $l(r,e){return new be(r,e)}var Se=class extends g{ceremony;postResponse;constructor(e,t={}){super(e,"captcha"),this.ceremony=this.defineStep("ceremony"),this.postResponse=this.defineStep("post-response"),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function zl(r,e){return new Se(r,e)}var Ze=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 It=50,Vn=6e4,$n=40,jn=/^[A-Za-z0-9._-]+$/,we=class extends g{submit;skip;inputBinding;constructor(e,t){super(e,"form"),this.submit=this.defineStep("submit"),this.skip=this.defineStep("skip"),this.subflowStart(zn(e,t),Gn(e,t)),this.inputBinding=this.createLowCollector(()=>new Ze(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 Gn(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>Vn){Te(r,"Form: implausible startedAt ignored; using the current time");return}return{explicitTimestamp:t}}function zn(r,e){let t={},i=e?.name;typeof i=="string"&&i.trim()!==""?t.name=i:Te(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 Te(r,"Form: fields must be an array of field names; omitted from telemetry"),t;let o=n.filter(s=>typeof s=="string"&&s.length<=$n&&jn.test(s));return o.length<n.length&&Te(r,"Form: unsupported field names omitted from telemetry"),o.length>It&&Te(r,`Form: more than ${It} field names; the rest is omitted from telemetry`),o.length>0&&(t.fields=o.slice(0,It)),t}function Te(r,e){try{r.getLogger().warn(e)}catch{}}function ep(r,e){return new we(r,e)}function Pt(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 et(r,e,t){return{...r,start:(i,n)=>r.start(Pt(i,e,t),n),finished:(i,n)=>r.finished(Pt(i,e,t),n)}}var Ee=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-check"),t=$r(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{...et(n,t,i),errorTyped:(o,s)=>{n.errorTyped(Pt({code:o?.code,error:N(o?.error)},t,i),s)}}}},Ce=class extends g{getOptions;ceremony;postResponse;constructor(e,t){super(e,"trusted-device-enrollment"),t=$r(t,e);let i={purpose:t.purpose,storage:t.storage,trustName:t.trustName};this.getOptions=et(this.defineStep("get-options"),i,e),this.ceremony=et(this.defineStep("ceremony"),i,e),this.postResponse=et(this.defineStep("post-response"),i,e),this.subflowStart({explicitSpecType:t.explicitSpecType})}};function $r(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}function np(r,e){return new Ee(r,e)}function op(r,e){return new Ce(r,e)}var ke=class extends g{clientValidation;postResponse;lowEventTracker;constructor(e,t={}){super(e,"provide-data"),this.clientValidation=this.defineStep("client-validation"),this.postResponse=this.defineStep("post-response");let{inputHtmlField:i,...n}=t;this.subflowStart(n),i&&(this.lowEventTracker=this.createLowCollector(()=>new E(e.getLogger(),i,this.lowEventSink("input","data"))),this.registerLowFlusher(()=>this.lowEventTracker?.flushPending()))}destroy(){this.lowEventTracker?.destroy()}};function pp(r,e){return new ke(r,e)}var jr;function tt(r){jr=r}function w(){return jr}function R(r){return!!r&&typeof r=="object"&&typeof r.track=="function"&&typeof r.enqueueLowEvent=="function"}import{v7 as Jn}from"uuid";function rt(r){let e=Jn();return r.config.sessionContinuity?(r.persistContinuitySession(e,Date.now()),r.persistentStorage.setItem(k,0)):r.persistPerTabSession(e,Date.now()),r.sessionId=e,r.seq=0,r.queue.setSessionId(e),r.bridge?.reset(e),r.getLogger().debug(`Session reset: ${e}`),e}function it(r,e){r.track("flow_enriched",{match:{flowType:"*",at:"during"},expFol:!0},{...e})}function nt(r,e,t){let i=r.getLogger();try{if(!e||typeof e!="object"){i.warn("setFlowTags: ignoring non-object tags");return}let n={};for(let[s,a]of Object.entries(e)){if(s===""||typeof a!="string"){i.warn(`setFlowTags: ignoring invalid tag "${s}"`);continue}n[s]=a}if(Object.keys(n).length===0)return;let o={match:{flowType:t?.flowType??"*",at:"during"}};t?.expandToChildren!==void 0&&(o.expCh=t.expandToChildren),t?.expandToFollowing!==void 0&&(o.expFol=t.expandToFollowing),r.track("flow_enriched",o,void 0,n)}catch(n){i.warn("Failed to set flow tags",n)}}function ot(r,e){try{Object.prototype.hasOwnProperty.call(r.experiments,e)&&(delete r.experiments[e],r.persistExperiments())}catch(t){r.getLogger().error("Failed to clear experiment",t)}}function st(r){try{if(Object.keys(r.experiments).length===0)return;r.experiments={},r.persistExperiments()}catch(e){r.getLogger().error("Failed to clear experiments",e)}}function yp(r){let e=R(r)?r:w();return e?rt(e):void 0}function vp(r,e){let[t,i]=R(r)?[r,e]:[w(),r];t&&it(t,i)}function bp(r,e,t){let i=R(r),n=i?r:w();n&&nt(n,i?e:r,i?t:e)}function Sp(r,e,t){R(r)?r.setExperiments({[e]:t}):w()?.setExperiments({[r]:e})}function Tp(r,e){let[t,i]=R(r)?[r,e]:[w(),r];t&&ot(t,i)}function wp(r){let e=R(r)?r:w();e&&st(e)}function Ep(r,e){R(r)?r.telemetry("info",e):w()?.telemetry("info",r)}function Cp(r,e){R(r)?r.telemetry("error",e):w()?.telemetry("error",r)}function Gr(r,e,t,i){let{userId:n,identifier:o,crossEnvironmentTransactionID:s,...a}=e,l={userId:n,identifier:o,crossEnvironmentTransactionID:s},p={...r.options.defaultTags,...r.applicationTag(),...t};r.track("conversion",a,l,p,void 0,void 0,i)}function zr(r,e,t,i){r.track("auth_decision_started",e,void 0,t,void 0,void 0,i)}function Jr(r,e,t,i){r.track("auth_decision_finished",e,void 0,t,void 0,void 0,i)}function Yr(r,e,t,i){let n={subflowType:e,stepData:t};r.track("subflow_error",n,i?.userReference,void 0,void 0,i?.explicitTimestamp,i?.experiments,{subflowStartEventId:i?.subflowStartEventId,sessionId:i?.captureSessionId,initiator:i?.initiator})}var Yn={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}},Qn=1024,z=class extends Error{},Xn=["name","message","code","errors","stack"],Zn=/[^\x20-\x7E]/,J=r=>Object.prototype.toString.call(r).slice(8,-1),eo=r=>r===null?"null":typeof r=="object"?J(r):typeof r,to=r=>r instanceof Error||J(r)==="Error"||J(r)==="DOMException";function Zr(r){return Zn.test(r)?new TextEncoder().encode(r).byteLength:r.length}function G(r,e){let t=Yn[r];return typeof e!="number"||!Number.isFinite(e)?t.default:Math.min(t.max,Math.max(t.min,Math.floor(e)))}function Qr(r={}){return{stack:r.stack===!0,maxStackFrames:G("maxStackFrames",r.maxStackFrames),depth:G("depth",r.depth),maxBreadth:G("maxBreadth",r.maxBreadth),maxValueLength:G("maxValueLength",r.maxValueLength),maxCauseDepth:G("maxCauseDepth",r.maxCauseDepth),maxBytes:G("maxBytes",r.maxBytes)}}function ei(r,e={}){if(r===void 0)return;let t=Qr(),i=n=>{let o=JSON.stringify(n);return o===void 0||Zr(o)<=t.maxBytes};try{if(t=Qr(e),t.maxBytes===0)return;let n=M(eo(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:at(r,s,a)};if(i(l))return l}catch(l){if(!(l instanceof z))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 xe(r,e){if(r.length>e.limits.maxBytes)throw new z;if(e.textBytes+=Zr(JSON.stringify(r)),e.textBytes>e.limits.maxBytes)throw new z;return r}function at(r,e,t){if(++t.nodes>Qn)throw new z;let i=ro(r,e,t);return typeof i=="string"?xe(i,t):i}function ro(r,e,t){switch(typeof r){case"string":return M(r,t.limits.maxValueLength);case"number":return Number.isFinite(r)?r:String(r);case"boolean":case"undefined":return r;case"bigint":case"symbol":return M(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`[${J(i)}]`;t.seen.add(i);try{return io(i,e,t)}finally{t.seen.delete(i)}}function M(r,e){return r.length>e?r.slice(0,e)+"\u2026":r}function Xr(r,e,t){let i=r.length>t;r=M(r,t);let n=r.split(`
2
2
  `);if(n.length<=e+1)return M(r,t);let o=n.slice(0,e+1).join(`
3
3
  `),s=i?"[truncated]":`[+${n.length-e-1} frames]`;return M(`${o}
4
4
  ${s}`,t)}function io(r,e,t){let{limits:i}=t,n=J(r),o=u=>at(u,e-1,t);if(n==="Date")return Number.isNaN(r.getTime())?"[Invalid Date]":r.toISOString();if(n==="RegExp")return M(String(r),i.maxValueLength);if(n==="ArrayBuffer")return`[ArrayBuffer(${r.byteLength})]`;if(ArrayBuffer.isView(r))return`[${n}(${r.byteLength})]`;if(n==="Map"||n==="Set"){let u=r,f=[];for(let h of u){if(f.length===i.maxBreadth)break;f.push(o(h))}return u.size>f.length&&f.push(`[+${u.size-f.length} more]`),f}if(n==="Promise"||n==="WeakMap"||n==="WeakSet"||n==="Window")return`[${n}]`;if(typeof Node<"u"&&r instanceof Node)return`[${n}]`;if(Array.isArray(r)){let u=r.slice(0,i.maxBreadth).map(o);return r.length>i.maxBreadth&&u.push(`[+${r.length-i.maxBreadth} more]`),u}if(typeof Response<"u"&&r instanceof Response)return{status:o(r.status),statusText:o(r.statusText),url:o(r.url),redirected:o(r.redirected)};if(typeof Event<"u"&&r instanceof Event){let u=r,f={type:o(u.type)};for(let h of["message","filename","lineno","colno"])h in u&&(f[h]=o(u[h]));return"error"in u&&u.error!=null&&(f.error=o(u.error)),f}let s=Object.create(null),a=r,l=to(r);if(l){for(let f of Xn){if(f==="stack"&&!i.stack)continue;let h=a[f];if(!(h==null||typeof h=="function")){if(f==="stack"){i.stack&&typeof h=="string"&&(s.stack=xe(Xr(h,i.maxStackFrames,i.maxValueLength),t));continue}s[f]=o(h)}}let u=a.cause;u!=null&&typeof u!="function"&&(s.cause=no(u,e-1,t))}let p=0,d=Object.keys(a);for(let u of d){if(u in s||u==="stack"&&!i.stack||l&&u==="cause")continue;if(++p>i.maxBreadth){s["\u2026"]=`[+${d.length-i.maxBreadth} keys]`;break}let f=a[u];typeof f!="function"&&(s[xe(u,t)]=u==="stack"&&typeof f=="string"?xe(Xr(f,i.maxStackFrames,i.maxValueLength),t):o(f))}return!l&&n!=="Object"&&p===0?`[${n}]`:s}function no(r,e,t){if(typeof r!="object"||r===null)return at(r,e,t);if(t.causeBudget<=0)return xe(`[${J(r)}]`,t);t.causeBudget--;try{return at(r,e,t)}finally{t.causeBudget++}}function ti(){return{rawErrors:ei}}import{v7 as uo}from"uuid";var oo=500,so=512*1024,ri=200,ii=200*1024,ao=16*1024,Rp=32e3;function ni(r){let e=r.lane;if(e)return e;let t=new Rt(r);return r.lane=t,r.enqueueProbe=(i,n=r.sessionId)=>{try{r.destroyed||t.enqueue(i,n)}catch(o){r.logger.error("Failed to enqueue probe",o)}},r.droppedProbeCount=()=>t.dropped,t}var lo=32,Rt=class{constructor(e){this.queue=e}items=[];bytes=0;dropped=0;pageId;seqs=new Map;enqueue(e,t){let i=JSON.stringify(e.payload);if(typeof i!="string"||ee(i)>ao){this.dropped++;return}let n={...e,payload:JSON.parse(i)},o=ee(JSON.stringify(n));for(this.items.push({sessionId:t,entry:n,bytes:o,attempts:0,flushAfter:0}),this.bytes+=o;this.items.length>oo||this.bytes>so&&this.items.length>1;){let s=this.items.shift();this.bytes-=s.bytes,this.dropped++}this.queue.scheduleFlush(this.queue.flushInterval(),"timer")}selectBatch(e,t){return this.select(e,t,ri,ii)}select(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>=ii&&o.push(a);break}s+=a.bytes,o.push(a)}}return o}remove(e){if(e.length===0)return;let t=new Set(e);this.items=this.items.filter(i=>!t.has(i));for(let i of e)this.bytes-=i.bytes}drop(e){this.remove(e),this.dropped+=e.length}handleResult(e,t,i){if(t.length===0)return;let n=this.queue,o=e.statusCode;if(typeof o=="number"&&o>=200&&o<300){this.remove(t);return}if(!n.isRetryable(o)){this.drop(t);return}let s=Math.max(1,n.config.retry.maxAttempts),a=n.parseRetryAfter(e),l=[];for(let p of t)p.attempts+=1,p.attempts>=s?l.push(p):p.flushAfter=i+n.backoffForAttempt(p.attempts,a);this.drop(l)}sendUnload(e,t,i,n){let o=this.queue,s=o.sessionId,a={sessionId:s,events:[],sdk:o.sdk,probes:[]};o.attachBatchMeta(a,[],t);let l=ee(JSON.stringify(a))+120,p=e>l?this.select(this.items,s,ri,e-l):[];if(p.length>0){a.probes=p.map(u=>u.entry),o.attachBatchMeta(a,p,t);let d=o.transport;n&&o.config.beaconKeepalive&&d.sendBeacon?d.sendBeacon(a):Promise.resolve(d.send(a)).catch(()=>{}),this.remove(p)}i&&this.drop(this.items.slice())}defaultPageId(){return this.pageId??=co()}nextSeq(e){let t=this.seqs.get(e)??0;if(this.seqs.delete(e),this.seqs.set(e,t+1),this.seqs.size>lo){let i=this.seqs.keys().next().value;i!==void 0&&this.seqs.delete(i)}return t}},po="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function co(){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+=po[r[t]&63];return e}var fo=/^[a-z][a-z0-9_-]{0,31}$/,oi=/^[A-Za-z0-9_-]{1,16}$/,go=64;function si(){return{setup:r=>{ni(r.queue)}}}function ai(r,e){let t=r.getLogger();try{if(r.isTrackingBlocked()){t.debug("Skipping probe for blocked user agent.");return}let i=r.queue,n=i.lane;if(!n){t.debug("Dropping probe: no probes() plugin.");return}if(!e||typeof e!="object"||typeof e.kind!="string"||!fo.test(e.kind)){t.debug("Dropping probe with an invalid kind.");return}let o=e.payload;if(!o||typeof o!="object"){t.debug(`Dropping probe "${e.kind}" without an object payload.`);return}let s=typeof e.pageId=="string"&&oi.test(e.pageId)?e.pageId:n.defaultPageId(),a={id:uo(),kind:e.kind,ts:typeof e.ts=="number"&&Number.isFinite(e.ts)?Math.round(e.ts):Date.now(),pageId:s,seq:n.nextSeq(s),payload:o};typeof e.cfg=="string"&&oi.test(e.cfg)&&(a.cfg=e.cfg);let l=ho(e.ctx);l&&(a.ctx=l),i.enqueueProbe(a)}catch(i){t.error("Failed to process probe before enqueue",i)}}function ho(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,go))}return Object.keys(e).length>0?e:void 0}function li(r={}){let e=r?.cookieDomain;return{storage:t=>({engine:new We(t,e),source:"cookie"})}}var mo="cbo_xs",ci="1",yo=20;var vo=/^[A-Za-z0-9._~-]{1,128}$/,bo=1e3,So=300*1e3,To=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,wo=/^[A-Za-z0-9_-]{1,64}$/,Eo=/^[a-z0-9-]+(\.[a-z0-9-]+)+$/,pi=/^\d{1,15}$/,Co=1e9,di=1e3,ko=1e5;function Ft(r){return typeof r=="string"&&vo.test(r)}function xo(r){let e=r.split("."),[t,i,n,o]=e;if(e.length<4||t!==ci||!i||!To.test(i)||!n||!pi.test(n)||!o||!pi.test(o)||Number(o)>Co)return;let s=e.length>4?e.slice(4).join("."):void 0;if(!(s!==void 0&&!Ft(s)))return{sessionId:i.toLowerCase(),lastActiveAt:Number(n),seqMark:Number(o),...s!==void 0&&{context:s}}}function Oo(r){let e=[ci,r.sessionId,String(Math.floor(r.lastActiveAt)),String(Math.floor(r.seqMark))];return r.context!==void 0&&e.push(r.context),e.join(".")}function Io(r,e){let t=r.trim().toLowerCase().replace(/^\./,""),i=e.toLowerCase();if(Eo.test(t))return i===t||i.endsWith(`.${t}`)?t:void 0}var lt=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(!wo.test(e.projectId)){e.logger.debug("Cross-origin session off: project id is not cookie-safe");return}let t=e.scope?e.scope():tr(0);if(!t.https){e.logger.debug("Cross-origin session off: page is not served over HTTPS");return}let i=Io(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??re(0),o=e.jar??re(0);return new r(`${mo}_${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)+di;return this.reservedMark=l+di,this.highestSeen=this.reservedMark,l}let a=t>=this.reservedMark||s!==void 0&&s>this.reservedMark;return!a&&i-this.lastWriteAt<bo?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>ko){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,p=l?this.plausibleMark(t.seqMark,n):void 0;p!==void 0&&(this.highestSeen=Math.max(this.highestSeen,p)),l&&!a&&(this.context=t.context);let d=n,u;s?(d=Math.max(n,p??0,this.highestSeen),u=d+yo):u=Math.max(this.reservedMark,this.highestSeen,n);let f=Oo({sessionId:i,lastActiveAt:o,seqMark:u,...this.context!==void 0&&{context:this.context}});return this.write(e,f),s&&(this.reservedMark=u),this.highestSeen=Math.max(this.highestSeen,u),this.lastWriteAt=o,{seq:d,value:f}}maxAgeSeconds(){return Math.max(60,Math.ceil(this.deps.inactivityMs()/1e3))}write(e,t){e.write(`${this.name}=${t}; Domain=${this.domain}; Path=/; Max-Age=${this.maxAgeSeconds()}; SameSite=Lax; Secure`)}rawValues(e){let t=`${this.name}=`;return e.read().split(";").map(i=>i.trim()).filter(i=>i.startsWith(t)).map(i=>i.substring(t.length))}isStored(e){try{return this.rawValues(this.jar).includes(e)}catch{return!1}}read(e,t){let i=this.deps.inactivityMs(),n;for(let o of this.rawValues(e)){let s=xo(o);s&&t-s.lastActiveAt<i&&s.lastActiveAt<=t+So&&(!n||s.lastActiveAt>n.lastActiveAt)&&(n=s)}return n}};function ui(r){let e=r&&typeof r=="object"?r.cookieDomain:void 0;return{session:t=>typeof e=="string"?Oe.create(t,e):void 0}}var Oe=class r{constructor(e,t){this.tracker=e;this.cookie=t}adoptedId;static create(e,t){try{if(e.isTrackingBlocked())return;let i=lt.create({projectId:e.options.projectId,cookieDomain:t,logger:e.getLogger(),inactivityMs:()=>e.config.sessionInactivityMs,report:(n,o)=>e.reportTelemetry(n,o)});return i?new r(e,i):void 0}catch(i){e.getLogger().error("Failed to set up the cross-origin session",i);return}}resolve(){let e=this.tracker,t=this.readLocalSessionActivity();return e.sessionId=e.resolveSessionId(),this.boot(t),e.sessionId}claim(e,t,i){return this.cookie.claim(e,t,i)}meta(e){if(this.cookie.isEnabled())return e&&e===this.adoptedId?"adopted":"own"}reset(e){this.cookie.reset(e)}stop(){this.cookie.stop()}localSeq(){let e=this.tracker;return e.config.sessionContinuity?Math.max(e.seq,e.persistentStorage.getItem(k)??0):e.seq}readLocalSessionActivity(){let e=this.tracker,t=new Map;try{let i=e.persistentStorage.getItem(K);i?.id&&typeof i.lastActiveAt=="number"&&t.set(i.id,i.lastActiveAt);let n=e.sessionStorage.getItem(ie);n&&typeof n=="object"&&n.id&&typeof n.lastActiveAt=="number"&&t.set(n.id,Math.max(t.get(n.id)??0,n.lastActiveAt))}catch(i){e.getLogger().error("Failed to read local session activity",i)}return t}boot(e){let t=this.tracker;try{this.adoptedId=void 0;let i=Date.now(),n=t.config.sessionContinuity,o=t.sessionId,s=this.cookie.boot({sessionId:o,lastActiveAt:o&&e.get(o)||0,seq:this.localSeq()},i);if(!s||!s.sessionId)return;s.adopted&&(t.sessionId=s.sessionId,this.adoptedId=s.sessionId,n?t.persistContinuitySession(s.sessionId,i):t.persistPerTabSession(s.sessionId,i),t.getLogger().debug("Adopted cross-origin session id",s.sessionId)),t.seq=s.seq,n&&t.persistentStorage.setItem(k,s.seq)}catch(i){t.getLogger().error("Failed to apply the cross-origin session",i)}}};function fi(r,e){try{let t=r.bridge;if(!(t instanceof Oe))return!1;let i=e==null||e===""?void 0:e;if(i!==void 0&&!Ft(i))return r.getLogger().debug("Ignoring invalid cross-origin context (expected <= 128 chars of [A-Za-z0-9._~-])"),!1;let n=t.cookie.setContext(r.sessionId,t.localSeq(),i);return n===void 0?!1:(n>r.seq&&(r.seq=n,r.config.sessionContinuity&&r.persistentStorage.setItem(k,n)),!0)}catch(t){return r.getLogger().error("Failed to set the cross-origin context",t),!1}}function gi(r){try{let e=r.bridge;return e instanceof Oe?e.cookie.getContext(r.sessionId):void 0}catch(e){r.getLogger().error("Failed to read the cross-origin context",e);return}}function Po(r){let e=[ti(),si()];r.storage==="cookie"&&e.push(li({cookieDomain:r.cookieDomain}));let t=Le(r.fixedDataConfig)?.crossOriginSession;return t&&e.push(ui(t)),e}var pt=class extends W{constructor(e){super(e,Po(e))}isFullTracker(){return!0}setExperiment(e,t){this.setExperiments({[e]:t})}clearExperiment(e){ot(this,e)}clearExperiments(){st(this)}trackSubflowError(e,t,i){Yr(this,e,t,i)}conversion(e,t,i){Gr(this,e,t,i)}setUser(e){it(this,e)}setFlowTags(e,t){nt(this,e,t)}authDecisionStarted(e,t,i){zr(this,e,t,i)}authDecisionFinished(e,t,i){Jr(this,e,t,i)}probe(e){ai(this,e)}logInfo(e){this.telemetry("info",e)}logError(e){this.telemetry("error",e)}passkeyLoginFullOperation(e){return new ne(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 ge(this,e)}emailLinkOperationFull(e){return new pe(this,e)}continueEmailLinkOperation(e){return new de(this,e)}emailOtpOperationFull(e){return new se(this,e)}smsOtpOperationFull(e){return new ae(this,e)}totpOperationFull(e){return new ve(this,e)}provideIdentifierOperationFull(e){return new he(this,e)}provideDataOperationFull(e){return new ke(this,e)}formOperationFull(e){return new we(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 Q(this,e)}keyRegistrationOperationFull(e){return new X(this,e)}captchaOperationFull(e){return new Se(this,e)}trustedDeviceCheckOperationFull(e){return new Ee(this,e)}trustedDeviceEnrollmentOperationFull(e){return new Ce(this,e)}setCrossOriginContext(e){return fi(this,e)}getCrossOriginContext(){return gi(this)}resetSession(){return rt(this)}};var Ro=2048;function hi(r){let e=String(r??"").split("/").filter(t=>t!=="");return e.length===0?"/":"/"+e.map(()=>"*").join("/")}function _d(r){return typeof r!="function"?{}:{sourcePath:()=>{let{path:e,search:t}=er(0);try{let i=r(e,t);return typeof i=="string"?i.slice(0,Ro):hi(e)}catch{return hi(e)}}}}function Md(r){return typeof r!="function"?{}:{eventTime:e=>{try{let t=r(e);return typeof t=="number"&&Number.isFinite(t)?t:void 0}catch{return}}}}function Nd(r){return typeof r!="number"||!Number.isFinite(r)||r<=0?{}:{deviceHandleMaxAgeMs:r}}var Fo=["none","presence","size","class","format","partial","enum","computed","token","pseudonym","redacted","raw"],Lo=["personal-identifier","personal-data","secret","passkey","device","behavior","technical"];var mi=[1],yi={type:1,id:"credentialId",transports:mi},vi={appid:1,appidExclude:1,credProps:{rk:1},hmacCreateSecret:1,hmacGetSecret:{},largeBlob:{supported:1,written:1},prf:{enabled:1}},Ao={challenge:"zero",timeout:1,rpId:1,allowCredentials:[yi],userVerification:1,hints:[1],extensions:"names"},_o={rp:{id:1},user:{id:"userId"},challenge:"zero",pubKeyCredParams:[{type:1,alg:1}],timeout:1,excludeCredentials:[yi],authenticatorSelection:{authenticatorAttachment:1,requireResidentKey:1,residentKey:1,userVerification:1},attestation:1,attestationFormats:[1],hints:[1],extensions:"names"},Do={id:"credentialId",rawId:"credentialId",type:1,authenticatorAttachment:1,response:{clientDataJSON:"clientData",authenticatorData:"authData",userHandle:"userHandle"},clientExtensionResults:vi},Mo={id:"credentialId",rawId:"credentialId",type:1,authenticatorAttachment:1,response:{clientDataJSON:"clientData",attestationObject:"authData",authenticatorData:"authData",transports:mi,publicKeyAlgorithm:1},clientExtensionResults:vi},Ho={clientExtensionResults:"getClientExtensionResults",transports:"getTransports",authenticatorData:"getAuthenticatorData",publicKeyAlgorithm:"getPublicKeyAlgorithm"},No=["type","challenge","origin","crossOrigin","topOrigin"],Bo="AAAAAAAAAAAAAAAAAAAAAA",Uo=16,qo=256,Ko=1e3,Lt=new Map;function At(r,e){return Si(r,_o,e)}function _t(r,e){return Si(r,Ao,e)}function Dt(r,e){return Ti(r,Mo,e)}function Mt(r,e){return Ti(r,Do,e)}function bi(r){return{passkeyReference:r?.passkeyReference===!0,projectors:r??{}}}function Si(r,e,t){try{let i=ki(r);if(!i)return;let n=bi(t),o=i.challenge===void 0?Ie(ct(i,"publicKey")):void 0;return JSON.stringify(o?{publicKey:dt(o,e,n)}:dt(i,e,n))}catch{return}}function Ti(r,e,t){try{let i=ki(r);if(!i)return;let n=bi(t);if(!n.passkeyReference){let o=Pe(ct(i,"rawId"))??Pe(ct(i,"id"));o&&o.length>=Uo&&(n.swap={from:o,to:Ci(o)})}return JSON.stringify(dt(i,e,n))}catch{return}}function dt(r,e,t,i=0){if(i>8)throw new TypeError("Invalid telemetry payload");let n=Object.create(null);for(let o of Object.keys(e)){let s=ct(r,o),a=Ho[o];if(s===void 0&&a&&typeof r[a]=="function"&&(s=Reflect.apply(r[a],r,[])),s===void 0)continue;let l=wi(s,e[o],t,i+1);l!==void 0&&(n[o]=l)}return n}function wi(r,e,t,i){if(r===null)return e==="userId"||e==="userHandle"||e===1?null:void 0;switch(e){case 1:return typeof r=="string"||typeof r=="boolean"?r:typeof r=="number"?Number.isFinite(r)?r:null:Y(r)?F(Re(r)):void 0;case"zero":return Ei(r);case"credentialId":return Wo(r,t);case"userHandle":case"userId":return Vo(r,e,t);case"clientData":return $o(r);case"authData":return jo(r,t);case"names":{let o=Ie(r);if(!o)return;let s=Object.create(null);for(let a of Object.keys(o))s[a]=!0;return s}}if(Array.isArray(e))return Array.isArray(r)?r.slice(0,Ko).map(o=>wi(o,e[0],t,i)??null):void 0;let n=Ie(r);return n?dt(n,e,t,i):void 0}function Ei(r){return typeof r=="string"?r.replace(/[^=]/g,"A"):Y(r)?F(new Uint8Array(Re(r).length)):void 0}function Wo(r,e){if(e.passkeyReference)return typeof r=="string"?r:Y(r)?F(Re(r)):void 0;let t=Pe(r);return t?F(Ci(t)):void 0}function Vo(r,e,t){let i=typeof r=="string"?r:Y(r)?F(Re(r)):void 0;if(i===void 0)return;let n=t.projectors.userId;if(n)try{let o=n(i);return typeof o=="string"||o===null?o:void 0}catch{return}if(e!=="userId")return i===""?"":Bo}function $o(r){let e=Pe(r);if(!e)return;let t;try{t=Ie(JSON.parse(new TextDecoder().decode(e)))}catch{return}if(!t)return;let i={};for(let n of No){let o=t[n];o!==void 0&&(n==="challenge"?typeof o=="string"&&(i[n]=Ei(o)):(typeof o=="string"||typeof o=="boolean")&&(i[n]=o))}return F(new TextEncoder().encode(JSON.stringify(i)))}function jo(r,e){let t=Pe(r);if(!t)return;if(!e.swap)return F(t);let{from:i,to:n}=e.swap,o=t.slice();for(let s=0;s+i.length<=o.length;s++){let a=!0;for(let l=0;l<i.length;l++)if(o[s+l]!==i[l]){a=!1;break}a&&(o.set(n,s),s+=i.length-1)}return F(o)}function Ci(r){let e=F(r),t=Lt.get(e);if(t)return t;let i=new Uint8Array(r.length);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(i);else for(let n=0;n<i.length;n++)i[n]=Math.floor(Math.random()*256);return Lt.size<qo&&Lt.set(e,i),i}function ki(r){return Ie(typeof r=="string"?JSON.parse(r):r)}function ct(r,e){return r[e]}function Ie(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&!Y(r)?r:void 0}function Y(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Re(r){return r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function Pe(r){if(Y(r))return Re(r);if(typeof r=="string")try{let e=r.replace(/-/g,"+").replace(/_/g,"/").replace(/=+$/,""),t=atob(e+"===".slice((e.length+3)%4)),i=new Uint8Array(t.length);for(let n=0;n<t.length;n++)i[n]=t.charCodeAt(n);return i}catch{return}}function F(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var Go={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function zo(r,e){return typeof __CBO_DATA_CEREMONY__=="boolean"&&__CBO_DATA_CEREMONY__?At(r,e):ut(r,"creationOptions",e)}function Jo(r,e){return typeof __CBO_DATA_CEREMONY__=="boolean"&&__CBO_DATA_CEREMONY__?Dt(r,e):ut(r,"creationResponse",e)}function Yo(r,e){return typeof __CBO_DATA_CEREMONY__=="boolean"&&__CBO_DATA_CEREMONY__?_t(r,e):ut(r,"requestOptions")}function Qo(r,e){return typeof __CBO_DATA_CEREMONY__=="boolean"&&__CBO_DATA_CEREMONY__?Mt(r,e):ut(r,"assertionResponse",e)}function ut(r,e,t={}){try{let i=typeof r=="string"?JSON.parse(r):r;if(!Xo(i))return;let n=new Set(Go[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)?xi(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 xi(a);if(p>64||o.has(a))throw new TypeError("Invalid telemetry payload");o.add(a);try{if(Array.isArray(a))return a.map((h,c)=>s(h,`${l}/${c}`,p+1));let d=Object.create(null);for(let h in a){let c=`${l}/${h.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(n.has(c)||h==="toJSON")continue;let y=s(a[h],c,p+1);y!==void 0&&(d[h]=y)}let u=a,f=(h,c)=>{if(d[c]!==void 0||typeof u[h]!="function")return;let y=`${l}/${c}`,b=s(Reflect.apply(u[h],a,[]),y,p+1);b!==void 0&&(d[c]=b)};return l===""&&(e==="creationResponse"||e==="assertionResponse")&&f("getClientExtensionResults","clientExtensionResults"),l==="/response"&&e==="creationResponse"&&(f("getTransports","transports"),f("getAuthenticatorData","authenticatorData"),f("getPublicKey","publicKey"),f("getPublicKeyAlgorithm","publicKeyAlgorithm")),d}finally{o.delete(a)}}}};return JSON.stringify(s(i,""))}catch{return}}function Xo(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,"")}function zd(r){let e=new pt(r);return tt(e),e}function Jd(r){let e=new W(r);return tt(e),e}function Yd(){let r=w();return r?.isFullTracker()?r:void 0}function Qd(){return w()}function Xd(){return w()?.getSessionId()}function Zd(r){w()?.setExperiments(r)}function ec(){return w()?.getExperiments()??{}}function tc(r,e){w()?.telemetry(r,e)}async function rc(){let r=w();r&&(await r.destroy(),tt(void 0))}export{be as AppConfirmationOperationFull,Hi as AuthEventName,Ii as CEREMONY_LOW_EVENT_TAIL_MS,T as CONFIG_BOUNDS,qt as CONFIG_CACHE_STORAGE_KEY,Kt as CONFIG_REQUEST_HEADER,ft as CONFIG_STORAGE_KEY,Se as CaptchaOperationFull,We as CookieStorage,pt as CorbadoTracker,W as CorbadoTrackerCore,fs as DEFAULT_DEVICE_INFO_COLLECTOR_TIMEOUT_MS,cs as DEFAULT_FLUSH_INTERVAL_MS,Ki as DEFAULT_MAX_ENTRIES,Wi as DEFAULT_MAX_SERIALIZED_LENGTH,S as DEFAULT_RELIABILITY_CONFIG,us as DEFAULT_SEQ_LOCK_TIMEOUT_MS,Pi as DEFAULT_SESSION_INACTIVITY_MS,de as EmailLinkContinuationOperation,pe as EmailLinkOperationFull,se as EmailOtpOperationFull,q as EventStore,we as FormOperationFull,X as KeyRegistrationOperationFull,Q as KeySigningOperationFull,Ke as LocalStorage,qe as NamespacedStorage,ht as OUTBOX_LOCK_NAME,Vi as OUTBOX_MAX_AGE_MS,qi as OUTBOX_STORAGE_KEY,g as OperationFull,he as OperationFullProvideIdentifierWithCUI,ii as PROBE_BATCH_MAX_BYTES,ri as PROBE_BATCH_MAX_ITEMS,ao as PROBE_PAYLOAD_MAX_BYTES,so as PROBE_QUEUE_MAX_BYTES,oo as PROBE_QUEUE_MAX_ITEMS,ue as PasskeyDeletionOperationFull,ce as PasskeyEnrollmentOperationFull,ne as PasskeyLoginOperationFull,ge as PasswordEnrollmentOperationFull,fe as PasswordLoginOperationFull,Rt as ProbeLane,ke as ProvideDataOperationFull,Yn as RAW_ERROR_BOUNDS,Lo as READER_CATEGORIES,Fo as READER_EXPOSURES,Ne as RequestQueue,St as SDK_NAME,Tt as SDK_VERSION,Ai as STATIC_CONFIG_VERSION,Ve as SessionStorage,ae as SmsOtpOperationFull,me as SocialLoginOperationFull,ye as SsoLoginOperationFull,ve as TotpOperationFull,Ee as TrustedDeviceCheckOperationFull,Ce as TrustedDeviceEnrollmentOperationFull,mr as UNLOAD_BUDGET_BYTES,Rp as UNLOAD_PROBE_MAX_BYTES,$l as appConfirmationOperationFull,Jr as authDecisionFinished,zr as authDecisionStarted,jt as cacheConfigRecord,zl as captchaOperationFull,Mt as ceremonyAssertionResponse,At as ceremonyCreationOptions,Dt as ceremonyCreationResponse,_t as ceremonyRequestOptions,Tp as clearExperiment,wp as clearExperiments,fl as continueEmailLinkOperation,Gr as conversion,li as cookieStorage,Pr as createLogger,ui as crossOriginSession,rc as destroy,Ar as detectPasswordManagerExtensions,Nd as deviceHandleMaxAge,ul as emailLinkOperationFull,tl as emailOtpOperationFull,Md as eventTime,_d as fixedSourcePath,ep as formOperationFull,gi as getCrossOriginContext,ec as getExperiments,Xd as getSessionId,Yd as getTracker,Qd as getTrackerCore,zd as init,Jd as initCore,ni as installProbeLane,ps as keyRegistrationOperationFull,ls as keySigningOperationFull,$t as loadCachedConfig,Ae as loadConfigRecord,Cp as logError,Ep as logInfo,hi as maskedSourcePath,P as namespacedKey,$i as outboxEntryTime,B as parseReliabilityConfig,Sl as passkeyDeletionOperationFull,yl as passkeyEnrollmentFullOperation,Da as passkeyLoginFullOperation,Il as passwordEnrollmentFullOperation,Cl as passwordLoginFullOperation,ai as probe,si as probes,pp as provideDataOperationFull,Ll as provideIdentifierOperationFull,ti as rawErrors,yp as resetSession,Le as resolveFixedDataConfig,Qr as resolveRawErrorLimits,Fe as resolveReliabilityConfig,Qo as sanitizeAssertionResponse,zo as sanitizeCreationOptions,Jo as sanitizeCreationResponse,Yo as sanitizeRequestOptions,ei as serializeRawError,fi as setCrossOriginContext,Sp as setExperiment,Zd as setExperiments,bp as setFlowTags,vp as setUser,ol as smsOtpOperationFull,Dl as socialLoginOperationFull,Nl as ssoLoginOperationFull,Vt as staticReliabilityConfig,tc as telemetry,Kl as totpOperationFull,Yr as trackSubflowError,np as trustedDeviceCheckOperationFull,op as trustedDeviceEnrollmentOperationFull,ee as utf8Length};