Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Enhance form and input tracking by adding support for formName and ariaLabel properties. Updated event display logic to include formName in submissions. Improved element text retrieval to prioritize aria-label and title attributes, ensuring better accessibility tracking. Updated documentation to reflect these changes.

Bill Yang042f2893935c
diff --git a/client/src/lib/events.ts b/client/src/lib/events.ts
index 1bc4e90de..3badab472 100644
--- a/client/src/lib/events.ts
+++ b/client/src/lib/events.ts
@@ -57,6 +57,7 @@ export function getEventDisplayName(item: EventLike): string {
}
case "form_submit":
if (item.props?.formId) return `Submitted form "${item.props.formId}"`;
+ if (item.props?.formName) return `Submitted form "${item.props.formName}"`;
if (item.props?.formAction) return `Submitted form to "${item.props.formAction}"`;
return "Submitted form";
case "input_change": {
@@ -73,6 +74,6 @@ export function getEventDisplayName(item: EventLike): string {
export const PROPS_TO_HIDE: Record<string, string[]> = {
button_click: ["text"],
copy: ["text"],
- form_submit: ["formId", "formAction"],
+ form_submit: ["formId", "formName", "formAction"],
input_change: ["inputName", "inputType", "element"],
};
diff --git a/docs/content/docs/autocapture.mdx b/docs/content/docs/autocapture.mdx
index 838704a37..ce5088820 100644
--- a/docs/content/docs/autocapture.mdx
+++ b/docs/content/docs/autocapture.mdx
@@ -43,7 +43,7 @@ Automatically tracks clicks on:
- `<input type="submit">` and `<input type="button">`
**Tracked properties:**
-- `text` - The button's text content
+- `text` - The button's text content (falls back to `aria-label`, then `value` for input buttons, then `title`)
### Adding Custom Properties
@@ -96,6 +96,7 @@ Triggered when a form is submitted.
- `formAction` - The form's `action` URL
- `method` - HTTP method (GET, POST, etc.)
- `fieldCount` - Number of form fields
+- `ariaLabel` - The form's `aria-label` attribute (if present)
You can add custom properties using `data-rybbit-prop-*` on the form element:
@@ -111,13 +112,14 @@ You can add custom properties using `data-rybbit-prop-*` on the form element:
### Input Changes (`input_change`)
-Triggered when a user changes the value of an input, select, or textarea field.
+Triggered when a user changes the value of an input, select, or textarea field. Disabled inputs are automatically excluded from tracking.
**Tracked properties:**
- `element` - The element type (`input`, `select`, or `textarea`)
- `inputType` - For inputs: the type attribute (e.g., `text`, `email`, `checkbox`)
-- `inputName` - The field's `name` or `id` attribute
+- `inputName` - The field's `name`, `id`, `aria-label`, or `placeholder` attribute (first available)
- `formId` - The parent form's `id` (if within a form)
+- `formName` - The parent form's `name` (if within a form)
You can add custom properties using `data-rybbit-prop-*` on the input element:
@@ -135,7 +137,7 @@ You can add custom properties using `data-rybbit-prop-*` on the input element:
</select>
```
-**Privacy note:** Hidden inputs and password fields are automatically excluded from tracking.
+**Privacy note:** Hidden inputs, password fields, and disabled inputs are automatically excluded from tracking.
## Enabling Autocapture
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 0761cfce3..9c8abe13f 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -1053,7 +1053,16 @@
}
getElementText(element) {
const text = element.textContent?.trim().substring(0, 100);
- return text || void 0;
+ if (text) return text;
+ const ariaLabel = element.getAttribute("aria-label")?.trim().substring(0, 100);
+ if (ariaLabel) return ariaLabel;
+ if (element.tagName === "INPUT") {
+ const value = element.value?.trim().substring(0, 100);
+ if (value) return value;
+ }
+ const title = element.getAttribute("title")?.trim().substring(0, 100);
+ if (title) return title;
+ return void 0;
}
cleanup() {
document.removeEventListener("click", this.handleClick.bind(this), true);
@@ -1114,6 +1123,7 @@
formAction: form.action || "",
method: (form.method || "get").toUpperCase(),
fieldCount: form.elements.length,
+ ariaLabel: form.getAttribute("aria-label") || void 0,
...this.extractDataAttributes(form)
};
this.tracker.trackFormSubmit(properties);
@@ -1122,15 +1132,18 @@
const target = event.target;
const tagName = target.tagName.toUpperCase();
if (!["INPUT", "SELECT", "TEXTAREA"].includes(tagName)) return;
+ if (target.disabled) return;
if (tagName === "INPUT") {
const inputType = target.type?.toLowerCase();
if (inputType === "hidden" || inputType === "password") return;
}
+ const inputName = target.name || target.id || target.getAttribute("aria-label") || target.placeholder || "";
const properties = {
element: tagName.toLowerCase(),
inputType: tagName === "INPUT" ? target.type?.toLowerCase() : void 0,
- inputName: target.name || target.id || "",
+ inputName,
formId: target.form?.id || void 0,
+ formName: target.form?.name || void 0,
...this.extractDataAttributes(target)
};
this.tracker.trackInputChange(properties);
diff --git a/server/public/script.js b/server/public/script.js
index ba7bfcfaa..aabaf0b8e 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"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()})();})();
+"use strict";(()=>{var Me=Object.defineProperty;var Le=(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)=>Le(n,typeof e!="symbol"?e+"":e,t);function Ae(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(Ae(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"),Ee=w!==null?w!=="false":void 0,Q=n.getAttribute("data-replay-mask-input-options"),Ce=Q?R(Q,{password:!0,email:!0}):void 0,Y=n.getAttribute("data-replay-collect-fonts"),Se=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:Ee,sessionReplayMaskInputOptions:Ce,sessionReplayCollectFonts:Se,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,E=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},C=()=>J()?.activationStart??0,b=(n,e=-1)=>{let t=J(),r="navigate";return me>=0?r="back-forward-cache":t&&(document.prerendering||C()>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}},H=new WeakMap;function q(n,e){return H.get(n)||H.set(n,new e),H.get(n)}var F=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)}},S=(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)}},T=-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(T)||(T=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",W,!0))}},L=()=>{if(T<0){let n=C();T=(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),E((()=>{setTimeout((()=>{T=oe()}))}))}return{get firstHiddenTime(){return T},onHidden(n){fe.add(n)}}},A=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ce=[1800,3e3],X=(n,e={})=>{A((()=>{let t=L(),r,i=b("FCP"),s=S("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-C(),0),i.entries.push(c),r(!0)))}));s&&(r=y(n,i,ce,e.reportAllChanges),E((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=L();X(G((()=>{let r,i=b("CLS",0),s=q(e,F),a=h=>{for(let l of h)s.h(l);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},c=S("layout-shift",a);c&&(r=y(n,i,le,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),r(!0)})),E((()=>{s.i=0,i=b("CLS",0),r=y(n,i,le,e.reportAllChanges),K((()=>r()))})),setTimeout(r))})))},be=0,U=1/0,M=0,xe=n=>{for(let e of n)e.interactionId&&(U=Math.min(U,e.interactionId),M=Math.max(M,e.interactionId),be=M?(M-U)/7+1:0)},z,ue=()=>z?be:performance.interactionCount??0,Oe=()=>{"interactionCount"in performance||z||(z=S("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=L();A((()=>{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=S("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)})),E((()=>{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={})=>{A((()=>{let t=L(),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-C(),0),i.entries=[l],r())},c=S("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});E((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?A((()=>j(n))):document.readyState!=="complete"?addEventListener("load",(()=>j(n)),!0):setTimeout(n)},Te=(n,e={})=>{let t=b("TTFB"),r=y(n,t,ge,e.reportAllChanges);j((()=>{let i=J();i&&(t.value=Math.max(i.responseStart-C(),0),t.entries=[i],r(!0),E((()=>{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)),Te(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){let t=e.textContent?.trim().substring(0,100);if(t)return t;let r=e.getAttribute("aria-label")?.trim().substring(0,100);if(r)return r;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 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,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(r)}handleChange(e){let t=e.target,r=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r)||t.disabled)return;if(r==="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:r.toLowerCase(),inputType:r==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}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/clickTracking.ts b/server/src/analytics-script/clickTracking.ts
index 5effc91bb..5cb6d7f89 100644
--- a/server/src/analytics-script/clickTracking.ts
+++ b/server/src/analytics-script/clickTracking.ts
@@ -93,7 +93,20 @@ export class ClickTrackingManager {
private getElementText(element: HTMLElement): string | undefined {
const text = element.textContent?.trim().substring(0, 100);
- return text || undefined;
+ if (text) return text;
+
+ const ariaLabel = element.getAttribute("aria-label")?.trim().substring(0, 100);
+ if (ariaLabel) return ariaLabel;
+
+ if (element.tagName === "INPUT") {
+ const value = (element as HTMLInputElement).value?.trim().substring(0, 100);
+ if (value) return value;
+ }
+
+ const title = element.getAttribute("title")?.trim().substring(0, 100);
+ if (title) return title;
+
+ return undefined;
}
cleanup(): void {
diff --git a/server/src/analytics-script/formTracking.ts b/server/src/analytics-script/formTracking.ts
index aa79ac94b..56a90a4d6 100644
--- a/server/src/analytics-script/formTracking.ts
+++ b/server/src/analytics-script/formTracking.ts
@@ -37,6 +37,7 @@ export class FormTrackingManager {
formAction: form.action || "",
method: (form.method || "get").toUpperCase(),
fieldCount: form.elements.length,
+ ariaLabel: form.getAttribute("aria-label") || undefined,
...this.extractDataAttributes(form),
};
@@ -49,17 +50,28 @@ export class FormTrackingManager {
if (!["INPUT", "SELECT", "TEXTAREA"].includes(tagName)) return;
+ // Skip disabled inputs
+ if ((target as HTMLInputElement).disabled) return;
+
// Skip hidden inputs and password fields for privacy
if (tagName === "INPUT") {
const inputType = (target as HTMLInputElement).type?.toLowerCase();
if (inputType === "hidden" || inputType === "password") return;
}
+ const inputName =
+ (target as HTMLInputElement).name ||
+ target.id ||
+ target.getAttribute("aria-label") ||
+ (target as HTMLInputElement).placeholder ||
+ "";
+
const properties: InputChangeProperties = {
element: tagName.toLowerCase(),
inputType: tagName === "INPUT" ? (target as HTMLInputElement).type?.toLowerCase() : undefined,
- inputName: (target as HTMLInputElement).name || target.id || "",
+ inputName,
formId: (target as HTMLInputElement).form?.id || undefined,
+ formName: (target as HTMLInputElement).form?.name || undefined,
...this.extractDataAttributes(target),
};
diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.ts
index 3dec2ce13..85cded8f4 100644
--- a/server/src/analytics-script/types.ts
+++ b/server/src/analytics-script/types.ts
@@ -74,14 +74,16 @@ export interface FormSubmitProperties {
formAction: string;
method: string;
fieldCount: number;
+ ariaLabel?: string;
[key: string]: string | number | undefined;
}
export interface InputChangeProperties {
element: string; // "input" | "select" | "textarea"
inputType?: string; // For inputs: "text", "email", "checkbox", etc.
- inputName: string; // Name or id attribute
+ inputName: string; // Name, id, aria-label, or placeholder attribute
formId?: string; // Parent form id if within a form
+ formName?: string; // Parent form name if within a form
[key: string]: string | undefined;
}