Skip to content

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

Add tagging (#941)

Goldflagbd89efdc1789
diff --git a/client/messages/de.json b/client/messages/de.json
index d19990eb7..53a09a219 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM-Begriff",
"MbeLHv": "Breitengrad",
"S1utKH": "Längengrad",
+ "18HJlm": "",
"7nUCu9": "Zeitzone",
"PfUTPz": "VPN",
"1fzzQF": "Crawler",
@@ -194,8 +195,8 @@
"Zx7WPP": "Alle Event-Reihen ausgeblendet",
"AKRVhS": "Klicken Sie auf ein Legendenelement, um es anzuzeigen",
"NuhCPH": "Erfahren Sie, wie Sie Events verfolgen",
- "ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",
"/aq5/F": "Keine benutzerdefinierten Events gefunden",
+ "ES6IYH": "Versuchen Sie einen anderen Zeitraum oder Filter",
"j7BiRg": "Kein Event ausgewählt.",
"kF9XUo": "Zeitstempel",
"EwRIOm": "Benutzer",
diff --git a/client/messages/en.json b/client/messages/en.json
index 8ae4a06e7..974d71626 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM Term",
"MbeLHv": "Lat",
"S1utKH": "Lon",
+ "18HJlm": "Tag",
"7nUCu9": "Timezone",
"PfUTPz": "VPN",
"1fzzQF": "Crawler",
@@ -194,8 +195,8 @@
"Zx7WPP": "All event series hidden",
"AKRVhS": "Click a legend item to show it",
"NuhCPH": "Learn how to track events",
- "ES6IYH": "Try a different date range or filter",
"/aq5/F": "No custom events found",
+ "ES6IYH": "Try a different date range or filter",
"j7BiRg": "No event selected.",
"kF9XUo": "Timestamp",
"EwRIOm": "User",
diff --git a/client/messages/es.json b/client/messages/es.json
index debe0def3..c087c51fc 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -118,6 +118,7 @@
"a1ydAX": "Término UTM",
"MbeLHv": "Latitud",
"S1utKH": "Longitud",
+ "18HJlm": "",
"7nUCu9": "Zona horaria",
"PfUTPz": "VPN",
"1fzzQF": "Rastreador",
@@ -194,8 +195,8 @@
"Zx7WPP": "Todas las series de eventos ocultas",
"AKRVhS": "Haz clic en un elemento de la leyenda para mostrarlo",
"NuhCPH": "Aprende cómo rastrear eventos",
- "ES6IYH": "Prueba un rango de fechas o filtro diferente",
"/aq5/F": "No se encontraron eventos personalizados",
+ "ES6IYH": "Prueba un rango de fechas o filtro diferente",
"j7BiRg": "Ningún evento seleccionado.",
"kF9XUo": "Marca de tiempo",
"EwRIOm": "Usuario",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index 83f8a820d..2688c52b4 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -118,6 +118,7 @@
"a1ydAX": "Terme UTM",
"MbeLHv": "Latitude",
"S1utKH": "Longitude",
+ "18HJlm": "",
"7nUCu9": "Fuseau horaire",
"PfUTPz": "VPN",
"1fzzQF": "Robot",
@@ -194,8 +195,8 @@
"Zx7WPP": "Toutes les séries d'événements masquées",
"AKRVhS": "Cliquez sur un élément de la légende pour l'afficher",
"NuhCPH": "Apprenez à suivre les événements",
- "ES6IYH": "Essayez une autre période ou un autre filtre",
"/aq5/F": "Aucun événement personnalisé trouvé",
+ "ES6IYH": "Essayez une autre période ou un autre filtre",
"j7BiRg": "Aucun événement sélectionné.",
"kF9XUo": "Horodatage",
"EwRIOm": "Utilisateur",
diff --git a/client/messages/it.json b/client/messages/it.json
index 4b1a730e0..2f25b9849 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM Term",
"MbeLHv": "Lat",
"S1utKH": "Lon",
+ "18HJlm": "",
"7nUCu9": "Fuso orario",
"PfUTPz": "VPN",
"1fzzQF": "Crawler",
@@ -194,8 +195,8 @@
"Zx7WPP": "Tutte le serie di eventi nascoste",
"AKRVhS": "Clicca un elemento della legenda per mostrarlo",
"NuhCPH": "Scopri come tracciare gli eventi",
- "ES6IYH": "Prova un intervallo di date diverso o un filtro",
"/aq5/F": "Nessun evento personalizzato trovato",
+ "ES6IYH": "Prova un intervallo di date diverso o un filtro",
"j7BiRg": "Nessun evento selezionato.",
"kF9XUo": "Timestamp",
"EwRIOm": "Utente",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index 3639e4b1c..f33881e9e 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTMターム",
"MbeLHv": "緯度",
"S1utKH": "経度",
+ "18HJlm": "",
"7nUCu9": "タイムゾーン",
"PfUTPz": "VPN",
"1fzzQF": "クローラー",
@@ -194,8 +195,8 @@
"Zx7WPP": "すべてのイベント系列が非表示です",
"AKRVhS": "凡例の項目をクリックして表示します",
"NuhCPH": "イベントのトラッキング方法を学ぶ",
- "ES6IYH": "別の日付範囲またはフィルターをお試しください",
"/aq5/F": "カスタムイベントが見つかりません",
+ "ES6IYH": "別の日付範囲またはフィルターをお試しください",
"j7BiRg": "イベントが選択されていません。",
"kF9XUo": "タイムスタンプ",
"EwRIOm": "ユーザー",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 11adf17be..ad5d6f8dc 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM 용어",
"MbeLHv": "위도",
"S1utKH": "경도",
+ "18HJlm": "",
"7nUCu9": "시간대",
"PfUTPz": "VPN",
"1fzzQF": "크롤러",
@@ -194,8 +195,8 @@
"Zx7WPP": "모든 이벤트 시리즈 숨김",
"AKRVhS": "범례 항목을 클릭하여 표시",
"NuhCPH": "이벤트 추적 방법 알아보기",
- "ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",
"/aq5/F": "사용자 정의 이벤트를 찾을 수 없음",
+ "ES6IYH": "다른 날짜 범위 또는 필터를 시도하세요",
"j7BiRg": "이벤트가 선택되지 않았습니다.",
"kF9XUo": "타임스탬프",
"EwRIOm": "사용자",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index 6bf3d4847..33c3abe0e 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM Term",
"MbeLHv": "Szer. geogr.",
"S1utKH": "Dł. geogr.",
+ "18HJlm": "",
"7nUCu9": "Strefa czasowa",
"PfUTPz": "VPN",
"1fzzQF": "Crawler",
@@ -194,8 +195,8 @@
"Zx7WPP": "Wszystkie serie zdarzeń ukryte",
"AKRVhS": "Kliknij element legendy, aby go wyświetlić",
"NuhCPH": "Dowiedz się, jak śledzić zdarzenia",
- "ES6IYH": "Spróbuj innego zakresu dat lub filtra",
"/aq5/F": "Nie znaleziono niestandardowych zdarzeń",
+ "ES6IYH": "Spróbuj innego zakresu dat lub filtra",
"j7BiRg": "Nie wybrano zdarzenia.",
"kF9XUo": "Znacznik czasu",
"EwRIOm": "Użytkownik",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index 0770b6e0a..a86792293 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM Term",
"MbeLHv": "Lat",
"S1utKH": "Lon",
+ "18HJlm": "",
"7nUCu9": "Fuso Horário",
"PfUTPz": "VPN",
"1fzzQF": "Crawler",
@@ -194,8 +195,8 @@
"Zx7WPP": "Todas as séries de eventos ocultas",
"AKRVhS": "Clique em um item da legenda para exibi-lo",
"NuhCPH": "Saiba como rastrear eventos",
- "ES6IYH": "Tente um intervalo de datas diferente ou filtro",
"/aq5/F": "Nenhum evento personalizado encontrado",
+ "ES6IYH": "Tente um intervalo de datas diferente ou filtro",
"j7BiRg": "Nenhum evento selecionado.",
"kF9XUo": "Data/Hora",
"EwRIOm": "Usuário",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index 43bf91f25..4f8e94704 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -118,6 +118,7 @@
"a1ydAX": "UTM 关键词",
"MbeLHv": "纬度",
"S1utKH": "经度",
+ "18HJlm": "",
"7nUCu9": "时区",
"PfUTPz": "VPN",
"1fzzQF": "爬虫",
@@ -194,8 +195,8 @@
"Zx7WPP": "所有事件系列已隐藏",
"AKRVhS": "点击图例项以显示它",
"NuhCPH": "了解如何追踪事件",
- "ES6IYH": "尝试不同的日期范围或过滤器",
"/aq5/F": "未找到自定义事件",
+ "ES6IYH": "尝试不同的日期范围或过滤器",
"j7BiRg": "未选择事件。",
"kF9XUo": "时间戳",
"EwRIOm": "用户",
diff --git a/client/src/app/[site]/components/SubHeader/Filters/FilterComponent.tsx b/client/src/app/[site]/components/SubHeader/Filters/FilterComponent.tsx
index f50555929..f969cfcaa 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/FilterComponent.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/FilterComponent.tsx
@@ -73,6 +73,7 @@ export function FilterComponent({
case "utm_term": return t("UTM Term");
case "lat": return t("Lat");
case "lon": return t("Lon");
+ case "tag": return t("Tag");
case "timezone": return t("Timezone");
case "vpn": return t("VPN");
case "crawler": return t("Crawler");
@@ -89,8 +90,8 @@ export function FilterComponent({
const availableFilterOptions = availableFilters
? FilterOptions.filter(option => availableFilters?.includes(option.value)).filter(
- option => IS_CLOUD || !option.cloudOnly
- )
+ option => IS_CLOUD || !option.cloudOnly
+ )
: FilterOptions.filter(option => IS_CLOUD || !option.cloudOnly);
const isNumeric = isNumericParameter(filter.parameter);
diff --git a/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx b/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx
index f76e03363..8e00af3da 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx
@@ -52,6 +52,7 @@ export function Filters({ availableFilters }: { availableFilters?: FilterParamet
case "asn_org": return t("ASN Org");
case "asn_type": return t("ASN Type");
case "asn_domain": return t("ASN Domain");
+ case "tag": return t("Tag");
default: return parameter;
}
};
diff --git a/client/src/app/[site]/components/SubHeader/Filters/const.tsx b/client/src/app/[site]/components/SubHeader/Filters/const.tsx
index fd086688b..6a84de793 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/const.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/const.tsx
@@ -163,6 +163,11 @@ export const FilterOptions: {
value: "utm_term",
icon: <Tag className="h-4 w-4" />,
},
+ {
+ label: "Tag",
+ value: "tag",
+ icon: <Tag className="h-4 w-4" />,
+ },
{
label: "Lat",
value: "lat",
diff --git a/client/src/app/[site]/components/SubHeader/Filters/utils.ts b/client/src/app/[site]/components/SubHeader/Filters/utils.ts
index 902a519f0..533ccac5d 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/utils.ts
+++ b/client/src/app/[site]/components/SubHeader/Filters/utils.ts
@@ -77,6 +77,8 @@ export function getParameterNameLabel(parameter: FilterParameter) {
return "ASN Type";
case "asn_domain":
return "ASN Domain";
+ case "tag":
+ return "Tag";
default:
return parameter;
}
diff --git a/client/src/lib/filterGroups.ts b/client/src/lib/filterGroups.ts
index 509426609..ddbb1112c 100644
--- a/client/src/lib/filterGroups.ts
+++ b/client/src/lib/filterGroups.ts
@@ -24,6 +24,7 @@ const BASE_FILTERS: FilterParameter[] = [
"user_id",
"lat",
"lon",
+ "tag",
];
export const SESSION_PAGE_FILTERS: FilterParameter[] = [...BASE_FILTERS, "pathname", "entry_page", "exit_page", "event_name"];
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index 4a2be8bb3..5f1be5f8e 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -11,6 +11,7 @@
"track-events",
"autocapture",
"identify-users",
+ "tagging",
"guides",
"proxy-guide",
"sdks",
diff --git a/docs/content/docs/script.mdx b/docs/content/docs/script.mdx
index 428bdbc6c..9e8ca401d 100644
--- a/docs/content/docs/script.mdx
+++ b/docs/content/docs/script.mdx
@@ -42,6 +42,7 @@ These are the attributes you can pass to the script tag.
| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments), plus regex patterns prefixed with `re:`. |
| `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards and `re:` regex patterns as `data-skip-patterns`. |
| `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |
+| `data-tag` | `string` | `""` | A label applied to all events from this script instance. Useful for A/B testing, deploy versioning, or cohort segmentation. Max 256 characters. See [Tagging](/docs/tagging). |
### Session Replay Attributes
diff --git a/docs/content/docs/tagging.mdx b/docs/content/docs/tagging.mdx
new file mode 100644
index 000000000..5487308a0
--- /dev/null
+++ b/docs/content/docs/tagging.mdx
@@ -0,0 +1,100 @@
+---
+title: Tagging
+description: How to use tags to label and segment analytics data in Rybbit
+---
+
+Tags let you label all events from a script instance with a string identifier. This is useful for A/B testing, deploy labeling, cohort segmentation, and any scenario where you want to slice your analytics by a custom dimension that applies to the entire page.
+
+## How It Works
+
+Add a `data-tag` attribute to your Rybbit script tag. Every event (pageviews, custom events, outbound clicks, etc.) sent from that page will include the tag value, which is stored in ClickHouse and available as a filter in the dashboard.
+
+```html
+<script
+ src="https://app.rybbit.io/api/script.js"
+ async
+ data-site-id="YOUR_SITE_ID"
+ data-tag="variant-a"
+></script>
+```
+
+The tag is a simple string with a maximum length of 256 characters. If `data-tag` is not set or is empty, no tag is stored.
+
+## Use Cases
+
+### A/B Testing
+
+Serve different script tags to different user groups and compare behavior:
+
+```html
+<!-- Variant A -->
+<script src="https://app.rybbit.io/api/script.js" async data-site-id="1" data-tag="homepage-v2-a"></script>
+
+<!-- Variant B -->
+<script src="https://app.rybbit.io/api/script.js" async data-site-id="1" data-tag="homepage-v2-b"></script>
+```
+
+Then filter by tag in the dashboard to compare metrics between variants.
+
+### Deploy / Release Labeling
+
+Tag events with the current deploy version to correlate releases with changes in user behavior or errors:
+
+```html
+<script
+ src="https://app.rybbit.io/api/script.js"
+ async
+ data-site-id="1"
+ data-tag="v2.4.1"
+></script>
+```
+
+### Cohort Segmentation
+
+Label traffic from different sources, campaigns, or user segments:
+
+```html
+<script
+ src="https://app.rybbit.io/api/script.js"
+ async
+ data-site-id="1"
+ data-tag="beta-users"
+></script>
+```
+
+## Filtering by Tag
+
+Once events with tags are flowing in, you can filter by tag anywhere in the dashboard:
+
+1. Click the **filter** button in the dashboard header
+2. Select **Tag** from the filter parameter dropdown
+3. Choose an operator (is, is not, contains, etc.)
+4. Enter the tag value
+
+The tag filter works on all dashboard pages including overview, pages, referrers, events, users, funnels, and goals.
+
+## API Usage
+
+When sending events via the [HTTP API](/docs/api/sending-events), include `tag` in the request body:
+
+```json
+{
+ "site_id": "YOUR_SITE_ID",
+ "type": "pageview",
+ "hostname": "example.com",
+ "pathname": "/",
+ "tag": "variant-a"
+}
+```
+
+## Important Notes
+
+- Each script instance can only have one tag. If you need multiple dimensions, consider using [custom event properties](/docs/track-events) instead.
+- Tags are set at the script level, not per-event. All events from a page load share the same tag.
+- The tag value is stored as-is (no hashing or transformation).
+- Empty or missing `data-tag` attributes result in no tag being stored.
+
+**Related Documentation:**
+- [Tracking Script](/docs/script)
+- [Track Events](/docs/track-events)
+- [Identify Users](/docs/identify-users)
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 136cc0e51..edcf1fe87 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -110,6 +110,7 @@
const sessionReplaySlimDOMOptions = slimDOMAttr ? parseJsonSafely(slimDOMAttr, {}) : void 0;
const sampleRateAttr = scriptTag.getAttribute("data-replay-sample-rate");
const sessionReplaySampleRate = sampleRateAttr ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10))) : void 0;
+ const tag = scriptTag.getAttribute("data-tag") || "";
const defaultConfig = {
namespace,
analyticsHost,
@@ -131,6 +132,7 @@
trackButtonClicks: false,
trackCopy: false,
trackFormInteractions: false,
+ tag,
// rrweb session replay options (undefined means use rrweb defaults)
sessionReplayBlockClass,
sessionReplayBlockSelector,
@@ -455,6 +457,9 @@
if (this.customUserId) {
payload.user_id = this.customUserId;
}
+ if (this.config.tag) {
+ payload.tag = this.config.tag;
+ }
return payload;
}
async sendTrackingData(payload) {
diff --git a/server/public/script.js b/server/public/script.js
index 89e64cb99..4af5a0a42 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 k=(n,e,t)=>Ae(n,typeof e!="symbol"?e+"":e,t);function Le(n){if(n.startsWith("re:")){let l=n.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}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 F(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 se(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function ae(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 oe(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"),[]),l=R(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,h=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,b=n.getAttribute("data-replay-block-class")||void 0,C=n.getAttribute("data-replay-block-selector")||void 0,v=n.getAttribute("data-replay-ignore-class")||void 0,o=n.getAttribute("data-replay-ignore-selector")||void 0,c=n.getAttribute("data-replay-mask-text-class")||void 0,p=n.getAttribute("data-replay-mask-all-inputs"),I=p!==null?p!=="false":void 0,T=n.getAttribute("data-replay-mask-input-options"),U=T?R(T,{password:!0,email:!0}):void 0,ee=n.getAttribute("data-replay-collect-fonts"),Ce=ee!==null?ee!=="false":void 0,te=n.getAttribute("data-replay-sampling"),we=te?R(te,{}):void 0,re=n.getAttribute("data-replay-slim-dom-options"),Pe=re?R(re,{}):void 0,ne=n.getAttribute("data-replay-sample-rate"),Ie=ne?Math.min(100,Math.max(0,parseInt(ne,10))):void 0,g={namespace:i,analyticsHost:t,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:l,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:b,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:v,sessionReplayIgnoreSelector:o,sessionReplayMaskTextClass:c,sessionReplayMaskAllInputs:I,sessionReplayMaskInputOptions:U,sessionReplayCollectFonts:Ce,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Pe,sessionReplaySampleRate:Ie};try{let H=`${t}/site/tracking-config/${r}`,ie=await fetch(H,{method:"GET",credentials:"omit"});if(ie.ok){let m=await ie.json();return{...g,autoTrackPageview:m.trackInitialPageView??g.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??g.autoTrackSpa,trackQuerystring:m.trackUrlParams??g.trackQuerystring,trackOutbound:m.trackOutbound??g.trackOutbound,enableWebVitals:m.webVitals??g.enableWebVitals,trackErrors:m.trackErrors??g.trackErrors,enableSessionReplay:m.sessionReplay??g.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??g.trackButtonClicks,trackCopy:m.trackCopy??g.trackCopy,trackFormInteractions:m.trackFormInteractions??g.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),g}catch(H){return console.warn("Error fetching tracking config:",H),g}}var ce="rybbit-replay-sampled";function Be(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(ce);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(ce,t?"1":"0"),t}catch{return Math.random()*100<n}}var M=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 A=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 M(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)),F(t,this.config.skipPatterns))return null;let r=F(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 d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),h=6e4,b=this.errorDedupeCache.get(d);if(b&&u-b<h)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>h){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let v={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(v.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(v.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(v.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(v[o]=t[o]);this.track("error",e.name||"Error",v)}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 ye=-1,S=n=>{addEventListener("pageshow",(e=>{e.persisted&&(ye=e.timeStamp,n(e))}),!0)},f=(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=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),n(e)))}},G=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Q=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},w=()=>Q()?.activationStart??0,y=(n,e=-1)=>{let t=Q(),r="navigate";return ye>=0?r="back-forward-cache":t&&(document.prerendering||w()>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}},W=new WeakMap;function X(n,e){return W.get(n)||W.set(n,new e),W.get(n)}var V=class{constructor(){k(this,"t");k(this,"i",0);k(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)}},P=(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{}},Y=n=>{let e=!1;return()=>{e||(n(),e=!0)}},E=-1,be=new Set,le=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,$=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of be)e();isFinite(E)||(E=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",$,!0))}},B=()=>{if(E<0){let n=w();E=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??le(),addEventListener("visibilitychange",$,!0),addEventListener("prerenderingchange",$,!0),S((()=>{setTimeout((()=>{E=le()}))}))}return{get firstHiddenTime(){return E},onHidden(n){be.add(n)}}},x=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ue=[1800,3e3],Z=(n,e={})=>{x((()=>{let t=B(),r,i=y("FCP"),s=P("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-w(),0),i.entries.push(l),r(!0)))}));s&&(r=f(n,i,ue,e.reportAllChanges),S((a=>{i=y("FCP"),r=f(n,i,ue,e.reportAllChanges),G((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},de=[.1,.25],ve=(n,e={})=>{let t=B();Z(Y((()=>{let r,i=y("CLS",0),s=X(e,V),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=P("layout-shift",a);l&&(r=f(n,i,de,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.i=0,i=y("CLS",0),r=f(n,i,de,e.reportAllChanges),G((()=>r()))})),setTimeout(r))})))},ke=0,z=1/0,L=0,xe=n=>{for(let e of n)e.interactionId&&(z=Math.min(z,e.interactionId),L=Math.max(L,e.interactionId),ke=L?(L-z)/7+1:0)},j,pe=()=>j?ke:performance.interactionCount??0,Oe=()=>{"interactionCount"in performance||j||(j=P("event",xe,{type:"event",buffered:!0,durationThreshold:0}))},he=0,K=class{constructor(){k(this,"u",[]);k(this,"l",new Map);k(this,"m");k(this,"p")}v(){he=pe(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((pe()-he)/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)}}},Re=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=Y(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},ge=[200,500],Te=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();x((()=>{Oe();let r,i=y("INP"),s=X(e,K),a=d=>{Re((()=>{for(let h of d)s.h(h);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=P("event",a,{durationThreshold:e.durationThreshold??40});r=f(n,i,ge,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.v(),i=y("INP"),r=f(n,i,ge,e.reportAllChanges)})))}))},J=class{constructor(){k(this,"m")}h(e){this.m?.(e)}},me=[2500,4e3],Ee=(n,e={})=>{x((()=>{let t=B(),r,i=y("LCP"),s=X(e,J),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-w(),0),i.entries=[u],r())},l=P("largest-contentful-paint",a);if(l){r=f(n,i,me,e.reportAllChanges);let d=Y((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=h=>{h.isTrusted&&(Re(d),removeEventListener(h.type,u,{capture:!0}))};for(let h of["keydown","click","visibilitychange"])addEventListener(h,u,{capture:!0});S((h=>{i=y("LCP"),r=f(n,i,me,e.reportAllChanges),G((()=>{i.value=performance.now()-h.timeStamp,r(!0)}))}))}}))},fe=[800,1800],q=n=>{document.prerendering?x((()=>q(n))):document.readyState!=="complete"?addEventListener("load",(()=>q(n)),!0):setTimeout(n)},Se=(n,e={})=>{let t=y("TTFB"),r=f(n,t,fe,e.reportAllChanges);q((()=>{let i=Q();i&&(t.value=Math.max(i.responseStart-w(),0),t.entries=[i],r(!0),S((()=>{t=y("TTFB",0),r=f(n,t,fe,e.reportAllChanges),r(!0)})))}))};var O=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{Ee(this.collectMetric.bind(this)),ve(this.collectMetric.bind(this)),Te(this.collectMetric.bind(this)),Z(this.collectMetric.bind(this)),Se(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 D=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 _=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 N=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=[],i=o=>(...c)=>{r.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await oe(n);if(!s)return;let a=new A(s);s.enableWebVitals&&new O(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new D(a,s),l.initialize()),s.trackCopy&&(d=new _(a),d.initialize()),s.trackFormInteractions&&(u=new N(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let h=()=>a.trackPageview(),b=s.debounceDuration>0?se(h,s.debounceDuration):h;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let I={};for(let T of c.attributes)if(T.name.startsWith("data-rybbit-prop-")){let U=T.name.replace("data-rybbit-prop-","");I[U]=T.value}a.trackEvent(p,I)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&ae(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),b(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),b(),a.onPageChange()},window.addEventListener("popstate",()=>{b(),a.onPageChange()}),window.addEventListener("hashchange",()=>{b(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let v=window[s.namespace];for(let[o,c]of r)v[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
+"use strict";(()=>{var Ae=Object.defineProperty;var Le=(n,e,t)=>e in n?Ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var k=(n,e,t)=>Le(n,typeof e!="symbol"?e+"":e,t);function Be(n){if(n.startsWith("re:")){let l=n.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}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 F(n,e){for(let t of e)try{if(Be(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function se(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function ae(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 oe(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"),[]),l=R(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,h=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,b=n.getAttribute("data-replay-block-class")||void 0,C=n.getAttribute("data-replay-block-selector")||void 0,v=n.getAttribute("data-replay-ignore-class")||void 0,o=n.getAttribute("data-replay-ignore-selector")||void 0,c=n.getAttribute("data-replay-mask-text-class")||void 0,p=n.getAttribute("data-replay-mask-all-inputs"),I=p!==null?p!=="false":void 0,T=n.getAttribute("data-replay-mask-input-options"),U=T?R(T,{password:!0,email:!0}):void 0,ee=n.getAttribute("data-replay-collect-fonts"),Ce=ee!==null?ee!=="false":void 0,te=n.getAttribute("data-replay-sampling"),we=te?R(te,{}):void 0,re=n.getAttribute("data-replay-slim-dom-options"),Pe=re?R(re,{}):void 0,ne=n.getAttribute("data-replay-sample-rate"),Ie=ne?Math.min(100,Math.max(0,parseInt(ne,10))):void 0,Me=n.getAttribute("data-tag")||"",g={namespace:i,analyticsHost:t,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:l,skipPatterns:s,maskPatterns:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Me,sessionReplayBlockClass:b,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:v,sessionReplayIgnoreSelector:o,sessionReplayMaskTextClass:c,sessionReplayMaskAllInputs:I,sessionReplayMaskInputOptions:U,sessionReplayCollectFonts:Ce,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Pe,sessionReplaySampleRate:Ie};try{let H=`${t}/site/tracking-config/${r}`,ie=await fetch(H,{method:"GET",credentials:"omit"});if(ie.ok){let f=await ie.json();return{...g,autoTrackPageview:f.trackInitialPageView??g.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??g.autoTrackSpa,trackQuerystring:f.trackUrlParams??g.trackQuerystring,trackOutbound:f.trackOutbound??g.trackOutbound,enableWebVitals:f.webVitals??g.enableWebVitals,trackErrors:f.trackErrors??g.trackErrors,enableSessionReplay:f.sessionReplay??g.enableSessionReplay,trackButtonClicks:f.trackButtonClicks??g.trackButtonClicks,trackCopy:f.trackCopy??g.trackCopy,trackFormInteractions:f.trackFormInteractions??g.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),g}catch(H){return console.warn("Error fetching tracking config:",H),g}}var ce="rybbit-replay-sampled";function xe(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(ce);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(ce,t?"1":"0"),t}catch{return Math.random()*100<n}}var M=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&&!xe(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 A=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 M(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)),F(t,this.config.skipPatterns))return null;let r=F(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),this.config.tag&&(i.tag=this.config.tag),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 d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),h=6e4,b=this.errorDedupeCache.get(d);if(b&&u-b<h)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>h){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let v={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(v.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(v.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(v.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(v[o]=t[o]);this.track("error",e.name||"Error",v)}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 ye=-1,S=n=>{addEventListener("pageshow",(e=>{e.persisted&&(ye=e.timeStamp,n(e))}),!0)},m=(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=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),n(e)))}},G=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Q=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},w=()=>Q()?.activationStart??0,y=(n,e=-1)=>{let t=Q(),r="navigate";return ye>=0?r="back-forward-cache":t&&(document.prerendering||w()>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}},W=new WeakMap;function X(n,e){return W.get(n)||W.set(n,new e),W.get(n)}var V=class{constructor(){k(this,"t");k(this,"i",0);k(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)}},P=(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{}},Y=n=>{let e=!1;return()=>{e||(n(),e=!0)}},E=-1,be=new Set,le=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,$=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of be)e();isFinite(E)||(E=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",$,!0))}},B=()=>{if(E<0){let n=w();E=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??le(),addEventListener("visibilitychange",$,!0),addEventListener("prerenderingchange",$,!0),S((()=>{setTimeout((()=>{E=le()}))}))}return{get firstHiddenTime(){return E},onHidden(n){be.add(n)}}},x=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ue=[1800,3e3],Z=(n,e={})=>{x((()=>{let t=B(),r,i=y("FCP"),s=P("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-w(),0),i.entries.push(l),r(!0)))}));s&&(r=m(n,i,ue,e.reportAllChanges),S((a=>{i=y("FCP"),r=m(n,i,ue,e.reportAllChanges),G((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},de=[.1,.25],ve=(n,e={})=>{let t=B();Z(Y((()=>{let r,i=y("CLS",0),s=X(e,V),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=P("layout-shift",a);l&&(r=m(n,i,de,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.i=0,i=y("CLS",0),r=m(n,i,de,e.reportAllChanges),G((()=>r()))})),setTimeout(r))})))},ke=0,z=1/0,L=0,Oe=n=>{for(let e of n)e.interactionId&&(z=Math.min(z,e.interactionId),L=Math.max(L,e.interactionId),ke=L?(L-z)/7+1:0)},j,pe=()=>j?ke:performance.interactionCount??0,De=()=>{"interactionCount"in performance||j||(j=P("event",Oe,{type:"event",buffered:!0,durationThreshold:0}))},he=0,K=class{constructor(){k(this,"u",[]);k(this,"l",new Map);k(this,"m");k(this,"p")}v(){he=pe(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((pe()-he)/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)}}},Re=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=Y(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},ge=[200,500],Te=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();x((()=>{De();let r,i=y("INP"),s=X(e,K),a=d=>{Re((()=>{for(let h of d)s.h(h);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=P("event",a,{durationThreshold:e.durationThreshold??40});r=m(n,i,ge,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.v(),i=y("INP"),r=m(n,i,ge,e.reportAllChanges)})))}))},J=class{constructor(){k(this,"m")}h(e){this.m?.(e)}},fe=[2500,4e3],Ee=(n,e={})=>{x((()=>{let t=B(),r,i=y("LCP"),s=X(e,J),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-w(),0),i.entries=[u],r())},l=P("largest-contentful-paint",a);if(l){r=m(n,i,fe,e.reportAllChanges);let d=Y((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=h=>{h.isTrusted&&(Re(d),removeEventListener(h.type,u,{capture:!0}))};for(let h of["keydown","click","visibilitychange"])addEventListener(h,u,{capture:!0});S((h=>{i=y("LCP"),r=m(n,i,fe,e.reportAllChanges),G((()=>{i.value=performance.now()-h.timeStamp,r(!0)}))}))}}))},me=[800,1800],q=n=>{document.prerendering?x((()=>q(n))):document.readyState!=="complete"?addEventListener("load",(()=>q(n)),!0):setTimeout(n)},Se=(n,e={})=>{let t=y("TTFB"),r=m(n,t,me,e.reportAllChanges);q((()=>{let i=Q();i&&(t.value=Math.max(i.responseStart-w(),0),t.entries=[i],r(!0),S((()=>{t=y("TTFB",0),r=m(n,t,me,e.reportAllChanges),r(!0)})))}))};var O=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{Ee(this.collectMetric.bind(this)),ve(this.collectMetric.bind(this)),Te(this.collectMetric.bind(this)),Z(this.collectMetric.bind(this)),Se(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 D=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 _=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 N=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=[],i=o=>(...c)=>{r.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await oe(n);if(!s)return;let a=new A(s);s.enableWebVitals&&new O(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new D(a,s),l.initialize()),s.trackCopy&&(d=new _(a),d.initialize()),s.trackFormInteractions&&(u=new N(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let h=()=>a.trackPageview(),b=s.debounceDuration>0?se(h,s.debounceDuration):h;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let I={};for(let T of c.attributes)if(T.name.startsWith("data-rybbit-prop-")){let U=T.name.replace("data-rybbit-prop-","");I[U]=T.value}a.trackEvent(p,I)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&ae(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),b(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),b(),a.onPageChange()},window.addEventListener("popstate",()=>{b(),a.onPageChange()}),window.addEventListener("hashchange",()=>{b(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let v=window[s.namespace];for(let[o,c]of r)v[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();
diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.ts
index a7bc35ef6..541dd124e 100644
--- a/server/src/analytics-script/config.ts
+++ b/server/src/analytics-script/config.ts
@@ -83,6 +83,8 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10)))
: undefined;
+ const tag = scriptTag.getAttribute("data-tag") || "";
+
// Default config with minimal settings
const defaultConfig: ScriptConfig = {
namespace,
@@ -105,6 +107,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S
trackButtonClicks: false,
trackCopy: false,
trackFormInteractions: false,
+ tag,
// rrweb session replay options (undefined means use rrweb defaults)
sessionReplayBlockClass,
sessionReplayBlockSelector,
diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.ts
index 5705dfc68..58a4667ae 100644
--- a/server/src/analytics-script/tracking.test.ts
+++ b/server/src/analytics-script/tracking.test.ts
@@ -94,6 +94,7 @@ describe("Tracker", () => {
trackButtonClicks: false,
trackCopy: false,
trackFormInteractions: false,
+ tag: "",
};
tracker = new Tracker(config);
diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.ts
index 7a3575903..1a2d0f716 100644
--- a/server/src/analytics-script/tracking.ts
+++ b/server/src/analytics-script/tracking.ts
@@ -93,6 +93,10 @@ export class Tracker {
payload.user_id = this.customUserId;
}
+ if (this.config.tag) {
+ payload.tag = this.config.tag;
+ }
+
return payload;
}
diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.ts
index 85cded8f4..231a70fd5 100644
--- a/server/src/analytics-script/types.ts
+++ b/server/src/analytics-script/types.ts
@@ -30,6 +30,7 @@ export interface ScriptConfig {
trackButtonClicks: boolean;
trackCopy: boolean;
trackFormInteractions: boolean;
+ tag: string;
}
export interface BasePayload {
@@ -43,6 +44,7 @@ export interface BasePayload {
page_title: string;
referrer: string;
user_id?: string;
+ tag?: string;
}
export interface TrackingPayload extends BasePayload {
@@ -55,6 +57,7 @@ export interface TrackingPayload extends BasePayload {
inp?: number | null;
fcp?: number | null;
ttfb?: number | null;
+ tag?: string;
}
export interface ButtonClickProperties {
diff --git a/server/src/api/analytics/funnels/getFunnelStepSessions.ts b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
index 2c32596d8..e0904e8ca 100644
--- a/server/src/api/analytics/funnels/getFunnelStepSessions.ts
+++ b/server/src/api/analytics/funnels/getFunnelStepSessions.ts
@@ -137,7 +137,8 @@ export async function getFunnelStepSessions(req: FastifyRequest<GetFunnelStepSes
type,
props,
hostname,
- url_parameters
+ url_parameters,
+ tag
FROM events
WHERE
site_id = {siteId:Int32}
@@ -236,7 +237,8 @@ export async function getFunnelStepSessions(req: FastifyRequest<GetFunnelStepSes
countIf(e.type = 'outbound') AS outbound,
argMax(e.ip, e.timestamp) AS ip,
argMax(e.lat, e.timestamp) AS lat,
- argMax(e.lon, e.timestamp) AS lon
+ argMax(e.lon, e.timestamp) AS lon,
+ argMax(e.tag, e.timestamp) AS tag
FROM events e
INNER JOIN TargetSessions ts ON e.session_id = ts.session_id
WHERE
diff --git a/server/src/api/analytics/goals/getGoalSessions.ts b/server/src/api/analytics/goals/getGoalSessions.ts
index 4e844ace9..116eff09c 100644
--- a/server/src/api/analytics/goals/getGoalSessions.ts
+++ b/server/src/api/analytics/goals/getGoalSessions.ts
@@ -144,7 +144,8 @@ export async function getGoalSessions(req: FastifyRequest<GetGoalSessionsRequest
countIf(e.type = 'outbound') AS outbound,
argMax(e.ip, e.timestamp) AS ip,
argMax(e.lat, e.timestamp) AS lat,
- argMax(e.lon, e.timestamp) AS lon
+ argMax(e.lon, e.timestamp) AS lon,
+ argMax(e.tag, e.timestamp) AS tag
FROM events e
INNER JOIN GoalSessions gs ON e.session_id = gs.session_id
WHERE
diff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.ts
index bbf7b1afb..bdf06a2f5 100644
--- a/server/src/api/analytics/sessions/getSessions.ts
+++ b/server/src/api/analytics/sessions/getSessions.ts
@@ -143,7 +143,8 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:
countIf(type = 'input_change') AS input_changes,
argMax(ip, timestamp) AS ip,
argMax(lat, timestamp) AS lat,
- argMax(lon, timestamp) AS lon
+ argMax(lon, timestamp) AS lon,
+ argMax(tag, timestamp) AS tag
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/users/getUsers.ts b/server/src/api/analytics/users/getUsers.ts
index 9d0c69d39..229d15700 100644
--- a/server/src/api/analytics/users/getUsers.ts
+++ b/server/src/api/analytics/users/getUsers.ts
@@ -125,7 +125,8 @@ WITH AggregatedUsers AS (
countIf(type = 'custom_event') AS events,
count(distinct session_id) AS sessions,
max(timestamp) AS last_seen,
- min(timestamp) AS first_seen
+ min(timestamp) AS first_seen,
+ argMax(tag, timestamp) AS tag
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.ts
index 12ae929e0..605a388cf 100644
--- a/server/src/api/analytics/utils/query-validation.ts
+++ b/server/src/api/analytics/utils/query-validation.ts
@@ -231,6 +231,7 @@ export const filterParamSchema = z.enum([
"asn_org",
"asn_type",
"asn_domain",
+ "tag",
]);
/**
diff --git a/server/src/db/clickhouse/clickhouse.ts b/server/src/db/clickhouse/clickhouse.ts
index 4e53bb45f..6f803a57c 100644
--- a/server/src/db/clickhouse/clickhouse.ts
+++ b/server/src/db/clickhouse/clickhouse.ts
@@ -60,7 +60,8 @@ export const initializeClickhouse = async () => {
ADD COLUMN IF NOT EXISTS ip Nullable(String),
ADD COLUMN IF NOT EXISTS timezone LowCardinality(String) DEFAULT '',
ADD COLUMN IF NOT EXISTS identified_user_id String DEFAULT '',
- ADD COLUMN IF NOT EXISTS import_id Nullable(UUID)
+ ADD COLUMN IF NOT EXISTS import_id Nullable(UUID),
+ ADD COLUMN IF NOT EXISTS tag LowCardinality(String) DEFAULT ''
`,
});
diff --git a/server/src/services/tracker/pageviewQueue.ts b/server/src/services/tracker/pageviewQueue.ts
index bddedb7df..92bdd4d13 100644
--- a/server/src/services/tracker/pageviewQueue.ts
+++ b/server/src/services/tracker/pageviewQueue.ts
@@ -98,6 +98,7 @@ class PageviewQueue {
ttfb: pv.ttfb || null,
ip: pv.storeIp ? pv.ipAddress : null,
timezone: timezone,
+ tag: pv.tag || "",
import_id: null,
company: dataForIp?.company?.name || "",
company_domain: dataForIp?.company?.domain || "",
diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.ts
index 9145b4a61..f3f893552 100644
--- a/server/src/services/tracker/trackEvent.ts
+++ b/server/src/services/tracker/trackEvent.ts
@@ -21,6 +21,7 @@ const baseEventFields = {
page_title: z.string().max(512).optional(),
referrer: z.string().max(2048).optional(),
user_id: z.string().max(255).optional(),
+ tag: z.string().max(256).optional(),
ip_address: z.string().ip().optional(),
user_agent: z.string().max(512).optional(),
};
diff --git a/server/src/services/tracker/types.ts b/server/src/services/tracker/types.ts
index 1e773911a..6e8f70cf3 100644
--- a/server/src/services/tracker/types.ts
+++ b/server/src/services/tracker/types.ts
@@ -9,4 +9,5 @@ export interface TrackingPayload {
language: string;
page_title: string;
referrer: string;
+ tag?: string;
}
diff --git a/server/src/services/tracker/utils.ts b/server/src/services/tracker/utils.ts
index 567d17515..6c0838db0 100644
--- a/server/src/services/tracker/utils.ts
+++ b/server/src/services/tracker/utils.ts
@@ -23,6 +23,7 @@ export type TotalTrackingPayload = TrackingPayload & {
inp?: number;
fcp?: number;
ttfb?: number;
+ tag?: string;
};
// Infer type from Zod schema
diff --git a/shared/src/filters.ts b/shared/src/filters.ts
index 805d80d52..7339ffbea 100644
--- a/shared/src/filters.ts
+++ b/shared/src/filters.ts
@@ -45,7 +45,8 @@ export type FilterParameter =
| "company_domain"
| "asn_org"
| "asn_type"
- | "asn_domain";
+ | "asn_domain"
+ | "tag";
export interface Filter {
parameter: FilterParameter;