🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add error deduplication and cleanup logic in Tracker class
Bill Yang2e054ac1af37
diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 31a15d825..0761cfce3 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -382,6 +382,8 @@var Tracker = class {constructor(config) {this.customUserId = null;+ this.errorDedupeCache = /* @__PURE__ */ new Map();+ this.errorDedupeLastCleanup = 0;this.config = config;this.loadUserId();if (config.enableSessionReplay) {@@ -511,6 +513,10 @@this.sendTrackingData(payload);}trackError(error, additionalInfo = {}) {+ const message = error?.message || "";+ if (message.includes("ResizeObserver loop completed with undelivered notifications") || message.includes("ResizeObserver loop limit exceeded")) {+ return;+ }const currentOrigin = window.location.origin;const filename = additionalInfo.filename || "";const errorStack = error.stack || "";@@ -527,6 +533,30 @@return;}}+ const dedupeKeyParts = [+ error.name || "Error",+ message,+ additionalInfo.filename || "",+ additionalInfo.lineno ?? "",+ additionalInfo.colno ?? ""+ ];+ const dedupeKey = dedupeKeyParts.join("|");+ const now = Date.now();+ const dedupeWindowMs = 6e4;+ const lastSeen = this.errorDedupeCache.get(dedupeKey);+ if (lastSeen && now - lastSeen < dedupeWindowMs) {+ return;+ }+ this.errorDedupeCache.set(dedupeKey, now);+ const pruneAfterMs = 10 * 6e4;+ if (now - this.errorDedupeLastCleanup > dedupeWindowMs) {+ for (const [key, ts] of this.errorDedupeCache.entries()) {+ if (now - ts > pruneAfterMs) {+ this.errorDedupeCache.delete(key);+ }+ }+ this.errorDedupeLastCleanup = now;+ }const errorProperties = {message: error.message?.substring(0, 500) || "Unknown error",// Truncate to 500 charsdiff --git a/server/public/script.js b/server/public/script.jsindex eb81dc83b..ba7bfcfaa 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var Mt=Object.defineProperty;var At=(n,t,e)=>t in n?Mt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var b=(n,t,e)=>At(n,typeof t!="symbol"?t+"":t,e);function Lt(n){if(n.startsWith("re:")){let a=n.slice(3);if(!a)throw new Error("Empty regex pattern");return new RegExp(a)}let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(e,"g"),".*"),s=s.replace(/\//g,"\\/");let o=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+o+"$")}function U(n,t){for(let e of t)try{if(Lt(e).test(n))return e}catch(r){console.error(`Invalid pattern: ${e}`,r)}return null}function nt(n,t){let e=null;return(...r)=>{e&&clearTimeout(e),e=setTimeout(()=>n(...r),t)}}function it(n){try{let t=window.location.hostname,e=new URL(n).hostname;return e!==t&&e!==""}catch{return!1}}function v(n,t){if(!n)return t;try{let e=JSON.parse(n);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}async function st(n){let t=n.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=v(n.getAttribute("data-skip-patterns"),[]),o=v(n.getAttribute("data-mask-patterns"),[]),a=v(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,u=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,g=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,c=n.getAttribute("data-replay-block-class")||void 0,l=n.getAttribute("data-replay-block-selector")||void 0,p=n.getAttribute("data-replay-ignore-class")||void 0,C=n.getAttribute("data-replay-ignore-selector")||void 0,T=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),St=w!==null?w!=="false":void 0,Q=n.getAttribute("data-replay-mask-input-options"),Et=Q?v(Q,{password:!0,email:!0}):void 0,Y=n.getAttribute("data-replay-collect-fonts"),Ct=Y!==null?Y!=="false":void 0,Z=n.getAttribute("data-replay-sampling"),wt=Z?v(Z,{}):void 0,tt=n.getAttribute("data-replay-slim-dom-options"),Pt=tt?v(tt,{}):void 0,et=n.getAttribute("data-replay-sample-rate"),It=et?Math.min(100,Math.max(0,parseInt(et,10))):void 0,h={namespace:i,analyticsHost:e,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:g,sessionReplayMaskTextSelectors:a,skipPatterns:s,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,sessionReplayBlockClass:c,sessionReplayBlockSelector:l,sessionReplayIgnoreClass:p,sessionReplayIgnoreSelector:C,sessionReplayMaskTextClass:T,sessionReplayMaskAllInputs:St,sessionReplayMaskInputOptions:Et,sessionReplayCollectFonts:Ct,sessionReplaySampling:wt,sessionReplaySlimDOMOptions:Pt,sessionReplaySampleRate:It};try{let N=`${e}/site/tracking-config/${r}`,rt=await fetch(N,{method:"GET",credentials:"omit"});if(rt.ok){let m=await rt.json();return{...h,autoTrackPageview:m.trackInitialPageView??h.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??h.autoTrackSpa,trackQuerystring:m.trackUrlParams??h.trackQuerystring,trackOutbound:m.trackOutbound??h.trackOutbound,enableWebVitals:m.webVitals??h.enableWebVitals,trackErrors:m.trackErrors??h.trackErrors,enableSessionReplay:m.sessionReplay??h.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??h.trackButtonClicks,trackCopy:m.trackCopy??h.trackCopy,trackFormInteractions:m.trackFormInteractions??h.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),h}catch(N){return console.warn("Error fetching tracking config:",N),h}}var at="rybbit-replay-sampled";function Bt(n){if(n>=100)return!0;if(n<=0)return!1;try{let t=sessionStorage.getItem(at);if(t!==null)return t==="1";let e=Math.random()*100<n;return sessionStorage.setItem(at,e?"1":"0"),e}catch{return Math.random()*100<n}}var P=class{constructor(t,e,r){this.isRecording=!1;this.eventBuffer=[];this.config=t,this.userId=e,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let t=this.config.sessionReplaySampleRate;t!==void 0&&!Bt(t)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((t,e)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{t()},r.onerror=()=>e(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let t={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},e={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},r={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??t,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??e};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(t){this.eventBuffer.push(t),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let t=[...this.eventBuffer];this.eventBuffer=[];let e={userId:this.userId,events:t,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(e)}catch{this.eventBuffer.unshift(...t)}}updateUserId(t){this.userId=t}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var I=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId(),t.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let t=localStorage.getItem(`${this.config.namespace}-user-id`);t&&(this.customUserId=t)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new P(this.config,this.customUserId||"",t=>this.sendSessionReplayBatch(t)),await this.sessionReplayRecorder.initialize()}catch(t){console.error("Failed to initialize session replay:",t)}}async sendSessionReplayBatch(t){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!1})}catch(e){throw console.error("Failed to send session replay batch:",e),e}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),U(e,this.config.skipPatterns))return null;let r=U(e,this.config.maskPatterns);r&&(e=r);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",r={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let o={...i,type:t,event_name:e,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(t)?JSON.stringify(r):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",r="_self"){this.track("outbound","",{url:t,text:e,target:r})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let r={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(r)}trackError(t,e={}){let r=window.location.origin,i=e.filename||"",s=t.stack||"";if(i)try{if(new URL(i).origin!==r)return}catch{}else if(s&&!s.includes(r))return;let o={message:t.message?.substring(0,500)||"Unknown error",stack:s.substring(0,2e3)||""};if(i&&(o.fileName=i),e.lineno){let a=typeof e.lineno=="string"?parseInt(e.lineno,10):e.lineno;a&&a!==0&&(o.lineNumber=a)}if(e.colno){let a=typeof e.colno=="string"?parseInt(e.colno,10):e.colno;a&&a!==0&&(o.columnNumber=a)}for(let a in e)!["lineno","colno"].includes(a)&&e[a]!==void 0&&(o[a]=e[a]);this.track("error",t.name||"Error",o)}trackButtonClick(t){this.track("button_click","",t)}trackCopy(t){this.track("copy","",t)}trackFormSubmit(t){this.track("form_submit","",t)}trackInputChange(t){this.track("input_change","",t)}identify(t,e){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.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,e,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(t){if(!t||typeof t!="object"){console.error("Traits must be an object");return}let e=this.customUserId;if(!e){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(e,t,!1)}async sendIdentifyEvent(t,e,r=!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:t,traits:e,is_new_identify:r}),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{}}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.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var mt=-1,R=n=>{addEventListener("pageshow",(t=>{t.persisted&&(mt=t.timeStamp,n(t))}),!0)},f=(n,t,e,r)=>{let i,s;return o=>{t.value>=0&&(o||r)&&(s=t.value-(i??0),(s||i===void 0)&&(i=t.value,t.delta=s,t.rating=((a,d)=>a>d[1]?"poor":a>d[0]?"needs-improvement":"good")(t.value,e),n(t)))}},J=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},K=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},S=()=>K()?.activationStart??0,y=(n,t=-1)=>{let e=K(),r="navigate";return mt>=0?r="back-forward-cache":e&&(document.prerendering||S()>0?r="prerender":document.wasDiscarded?r="restore":e.type&&(r=e.type.replace(/_/g,"-"))),{name:n,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},D=new WeakMap;function q(n,t){return D.get(n)||D.set(n,new t),D.get(n)}var H=class{constructor(){b(this,"t");b(this,"i",0);b(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],r=this.o.at(-1);this.i&&e&&r&&t.startTime-r.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},E=(n,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{t(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...e}),r}}catch{}},G=n=>{let t=!1;return()=>{t||(n(),t=!0)}},k=-1,ft=new Set,ot=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let t of ft)t();isFinite(k)||(k=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},A=()=>{if(k<0){let n=S();k=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((e=>e.name==="hidden"&&e.startTime>n))[0]?.startTime)??ot(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),R((()=>{setTimeout((()=>{k=ot()}))}))}return{get firstHiddenTime(){return k},onHidden(n){ft.add(n)}}},L=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ct=[1800,3e3],X=(n,t={})=>{L((()=>{let e=A(),r,i=y("FCP"),s=E("paint",(o=>{for(let a of o)a.name==="first-contentful-paint"&&(s.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-S(),0),i.entries.push(a),r(!0)))}));s&&(r=f(n,i,ct,t.reportAllChanges),R((o=>{i=y("FCP"),r=f(n,i,ct,t.reportAllChanges),J((()=>{i.value=performance.now()-o.timeStamp,r(!0)}))})))}))},lt=[.1,.25],yt=(n,t={})=>{let e=A();X(G((()=>{let r,i=y("CLS",0),s=q(t,H),o=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},a=E("layout-shift",o);a&&(r=f(n,i,lt,t.reportAllChanges),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.i=0,i=y("CLS",0),r=f(n,i,lt,t.reportAllChanges),J((()=>r()))})),setTimeout(r))})))},bt=0,F=1/0,M=0,xt=n=>{for(let t of n)t.interactionId&&(F=Math.min(F,t.interactionId),M=Math.max(M,t.interactionId),bt=M?(M-F)/7+1:0)},z,ut=()=>z?bt:performance.interactionCount??0,Ot=()=>{"interactionCount"in performance||z||(z=E("event",xt,{type:"event",buffered:!0,durationThreshold:0}))},dt=0,V=class{constructor(){b(this,"u",[]);b(this,"l",new Map);b(this,"m");b(this,"p")}v(){dt=ut(),this.u.length=0,this.l.clear()}L(){let t=Math.min(this.u.length-1,Math.floor((ut()-dt)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),r=this.l.get(t.interactionId);if(r||this.u.length<10||t.duration>e.P){if(r?t.duration>r.P?(r.entries=[t],r.P=t.duration):t.duration===r.P&&t.startTime===r.entries[0].startTime&&r.entries.push(t):(r={id:t.interactionId,entries:[t],P:t.duration},this.l.set(r.id,r),this.u.push(r)),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?.(r)}}},vt=n=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=G(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),t((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},pt=[200,500],kt=(n,t={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let e=A();L((()=>{Ot();let r,i=y("INP"),s=q(t,V),o=d=>{vt((()=>{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,r())}))},a=E("event",o,{durationThreshold:t.durationThreshold??40});r=f(n,i,pt,t.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),e.onHidden((()=>{o(a.takeRecords()),r(!0)})),R((()=>{s.v(),i=y("INP"),r=f(n,i,pt,t.reportAllChanges)})))}))},$=class{constructor(){b(this,"m")}h(t){this.m?.(t)}},ht=[2500,4e3],Rt=(n,t={})=>{L((()=>{let e=A(),r,i=y("LCP"),s=q(t,$),o=d=>{t.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<e.firstHiddenTime&&(i.value=Math.max(u.startTime-S(),0),i.entries=[u],r())},a=E("largest-contentful-paint",o);if(a){r=f(n,i,ht,t.reportAllChanges);let d=G((()=>{o(a.takeRecords()),a.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(vt(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});R((g=>{i=y("LCP"),r=f(n,i,ht,t.reportAllChanges),J((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},gt=[800,1800],j=n=>{document.prerendering?L((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Tt=(n,t={})=>{let e=y("TTFB"),r=f(n,e,gt,t.reportAllChanges);j((()=>{let i=K();i&&(e.value=Math.max(i.responseStart-S(),0),e.entries=[i],r(!0),R((()=>{e=y("TTFB",0),r=f(n,e,gt,t.reportAllChanges),r(!0)})))}))};var B=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{Rt(this.collectMetric.bind(this)),yt(this.collectMetric.bind(this)),kt(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),Tt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}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 x=class{constructor(t,e){this.tracker=t,this.config=e}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(t){let e=t.target;this.config.trackButtonClicks&&this.isButton(e)&&this.trackButtonClick(e)}isButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;e=e.parentElement,r++}return!1}trackButtonClick(t){let e=this.findButton(t);if(!e||e.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(e),...this.extractDataAttributes(e)};this.tracker.trackButtonClick(r)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}findButton(t){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;if(t.tagName==="INPUT"){let i=t.type?.toLowerCase();if(i==="submit"||i==="button")return t}let e=t.parentElement,r=0;for(;e&&r<3;){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;e=e.parentElement,r++}return null}getElementText(t){return t.textContent?.trim().substring(0,100)||void 0}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var O=class{constructor(t){this.tracker=t}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let t=window.getSelection();if(!t||t.isCollapsed)return;let e=t.toString(),r=e.length;if(r===0)return;let i=t.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let o={text:e.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(o)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var _=class{constructor(t,e){this.tracker=t,this.config=e,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(t){let e=t.target;if(e.tagName!=="FORM")return;let r={formId:e.id||"",formName:e.name||"",formAction:e.action||"",method:(e.method||"get").toUpperCase(),fieldCount:e.elements.length,...this.extractDataAttributes(e)};this.tracker.trackFormSubmit(r)}handleChange(t){let e=t.target,r=e.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r))return;if(r==="INPUT"){let s=e.type?.toLowerCase();if(s==="hidden"||s==="password")return}let i={element:r.toLowerCase(),inputType:r==="INPUT"?e.type?.toLowerCase():void 0,inputName:e.name||e.id||"",formId:e.form?.id||void 0,...this.extractDataAttributes(e)};this.tracker.trackInputChange(i)}extractDataAttributes(t){let e={};for(let r of t.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");e[i]=r.value}return e}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let t=n.getAttribute("data-namespace")||"rybbit",e=`disable-${t}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(e)!==null){window[t]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=await st(n);if(!r)return;let i=new I(r);r.enableWebVitals&&new B(l=>{i.trackWebVitals(l)}).initialize();let s=null,o=null,a=null;r.trackButtonClicks&&(s=new x(i,r),s.initialize()),r.trackCopy&&(o=new O(i),o.initialize()),r.trackFormInteractions&&(a=new _(i,r),a.initialize()),r.trackErrors&&(window.addEventListener("error",c=>{i.trackError(c.error||new Error(c.message),{filename:c.filename,lineno:c.lineno,colno:c.colno})}),window.addEventListener("unhandledrejection",c=>{let l=c.reason instanceof Error?c.reason:new Error(String(c.reason));i.trackError(l,{type:"unhandledrejection"})}));let d=()=>i.trackPageview(),u=r.debounceDuration>0?nt(d,r.debounceDuration):d;function g(){if(document.addEventListener("click",function(c){let l=c.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let C={};for(let T of l.attributes)if(T.name.startsWith("data-rybbit-prop-")){let w=T.name.replace("data-rybbit-prop-","");C[w]=T.value}i.trackEvent(p,C)}break}l=l.parentElement}if(r.trackOutbound){let p=c.target.closest("a");p?.href&&it(p.href)&&i.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),r.autoTrackSpa){let c=history.pushState,l=history.replaceState;history.pushState=function(...p){c.apply(this,p),u(),i.onPageChange()},history.replaceState=function(...p){l.apply(this,p),u(),i.onPageChange()},window.addEventListener("popstate",()=>{u(),i.onPageChange()}),window.addEventListener("hashchange",()=>{u(),i.onPageChange()})}}window[r.namespace]={pageview:()=>i.trackPageview(),event:(c,l={})=>i.trackEvent(c,l),error:(c,l={})=>i.trackError(c,l),trackOutbound:(c,l="",p="_self")=>i.trackOutbound(c,l,p),identify:(c,l)=>i.identify(c,l),setTraits:c=>i.setTraits(c),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},g(),window.addEventListener("beforeunload",()=>{s?.cleanup(),o?.cleanup(),i.cleanup()}),r.autoTrackPageview&&i.trackPageview()})();})();+"use strict";(()=>{var Me=Object.defineProperty;var Ae=(n,e,t)=>e in n?Me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var v=(n,e,t)=>Ae(n,typeof e!="symbol"?e+"":e,t);function Le(n){if(n.startsWith("re:")){let c=n.slice(3);if(!c)throw new Error("Empty regex pattern");return new RegExp(c)}let t="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,t).replace(/\*/g,r).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(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function N(n,e){for(let t of e)try{if(Le(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ne(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function ie(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function R(n,e){if(!n)return e;try{let t=JSON.parse(n);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}async function se(n){let e=n.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 r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=R(n.getAttribute("data-skip-patterns"),[]),a=R(n.getAttribute("data-mask-patterns"),[]),c=R(n.getAttribute("data-replay-mask-text-selectors"),[]),h=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,l=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,g=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,o=n.getAttribute("data-replay-block-class")||void 0,u=n.getAttribute("data-replay-block-selector")||void 0,d=n.getAttribute("data-replay-ignore-class")||void 0,p=n.getAttribute("data-replay-ignore-selector")||void 0,k=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),Te=w!==null?w!=="false":void 0,Q=n.getAttribute("data-replay-mask-input-options"),Se=Q?R(Q,{password:!0,email:!0}):void 0,Y=n.getAttribute("data-replay-collect-fonts"),Ee=Y!==null?Y!=="false":void 0,Z=n.getAttribute("data-replay-sampling"),we=Z?R(Z,{}):void 0,ee=n.getAttribute("data-replay-slim-dom-options"),Pe=ee?R(ee,{}):void 0,te=n.getAttribute("data-replay-sample-rate"),Ie=te?Math.min(100,Math.max(0,parseInt(te,10))):void 0,m={namespace:i,analyticsHost:t,siteId:r,debounceDuration:h,sessionReplayBatchSize:l,sessionReplayBatchInterval:g,sessionReplayMaskTextSelectors:c,skipPatterns:s,maskPatterns:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,sessionReplayBlockClass:o,sessionReplayBlockSelector:u,sessionReplayIgnoreClass:d,sessionReplayIgnoreSelector:p,sessionReplayMaskTextClass:k,sessionReplayMaskAllInputs:Te,sessionReplayMaskInputOptions:Se,sessionReplayCollectFonts:Ee,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Pe,sessionReplaySampleRate:Ie};try{let _=`${t}/site/tracking-config/${r}`,re=await fetch(_,{method:"GET",credentials:"omit"});if(re.ok){let f=await re.json();return{...m,autoTrackPageview:f.trackInitialPageView??m.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??m.autoTrackSpa,trackQuerystring:f.trackUrlParams??m.trackQuerystring,trackOutbound:f.trackOutbound??m.trackOutbound,enableWebVitals:f.webVitals??m.enableWebVitals,trackErrors:f.trackErrors??m.trackErrors,enableSessionReplay:f.sessionReplay??m.enableSessionReplay,trackButtonClicks:f.trackButtonClicks??m.trackButtonClicks,trackCopy:f.trackCopy??m.trackCopy,trackFormInteractions:f.trackFormInteractions??m.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),m}catch(_){return console.warn("Error fetching tracking config:",_),m}}var ae="rybbit-replay-sampled";function Be(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(ae);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(ae,t?"1":"0"),t}catch{return Math.random()*100<n}}var P=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Be(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{e()},r.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(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},r={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&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.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.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var I=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new P(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){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),N(t,this.config.skipPatterns))return null;let r=N(t,this.config.maskPatterns);r&&(t=r);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:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),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="",r={}){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(r):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",r="_self"){this.track("outbound","",{url:e,text:t,target:r})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let r={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(r)}trackError(e,t={}){let r=e?.message||"";if(r.includes("ResizeObserver loop completed with undelivered notifications")||r.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 h=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),l=Date.now(),g=6e4,o=this.errorDedupeCache.get(h);if(o&&l-o<g)return;this.errorDedupeCache.set(h,l);let u=10*6e4;if(l-this.errorDedupeLastCleanup>g){for(let[p,k]of this.errorDedupeCache.entries())l-k>u&&this.errorDedupeCache.delete(p);this.errorDedupeLastCleanup=l}let d={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(d.fileName=s),t.lineno){let p=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;p&&p!==0&&(d.lineNumber=p)}if(t.colno){let p=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;p&&p!==0&&(d.columnNumber=p)}for(let p in t)!["lineno","colno"].includes(p)&&t[p]!==void 0&&(d[p]=t[p]);this.track("error",e.name||"Error",d)}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),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)}async sendIdentifyEvent(e,t,r=!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:r}),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{}}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.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var me=-1,T=n=>{addEventListener("pageshow",(e=>{e.persisted&&(me=e.timeStamp,n(e))}),!0)},y=(n,e,t,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((c,h)=>c>h[1]?"poor":c>h[0]?"needs-improvement":"good")(e.value,t),n(e)))}},K=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},J=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},S=()=>J()?.activationStart??0,b=(n,e=-1)=>{let t=J(),r="navigate";return me>=0?r="back-forward-cache":t&&(document.prerendering||S()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:n,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},U=new WeakMap;function q(n,e){return U.get(n)||U.set(n,new e),U.get(n)}var H=class{constructor(){v(this,"t");v(this,"i",0);v(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.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)}},E=(n,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...t}),r}}catch{}},G=n=>{let e=!1;return()=>{e||(n(),e=!0)}},C=-1,fe=new Set,oe=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,W=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of fe)e();isFinite(C)||(C=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},A=()=>{if(C<0){let n=S();C=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??oe(),addEventListener("visibilitychange",W,!0),addEventListener("prerenderingchange",W,!0),T((()=>{setTimeout((()=>{C=oe()}))}))}return{get firstHiddenTime(){return C},onHidden(n){fe.add(n)}}},L=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ce=[1800,3e3],X=(n,e={})=>{L((()=>{let t=A(),r,i=b("FCP"),s=E("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-S(),0),i.entries.push(c),r(!0)))}));s&&(r=y(n,i,ce,e.reportAllChanges),T((a=>{i=b("FCP"),r=y(n,i,ce,e.reportAllChanges),K((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},le=[.1,.25],ye=(n,e={})=>{let t=A();X(G((()=>{let r,i=b("CLS",0),s=q(e,H),a=h=>{for(let l of h)s.h(l);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},c=E("layout-shift",a);c&&(r=y(n,i,le,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),r(!0)})),T((()=>{s.i=0,i=b("CLS",0),r=y(n,i,le,e.reportAllChanges),K((()=>r()))})),setTimeout(r))})))},be=0,F=1/0,M=0,xe=n=>{for(let e of n)e.interactionId&&(F=Math.min(F,e.interactionId),M=Math.max(M,e.interactionId),be=M?(M-F)/7+1:0)},z,ue=()=>z?be:performance.interactionCount??0,Oe=()=>{"interactionCount"in performance||z||(z=E("event",xe,{type:"event",buffered:!0,durationThreshold:0}))},de=0,V=class{constructor(){v(this,"u",[]);v(this,"l",new Map);v(this,"m");v(this,"p")}v(){de=ue(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((ue()-de)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),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?.(r)}}},ve=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=G(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},pe=[200,500],ke=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=A();L((()=>{Oe();let r,i=b("INP"),s=q(e,V),a=h=>{ve((()=>{for(let g of h)s.h(g);let l=s.L();l&&l.P!==i.value&&(i.value=l.P,i.entries=l.entries,r())}))},c=E("event",a,{durationThreshold:e.durationThreshold??40});r=y(n,i,pe,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(c.takeRecords()),r(!0)})),T((()=>{s.v(),i=b("INP"),r=y(n,i,pe,e.reportAllChanges)})))}))},$=class{constructor(){v(this,"m")}h(e){this.m?.(e)}},he=[2500,4e3],Re=(n,e={})=>{L((()=>{let t=A(),r,i=b("LCP"),s=q(e,$),a=h=>{e.reportAllChanges||(h=h.slice(-1));for(let l of h)s.h(l),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-S(),0),i.entries=[l],r())},c=E("largest-contentful-paint",a);if(c){r=y(n,i,he,e.reportAllChanges);let h=G((()=>{a(c.takeRecords()),c.disconnect(),r(!0)})),l=g=>{g.isTrusted&&(ve(h),removeEventListener(g.type,l,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,l,{capture:!0});T((g=>{i=b("LCP"),r=y(n,i,he,e.reportAllChanges),K((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},ge=[800,1800],j=n=>{document.prerendering?L((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Ce=(n,e={})=>{let t=b("TTFB"),r=y(n,t,ge,e.reportAllChanges);j((()=>{let i=J();i&&(t.value=Math.max(i.responseStart-S(),0),t.entries=[i],r(!0),T((()=>{t=b("TTFB",0),r=y(n,t,ge,e.reportAllChanges),r(!0)})))}))};var B=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{Re(this.collectMetric.bind(this)),ye(this.collectMetric.bind(this)),ke(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),Ce(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||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,Object.values(this.data).every(i=>i!==null)&&this.sendData()}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 x=class{constructor(e,t){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,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,r++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(r)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.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,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,r++}return null}getElementText(e){return e.textContent?.trim().substring(0,100)||void 0}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var O=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(),r=t.length;if(r===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var D=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.tagName!=="FORM")return;let r={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(r)}handleChange(e){let t=e.target,r=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r))return;if(r==="INPUT"){let s=t.type?.toLowerCase();if(s==="hidden"||s==="password")return}let i={element:r.toLowerCase(),inputType:r==="INPUT"?t.type?.toLowerCase():void 0,inputName:t.name||t.id||"",formId:t.form?.id||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(i)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let e=n.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=await se(n);if(!r)return;let i=new I(r);r.enableWebVitals&&new B(u=>{i.trackWebVitals(u)}).initialize();let s=null,a=null,c=null;r.trackButtonClicks&&(s=new x(i,r),s.initialize()),r.trackCopy&&(a=new O(i),a.initialize()),r.trackFormInteractions&&(c=new D(i,r),c.initialize()),r.trackErrors&&(window.addEventListener("error",o=>{i.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let u=o.reason instanceof Error?o.reason:new Error(String(o.reason));i.trackError(u,{type:"unhandledrejection"})}));let h=()=>i.trackPageview(),l=r.debounceDuration>0?ne(h,r.debounceDuration):h;function g(){if(document.addEventListener("click",function(o){let u=o.target;for(;u&&u!==document.documentElement;){if(u.hasAttribute("data-rybbit-event")){let d=u.getAttribute("data-rybbit-event");if(d){let p={};for(let k of u.attributes)if(k.name.startsWith("data-rybbit-prop-")){let w=k.name.replace("data-rybbit-prop-","");p[w]=k.value}i.trackEvent(d,p)}break}u=u.parentElement}if(r.trackOutbound){let d=o.target.closest("a");d?.href&&ie(d.href)&&i.trackOutbound(d.href,d.innerText||d.textContent||"",d.target||"_self")}}),r.autoTrackSpa){let o=history.pushState,u=history.replaceState;history.pushState=function(...d){o.apply(this,d),l(),i.onPageChange()},history.replaceState=function(...d){u.apply(this,d),l(),i.onPageChange()},window.addEventListener("popstate",()=>{l(),i.onPageChange()}),window.addEventListener("hashchange",()=>{l(),i.onPageChange()})}}window[r.namespace]={pageview:()=>i.trackPageview(),event:(o,u={})=>i.trackEvent(o,u),error:(o,u={})=>i.trackError(o,u),trackOutbound:(o,u="",d="_self")=>i.trackOutbound(o,u,d),identify:(o,u)=>i.identify(o,u),setTraits:o=>i.setTraits(o),clearUserId:()=>i.clearUserId(),getUserId:()=>i.getUserId(),startSessionReplay:()=>i.startSessionReplay(),stopSessionReplay:()=>i.stopSessionReplay(),isSessionReplayActive:()=>i.isSessionReplayActive()},g(),window.addEventListener("beforeunload",()=>{s?.cleanup(),a?.cleanup(),i.cleanup()}),r.autoTrackPageview&&i.trackPageview()})();})();diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex 47f7c7616..7a3575903 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -6,6 +6,8 @@ export class Tracker {private config: ScriptConfig;private customUserId: string | null = null;private sessionReplayRecorder?: SessionReplayRecorder;+ private errorDedupeCache: Map<string, number> = new Map();+ private errorDedupeLastCleanup = 0;constructor(config: ScriptConfig) {this.config = config;@@ -163,6 +165,15 @@ export class Tracker {}trackError(error: Error, additionalInfo: Record<string, any> = {}): void {+ // Ignore known noisy browser warnings that aren't actionable app errors.+ const message = error?.message || "";+ if (+ message.includes("ResizeObserver loop completed with undelivered notifications") ||+ message.includes("ResizeObserver loop limit exceeded")+ ) {+ return;+ }+// Industry-standard filtering: Only track errors from the same origin to avoid noise from third-party scriptsconst currentOrigin = window.location.origin;const filename = additionalInfo.filename || "";@@ -192,6 +203,34 @@ export class Tracker {// If neither filename nor stack can determine origin, track the error// This covers cases like NetworkError where the source is unclear but could be first-party+ // Dedupe identical errors within a short window to prevent spam.+ const dedupeKeyParts = [+ error.name || "Error",+ message,+ additionalInfo.filename || "",+ additionalInfo.lineno ?? "",+ additionalInfo.colno ?? "",+ ];+ const dedupeKey = dedupeKeyParts.join("|");+ const now = Date.now();+ const dedupeWindowMs = 60_000;+ const lastSeen = this.errorDedupeCache.get(dedupeKey);+ if (lastSeen && now - lastSeen < dedupeWindowMs) {+ return;+ }+ this.errorDedupeCache.set(dedupeKey, now);++ // Periodically prune old keys to avoid unbounded growth.+ const pruneAfterMs = 10 * 60_000;+ if (now - this.errorDedupeLastCleanup > dedupeWindowMs) {+ for (const [key, ts] of this.errorDedupeCache.entries()) {+ if (now - ts > pruneAfterMs) {+ this.errorDedupeCache.delete(key);+ }+ }+ this.errorDedupeLastCleanup = now;+ }+const errorProperties: Record<string, any> = {message: error.message?.substring(0, 500) || "Unknown error", // Truncate to 500 charsstack: errorStack.substring(0, 2000) || "", // Truncate to 2000 chars