🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
"use strict";(()=>{var qe=Object.defineProperty;var Je=(r,e,t)=>e in r?qe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var k=(r,e,t)=>Je(r,typeof e!="symbol"?e+"":e,t);function Xe(r){if(r.startsWith("re:")){let c=r.slice(3);if(!c)throw new Error("Empty regex pattern");return new RegExp(c)}let t="__DOUBLE_ASTERISK_TOKEN__",n="__SINGLE_ASTERISK_TOKEN__",s=r.replace(/\*\*/g,t).replace(/\*/g,n).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(n,"g"),"[^/]+");return new RegExp("^"+a+"$")}function j(r,e){for(let t of e)try{if(Xe(t).test(r))return t}catch(n){console.error(`Invalid pattern: ${t}`,n)}return null}function pe(r,e){let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function ge(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function L(r,e){if(r.length<=e)return r;let t=r.charCodeAt(e-1);return r.slice(0,t>=55296&&t<=56319?e-1:e)}function I(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function P(r,e=!1){return r.hash.startsWith("#/")?r.hash.substring(1):r.hash.startsWith("#!/")?r.hash.substring(2):r.pathname+(e?r.hash:"")}var Qe=2e3;function $(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}var Ye=64;function Ze(r){let e=`${r}-visitor-id`;try{let t=localStorage.getItem(e);if(t&&t.length<=Ye)return t;let n=$();return localStorage.setItem(e,n),n}catch{return $()}}function et(r){try{return localStorage.getItem(`${r}-user-id`)||void 0}catch{return}}async function tt(r,e,t,n,i){let s=new AbortController,a=window.setTimeout(()=>s.abort(),Qe);try{let c=new URL(window.location.href),d=await fetch(`${r}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:s.signal,body:JSON.stringify({anonymousId:n,identifiedUserId:et(t),hostname:c.hostname,pathname:P(c,i),querystring:c.search,query:Object.fromEntries(c.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!d.ok)return{enabled:!0,flags:{}};let u=await d.json();return{enabled:u?.featureFlagsEnabled!==!1,flags:u?.flags&&typeof u.flags=="object"?u.flags:{}}}catch{return{enabled:!0,flags:{}}}finally{window.clearTimeout(a)}}function nt(r){try{let e=new URL(r,window.location.href);return e.searchParams.get("siteId")||e.searchParams.get("site-id")||e.searchParams.get("site_id")}catch{return null}}async function he(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let n=nt(e)||r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the ?siteId= query parameter or the data-site-id attribute"),null;let i=r.getAttribute("data-namespace")||"rybbit",s=$(),a=I(r.getAttribute("data-skip-patterns"),[]),c=I(r.getAttribute("data-mask-patterns"),[]),d=I(r.getAttribute("data-replay-mask-text-selectors"),[]),u=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,g=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,y=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,R=r.getAttribute("data-replay-block-class")||void 0,h=r.getAttribute("data-replay-block-selector")||void 0,o=r.getAttribute("data-replay-ignore-class")||void 0,l=r.getAttribute("data-replay-ignore-selector")||void 0,p=r.getAttribute("data-replay-mask-text-class")||void 0,w=r.getAttribute("data-replay-mask-all-inputs"),E=w!==null?w!=="false":void 0,C=r.getAttribute("data-replay-mask-input-options"),Ve=C?I(C,{password:!0,email:!0}):void 0,oe=r.getAttribute("data-replay-collect-fonts"),Ge=oe!==null?oe!=="false":void 0,le=r.getAttribute("data-replay-sampling"),ze=le?I(le,{}):void 0,ce=r.getAttribute("data-replay-slim-dom-options"),je=ce?I(ce,{}):void 0,ue=r.getAttribute("data-replay-sample-rate"),$e=ue?Math.min(100,Math.max(0,parseInt(ue,10))):void 0,Ke=r.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:n,visitorId:s,debounceDuration:u,sessionReplayBatchSize:g,sessionReplayBatchInterval:y,sessionReplayMaskTextSelectors:d,skipPatterns:a,maskPatterns:c,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackUrlFragments:!1,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Ke,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:R,sessionReplayBlockSelector:h,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:l,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:Ve,sessionReplayCollectFonts:Ge,sessionReplaySampling:ze,sessionReplaySlimDOMOptions:je,sessionReplaySampleRate:$e},T=f;try{let _=`${t}/site/tracking-config/${n}`,de=await fetch(_,{method:"GET",credentials:"omit"});if(de.ok){let m=await de.json();T={...f,autoTrackPageview:m.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:m.trackUrlParams??f.trackQuerystring,trackUrlFragments:m.trackUrlFragments??f.trackUrlFragments,trackOutbound:m.trackOutbound??f.trackOutbound,enableWebVitals:m.webVitals??f.enableWebVitals,trackErrors:m.trackErrors??f.trackErrors,enableSessionReplay:m.sessionReplay??f.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??f.trackButtonClicks,trackCopy:m.trackCopy??f.trackCopy,trackFormInteractions:m.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:m.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(_){console.warn("Error fetching tracking config:",_)}if(T.featureFlagsEnabled){T.visitorId=Ze(i);let _=await tt(t,n,i,T.visitorId,T.trackUrlFragments);T.featureFlagsEnabled=_.enabled,T.featureFlags=_.flags}return T}var b={automationApi:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024,squareScreen:2048,missingScreenDimensions:4096},rt=Object.keys(b),ye={automationApi:3,zeroOuterDimensions:2,missingChrome:1,swiftShader:1,emptyPlugins:1,defaultViewport800x600:3,defaultViewport1024x768:3,impossibleDimensions:3,outerDimensionsWeird:2,pluginApiAbsence:0,defaultViewport1280x1200:3,squareScreen:3,missingScreenDimensions:1},_t=rt.reduce((r,e)=>r|b[e],0),Pt=b.automationApi|b.impossibleDimensions|b.defaultViewport800x600|b.defaultViewport1024x768|b.defaultViewport1280x1200|b.squareScreen,be=10,fe=200,me=8192,it=[{width:800,height:600,signal:"defaultViewport800x600"},{width:1024,height:768,signal:"defaultViewport1024x768"},{width:1280,height:1200,signal:"defaultViewport1280x1200"}];function st(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=fe&&e>=fe&&r<=me&&e<=me}function at(r){return/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r)}function ve(r,e,t){if(!st(r,e))return["impossibleDimensions"];let n=[];if(r===e&&n.push("squareScreen"),at(t))for(let i of it)r===i.width&&e===i.height&&n.push(i.signal);return n}var Se=null;function we(){return Te().score}function x(){return Te().mask}function Ee(){return document.prerendering===!0}function Te(){return Ee()?ke():(Se??(Se=ke()),Se)}function ke(){let r=0,e=0;function t(n){let i=b[n];(e&i)===0&&(e|=i,r+=ye[n])}try{let n=navigator.userAgent,i=/Chrome\//.test(n)&&!/\bwv\b|; wv\)/.test(n),s=Number(window.screen?.width),a=Number(window.screen?.height),c=Number(window.outerWidth),d=Number(window.outerHeight),u=Number(window.innerWidth),g=Number(window.innerHeight),R=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(o=>o in window||o in document);(navigator.webdriver===!0||R)&&t("automationApi"),(d===0||c===0)&&!Ee()&&t("zeroOuterDimensions");for(let o of ve(s,a,n))t(o);Number.isFinite(c)&&Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(g)&&c>0&&d>0&&u>0&&g>0&&(c+8<u||d+8<g)&&t("outerDimensionsWeird");let h=!1;!window.chrome&&i&&(t("missingChrome"),h=!0);try{let o=document.createElement("canvas"),l=o.getContext("webgl")||o.getContext("experimental-webgl");if(l)try{let p=[],w=l.getParameter(l.RENDERER);typeof w=="string"&&p.push(w);try{let E=l.getExtension("WEBGL_debug_renderer_info");if(E){let C=l.getParameter(E.UNMASKED_RENDERER_WEBGL);typeof C=="string"&&p.push(C)}}catch{}p.join(" ").toLowerCase().includes("swiftshader")&&t("swiftShader")}finally{ot(o,l)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t("emptyPlugins"),h=!0),h&&t("pluginApiAbsence")}catch{}return{score:Math.min(r,be),mask:e}}function ot(r,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}r.width=0,r.height=0}var Re="rybbit-replay-sampled",lt=1e4;function ct(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(Re);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(Re,t?"1":"0"),t}catch{return Math.random()*100<r}}var N=class{constructor(e,t,n){this.isRecording=!1;this.capped=!1;this.eventBuffer=[];this.failedBatches=[];this.lastFullSnapshotRequestAt=-1/0;this.config=e,this.userId=t,this.sendBatch=n,document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flushEvents()}),window.addEventListener("pagehide",()=>void this.flushEvents())}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!ct(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.capped||this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.deferredSnapshotTimer!==void 0&&(clearTimeout(this.deferredSnapshotTimer),this.deferredSnapshotTimer=void 0),(this.eventBuffer.length>0||this.failedBatches.length>0)&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{(this.eventBuffer.length>0||this.failedBatches.length>0)&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){let e=this.failedBatches;this.failedBatches=[],this.eventBuffer.length>0&&(e.push({userId:this.userId,events:this.eventBuffer,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language},_bsm:x()}),this.eventBuffer=[]),await Promise.all(e.map(t=>this.sendOrRequeue(t)))}async sendOrRequeue(e){try{let t=await this.sendBatch(e);t?.stopRecording?this.stopForSizeCap():t?.takeFullSnapshot?this.takeFullSnapshot():this.deferredSnapshotTimer!==void 0&&e.events.some(n=>n.type===2)&&(clearTimeout(this.deferredSnapshotTimer),this.deferredSnapshotTimer=void 0)}catch{this.capped||this.requeue(e)}}requeue(e){let t=this.failedBatches[this.failedBatches.length-1];if(t&&t.userId===e.userId&&JSON.stringify(t.metadata)===JSON.stringify(e.metadata)){t.events=t.events.concat(e.events);return}this.failedBatches.push(e)}takeFullSnapshot(){if(!this.isRecording)return;let e=this.lastFullSnapshotRequestAt+lt-Date.now();if(e>0){this.deferredSnapshotTimer===void 0&&(this.deferredSnapshotTimer=window.setTimeout(()=>{this.deferredSnapshotTimer=void 0,this.takeFullSnapshot()},e));return}this.lastFullSnapshotRequestAt=Date.now(),this.flushEvents();try{window.rrweb?.record.takeFullSnapshot?.(!0)}catch{}this.flushEvents()}stopForSizeCap(){this.capped=!0,this.stopRecordingFn&&(this.stopRecordingFn(),this.stopRecordingFn=void 0),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer=[],this.failedBatches=[]}updateUserId(e){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var ut=2e3,dt=2048,pt=512,gt=2048,ht=500,ft=48*1024,mt=[408,429,502,503,504],O=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.replayKeepaliveBytesInFlight=0;this.config=e,this.lastPageviewUrl=this.getPageviewUrl(),this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}isUnassignedVariant(e){return e.flagType==="multivariate"&&typeof e.value!="string"}getFeatureFlagEventPayload(){let e={};for(let[t,n]of Object.entries(this.config.featureFlags||{}))this.isUnassignedVariant(n)||(e[t]=this.serializeFeatureFlagValue(n.value));return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=P(e,this.config.trackUrlFragments);return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){if(!this.config.featureFlagsEnabled)return;let e=new AbortController,t=window.setTimeout(()=>e.abort(),ut);try{let n=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0,signal:e.signal});if(!n.ok)return;let i=await n.json();this.config.featureFlags=i?.flags&&typeof i.flags=="object"?i.flags:{},i?.featureFlagsEnabled===!1&&(this.config.featureFlagsEnabled=!1)}catch{}finally{window.clearTimeout(t)}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new N(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){let t=JSON.stringify(e),n=ft-this.replayKeepaliveBytesInFlight,i=t.length<=n?new Blob([t]).size:1/0,s=i<=n;s&&(this.replayKeepaliveBytesInFlight+=i);let a;try{a=await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:t,mode:"cors",keepalive:s})}catch(c){throw console.error("Failed to send session replay batch:",c),c}finally{s&&(this.replayKeepaliveBytesInFlight-=i)}if(!a.ok){if(mt.includes(a.status))throw new Error(`Session replay batch failed with status ${a.status}`);return}try{return await a.json()}catch{return}}createBasePayload(){let e=new URL(window.location.href),t=P(e,this.config.trackUrlFragments);if(j(t,this.config.skipPatterns))return null;let n=j(t,this.config.maskPatterns);n&&(t=n);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:L(document.title,pt),referrer:L(document.referrer,dt),_bs:we(),_bsm:x()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),this.config.featureFlagsEnabled&&(i.visitor_id=this.config.visitorId),i}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",n={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(n):void 0};this.sendTrackingData(a)}trackPageview(){this.lastPageviewUrl=this.getPageviewUrl(),this.track("pageview")}trackPageviewIfUrlChanged(){this.getPageviewUrl()!==this.lastPageviewUrl&&this.trackPageview()}getPageviewUrl(){let e=new URL(window.location.href);return JSON.stringify([e.hostname,P(e,this.config.trackUrlFragments),this.config.trackQuerystring?e.search:""])}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let n=this.config.featureFlags?.[e];if(!n||this.isUnassignedVariant(n))return t;let i=`${e}:${n.version}:${this.serializeFeatureFlagValue(n.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(n.value),version:n.version,reason:n.reason})),n.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>!this.isUnassignedVariant(e)).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let n=this.config.featureFlags?.[e];return!n||n.payload===void 0?t:n.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}trackOutbound(e,t="",n="_self"){let i={url:e,text:L(t,ht),target:n},s=JSON.stringify(i).length-gt;s>0&&(i.url=L(e,Math.max(0,e.length-s))),this.track("outbound","",i)}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let n={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,t={}){let n=e?.message||"";if(n.includes("ResizeObserver loop completed with undelivered notifications")||n.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let d=[e.name||"Error",n,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),g=6e4,y=this.errorDedupeCache.get(d);if(y&&u-y<g)return;this.errorDedupeCache.set(d,u);let R=10*6e4;if(u-this.errorDedupeLastCleanup>g){for(let[o,l]of this.errorDedupeCache.entries())u-l>R&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let h={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(h.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(h.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(h.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(h[o]=t[o]);this.track("error",e.name||"Error",h)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}identify(e,t){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0).then(()=>this.refreshFeatureFlags()),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let t=this.customUserId;if(!t){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(t,e,!1).then(()=>this.refreshFeatureFlags())}async sendIdentifyEvent(e,t,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(""),this.refreshFeatureFlags()}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Me=-1,F=r=>{addEventListener("pageshow",(e=>{e.persisted&&(Me=e.timeStamp,r(e))}),!0)},v=(r,e,t,n)=>{let i,s;return a=>{e.value>=0&&(a||n)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((c,d)=>c>d[1]?"poor":c>d[0]?"needs-improvement":"good")(e.value,t),r(e)))}},te=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},ne=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},B=()=>ne()?.activationStart??0,S=(r,e=-1)=>{let t=ne(),n="navigate";return Me>=0?n="back-forward-cache":t&&(document.prerendering||B()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},K=new WeakMap;function re(r,e){return K.get(r)||K.set(r,new e),K.get(r)}var J=class{constructor(){k(this,"t");k(this,"i",0);k(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},M=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:r,buffered:!0,...t}),n}}catch{}},ie=r=>{let e=!1;return()=>{e||(r(),e=!0)}},A=-1,xe=new Set,Ce=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,X=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of xe)e();isFinite(A)||(A=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",X,!0))}},D=()=>{if(A<0){let r=B();A=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??Ce(),addEventListener("visibilitychange",X,!0),addEventListener("prerenderingchange",X,!0),F((()=>{setTimeout((()=>{A=Ce()}))}))}return{get firstHiddenTime(){return A},onHidden(r){xe.add(r)}}},H=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},Ie=[1800,3e3],se=(r,e={})=>{H((()=>{let t=D(),n,i=S("FCP"),s=M("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-B(),0),i.entries.push(c),n(!0)))}));s&&(n=v(r,i,Ie,e.reportAllChanges),F((a=>{i=S("FCP"),n=v(r,i,Ie,e.reportAllChanges),te((()=>{i.value=performance.now()-a.timeStamp,n(!0)}))})))}))},_e=[.1,.25],Ne=(r,e={})=>{let t=D();se(ie((()=>{let n,i=S("CLS",0),s=re(e,J),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,n())},c=M("layout-shift",a);c&&(n=v(r,i,_e,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),F((()=>{s.i=0,i=S("CLS",0),n=v(r,i,_e,e.reportAllChanges),te((()=>n()))})),setTimeout(n))})))},Oe=0,q=1/0,U=0,yt=r=>{for(let e of r)e.interactionId&&(q=Math.min(q,e.interactionId),U=Math.max(U,e.interactionId),Oe=U?(U-q)/7+1:0)},Q,Pe=()=>Q?Oe:performance.interactionCount??0,bt=()=>{"interactionCount"in performance||Q||(Q=M("event",yt,{type:"event",buffered:!0,durationThreshold:0}))},Ae=0,Y=class{constructor(){k(this,"u",[]);k(this,"l",new Map);k(this,"m");k(this,"p")}v(){Ae=Pe(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Pe()-Ae)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>t.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(n)}}},Ue=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=ie(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},Fe=[200,500],De=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=D();H((()=>{bt();let n,i=S("INP"),s=re(e,Y),a=d=>{Ue((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,n())}))},c=M("event",a,{durationThreshold:e.durationThreshold??40});n=v(r,i,Fe,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),F((()=>{s.v(),i=S("INP"),n=v(r,i,Fe,e.reportAllChanges)})))}))},Z=class{constructor(){k(this,"m")}h(e){this.m?.(e)}},Le=[2500,4e3],He=(r,e={})=>{H((()=>{let t=D(),n,i=S("LCP"),s=re(e,Z),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-B(),0),i.entries=[u],n())},c=M("largest-contentful-paint",a);if(c){n=v(r,i,Le,e.reportAllChanges);let d=ie((()=>{a(c.takeRecords()),c.disconnect(),n(!0)})),u=g=>{g.isTrusted&&(Ue(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});F((g=>{i=S("LCP"),n=v(r,i,Le,e.reportAllChanges),te((()=>{i.value=performance.now()-g.timeStamp,n(!0)}))}))}}))},Be=[800,1800],ee=r=>{document.prerendering?H((()=>ee(r))):document.readyState!=="complete"?addEventListener("load",(()=>ee(r)),!0):setTimeout(r)},We=(r,e={})=>{let t=S("TTFB"),n=v(r,t,Be,e.reportAllChanges);ee((()=>{let i=ne();i&&(t.value=Math.max(i.responseStart-B(),0),t.entries=[i],n(!0),F((()=>{t=S("TTFB",0),n=v(r,t,Be,e.reportAllChanges),n(!0)})))}))};var vt=2e4,W=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{He(this.collectMetric.bind(this),{reportAllChanges:!0}),Ne(this.collectMetric.bind(this),{reportAllChanges:!0}),De(this.collectMetric.bind(this),{reportAllChanges:!0}),se(this.collectMetric.bind(this)),We(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>this.sendData(),vt),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.sendData()}),window.addEventListener("pagehide",()=>this.sendData())}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var St=1e3,V=class{constructor(e,t){this.lastClickAt=new WeakMap;this.tracker=e,this.config=t}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(e){let t=e.target;this.config.trackButtonClicks&&this.isButton(t)&&this.trackButtonClick(t)}isButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let t=e.parentElement,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,n++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let n=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&n-i<St)return;this.lastClickAt.set(t,n);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,n++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let n=e.getAttribute("aria-label")?.trim().substring(0,100);if(n)return n;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var G=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),n=t.length;if(n===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...n>500&&{textLength:n},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};function ae(r,e){return Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,e)?.get?.call(r)}var z=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(!(t instanceof HTMLFormElement))return;let n={formId:t.getAttribute("id")||"",formName:t.getAttribute("name")||"",formAction:ae(t,"action")||"",method:(ae(t,"method")||"get").toUpperCase(),fieldCount:ae(t,"elements")?.length??0,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(n)}handleChange(e){let t=e.target;if(!(t instanceof Element))return;let n=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(n)||t.disabled||t.readOnly)return;if(n==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:n.toLowerCase(),inputType:n==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.getAttribute("id")||void 0,formName:t.form?.getAttribute("name")||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}};function kt(r){if(window.__RYBBIT_OPTOUT__)return!0;try{return localStorage.getItem(r)!==null}catch{return!1}}(async function(){let r=document.currentScript||document.querySelector('script[src*="/script.js"]');if(!r){console.error("Could not find current script tag");return}let e=r.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(kt(t)){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,flag:(o,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=[],i=o=>(...l)=>{n.push([o,l])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,flag:(o,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await he(r);if(!s)return;let a=new O(s);s.enableWebVitals&&new W(l=>{a.trackWebVitals(l)}).initialize();let c=null,d=null,u=null;s.trackButtonClicks&&(c=new V(a,s),c.initialize()),s.trackCopy&&(d=new G(a),d.initialize()),s.trackFormInteractions&&(u=new z(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let l=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(l,{type:"unhandledrejection"})}));let g=()=>a.trackPageviewIfUrlChanged(),y=s.debounceDuration>0?pe(g,s.debounceDuration):g;function R(){if(document.addEventListener("click",function(o){let l=o.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let w={};for(let E of l.attributes)if(E.name.startsWith("data-rybbit-prop-")){let C=E.name.replace("data-rybbit-prop-","");w[C]=E.value}a.trackEvent(p,w)}break}l=l.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&ge(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,l=history.replaceState;history.pushState=function(...p){o.apply(this,p),y(),a.onPageChange()},history.replaceState=function(...p){l.apply(this,p),y(),a.onPageChange()},window.addEventListener("popstate",()=>{y(),a.onPageChange()}),window.addEventListener("hashchange",()=>{y(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,l={})=>a.trackEvent(o,l),error:(o,l={})=>a.trackError(o,l),trackOutbound:(o,l="",p="_self")=>a.trackOutbound(o,l,p),identify:(o,l)=>a.identify(o,l),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,l)=>a.getFeatureFlag(o,l),flagPayload:(o,l)=>a.getFeatureFlagPayload(o,l),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let h=window[s.namespace];for(let[o,l]of n)h[o](...l);R(),window.addEventListener("beforeunload",()=>{c?.cleanup(),d?.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();