🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feature flags (#1010)
Goldflag83128ea58dfa
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex b8ae38d21..8ea71d5c0 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -61,6 +61,7 @@"mByYl9": "Zobrazení stránek %","IuFETn": "Doba trvání","0eoYsu": "Míra okamžitého opuštění",+ "QashlR": "Při načítání dat došlo k chybě","IxrHg4": "Filtruj {count} položek...","tL4WC1": "Načítám další...","HPx76n": "Všechny položky načteny",@@ -74,6 +75,8 @@"XHLYdJ": "Cíle","9d/EEp": "Produktová analytika","5yUsUe": "Přehrávání",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Trychtýře","08hqOd": "Cesty návštěvníků","nL6Jl0": "Retence",@@ -242,6 +245,212 @@"BReFYW": "Změny vstupu","NDoUa9": "Všechny typy událostí skryty","MJ2jZQ": "Celkem",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Cíl #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Název události",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Koncept",+ "LHF3Za": "",+ "47FYwb": "Zrušit",+ "rbrahO": "Zavřít",+ "cyR7Kh": "",+ "TiR/Hq": "Ukládám...",+ "mRL9Vh": "Vytvářím...",+ "X0ha1a": "",+ "JXdbo8": "Hotovo",+ "acrOoz": "Pokračovat",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pozastavit",+ "U78NhE": "",+ "wL7VAE": "Akce",+ "wEQDC6": "",+ "K3r6DQ": "Smazat",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Stav",+ "Zh+5A6": "Zapnuto",+ "OvzONl": "Vypnuto",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Vytvořeno",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Klíč",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Všechny kroky musí mít hodnoty","jm52QG": "Zadej prosím název trychtýře","+N7isb": "Trychtýř úspěšně uložen",@@ -273,7 +482,6 @@"+U6ozc": "Typ","m1czzY": "Událost","Y6DkLY": "Cesta (např. /pricing)",- "eOj4Bs": "Název události","Hp/0iW": "Zadej cestu (např. /checkout), ne celou URL.","Asi2Jg": "Skrýt pokročilé možnosti","lIEejV": "Zobrazit pokročilé možnosti",@@ -287,8 +495,6 @@"tINfvW": "Použij * pro shodu s jedním segmentem cesty (např. /blog/*) nebo ** pro shodu s více segmenty (např. /docs/**/intro)","ox304v": "Došlo k chybě","KbGBQH": "Při ukládání došlo k chybě",- "47FYwb": "Zrušit",- "TiR/Hq": "Ukládám...","/liMUf": "Trychtýř úspěšně smazán","753yX5": "Popisek","+SDMR3": "Vlastnost",@@ -298,7 +504,6 @@"SB3+JE": "Žádná data trychtýře k dispozici","45gABM": "Opravdu chceš smazat \"{name}\"? Tuto akci nelze vrátit zpět.","noZdV2": "Mažu...",- "K3r6DQ": "Smazat","GoxzAN": "Filtrovat trychtýře","qGN7M9": "Nepodařilo se načíst trychtýře","5/6deG": "Při načítání trychtýřů nastal problém. Zkus to prosím později.",@@ -328,16 +533,15 @@"h3ICzV": "Načítám relace...","KjXPXZ": "{count} relací","9iSdEj": "{count} relace",- "tFFMkF": "Pozastavit","J3ca41": "Přehrát","Ggedt8": "Zobrazeny pouze první {count} relace. K dispozici mohou být další data.","5WuADX": "Přidat cíl",+ "WuHoZ9": "Konverze",+ "e/U0Xt": "Konverzní poměr","+Ior19": "Cíl stránky","rTE34i": "Cíl události",- "FYBPJU": "Cíl #{goalId}","pW4lxD": "Vzor",- "WuHoZ9": "Konverze",- "e/U0Xt": "Konverzní poměr",+ "99Lkvz": "","sOXElg": "Upravit cíl","N/ctXb": "Naklonovat cíl","F3XA9+": "Smazat cíl",@@ -395,10 +599,10 @@"zuqMfZ": "Mapa","jUSc45": "Časová pásma","NdE4Ps": "Prohlížeče",+ "/VnDMl": "Ostatní","+20FW7": "Zařízení","aTW7It": "Operační systémy","3X4r56": "Rozlišení obrazovky",- "/VnDMl": "Ostatní","Aujn2T": "Počet","ogKEiU": "Odchozí odkazy","VLKK35": "Kliknutí",@@ -407,13 +611,14 @@"pEc/5k": "Kliknutí %","wU7PzI": "Naposledy kliknuto","4KEfRY": "Titulky",- "87ZCAe": "Vstupy",- "0ogV14": "Výstupy",- "P6RGqE": "Hostnames","gvOzOl": "Název stránky",+ "87ZCAe": "Vstupy","vFf5xV": "Vstupní stránky",+ "0ogV14": "Výstupy","KtC97P": "Výstupní stránky",+ "P6RGqE": "Hostnames","iF/x8v": "Odkazující stránky",+ "UF6kPm": "Přímý","LUrJwE": "Kanály","aH4De2": "Zdroj","ovJ26C": "Médium",@@ -421,7 +626,6 @@"qTy5se": "Výraz","Jq3FDz": "Obsah","grtbAW": "UTM",- "UF6kPm": "Přímý","0E9k6Y": "Připoj svůj účet Google Search Console pro zobrazení dat o výkonu ve vyhledávání, včetně nejlepších klíčových slov a stránek.","jioGL4": "Připojit Google Search Console","M/h5TN": "Zobrazení",@@ -550,7 +754,6 @@"uiy9pN": "Události (30d)","9juexR": "Detail předplatného","fz0z4c": "Plán",- "tzMNF3": "Stav","T8qVXf": "Limit událostí","ekXood": "Neomezený","5x9Sl1": "Konec období",@@ -563,7 +766,6 @@"bGIAle": "Členové ({count})","hQZhn8": "Převzít identitu","2ZpsMl": "Žádní členové",- "G/yZLu": "","nJuUfX": "Hledat podle názvu, slugu, domény nebo e-mailu člena...","RllRQH": "Zobrazit organizace s 0 událostmi (30d)","7OL11E": "Pouze přes limit",@@ -578,7 +780,6 @@"uL0dMG": "Využití celé služby – posledních {timePeriod}","SVwJTM": "Exportovat","K56Dim": "Organizace",- "ORGv1Q": "Vytvořeno","JKxOsh": "Měsíční události","R/6nsx": "Předplatné","DDhP4z": "Weby",@@ -596,8 +797,6 @@"viXE32": "Soukromý","6hdNA5": "Události (24h)","J4r/Gi": "Události (30d)",- "Zh+5A6": "Zapnuto",- "OvzONl": "Vypnuto","C2EM7h": "E-mail vlastníka","sEqhTf": "Nepodařilo se načíst data webů. Zkus to prosím později.","r9Y1x6": "Hledej podle domény nebo emailu vlastníka...",@@ -626,7 +825,6 @@"uA0DvF": "Nepodařilo se odebrat uživatele z organizace","PW+sL4": "N/A","wittYy": "Vytvořeno",- "wL7VAE": "Akce","bdcMGy": "Otevřít menu","6gHGy0": "Odebrat z organizace","J2wna+": "Odebrat uživatele z organizace?",@@ -744,19 +942,16 @@"u4673k": "Vygeneruj API klíče pro přístup k analytickým endpointům z tvých aplikací","1fe3VI": "Klíče API jsou dostupné v plánech Standard a Pro.","AkVL9j": "Název API klíče",- "mRL9Vh": "Vytvářím...","jDvHYJ": "Tvé API klíče","MUaUWe": "Načítám API klíče...","iX4wwR": "Nepodařilo se načíst API klíče","62nsdy": "Zkusit znovu",- "EcglP9": "Klíč","IY105q": "Zatím žádné API klíče","wPtCEB": "API klíč vytvořen","qcTCG8": "Ulož si tento API klíč bezpečně. Znovu ho neuvidíš.","51jo4g": "Tvůj API klíč","+fICx5": "Důležité","TsKkxv": "Ulož si tento klíč bezpečně. Znovu nebude zobrazen.",- "JXdbo8": "Hotovo","LuNBqj": "Heslo by mělo mít alespoň 8 znaků","UjlqkD": "Silné heslo","EK3962": "Dobré heslo",@@ -886,7 +1081,6 @@"S5IFjk": "Vytvořte tým pro seskupení webů a správu přístupu členů.","StUScz": "{count} členů","RNCPOG": "Registrace",- "acrOoz": "Pokračovat","uCk8r+": "Už máš účet?","odXlk8": "Přihlásit se","uWRAQk": "Vyberte svůj plán",@@ -996,7 +1190,6 @@"W5IIP8": "Upgraduj na {planName} pro odemknutí {message}","4Y+tpi": "Podívej se na ukázku této funkce","RL7HbL": "Požádej vlastníka organizace o upgrade na Pro pro odemknutí {message}",- "QashlR": "Při načítání dat došlo k chybě","jsy7pk": "Zkusit znovu","hyfdry": "Zobrazení stránky","/kZg9i": "Kliknutí na tlačítko",@@ -1196,7 +1389,6 @@"jjBvFh": "","6cBDhe": "","IP4n+n": "",- "rbrahO": "Zavřít","scL+IP": "","8pKlHk": "","mhmZ+P": "Přehrávání relací",@@ -1243,7 +1435,6 @@"u/vOPu": "Zaplaceno","jHfCjd": "Neplatné","45hFQt": "Nevymahatelné",- "W6nwjo": "Koncept","6dqYnF": "Faktury","P7PLVj": "Datum","/0TOL5": "Částka",diff --git a/client/messages/de.json b/client/messages/de.jsonindex 652aac18e..9aa324f67 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -61,6 +61,7 @@"mByYl9": "Seitenaufrufe %","IuFETn": "Dauer","0eoYsu": "Absprungrate",+ "QashlR": "Beim Abrufen der Daten ist ein Fehler aufgetreten","IxrHg4": "{count} Einträge filtern...","tL4WC1": "Lade mehr...","HPx76n": "Alle Einträge geladen",@@ -74,6 +75,8 @@"XHLYdJ": "Ziele","9d/EEp": "Produktanalyse","5yUsUe": "Wiedergabe",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Trichter","08hqOd": "Pfade","nL6Jl0": "Bindung",@@ -242,6 +245,212 @@"BReFYW": "Eingabeänderungen","NDoUa9": "Alle Event-Typen ausgeblendet","MJ2jZQ": "Gesamt",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Ziel #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Event-Name",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Entwurf",+ "LHF3Za": "",+ "47FYwb": "Abbrechen",+ "rbrahO": "Schließen",+ "cyR7Kh": "",+ "TiR/Hq": "Wird gespeichert...",+ "mRL9Vh": "Wird erstellt...",+ "X0ha1a": "",+ "JXdbo8": "Fertig",+ "acrOoz": "Weiter",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pause",+ "U78NhE": "",+ "wL7VAE": "Aktionen",+ "wEQDC6": "",+ "K3r6DQ": "Löschen",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Entfernen",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Status",+ "Zh+5A6": "Ein",+ "OvzONl": "Aus",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Erstellt",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Schlüssel",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Alle Schritte müssen Werte haben","jm52QG": "Bitte geben Sie einen Trichternamen ein","+N7isb": "Trichter erfolgreich gespeichert",@@ -273,7 +482,6 @@"+U6ozc": "Typ","m1czzY": "Ereignis","Y6DkLY": "Pfad (z.B. /pricing)",- "eOj4Bs": "Event-Name","Hp/0iW": "Geben Sie einen Pfad ein (z.B. /checkout), keine vollständige URL.","Asi2Jg": "Erweiterte Optionen ausblenden","lIEejV": "Erweiterte Optionen anzeigen",@@ -287,8 +495,6 @@"tINfvW": "Verwenden Sie * für ein einzelnes Pfadsegment (z.B. /blog/*) oder ** für mehrere Segmente (z.B. /docs/**/intro)","ox304v": "Ein Fehler ist aufgetreten","KbGBQH": "Beim Speichern ist ein Fehler aufgetreten",- "47FYwb": "Abbrechen",- "TiR/Hq": "Wird gespeichert...","/liMUf": "Trichter erfolgreich gelöscht","753yX5": "Bezeichnung","+SDMR3": "Eigenschaft",@@ -298,7 +504,6 @@"SB3+JE": "Keine Trichterdaten verfügbar","45gABM": "Sind Sie sicher, dass Sie \"{name}\" löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.","noZdV2": "Wird gelöscht...",- "K3r6DQ": "Löschen","GoxzAN": "Trichter filtern","qGN7M9": "Trichter konnten nicht geladen werden","5/6deG": "Beim Abrufen der Trichter ist ein Problem aufgetreten. Bitte versuchen Sie es später erneut.",@@ -328,16 +533,15 @@"h3ICzV": "Sitzungen werden geladen...","KjXPXZ": "{count} Sitzungen","9iSdEj": "{count} Sitzung",- "tFFMkF": "Pause","J3ca41": "Abspielen","Ggedt8": "Es werden nur die ersten {count} Sitzungen angezeigt. Weitere Daten sind möglicherweise verfügbar.","5WuADX": "Ziel hinzufügen",+ "WuHoZ9": "Konversionen",+ "e/U0Xt": "Konversionsrate","+Ior19": "Seitenziel","rTE34i": "Event-Ziel",- "FYBPJU": "Ziel #{goalId}","pW4lxD": "Muster",- "WuHoZ9": "Konversionen",- "e/U0Xt": "Konversionsrate",+ "99Lkvz": "","sOXElg": "Ziel bearbeiten","N/ctXb": "Ziel duplizieren","F3XA9+": "Ziel löschen",@@ -395,10 +599,10 @@"zuqMfZ": "Karte","jUSc45": "Zeitzonen","NdE4Ps": "Browser",+ "/VnDMl": "Sonstige","+20FW7": "Geräte","aTW7It": "Betriebssysteme","3X4r56": "Bildschirmauflösungen",- "/VnDMl": "Sonstige","Aujn2T": "Anzahl","ogKEiU": "Ausgehende Links","VLKK35": "Klicks",@@ -407,13 +611,14 @@"pEc/5k": "Klick %","wU7PzI": "Zuletzt geklickt","4KEfRY": "Titel",- "87ZCAe": "Einstiege",- "0ogV14": "Ausstiege",- "P6RGqE": "Hostnamen","gvOzOl": "Seitentitel",+ "87ZCAe": "Einstiege","vFf5xV": "Einstiegsseiten",+ "0ogV14": "Ausstiege","KtC97P": "Ausstiegsseiten",+ "P6RGqE": "Hostnamen","iF/x8v": "Referrer",+ "UF6kPm": "Direkt","LUrJwE": "Kanäle","aH4De2": "Quelle","ovJ26C": "Medium",@@ -421,7 +626,6 @@"qTy5se": "Begriff","Jq3FDz": "Inhalt","grtbAW": "UTM",- "UF6kPm": "Direkt","0E9k6Y": "Verbinden Sie Ihr Google Search Console-Konto, um Suchleistungsdaten einschließlich der besten Keywords und Seiten anzuzeigen.","jioGL4": "Google Search Console verbinden","M/h5TN": "Impressionen",@@ -550,7 +754,6 @@"uiy9pN": "30d-Events","9juexR": "Abonnementdetails","fz0z4c": "Plan",- "tzMNF3": "Status","T8qVXf": "Event-Limit","ekXood": "Unbegrenzt","5x9Sl1": "Periodenende",@@ -563,7 +766,6 @@"bGIAle": "Mitglieder ({count})","hQZhn8": "Identität annehmen","2ZpsMl": "Keine Mitglieder",- "G/yZLu": "Entfernen","nJuUfX": "Nach Name, Slug, Domain oder Mitglieds-E-Mail suchen...","RllRQH": "Organisationen mit 0 Events (30d) anzeigen","7OL11E": "Nur über Limit",@@ -578,7 +780,6 @@"uL0dMG": "Dienstweite Nutzung - Letzte {timePeriod}","SVwJTM": "Exportieren","K56Dim": "Organisation",- "ORGv1Q": "Erstellt","JKxOsh": "Monatliche Events","R/6nsx": "Abonnement","DDhP4z": "Websites",@@ -596,8 +797,6 @@"viXE32": "Privat","6hdNA5": "Ereignisse (24 Std.)","J4r/Gi": "Ereignisse (30 Tage)",- "Zh+5A6": "Ein",- "OvzONl": "Aus","C2EM7h": "Inhaber-E-Mail","sEqhTf": "Website-Daten konnten nicht geladen werden. Bitte versuchen Sie es später erneut.","r9Y1x6": "Nach Domain oder Inhaber-E-Mail suchen...",@@ -626,7 +825,6 @@"uA0DvF": "Benutzer konnte nicht aus Organisation entfernt werden","PW+sL4": "k.A.","wittYy": "Erstellt am",- "wL7VAE": "Aktionen","bdcMGy": "Menü öffnen","6gHGy0": "Aus Organisation entfernen","J2wna+": "Benutzer aus Organisation entfernen?",@@ -744,19 +942,16 @@"u4673k": "Generieren Sie API-Schlüssel für den Zugriff auf Analyse-Endpunkte aus Ihren Anwendungen","1fe3VI": "API-Schlüssel sind in den Standard- und Pro-Plänen verfügbar.","AkVL9j": "API-Schlüsselname",- "mRL9Vh": "Wird erstellt...","jDvHYJ": "Ihre API-Schlüssel","MUaUWe": "API-Schlüssel werden geladen...","iX4wwR": "API-Schlüssel konnten nicht geladen werden","62nsdy": "Erneut versuchen",- "EcglP9": "Schlüssel","IY105q": "Noch keine API-Schlüssel erstellt","wPtCEB": "API-Schlüssel erstellt","qcTCG8": "Bewahren Sie diesen API-Schlüssel sicher auf. Sie können ihn nicht erneut anzeigen.","51jo4g": "Ihr API-Schlüssel","+fICx5": "Wichtig","TsKkxv": "Bewahren Sie diesen Schlüssel sicher auf. Er wird nicht erneut angezeigt.",- "JXdbo8": "Fertig","LuNBqj": "Passwort sollte mindestens 8 Zeichen lang sein","UjlqkD": "Starkes Passwort","EK3962": "Gutes Passwort",@@ -886,7 +1081,6 @@"S5IFjk": "Erstellen Sie ein Team, um Websites zu gruppieren und den Mitgliederzugriff zu verwalten.","StUScz": "{count} Mitglieder","RNCPOG": "Registrierung",- "acrOoz": "Weiter","uCk8r+": "Haben Sie bereits ein Konto?","odXlk8": "Anmelden","uWRAQk": "Wählen Sie Ihren Plan",@@ -996,7 +1190,6 @@"W5IIP8": "Upgrade auf {planName}, um {message} freizuschalten","4Y+tpi": "Demo dieser Funktion ansehen","RL7HbL": "Bitten Sie Ihren Organisationsinhaber, auf Pro upzugraden, um {message} freizuschalten",- "QashlR": "Beim Abrufen der Daten ist ein Fehler aufgetreten","jsy7pk": "Erneut versuchen","hyfdry": "Seitenaufruf","/kZg9i": "Klick auf Schaltfläche",@@ -1196,7 +1389,6 @@"jjBvFh": "Ausschlüsse","6cBDhe": "Integrationen","IP4n+n": "Widget-Einbettungen",- "rbrahO": "Schließen","scL+IP": "Widget aktiviert","8pKlHk": "Einbettungs-Widget aktivieren","mhmZ+P": "Sitzungsaufzeichnung",@@ -1243,7 +1435,6 @@"u/vOPu": "Bezahlt","jHfCjd": "Ungültig","45hFQt": "Uneinbringlich",- "W6nwjo": "Entwurf","6dqYnF": "Rechnungen","P7PLVj": "Datum","/0TOL5": "Betrag",diff --git a/client/messages/en.json b/client/messages/en.jsonindex 1226dd0fe..714adce97 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -61,6 +61,7 @@"mByYl9": "Pageviews %","IuFETn": "Duration","0eoYsu": "Bounce Rate",+ "QashlR": "An error occurred while fetching data","IxrHg4": "Filter {count} items...","tL4WC1": "Loading more...","HPx76n": "All items loaded",@@ -74,6 +75,8 @@"XHLYdJ": "Goals","9d/EEp": "Product Analytics","5yUsUe": "Replay",+ "mZDrWI": "Feature Flags",+ "5qmtY1": "Experiments","puhcpn": "Funnels","08hqOd": "Journeys","nL6Jl0": "Retention",@@ -242,6 +245,212 @@"BReFYW": "Input Changes","NDoUa9": "All event types hidden","MJ2jZQ": "Total",+ "jZu+25": "Define the question",+ "l31E69": "Start with the behavior you want to change and the metric you expect to move.",+ "E/9k/a": "The hypothesis is internal context for your team. It does not change assignment or tracking.",+ "yl0JSO": "Changing these notes does not change assignment or tracking.",+ "gyIvpP": "New experiments are created as drafts so you can add the implementation before starting traffic.",+ "z2PIbo": "Create the assignment",+ "zZE+e+": "Experiments use multivariate feature flags to assign each visitor to one stable variant.",+ "c6cv5o": "Calling rybbit.flag records the exposure that powers experiment results.",+ "U3UQfB": "A full split should add up to 100 percent unless you intentionally want unassigned traffic.",+ "f5efCD": "Pick the outcome",+ "SDTG4X": "The primary goal is the conversion event or page visit used to compare variants.",+ "z0076i": "Path goals work when conversion is a URL, like /thank-you. Event goals work for explicit actions.",+ "iKhvJV": "You can skip this for now, but conversion results need a goal later.",+ "XocxqF": "Implement and expose",+ "dv+Q6J": "Use the generated flag key in your app and branch your UI or behavior by variant.",+ "rYzinM": "Read the flag in code before rendering the tested experience.",+ "qkaC6i": "For event goals, fire the event when the conversion action happens.",+ "Gvxoji": "Name is required",+ "C4BsF8": "Choose a multivariate feature flag",+ "CZmGBZ": "Flag key is required",+ "9VDOG/": "Add at least two variants",+ "k/CG+N": "Variant keys are required",+ "dSrAoR": "Variant keys must be unique",+ "/ZZy+J": "Variant traffic must add up to 100%",+ "PqvkpE": "Choose a goal",+ "VUiN28": "Path pattern is required",+ "VYRbh1": "Event name is required",+ "DSOKGF": "Experiment created",+ "ERZKPw": "Failed to save experiment",+ "4gDkIw": "Experiment updated",+ "5CbP3g": "Experiment name",+ "ANmBWb": "Checkout CTA test",+ "iBImEo": "Hypothesis",+ "JfUnvy": "Changing the CTA copy will increase signup conversions.",+ "Q8Qw5B": "Description",+ "Yx6aRS": "Optional notes for this experiment",+ "F4tWun": "Create a new flag",+ "rv+WdZ": "Best for a new experiment that needs its own assignment split.",+ "8mBWZJ": "Use an existing flag",+ "2Rli0c": "Choose a multivariate flag that is not already connected to an experiment.",+ "2S4QtW": "Assignment flag",+ "6bhRx4": "Select a flag",+ "3kwz2Z": "No unused multivariate flags are available. Create a new flag for this experiment.",+ "O6zCyZ": "Flag key",+ "LICoyV": "Flag description",+ "NFTkNB": "Assignment flag for this experiment",+ "h5P++h": "Variants",+ "1HsqR2": "{rolloutTotal}% assigned",+ "JWzoaP": "variant",+ "dOQCL8": "Display name",+ "MYsZNO": "Remove variant",+ "5U2wOH": "Add variant",+ "nDvQwt": "Create a new goal",+ "dCxCGt": "Define the conversion while creating the experiment.",+ "I5k4g/": "Use existing",+ "8O/fqy": "Connect this experiment to a goal you already track.",+ "WYzHAI": "Skip for now",+ "gpx4DX": "Create the experiment now and add a goal later.",+ "wIRNFx": "Primary goal",+ "UHg01d": "Select a goal",+ "FYBPJU": "Goal #{goalId}",+ "93jr/b": "Goal name",+ "WCs0QZ": "Signup completed",+ "VUomb6": "Page goal",+ "9E7Zda": "Count sessions that reach a URL path.",+ "99HM2b": "Event goal",+ "S4zxrU": "Count sessions where your app fires a named event.",+ "XQSLMK": "Path pattern",+ "eOj4Bs": "Event name",+ "sXo0km": "Experiment created as a draft",+ "qWzbG9": "Experiment changes saved",+ "pH6sDe": "Add this code to your app, then start the experiment from the list when you are ready.",+ "TUwf1V": "Variant implementation",+ "vmlGzW": "Conversion event",+ "Dmxerh": "No conversion event code is needed for this path goal. Rybbit will count sessions that reach {goalLabel}.",+ "wzKC2G": "Add a primary goal later to calculate conversions for each variant.",+ "itC9lG": "Basics",+ "XPX/Qj": "Assignment",+ "0VV/sK": "Goal",+ "dLj+dT": "Implement",+ "Lu6+QS": "Edit experiment",+ "qdOqu/": "Create experiment",+ "tGuKrF": "New experiment",+ "W6nwjo": "Draft",+ "LHF3Za": "Existing",+ "47FYwb": "Cancel",+ "rbrahO": "Close",+ "cyR7Kh": "Back",+ "TiR/Hq": "Saving...",+ "mRL9Vh": "Creating...",+ "X0ha1a": "Save changes",+ "JXdbo8": "Done",+ "acrOoz": "Continue",+ "H+vBOj": "Winner",+ "1SjAqf": "Leading",+ "NZ9+vv": "Control",+ "UAVBcs": "{sessions} sessions · {conversions} conv.",+ "QFTqtX": "Baseline",+ "ytceSa": "No goal connected",+ "vGMvPS": "Add a primary goal to measure conversions for each variant.",+ "XQ/KBk": "Winner: {variant}",+ "jt9BUv": "No conversions yet",+ "nW9O3w": "{variant} leading",+ "cT4fRl": "No clear winner",+ "EHoeo0": "Gathering data",+ "ttyUm0": "{sessions} sessions · {conversions} conversions",+ "l94vPo": "{confidence}% confidence",+ "qQTwNl": "Not yet significant",+ "IuPATc": "Showing assigned visitors. Call rybbit.flag(\"{flagKey}\") where the variant renders to measure visitors actually exposed to it.",+ "W1QsrY": "No goal",+ "UBQJK/": "Untitled goal",+ "4IJvOg": "Ended {time}",+ "iHip8n": "Started {time}",+ "kNp7lL": "Created {time}",+ "VK7C0v": "Delete this experiment?",+ "G2HskF": "Experiment deleted",+ "l6cRsG": "Failed to delete experiment",+ "6MkXA0": "Failed to update experiment",+ "mOFG3K": "Start",+ "tFFMkF": "Pause",+ "U78NhE": "Complete",+ "wL7VAE": "Actions",+ "wEQDC6": "Edit",+ "K3r6DQ": "Delete",+ "poMLbD": "Filter experiments",+ "qzqYO3": "No experiments found",+ "4YGHzj": "No experiments match \"{search}\"",+ "l2og1o": "No experiments yet",+ "wLuWPJ": "Create an experiment from a multivariate feature flag and connect it to a conversion goal.",+ "39mVGa": "Targeted configs",+ "sL8dAy": "Release conditions",+ "U5hCuK": "Each condition returns its own payload. The first match wins.",+ "wmdo1a": "Each condition is evaluated in order. The first match wins.",+ "fg8dzN": "Add condition",+ "Rp+Vr1": "Condition name",+ "lKv8ex": "Default",+ "wmFdws": "Move up",+ "H/r5m6": "Move down",+ "G/yZLu": "Remove",+ "7/7DdD": "Config payload",+ "Cn4/rZ": "Payload",+ "Vwukkb": "Add JSON payload",+ "d1OgED": "(optional)",+ "rdE5Ca": "Rollout",+ "CoSEZb": "everyone matched",+ "obVxeM": "no one",+ "GeY2EU": "{pct}% of matched users",+ "9ctGsY": "Feature flag updated",+ "Ctj1re": "Feature flag created",+ "TFVlrR": "Failed to save feature flag",+ "TI5GPL": "Returns true or false",+ "5kpx3b": "Split traffic across keys",+ "I4Etgx": "Return a JSON payload",+ "n5XyC0": "This flag is evaluated server-side. Call the evaluate API from your backend instead of the browser script.",+ "+9SBpl": "This flag also evaluates server-side. Your backend can read it from the evaluate API.",+ "rHJwM0": "Edit feature flag {key}",+ "jTMl6R": "Create feature flag",+ "2Nj3gm": "Edit flag",+ "bAv8xK": "New flag",+ "Dn82AL": "Live",+ "C2iTEH": "Paused",+ "gnvAJX": "The identifier you'll reference in code",+ "IX0C9y": "Feature flag changes saved",+ "4QGk64": "Read this flag in your app to control behavior for your visitors.",+ "wbsq7O": "Usage",+ "WuGkfJ": "Returns",+ "E/O9LL": "Optional — describe what this flag controls",+ "V52jNn": "Enabled",+ "66kGA0": "Runtime",+ "vPG+A7": "Create flag",+ "+R0VMp": "Delete this feature flag?",+ "q2ZLFN": "Feature flag deleted",+ "rxCN7M": "Failed to delete feature flag",+ "bSCV9J": "Flag",+ "tzMNF3": "Status",+ "Zh+5A6": "On",+ "OvzONl": "Off",+ "kAAlGL": "Rules",+ "ZDpTud": "Traffic",+ "ORGv1Q": "Created",+ "xrk6zg": "Updated",+ "9qBH5R": "No feature flags found",+ "10IQpb": "Targeting rules",+ "gzM1em": "Add rule",+ "V+QgiY": "Applies to everyone — add a rule to narrow targeting",+ "3mvL2Q": "and",+ "AbvQFb": "Field",+ "EcglP9": "Key",+ "gzX6Vt": "key",+ "7CyD7e": "value",+ "LzfPAG": "Variant key",+ "HcAcrp": "variant_key",+ "J4E+jp": "Variant name",+ "DIZgr3": "Boolean",+ "lu/vDB": "Multiple variants",+ "9uKBh7": "Remote config",+ "JX0502": "Client",+ "F/6VqP": "Server",+ "oA0ogD": "Both",+ "4ZtLoe": "Pathname",+ "rWPtv+": "Query parameter",+ "VJWJyq": "Device type",+ "3tP/PN": "User trait",+ "jhVKvF": "Does not equal",+ "SBUMrd": "Filter feature flags",+ "wsKkfk": "No feature flags yet","z6IYcX": "All steps must have values","jm52QG": "Please enter a funnel name","+N7isb": "Funnel saved successfully",@@ -273,7 +482,6 @@"+U6ozc": "Type","m1czzY": "Event","Y6DkLY": "Path (e.g. /pricing)",- "eOj4Bs": "Event name","Hp/0iW": "Enter a path (e.g., /checkout), not a full URL.","Asi2Jg": "Hide advanced options","lIEejV": "Show advanced options",@@ -287,8 +495,6 @@"tINfvW": "Use * to match a single path segment (e.g., /blog/*) or ** to match multiple segments (e.g., /docs/**/intro)","ox304v": "An error occurred","KbGBQH": "An error occurred while saving",- "47FYwb": "Cancel",- "TiR/Hq": "Saving...","/liMUf": "Funnel deleted successfully","753yX5": "Label","+SDMR3": "Property",@@ -298,7 +504,6 @@"SB3+JE": "No funnel data available","45gABM": "Are you sure you want to delete \"{name}\"? This action cannot be undone.","noZdV2": "Deleting...",- "K3r6DQ": "Delete","GoxzAN": "Filter funnels","qGN7M9": "Failed to load funnels","5/6deG": "There was a problem fetching the funnels. Please try again later.",@@ -328,16 +533,15 @@"h3ICzV": "Loading sessions...","KjXPXZ": "{count} sessions","9iSdEj": "{count} session",- "tFFMkF": "Pause","J3ca41": "Play","Ggedt8": "Showing only the first {count} sessions. More data may be available.","5WuADX": "Add Goal",+ "WuHoZ9": "Conversions",+ "e/U0Xt": "Conversion Rate","+Ior19": "Page Goal","rTE34i": "Event Goal",- "FYBPJU": "Goal #{goalId}","pW4lxD": "Pattern",- "WuHoZ9": "Conversions",- "e/U0Xt": "Conversion Rate",+ "99Lkvz": "Goal actions","sOXElg": "Edit Goal","N/ctXb": "Clone Goal","F3XA9+": "Delete Goal",@@ -395,10 +599,10 @@"zuqMfZ": "Map","jUSc45": "Timezones","NdE4Ps": "Browsers",+ "/VnDMl": "Other","+20FW7": "Devices","aTW7It": "Operating Systems","3X4r56": "Screen Dimensions",- "/VnDMl": "Other","Aujn2T": "Count","ogKEiU": "Outbound Links","VLKK35": "Clicks",@@ -407,13 +611,14 @@"pEc/5k": "Click %","wU7PzI": "Last Clicked","4KEfRY": "Titles",- "87ZCAe": "Entries",- "0ogV14": "Exits",- "P6RGqE": "Hostnames","gvOzOl": "Page Title",+ "87ZCAe": "Entries","vFf5xV": "Entry Pages",+ "0ogV14": "Exits","KtC97P": "Exit Pages",+ "P6RGqE": "Hostnames","iF/x8v": "Referrers",+ "UF6kPm": "Direct","LUrJwE": "Channels","aH4De2": "Source","ovJ26C": "Medium",@@ -421,7 +626,6 @@"qTy5se": "Term","Jq3FDz": "Content","grtbAW": "UTM",- "UF6kPm": "Direct","0E9k6Y": "Connect your Google Search Console account to view search performance data including top keywords and pages.","jioGL4": "Connect Google Search Console","M/h5TN": "Impressions",@@ -550,7 +754,6 @@"uiy9pN": "30d Events","9juexR": "Subscription Details","fz0z4c": "Plan",- "tzMNF3": "Status","T8qVXf": "Event Limit","ekXood": "Unlimited","5x9Sl1": "Period End",@@ -563,7 +766,6 @@"bGIAle": "Members ({count})","hQZhn8": "Impersonate","2ZpsMl": "No members",- "G/yZLu": "Remove","nJuUfX": "Search by name, slug, domain, or member email...","RllRQH": "Show orgs with 0 events (30d)","7OL11E": "Only over limit",@@ -578,7 +780,6 @@"uL0dMG": "Service-wide Usage - Last {timePeriod}","SVwJTM": "Export","K56Dim": "Organization",- "ORGv1Q": "Created","JKxOsh": "Monthly Events","R/6nsx": "Subscription","DDhP4z": "Sites",@@ -596,8 +797,6 @@"viXE32": "Private","6hdNA5": "Events (24h)","J4r/Gi": "Events (30d)",- "Zh+5A6": "On",- "OvzONl": "Off","C2EM7h": "Owner Email","sEqhTf": "Failed to load sites data. Please try again later.","r9Y1x6": "Search by domain or owner email...",@@ -626,7 +825,6 @@"uA0DvF": "Failed to remove user from organization","PW+sL4": "N/A","wittYy": "Created At",- "wL7VAE": "Actions","bdcMGy": "Open menu","6gHGy0": "Remove from Organization","J2wna+": "Remove user from organization?",@@ -744,19 +942,16 @@"u4673k": "Generate API keys to access analytics endpoints from your applications","1fe3VI": "API keys are available on Standard and Pro plans.","AkVL9j": "API Key Name",- "mRL9Vh": "Creating...","jDvHYJ": "Your API Keys","MUaUWe": "Loading API keys...","iX4wwR": "Failed to load API keys","62nsdy": "Retry",- "EcglP9": "Key","IY105q": "No API keys created yet","wPtCEB": "API Key Created","qcTCG8": "Save this API key securely. You won't be able to see it again.","51jo4g": "Your API Key","+fICx5": "Important","TsKkxv": "Store this key securely. It won't be displayed again.",- "JXdbo8": "Done","LuNBqj": "Password should be at least 8 characters","UjlqkD": "Strong password","EK3962": "Good password",@@ -886,7 +1081,6 @@"S5IFjk": "Create a team to group sites and manage member access.","StUScz": "{count} members","RNCPOG": "Signup",- "acrOoz": "Continue","uCk8r+": "Already have an account?","odXlk8": "Log in","uWRAQk": "Choose your plan",@@ -996,7 +1190,6 @@"W5IIP8": "Upgrade to {planName} to unlock {message}","4Y+tpi": "See a demo of this feature","RL7HbL": "Ask your organization owner to upgrade to Pro to unlock {message}",- "QashlR": "An error occurred while fetching data","jsy7pk": "Try Again","hyfdry": "Pageview","/kZg9i": "Button Click",@@ -1196,7 +1389,6 @@"jjBvFh": "Exclusions","6cBDhe": "Integrations","IP4n+n": "Widget Embeds",- "rbrahO": "Close","scL+IP": "Widget Enabled","8pKlHk": "Enable Embed Widget","mhmZ+P": "Session Replay",@@ -1243,7 +1435,6 @@"u/vOPu": "Paid","jHfCjd": "Void","45hFQt": "Uncollectible",- "W6nwjo": "Draft","6dqYnF": "Invoices","P7PLVj": "Date","/0TOL5": "Amount",diff --git a/client/messages/es.json b/client/messages/es.jsonindex abf929c71..cf6551fd0 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -61,6 +61,7 @@"mByYl9": "% Visitas","IuFETn": "Duración","0eoYsu": "Tasa de rebote",+ "QashlR": "Ocurrió un error al obtener datos","IxrHg4": "Filtrar {count} elementos...","tL4WC1": "Cargando más...","HPx76n": "Todos los elementos cargados",@@ -74,6 +75,8 @@"XHLYdJ": "Objetivos","9d/EEp": "Analíticas de Producto","5yUsUe": "Repetición",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Embudos","08hqOd": "Viajes","nL6Jl0": "Retención",@@ -242,6 +245,212 @@"BReFYW": "Cambios de entrada","NDoUa9": "Todos los tipos de eventos ocultos","MJ2jZQ": "Total",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Objetivo #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Nombre del evento",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Borrador",+ "LHF3Za": "",+ "47FYwb": "Cancelar",+ "rbrahO": "Cerrar",+ "cyR7Kh": "",+ "TiR/Hq": "Guardando...",+ "mRL9Vh": "Creando...",+ "X0ha1a": "",+ "JXdbo8": "Hecho",+ "acrOoz": "Continuar",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pausa",+ "U78NhE": "",+ "wL7VAE": "Acciones",+ "wEQDC6": "",+ "K3r6DQ": "Eliminar",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Eliminar",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Estado",+ "Zh+5A6": "Activado",+ "OvzONl": "Desactivado",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Creado",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Clave",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Todos los pasos deben tener valores","jm52QG": "Por favor, introduce un nombre para el embudo","+N7isb": "Embudo guardado correctamente",@@ -273,7 +482,6 @@"+U6ozc": "Tipo","m1czzY": "Evento","Y6DkLY": "Ruta (ej. /precios)",- "eOj4Bs": "Nombre del evento","Hp/0iW": "Introduce una ruta (ej. /pago), no una URL completa.","Asi2Jg": "Ocultar opciones avanzadas","lIEejV": "Mostrar opciones avanzadas",@@ -287,8 +495,6 @@"tINfvW": "Usa * para coincidir con un segmento de ruta (ej. /blog/*) o ** para múltiples segmentos (ej. /docs/**/intro)","ox304v": "Ocurrió un error","KbGBQH": "Ocurrió un error al guardar",- "47FYwb": "Cancelar",- "TiR/Hq": "Guardando...","/liMUf": "Embudo eliminado correctamente","753yX5": "Etiqueta","+SDMR3": "Propiedad",@@ -298,7 +504,6 @@"SB3+JE": "No hay datos de embudo disponibles","45gABM": "¿Estás seguro de que quieres eliminar \"{name}\"? Esta acción no se puede deshacer.","noZdV2": "Eliminando...",- "K3r6DQ": "Eliminar","GoxzAN": "Filtrar embudos","qGN7M9": "Error al cargar embudos","5/6deG": "Hubo un problema al obtener los embudos. Inténtalo de nuevo más tarde.",@@ -328,16 +533,15 @@"h3ICzV": "Cargando sesiones...","KjXPXZ": "{count} sesiones","9iSdEj": "{count} sesión",- "tFFMkF": "Pausa","J3ca41": "Reproducir","Ggedt8": "Mostrando solo las primeras {count} sesiones. Es posible que haya más datos disponibles.","5WuADX": "Añadir objetivo",+ "WuHoZ9": "Conversiones",+ "e/U0Xt": "Tasa de conversión","+Ior19": "Objetivo de página","rTE34i": "Objetivo de evento",- "FYBPJU": "Objetivo #{goalId}","pW4lxD": "Patrón",- "WuHoZ9": "Conversiones",- "e/U0Xt": "Tasa de conversión",+ "99Lkvz": "","sOXElg": "Editar objetivo","N/ctXb": "Clonar objetivo","F3XA9+": "Eliminar objetivo",@@ -395,10 +599,10 @@"zuqMfZ": "Mapa","jUSc45": "Zonas horarias","NdE4Ps": "Navegadores",+ "/VnDMl": "Otros","+20FW7": "Dispositivos","aTW7It": "Sistemas operativos","3X4r56": "Dimensiones de la pantalla",- "/VnDMl": "Otros","Aujn2T": "Recuento","ogKEiU": "Enlaces salientes","VLKK35": "Clics",@@ -407,13 +611,14 @@"pEc/5k": "% Clic","wU7PzI": "Último clic","4KEfRY": "Títulos",- "87ZCAe": "Entradas",- "0ogV14": "Salidas",- "P6RGqE": "Nombres de host","gvOzOl": "Título de la página",+ "87ZCAe": "Entradas","vFf5xV": "Páginas de entrada",+ "0ogV14": "Salidas","KtC97P": "Páginas de salida",+ "P6RGqE": "Nombres de host","iF/x8v": "Referidores",+ "UF6kPm": "Directo","LUrJwE": "Canales","aH4De2": "Fuente","ovJ26C": "Medio",@@ -421,7 +626,6 @@"qTy5se": "Término","Jq3FDz": "Contenido","grtbAW": "UTM",- "UF6kPm": "Directo","0E9k6Y": "Conecta tu cuenta de Google Search Console para ver datos de rendimiento de búsqueda incluyendo palabras clave principales y páginas.","jioGL4": "Conectar Google Search Console","M/h5TN": "Impresiones",@@ -550,7 +754,6 @@"uiy9pN": "Eventos 30d","9juexR": "Detalles de la suscripción","fz0z4c": "Plan",- "tzMNF3": "Estado","T8qVXf": "Límite de eventos","ekXood": "Ilimitado","5x9Sl1": "Fin del periodo",@@ -563,7 +766,6 @@"bGIAle": "Miembros ({count})","hQZhn8": "Suplantar","2ZpsMl": "No hay miembros",- "G/yZLu": "Eliminar","nJuUfX": "Buscar por nombre, slug, dominio o correo de miembro...","RllRQH": "Mostrar organizaciones con 0 eventos (30d)","7OL11E": "Solo sobre el límite",@@ -578,7 +780,6 @@"uL0dMG": "Uso de todo el servicio - Últimos {timePeriod}","SVwJTM": "Exportar","K56Dim": "Organización",- "ORGv1Q": "Creado","JKxOsh": "Eventos mensuales","R/6nsx": "Suscripción","DDhP4z": "Sitios",@@ -596,8 +797,6 @@"viXE32": "Privado","6hdNA5": "Eventos (24h)","J4r/Gi": "Eventos (30d)",- "Zh+5A6": "Activado",- "OvzONl": "Desactivado","C2EM7h": "Correo del propietario","sEqhTf": "Error al cargar los datos de sitios. Inténtalo de nuevo más tarde.","r9Y1x6": "Buscar por dominio o correo del propietario...",@@ -626,7 +825,6 @@"uA0DvF": "Error al eliminar usuario de la organización","PW+sL4": "N/A","wittYy": "Creado el",- "wL7VAE": "Acciones","bdcMGy": "Abrir menú","6gHGy0": "Eliminar de la organización","J2wna+": "¿Eliminar usuario de la organización?",@@ -744,19 +942,16 @@"u4673k": "Genera claves de API para acceder a los endpoints de analíticas desde tus aplicaciones","1fe3VI": "Las claves de API están disponibles en los planes Standard y Pro.","AkVL9j": "Nombre de la clave de API",- "mRL9Vh": "Creando...","jDvHYJ": "Tus claves de API","MUaUWe": "Cargando claves de API...","iX4wwR": "Error al cargar claves de API","62nsdy": "Reintentar",- "EcglP9": "Clave","IY105q": "No se han creado claves de API aún","wPtCEB": "Clave de API creada","qcTCG8": "Guarda esta clave de API de forma segura. No podrás volver a verla.","51jo4g": "Tu clave de API","+fICx5": "Importante","TsKkxv": "Guarda esta clave de forma segura. No se mostrará de nuevo.",- "JXdbo8": "Hecho","LuNBqj": "La contraseña debe tener al menos 8 caracteres","UjlqkD": "Contraseña fuerte","EK3962": "Contraseña buena",@@ -886,7 +1081,6 @@"S5IFjk": "Crea un equipo para agrupar sitios y administrar el acceso de los miembros.","StUScz": "{count} miembros","RNCPOG": "Registro",- "acrOoz": "Continuar","uCk8r+": "¿Ya tienes una cuenta?","odXlk8": "Iniciar sesión","uWRAQk": "Elige tu plan",@@ -996,7 +1190,6 @@"W5IIP8": "Actualiza a {planName} para desbloquear {message}","4Y+tpi": "Ver una demostración de esta función","RL7HbL": "Pide al propietario de tu organización que actualice a Pro para desbloquear {message}",- "QashlR": "Ocurrió un error al obtener datos","jsy7pk": "Intentar de nuevo","hyfdry": "Vista de página","/kZg9i": "Clic en botón",@@ -1196,7 +1389,6 @@"jjBvFh": "Exclusiones","6cBDhe": "Integraciones","IP4n+n": "Inserciones de Widget",- "rbrahO": "Cerrar","scL+IP": "Widget Activado","8pKlHk": "Habilitar Widget de Inserción","mhmZ+P": "Repetición de Sesión",@@ -1243,7 +1435,6 @@"u/vOPu": "Pagada","jHfCjd": "Anulada","45hFQt": "Incobrable",- "W6nwjo": "Borrador","6dqYnF": "Facturas","P7PLVj": "Fecha","/0TOL5": "Monto",diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex 24befd5c7..57f2c044e 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -61,6 +61,7 @@"mByYl9": "Pages vues %","IuFETn": "Durée","0eoYsu": "Taux de rebond",+ "QashlR": "Une erreur est survenue lors de la récupération des données","IxrHg4": "Filtrer {count} éléments...","tL4WC1": "Chargement en cours...","HPx76n": "Tous les éléments chargés",@@ -74,6 +75,8 @@"XHLYdJ": "Objectifs","9d/EEp": "Analyse produit","5yUsUe": "Replay",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Entonnoirs","08hqOd": "Parcours","nL6Jl0": "Rétention",@@ -242,6 +245,212 @@"BReFYW": "Changements de saisie","NDoUa9": "Tous les types d'événements masqués","MJ2jZQ": "Total",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Objectif #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Nom de l'événement",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Brouillon",+ "LHF3Za": "",+ "47FYwb": "Annuler",+ "rbrahO": "Fermer",+ "cyR7Kh": "",+ "TiR/Hq": "Enregistrement en cours...",+ "mRL9Vh": "Création en cours...",+ "X0ha1a": "",+ "JXdbo8": "Terminé",+ "acrOoz": "Continuer",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pause",+ "U78NhE": "",+ "wL7VAE": "Actions",+ "wEQDC6": "",+ "K3r6DQ": "Supprimer",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Supprimer",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Statut",+ "Zh+5A6": "Activé",+ "OvzONl": "Désactivé",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Créé",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Clé",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Toutes les étapes doivent avoir des valeurs","jm52QG": "Veuillez saisir un nom d'entonnoir","+N7isb": "Entonnoir enregistré avec succès",@@ -273,7 +482,6 @@"+U6ozc": "Type","m1czzY": "Événement","Y6DkLY": "Chemin (ex. /pricing)",- "eOj4Bs": "Nom de l'événement","Hp/0iW": "Saisissez un chemin (ex. /checkout), pas une URL complète.","Asi2Jg": "Masquer les options avancées","lIEejV": "Afficher les options avancées",@@ -287,8 +495,6 @@"tINfvW": "Utilisez * pour un seul segment de chemin (ex. /blog/*) ou ** pour plusieurs segments (ex. /docs/**/intro)","ox304v": "Une erreur est survenue","KbGBQH": "Une erreur est survenue lors de l'enregistrement",- "47FYwb": "Annuler",- "TiR/Hq": "Enregistrement en cours...","/liMUf": "Entonnoir supprimé avec succès","753yX5": "Libellé","+SDMR3": "Propriété",@@ -298,7 +504,6 @@"SB3+JE": "Aucune donnée d'entonnoir disponible","45gABM": "Êtes-vous sûr de vouloir supprimer \"{name}\" ? Cette action est irréversible.","noZdV2": "Suppression en cours...",- "K3r6DQ": "Supprimer","GoxzAN": "Filtrer les entonnoirs","qGN7M9": "Échec du chargement des entonnoirs","5/6deG": "Un problème est survenu lors de la récupération des entonnoirs. Veuillez réessayer plus tard.",@@ -328,16 +533,15 @@"h3ICzV": "Chargement des sessions...","KjXPXZ": "{count} sessions","9iSdEj": "{count} session",- "tFFMkF": "Pause","J3ca41": "Lecture","Ggedt8": "Affichage des {count} premières sessions uniquement. D'autres données peuvent être disponibles.","5WuADX": "Ajouter un objectif",+ "WuHoZ9": "Conversions",+ "e/U0Xt": "Taux de conversion","+Ior19": "Objectif de page","rTE34i": "Objectif d'événement",- "FYBPJU": "Objectif #{goalId}","pW4lxD": "Modèle",- "WuHoZ9": "Conversions",- "e/U0Xt": "Taux de conversion",+ "99Lkvz": "","sOXElg": "Modifier l'objectif","N/ctXb": "Dupliquer l'objectif","F3XA9+": "Supprimer l'objectif",@@ -395,10 +599,10 @@"zuqMfZ": "Carte","jUSc45": "Fuseaux horaires","NdE4Ps": "Navigateurs",+ "/VnDMl": "Autre","+20FW7": "Appareils","aTW7It": "Systèmes d'exploitation","3X4r56": "Résolutions d'écran",- "/VnDMl": "Autre","Aujn2T": "Nombre","ogKEiU": "Liens sortants","VLKK35": "Clics",@@ -407,13 +611,14 @@"pEc/5k": "Clic %","wU7PzI": "Dernier clic","4KEfRY": "Titres",- "87ZCAe": "Entrées",- "0ogV14": "Sorties",- "P6RGqE": "Noms d'hôte","gvOzOl": "Titre de la page",+ "87ZCAe": "Entrées","vFf5xV": "Pages d'entrée",+ "0ogV14": "Sorties","KtC97P": "Pages de sortie",+ "P6RGqE": "Noms d'hôte","iF/x8v": "Référents",+ "UF6kPm": "Direct","LUrJwE": "Canaux","aH4De2": "Source","ovJ26C": "Moyen",@@ -421,7 +626,6 @@"qTy5se": "Terme","Jq3FDz": "Contenu","grtbAW": "UTM",- "UF6kPm": "Direct","0E9k6Y": "Connectez votre compte Google Search Console pour voir les données de performance de recherche, y compris les meilleurs mots-clés et pages.","jioGL4": "Connecter Google Search Console","M/h5TN": "Impressions",@@ -550,7 +754,6 @@"uiy9pN": "Événements 30j","9juexR": "Détails de l'abonnement","fz0z4c": "Forfait",- "tzMNF3": "Statut","T8qVXf": "Limite d'événements","ekXood": "Illimité","5x9Sl1": "Fin de période",@@ -563,7 +766,6 @@"bGIAle": "Membres ({count})","hQZhn8": "Usurper l'identité","2ZpsMl": "Aucun membre",- "G/yZLu": "Supprimer","nJuUfX": "Rechercher par nom, slug, domaine ou e-mail de membre...","RllRQH": "Afficher les org. avec 0 événement (30j)","7OL11E": "Uniquement au-dessus de la limite",@@ -578,7 +780,6 @@"uL0dMG": "Utilisation globale du service - {timePeriod} derniers","SVwJTM": "Exporter","K56Dim": "Organisation",- "ORGv1Q": "Créé","JKxOsh": "Événements mensuels","R/6nsx": "Abonnement","DDhP4z": "Sites",@@ -596,8 +797,6 @@"viXE32": "Privé","6hdNA5": "Événements (24h)","J4r/Gi": "Événements (30j)",- "Zh+5A6": "Activé",- "OvzONl": "Désactivé","C2EM7h": "E-mail du propriétaire","sEqhTf": "Échec du chargement des données de sites. Veuillez réessayer plus tard.","r9Y1x6": "Rechercher par domaine ou e-mail du propriétaire...",@@ -626,7 +825,6 @@"uA0DvF": "Échec du retrait de l'utilisateur de l'organisation","PW+sL4": "N/A","wittYy": "Créé le",- "wL7VAE": "Actions","bdcMGy": "Ouvrir le menu","6gHGy0": "Retirer de l'organisation","J2wna+": "Retirer l'utilisateur de l'organisation ?",@@ -744,19 +942,16 @@"u4673k": "Générez des clés API pour accéder aux points d'accès analytiques depuis vos applications","1fe3VI": "Les clés API sont disponibles avec les forfaits Standard et Pro.","AkVL9j": "Nom de la clé API",- "mRL9Vh": "Création en cours...","jDvHYJ": "Vos clés API","MUaUWe": "Chargement des clés API...","iX4wwR": "Échec du chargement des clés API","62nsdy": "Réessayer",- "EcglP9": "Clé","IY105q": "Aucune clé API créée pour le moment","wPtCEB": "Clé API créée","qcTCG8": "Conservez cette clé API en lieu sûr. Vous ne pourrez plus la revoir.","51jo4g": "Votre clé API","+fICx5": "Important","TsKkxv": "Conservez cette clé en lieu sûr. Elle ne sera plus affichée.",- "JXdbo8": "Terminé","LuNBqj": "Le mot de passe doit contenir au moins 8 caractères","UjlqkD": "Mot de passe fort","EK3962": "Bon mot de passe",@@ -886,7 +1081,6 @@"S5IFjk": "Créez une équipe pour regrouper les sites et gérer l'accès des membres.","StUScz": "{count} membres","RNCPOG": "Inscription",- "acrOoz": "Continuer","uCk8r+": "Vous avez déjà un compte ?","odXlk8": "Se connecter","uWRAQk": "Choisissez votre plan",@@ -996,7 +1190,6 @@"W5IIP8": "Passez à {planName} pour débloquer {message}","4Y+tpi": "Voir une démo de cette fonctionnalité","RL7HbL": "Demandez au propriétaire de votre organisation de passer à Pro pour débloquer {message}",- "QashlR": "Une erreur est survenue lors de la récupération des données","jsy7pk": "Réessayer","hyfdry": "Page vue","/kZg9i": "Clic sur bouton",@@ -1196,7 +1389,6 @@"jjBvFh": "Exclusions","6cBDhe": "Intégrations","IP4n+n": "Intégrations de widgets",- "rbrahO": "Fermer","scL+IP": "Widget activé","8pKlHk": "Activer le widget d'intégration","mhmZ+P": "Enregistrement de session",@@ -1243,7 +1435,6 @@"u/vOPu": "Payée","jHfCjd": "Annulée","45hFQt": "Irrécouvrable",- "W6nwjo": "Brouillon","6dqYnF": "Factures","P7PLVj": "Date","/0TOL5": "Montant",diff --git a/client/messages/it.json b/client/messages/it.jsonindex 5c08f99ff..7c14a03c0 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -61,6 +61,7 @@"mByYl9": "% Visualizzazioni di pagina","IuFETn": "Durata","0eoYsu": "Frequenza di Rimbalzo",+ "QashlR": "Si è verificato un errore durante il recupero dei dati","IxrHg4": "Filtra {count} elementi...","tL4WC1": "Caricamento in corso...","HPx76n": "Tutti gli elementi caricati",@@ -74,6 +75,8 @@"XHLYdJ": "Obiettivi","9d/EEp": "Analisi del Prodotto","5yUsUe": "Replay",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Funnel","08hqOd": "Percorsi","nL6Jl0": "Fidelizzazione",@@ -242,6 +245,212 @@"BReFYW": "Modifiche agli input","NDoUa9": "Tutti i tipi di evento nascosti","MJ2jZQ": "Totale",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Obiettivo #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Nome evento",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Bozza",+ "LHF3Za": "",+ "47FYwb": "Annulla",+ "rbrahO": "Chiudi",+ "cyR7Kh": "",+ "TiR/Hq": "Salvataggio in corso...",+ "mRL9Vh": "Creazione in corso...",+ "X0ha1a": "",+ "JXdbo8": "Fatto",+ "acrOoz": "Continua",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pausa",+ "U78NhE": "",+ "wL7VAE": "Azioni",+ "wEQDC6": "",+ "K3r6DQ": "Elimina",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Rimuovi",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Stato",+ "Zh+5A6": "Attivo",+ "OvzONl": "Disattivo",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Creata",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Chiave",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Tutti i passaggi devono avere dei valori","jm52QG": "Inserisci il nome di un funnel","+N7isb": "Funnel salvato con successo",@@ -273,7 +482,6 @@"+U6ozc": "Tipo","m1czzY": "Evento","Y6DkLY": "Percorso (es. /pricing)",- "eOj4Bs": "Nome evento","Hp/0iW": "Inserisci un percorso (es. /checkout), non un URL completo.","Asi2Jg": "Nascondi opzioni avanzate","lIEejV": "Mostra opzioni avanzate",@@ -287,8 +495,6 @@"tINfvW": "Usa * per corrispondere a un singolo segmento di percorso (es. /blog/*) o ** per corrispondere a più segmenti (es. /docs/**/intro)","ox304v": "Si è verificato un errore","KbGBQH": "Si è verificato un errore durante il salvataggio",- "47FYwb": "Annulla",- "TiR/Hq": "Salvataggio in corso...","/liMUf": "Funnel eliminato con successo","753yX5": "Etichetta","+SDMR3": "Proprietà",@@ -298,7 +504,6 @@"SB3+JE": "Nessun dato del funnel disponibile","45gABM": "Sei sicuro di voler eliminare \"{name}\"? Questa azione non può essere annullata.","noZdV2": "Eliminazione in corso...",- "K3r6DQ": "Elimina","GoxzAN": "Filtra funnel","qGN7M9": "Impossibile caricare i funnel","5/6deG": "Si è verificato un problema nel recupero dei funnel. Riprova più tardi.",@@ -328,16 +533,15 @@"h3ICzV": "Caricamento sessioni...","KjXPXZ": "{count} sessioni","9iSdEj": "{count} sessione",- "tFFMkF": "Pausa","J3ca41": "Riproduci","Ggedt8": "Mostrando solo le prime {count} sessioni. Potrebbero essere disponibili più dati.","5WuADX": "Aggiungi Obiettivo",+ "WuHoZ9": "Conversioni",+ "e/U0Xt": "Tasso di Conversione","+Ior19": "Obiettivo Pagina","rTE34i": "Obiettivo Evento",- "FYBPJU": "Obiettivo #{goalId}","pW4lxD": "Modello",- "WuHoZ9": "Conversioni",- "e/U0Xt": "Tasso di Conversione",+ "99Lkvz": "","sOXElg": "Modifica Obiettivo","N/ctXb": "Clona Obiettivo","F3XA9+": "Elimina Obiettivo",@@ -395,10 +599,10 @@"zuqMfZ": "Mappa","jUSc45": "Fusi orari","NdE4Ps": "Browser",+ "/VnDMl": "Altro","+20FW7": "Dispositivi","aTW7It": "Sistemi Operativi","3X4r56": "Dimensioni Schermo",- "/VnDMl": "Altro","Aujn2T": "Conteggio","ogKEiU": "Link Esterni","VLKK35": "Clic",@@ -407,13 +611,14 @@"pEc/5k": "% Clic","wU7PzI": "Ultimo Clic","4KEfRY": "Titoli",- "87ZCAe": "Ingressi",- "0ogV14": "Uscite",- "P6RGqE": "Hostname","gvOzOl": "Titolo Pagina",+ "87ZCAe": "Ingressi","vFf5xV": "Pagine di Ingresso",+ "0ogV14": "Uscite","KtC97P": "Pagine di Uscita",+ "P6RGqE": "Hostname","iF/x8v": "Referrer",+ "UF6kPm": "Diretto","LUrJwE": "Canali","aH4De2": "Sorgente","ovJ26C": "Mezzo",@@ -421,7 +626,6 @@"qTy5se": "Termine","Jq3FDz": "Contenuto","grtbAW": "UTM",- "UF6kPm": "Diretto","0E9k6Y": "Connetti il tuo account Google Search Console per visualizzare i dati sulle prestazioni di ricerca, inclusi i termini e le pagine principali.","jioGL4": "Connetti Google Search Console","M/h5TN": "Impressioni",@@ -550,7 +754,6 @@"uiy9pN": "Eventi 30g","9juexR": "Dettagli Abbonamento","fz0z4c": "Piano",- "tzMNF3": "Stato","T8qVXf": "Limite Eventi","ekXood": "Illimitato","5x9Sl1": "Fine Periodo",@@ -563,7 +766,6 @@"bGIAle": "Membri ({count})","hQZhn8": "Impersona","2ZpsMl": "Nessun membro",- "G/yZLu": "Rimuovi","nJuUfX": "Cerca per nome, slug, dominio o email del membro...","RllRQH": "Mostra organizzazioni con 0 eventi (30g)","7OL11E": "Solo oltre il limite",@@ -578,7 +780,6 @@"uL0dMG": "Utilizzo dell'intero servizio - Ultimi {timePeriod}","SVwJTM": "Esporta","K56Dim": "Organizzazione",- "ORGv1Q": "Creata","JKxOsh": "Eventi Mensili","R/6nsx": "Abbonamento","DDhP4z": "Siti",@@ -596,8 +797,6 @@"viXE32": "Privato","6hdNA5": "Eventi (24h)","J4r/Gi": "Eventi (30g)",- "Zh+5A6": "Attivo",- "OvzONl": "Disattivo","C2EM7h": "Email Proprietario","sEqhTf": "Impossibile caricare i dati dei siti. Riprova più tardi.","r9Y1x6": "Cerca per dominio o email proprietario...",@@ -626,7 +825,6 @@"uA0DvF": "Impossibile rimuovere l'utente dall'organizzazione","PW+sL4": "N/D","wittYy": "Creato il",- "wL7VAE": "Azioni","bdcMGy": "Apri menu","6gHGy0": "Rimuovi dall'Organizzazione","J2wna+": "Rimuovere l'utente dall'organizzazione?",@@ -744,19 +942,16 @@"u4673k": "Genera chiavi API per accedere agli endpoint di analisi dalle tue applicazioni","1fe3VI": "Le chiavi API sono disponibili nei piani Standard e Pro.","AkVL9j": "Nome Chiave API",- "mRL9Vh": "Creazione in corso...","jDvHYJ": "Le tue Chiavi API","MUaUWe": "Caricamento chiavi API...","iX4wwR": "Impossibile caricare le chiavi API","62nsdy": "Riprova",- "EcglP9": "Chiave","IY105q": "Nessuna chiave API creata ancora","wPtCEB": "Chiave API Creata","qcTCG8": "Salva questa chiave API in modo sicuro. Non potrai più vederla.","51jo4g": "La tua Chiave API","+fICx5": "Importante","TsKkxv": "Conserva questa chiave in modo sicuro. Non verrà mostrata di nuovo.",- "JXdbo8": "Fatto","LuNBqj": "La password dovrebbe essere lunga almeno 8 caratteri","UjlqkD": "Password forte","EK3962": "Password buona",@@ -886,7 +1081,6 @@"S5IFjk": "Crea un team per raggruppare i siti e gestire l'accesso dei membri.","StUScz": "{count} membri","RNCPOG": "Registrazione",- "acrOoz": "Continua","uCk8r+": "Hai già un account?","odXlk8": "Accedi","uWRAQk": "Scegli il tuo piano",@@ -996,7 +1190,6 @@"W5IIP8": "Passa a {planName} per sbloccare {message}","4Y+tpi": "Guarda una demo di questa funzionalità","RL7HbL": "Chiedi al proprietario della tua organizzazione di passare a Pro per sbloccare {message}",- "QashlR": "Si è verificato un errore durante il recupero dei dati","jsy7pk": "Riprova","hyfdry": "Visualizzazione pagina","/kZg9i": "Clic su pulsante",@@ -1196,7 +1389,6 @@"jjBvFh": "Esclusioni","6cBDhe": "Integrazioni","IP4n+n": "Incorporamenti Widget",- "rbrahO": "Chiudi","scL+IP": "Widget Abilitato","8pKlHk": "Abilita Widget di Incorporamento","mhmZ+P": "Riproduzione Sessione",@@ -1243,7 +1435,6 @@"u/vOPu": "Pagata","jHfCjd": "Annullata","45hFQt": "Inesigibile",- "W6nwjo": "Bozza","6dqYnF": "Fatture","P7PLVj": "Data","/0TOL5": "Importo",diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 6ba728b46..2e5e21922 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -61,6 +61,7 @@"mByYl9": "ページビュー %","IuFETn": "滞在時間","0eoYsu": "直帰率",+ "QashlR": "データの取得中にエラーが発生しました","IxrHg4": "{count}件を検索...","tL4WC1": "さらに読み込み中...","HPx76n": "すべて読み込み済み",@@ -74,6 +75,8 @@"XHLYdJ": "目標","9d/EEp": "プロダクトアナリティクス","5yUsUe": "リプレイ",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "ファネル","08hqOd": "ジャーニー","nL6Jl0": "リテンション",@@ -242,6 +245,212 @@"BReFYW": "入力変更","NDoUa9": "すべてのイベントタイプが非表示です","MJ2jZQ": "合計",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "ゴール #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "イベント名",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "下書き",+ "LHF3Za": "",+ "47FYwb": "キャンセル",+ "rbrahO": "閉じる",+ "cyR7Kh": "",+ "TiR/Hq": "保存中...",+ "mRL9Vh": "作成中...",+ "X0ha1a": "",+ "JXdbo8": "完了",+ "acrOoz": "続行",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "一時停止",+ "U78NhE": "",+ "wL7VAE": "操作",+ "wEQDC6": "",+ "K3r6DQ": "削除",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "削除",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "ステータス",+ "Zh+5A6": "オン",+ "OvzONl": "オフ",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "作成日",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "キー",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "すべてのステップに値を入力してください","jm52QG": "ファネル名を入力してください","+N7isb": "ファネルを保存しました",@@ -273,7 +482,6 @@"+U6ozc": "タイプ","m1czzY": "イベント","Y6DkLY": "パス(例:/pricing)",- "eOj4Bs": "イベント名","Hp/0iW": "パスを入力してください(例:/checkout)。完全なURLではありません。","Asi2Jg": "詳細オプションを非表示","lIEejV": "詳細オプションを表示",@@ -287,8 +495,6 @@"tINfvW": "*で単一のパスセグメントに一致(例:/blog/*)、**で複数セグメントに一致(例:/docs/**/intro)","ox304v": "エラーが発生しました","KbGBQH": "保存中にエラーが発生しました",- "47FYwb": "キャンセル",- "TiR/Hq": "保存中...","/liMUf": "ファネルを削除しました","753yX5": "ラベル","+SDMR3": "プロパティ",@@ -298,7 +504,6 @@"SB3+JE": "ファネルデータがありません","45gABM": "「{name}」を削除してもよろしいですか?この操作は元に戻せません。","noZdV2": "削除中...",- "K3r6DQ": "削除","GoxzAN": "ファネルをフィルター","qGN7M9": "ファネルの読み込みに失敗しました","5/6deG": "ファネルの取得中に問題が発生しました。後でもう一度お試しください。",@@ -328,16 +533,15 @@"h3ICzV": "セッションを読み込み中...","KjXPXZ": "{count}セッション","9iSdEj": "{count}セッション",- "tFFMkF": "一時停止","J3ca41": "再生","Ggedt8": "最初の{count}セッションのみ表示しています。より多くのデータがある場合があります。","5WuADX": "ゴールを追加",+ "WuHoZ9": "コンバージョン",+ "e/U0Xt": "コンバージョン率","+Ior19": "ページゴール","rTE34i": "イベントゴール",- "FYBPJU": "ゴール #{goalId}","pW4lxD": "パターン",- "WuHoZ9": "コンバージョン",- "e/U0Xt": "コンバージョン率",+ "99Lkvz": "","sOXElg": "ゴールを編集","N/ctXb": "ゴールを複製","F3XA9+": "ゴールを削除",@@ -395,10 +599,10 @@"zuqMfZ": "マップ","jUSc45": "タイムゾーン","NdE4Ps": "ブラウザ",+ "/VnDMl": "その他","+20FW7": "デバイス","aTW7It": "オペレーティングシステム","3X4r56": "画面サイズ",- "/VnDMl": "その他","Aujn2T": "カウント","ogKEiU": "外部リンク","VLKK35": "クリック",@@ -407,13 +611,14 @@"pEc/5k": "クリック率","wU7PzI": "最終クリック","4KEfRY": "タイトル",- "87ZCAe": "入口",- "0ogV14": "出口",- "P6RGqE": "ホスト名","gvOzOl": "ページタイトル",+ "87ZCAe": "入口","vFf5xV": "入口ページ",+ "0ogV14": "出口","KtC97P": "出口ページ",+ "P6RGqE": "ホスト名","iF/x8v": "リファラー",+ "UF6kPm": "ダイレクト","LUrJwE": "チャネル","aH4De2": "ソース","ovJ26C": "メディア",@@ -421,7 +626,6 @@"qTy5se": "キーワード","Jq3FDz": "コンテンツ","grtbAW": "UTM",- "UF6kPm": "ダイレクト","0E9k6Y": "Google Search Consoleアカウントを接続して、上位キーワードやページを含む検索パフォーマンスデータを表示します。","jioGL4": "Google Search Consoleを接続","M/h5TN": "インプレッション",@@ -550,7 +754,6 @@"uiy9pN": "30日間イベント","9juexR": "サブスクリプション詳細","fz0z4c": "プラン",- "tzMNF3": "ステータス","T8qVXf": "イベント上限","ekXood": "無制限","5x9Sl1": "期間終了",@@ -563,7 +766,6 @@"bGIAle": "メンバー({count})","hQZhn8": "なりすまし","2ZpsMl": "メンバーなし",- "G/yZLu": "削除","nJuUfX": "名前、スラッグ、ドメイン、またはメンバーメールで検索...","RllRQH": "30日間イベント0の組織を表示","7OL11E": "上限超過のみ",@@ -578,7 +780,6 @@"uL0dMG": "サービス全体の使用量 - 過去{timePeriod}","SVwJTM": "エクスポート","K56Dim": "組織",- "ORGv1Q": "作成日","JKxOsh": "月間イベント","R/6nsx": "サブスクリプション","DDhP4z": "サイト",@@ -596,8 +797,6 @@"viXE32": "非公開","6hdNA5": "イベント(24時間)","J4r/Gi": "イベント(30日間)",- "Zh+5A6": "オン",- "OvzONl": "オフ","C2EM7h": "オーナーメール","sEqhTf": "サイトデータの読み込みに失敗しました。後でもう一度お試しください。","r9Y1x6": "ドメインまたはオーナーメールで検索...",@@ -626,7 +825,6 @@"uA0DvF": "ユーザーの組織からの削除に失敗しました","PW+sL4": "N/A","wittYy": "作成日時",- "wL7VAE": "操作","bdcMGy": "メニューを開く","6gHGy0": "組織から削除","J2wna+": "ユーザーを組織から削除しますか?",@@ -744,19 +942,16 @@"u4673k": "アプリケーションからアナリティクスエンドポイントにアクセスするためのAPIキーを生成","1fe3VI": "API キーはスタンダードプランおよびプロプランでご利用いただけます。","AkVL9j": "APIキー名",- "mRL9Vh": "作成中...","jDvHYJ": "あなたのAPIキー","MUaUWe": "APIキーを読み込み中...","iX4wwR": "APIキーの読み込みに失敗しました","62nsdy": "再試行",- "EcglP9": "キー","IY105q": "APIキーがまだ作成されていません","wPtCEB": "APIキーを作成しました","qcTCG8": "このAPIキーを安全に保存してください。再度表示することはできません。","51jo4g": "あなたのAPIキー","+fICx5": "重要","TsKkxv": "このキーを安全に保管してください。再度表示されません。",- "JXdbo8": "完了","LuNBqj": "パスワードは8文字以上である必要があります","UjlqkD": "強いパスワード","EK3962": "良いパスワード",@@ -886,7 +1081,6 @@"S5IFjk": "サイトをグループ化してメンバーアクセスを管理するチームを作成します。","StUScz": "{count} 名のメンバー","RNCPOG": "サインアップ",- "acrOoz": "続行","uCk8r+": "すでにアカウントをお持ちですか?","odXlk8": "ログイン","uWRAQk": "プランを選択",@@ -996,7 +1190,6 @@"W5IIP8": "{planName}にアップグレードして{message}をアンロック","4Y+tpi": "この機能のデモを見る","RL7HbL": "組織オーナーにProへのアップグレードを依頼して{message}をアンロック",- "QashlR": "データの取得中にエラーが発生しました","jsy7pk": "再試行","hyfdry": "ページビュー","/kZg9i": "ボタンクリック",@@ -1196,7 +1389,6 @@"jjBvFh": "除外","6cBDhe": "インテグレーション","IP4n+n": "ウィジェット埋め込み",- "rbrahO": "閉じる","scL+IP": "ウィジェット有効","8pKlHk": "埋め込みウィジェットを有効にする","mhmZ+P": "セッションリプレイ",@@ -1243,7 +1435,6 @@"u/vOPu": "支払済み","jHfCjd": "無効","45hFQt": "回収不能",- "W6nwjo": "下書き","6dqYnF": "請求書","P7PLVj": "日付","/0TOL5": "金額",diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex d2e37bd0c..731d7fca4 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -61,6 +61,7 @@"mByYl9": "페이지뷰 %","IuFETn": "기간","0eoYsu": "이탈률",+ "QashlR": "데이터를 가져오는 중 오류가 발생했습니다","IxrHg4": "{count}개 항목 필터...","tL4WC1": "더 불러오는 중...","HPx76n": "모든 항목 로드됨",@@ -74,6 +75,8 @@"XHLYdJ": "목표","9d/EEp": "제품 분석","5yUsUe": "리플레이",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "퍼널","08hqOd": "여정","nL6Jl0": "리텐션",@@ -242,6 +245,212 @@"BReFYW": "입력 변경","NDoUa9": "모든 이벤트 유형 숨김","MJ2jZQ": "합계",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "목표 #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "이벤트 이름",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "초안",+ "LHF3Za": "",+ "47FYwb": "취소",+ "rbrahO": "닫기",+ "cyR7Kh": "",+ "TiR/Hq": "저장 중...",+ "mRL9Vh": "생성 중...",+ "X0ha1a": "",+ "JXdbo8": "완료",+ "acrOoz": "계속",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "일시정지",+ "U78NhE": "",+ "wL7VAE": "작업",+ "wEQDC6": "",+ "K3r6DQ": "삭제",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "제거",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "상태",+ "Zh+5A6": "켜짐",+ "OvzONl": "꺼짐",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "생성일",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "키",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "모든 단계에 값이 있어야 합니다","jm52QG": "퍼널 이름을 입력하세요","+N7isb": "퍼널이 성공적으로 저장되었습니다",@@ -273,7 +482,6 @@"+U6ozc": "유형","m1czzY": "이벤트","Y6DkLY": "경로 (예: /pricing)",- "eOj4Bs": "이벤트 이름","Hp/0iW": "경로를 입력하세요 (예: /checkout), 전체 URL이 아닙니다.","Asi2Jg": "고급 옵션 숨기기","lIEejV": "고급 옵션 표시",@@ -287,8 +495,6 @@"tINfvW": "*를 사용하여 단일 경로 세그먼트를 일치시키거나 (예: /blog/*) **를 사용하여 여러 세그먼트를 일치시킵니다 (예: /docs/**/intro)","ox304v": "오류가 발생했습니다","KbGBQH": "저장 중 오류가 발생했습니다",- "47FYwb": "취소",- "TiR/Hq": "저장 중...","/liMUf": "퍼널이 성공적으로 삭제되었습니다","753yX5": "라벨","+SDMR3": "속성",@@ -298,7 +504,6 @@"SB3+JE": "사용 가능한 퍼널 데이터 없음","45gABM": "\"{name}\"을(를) 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.","noZdV2": "삭제 중...",- "K3r6DQ": "삭제","GoxzAN": "퍼널 필터","qGN7M9": "퍼널 로드 실패","5/6deG": "퍼널을 가져오는 중 문제가 발생했습니다. 나중에 다시 시도해 주세요.",@@ -328,16 +533,15 @@"h3ICzV": "세션 로딩 중...","KjXPXZ": "{count}개 세션","9iSdEj": "{count}개 세션",- "tFFMkF": "일시정지","J3ca41": "재생","Ggedt8": "처음 {count}개 세션만 표시됩니다. 더 많은 데이터가 있을 수 있습니다.","5WuADX": "목표 추가",+ "WuHoZ9": "전환",+ "e/U0Xt": "전환율","+Ior19": "페이지 목표","rTE34i": "이벤트 목표",- "FYBPJU": "목표 #{goalId}","pW4lxD": "패턴",- "WuHoZ9": "전환",- "e/U0Xt": "전환율",+ "99Lkvz": "","sOXElg": "목표 편집","N/ctXb": "목표 복제","F3XA9+": "목표 삭제",@@ -395,10 +599,10 @@"zuqMfZ": "지도","jUSc45": "시간대","NdE4Ps": "브라우저",+ "/VnDMl": "기타","+20FW7": "기기","aTW7It": "운영 체제","3X4r56": "화면 크기",- "/VnDMl": "기타","Aujn2T": "수","ogKEiU": "외부 링크","VLKK35": "클릭",@@ -407,13 +611,14 @@"pEc/5k": "클릭 %","wU7PzI": "마지막 클릭","4KEfRY": "제목",- "87ZCAe": "진입",- "0ogV14": "이탈",- "P6RGqE": "호스트명","gvOzOl": "페이지 제목",+ "87ZCAe": "진입","vFf5xV": "진입 페이지",+ "0ogV14": "이탈","KtC97P": "이탈 페이지",+ "P6RGqE": "호스트명","iF/x8v": "리퍼러",+ "UF6kPm": "직접","LUrJwE": "채널","aH4De2": "소스","ovJ26C": "매체",@@ -421,7 +626,6 @@"qTy5se": "용어","Jq3FDz": "콘텐츠","grtbAW": "UTM",- "UF6kPm": "직접","0E9k6Y": "검색 성과 데이터 및 상위 키워드와 페이지를 보려면 Google Search Console 계정을 연결하세요.","jioGL4": "Google Search Console 연결","M/h5TN": "노출수",@@ -550,7 +754,6 @@"uiy9pN": "30일 이벤트","9juexR": "구독 상세","fz0z4c": "플랜",- "tzMNF3": "상태","T8qVXf": "이벤트 한도","ekXood": "무제한","5x9Sl1": "기간 종료",@@ -563,7 +766,6 @@"bGIAle": "멤버 ({count})","hQZhn8": "대리 로그인","2ZpsMl": "멤버 없음",- "G/yZLu": "제거","nJuUfX": "이름, 슬러그, 도메인 또는 멤버 이메일로 검색...","RllRQH": "이벤트 0인 조직 표시 (30일)","7OL11E": "한도 초과만",@@ -578,7 +780,6 @@"uL0dMG": "서비스 전체 사용량 - 최근 {timePeriod}","SVwJTM": "내보내기","K56Dim": "조직",- "ORGv1Q": "생성일","JKxOsh": "월별 이벤트","R/6nsx": "구독","DDhP4z": "사이트",@@ -596,8 +797,6 @@"viXE32": "비공개","6hdNA5": "이벤트 (24시간)","J4r/Gi": "이벤트 (30일)",- "Zh+5A6": "켜짐",- "OvzONl": "꺼짐","C2EM7h": "소유자 이메일","sEqhTf": "사이트 데이터를 로드하지 못했습니다. 나중에 다시 시도해 주세요.","r9Y1x6": "도메인 또는 소유자 이메일로 검색...",@@ -626,7 +825,6 @@"uA0DvF": "사용자를 조직에서 제거하는 데 실패했습니다","PW+sL4": "해당 없음","wittYy": "생성일",- "wL7VAE": "작업","bdcMGy": "메뉴 열기","6gHGy0": "조직에서 제거","J2wna+": "사용자를 조직에서 제거하시겠습니까?",@@ -744,19 +942,16 @@"u4673k": "애플리케이션에서 분석 엔드포인트에 접근하기 위한 API 키 생성","1fe3VI": "API 키는 스탠다드 및 프로 플랜에서 사용할 수 있습니다.","AkVL9j": "API 키 이름",- "mRL9Vh": "생성 중...","jDvHYJ": "내 API 키","MUaUWe": "API 키 로딩 중...","iX4wwR": "API 키 로드에 실패했습니다","62nsdy": "재시도",- "EcglP9": "키","IY105q": "아직 생성된 API 키가 없습니다","wPtCEB": "API 키 생성됨","qcTCG8": "이 API 키를 안전하게 저장하세요. 다시 볼 수 없습니다.","51jo4g": "내 API 키","+fICx5": "중요","TsKkxv": "이 키를 안전하게 저장하세요. 다시 표시되지 않습니다.",- "JXdbo8": "완료","LuNBqj": "비밀번호는 최소 8자 이상이어야 합니다","UjlqkD": "강력한 비밀번호","EK3962": "좋은 비밀번호",@@ -886,7 +1081,6 @@"S5IFjk": "사이트를 그룹화하고 멤버 액세스를 관리하는 팀을 만듭니다.","StUScz": "멤버 {count}명","RNCPOG": "가입",- "acrOoz": "계속","uCk8r+": "이미 계정이 있으신가요?","odXlk8": "로그인","uWRAQk": "플랜 선택",@@ -996,7 +1190,6 @@"W5IIP8": "{message}을(를) 잠금 해제하려면 {planName}으로 업그레이드하세요","4Y+tpi": "이 기능의 데모 보기","RL7HbL": "{message}을(를) 잠금 해제하려면 조직 소유자에게 Pro 업그레이드를 요청하세요",- "QashlR": "데이터를 가져오는 중 오류가 발생했습니다","jsy7pk": "다시 시도","hyfdry": "페이지뷰","/kZg9i": "버튼 클릭",@@ -1196,7 +1389,6 @@"jjBvFh": "제외","6cBDhe": "통합","IP4n+n": "위젯 임베드",- "rbrahO": "닫기","scL+IP": "위젯 활성화됨","8pKlHk": "임베드 위젯 활성화","mhmZ+P": "세션 리플레이",@@ -1243,7 +1435,6 @@"u/vOPu": "결제됨","jHfCjd": "무효","45hFQt": "회수 불가",- "W6nwjo": "초안","6dqYnF": "청구서","P7PLVj": "날짜","/0TOL5": "금액",diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex def729b5a..356972cfa 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -61,6 +61,7 @@"mByYl9": "% odsłon","IuFETn": "Czas trwania","0eoYsu": "Współczynnik odrzuceń",+ "QashlR": "Wystąpił błąd podczas pobierania danych","IxrHg4": "Filtruj {count} elementów...","tL4WC1": "Ładowanie kolejnych...","HPx76n": "Wszystkie elementy załadowane",@@ -74,6 +75,8 @@"XHLYdJ": "Cele","9d/EEp": "Analityka produktowa","5yUsUe": "Odtwarzanie",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Lejki","08hqOd": "Ścieżki","nL6Jl0": "Retencja",@@ -242,6 +245,212 @@"BReFYW": "Zmiany wejść","NDoUa9": "Wszystkie typy zdarzeń ukryte","MJ2jZQ": "Razem",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Cel #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Nazwa zdarzenia",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Szkic",+ "LHF3Za": "",+ "47FYwb": "Anuluj",+ "rbrahO": "Zamknij",+ "cyR7Kh": "",+ "TiR/Hq": "Zapisywanie...",+ "mRL9Vh": "Tworzenie...",+ "X0ha1a": "",+ "JXdbo8": "Gotowe",+ "acrOoz": "Kontynuuj",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pauza",+ "U78NhE": "",+ "wL7VAE": "Akcje",+ "wEQDC6": "",+ "K3r6DQ": "Usuń",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Usuń",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Status",+ "Zh+5A6": "Włączone",+ "OvzONl": "Wyłączone",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Utworzono",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Klucz",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Wszystkie kroki muszą mieć wartości","jm52QG": "Wprowadź nazwę lejka","+N7isb": "Lejek zapisany pomyślnie",@@ -273,7 +482,6 @@"+U6ozc": "Typ","m1czzY": "Zdarzenie","Y6DkLY": "Ścieżka (np. /pricing)",- "eOj4Bs": "Nazwa zdarzenia","Hp/0iW": "Wprowadź ścieżkę (np. /checkout), nie pełny URL.","Asi2Jg": "Ukryj zaawansowane opcje","lIEejV": "Pokaż zaawansowane opcje",@@ -287,8 +495,6 @@"tINfvW": "Użyj * aby dopasować pojedynczy segment ścieżki (np. /blog/*) lub ** aby dopasować wiele segmentów (np. /docs/**/intro)","ox304v": "Wystąpił błąd","KbGBQH": "Wystąpił błąd podczas zapisywania",- "47FYwb": "Anuluj",- "TiR/Hq": "Zapisywanie...","/liMUf": "Lejek usunięty pomyślnie","753yX5": "Etykieta","+SDMR3": "Właściwość",@@ -298,7 +504,6 @@"SB3+JE": "Brak dostępnych danych lejka","45gABM": "Czy na pewno chcesz usunąć \"{name}\"? Tej czynności nie można cofnąć.","noZdV2": "Usuwanie...",- "K3r6DQ": "Usuń","GoxzAN": "Filtruj lejki","qGN7M9": "Nie udało się załadować lejków","5/6deG": "Wystąpił problem z pobieraniem lejków. Spróbuj ponownie później.",@@ -328,16 +533,15 @@"h3ICzV": "Ładowanie sesji...","KjXPXZ": "{count} sesji","9iSdEj": "{count} sesja",- "tFFMkF": "Pauza","J3ca41": "Odtwarzaj","Ggedt8": "Wyświetlanie tylko pierwszych {count} sesji. Więcej danych może być dostępnych.","5WuADX": "Dodaj cel",+ "WuHoZ9": "Konwersje",+ "e/U0Xt": "Współczynnik konwersji","+Ior19": "Cel strony","rTE34i": "Cel zdarzenia",- "FYBPJU": "Cel #{goalId}","pW4lxD": "Wzorzec",- "WuHoZ9": "Konwersje",- "e/U0Xt": "Współczynnik konwersji",+ "99Lkvz": "","sOXElg": "Edytuj cel","N/ctXb": "Klonuj cel","F3XA9+": "Usuń cel",@@ -395,10 +599,10 @@"zuqMfZ": "Mapa","jUSc45": "Strefy czasowe","NdE4Ps": "Przeglądarki",+ "/VnDMl": "Inne","+20FW7": "Urządzenia","aTW7It": "Systemy operacyjne","3X4r56": "Wymiary ekranu",- "/VnDMl": "Inne","Aujn2T": "Liczba","ogKEiU": "Linki wychodzące","VLKK35": "Kliknięcia",@@ -407,13 +611,14 @@"pEc/5k": "% kliknięć","wU7PzI": "Ostatnio kliknięto","4KEfRY": "Tytuły",- "87ZCAe": "Wejścia",- "0ogV14": "Wyjścia",- "P6RGqE": "Nazwy hostów","gvOzOl": "Tytuł strony",+ "87ZCAe": "Wejścia","vFf5xV": "Strony wejściowe",+ "0ogV14": "Wyjścia","KtC97P": "Strony wyjściowe",+ "P6RGqE": "Nazwy hostów","iF/x8v": "Źródła odesłań",+ "UF6kPm": "Bezpośrednie","LUrJwE": "Kanały","aH4De2": "Źródło","ovJ26C": "Medium",@@ -421,7 +626,6 @@"qTy5se": "Termin","Jq3FDz": "Treść","grtbAW": "UTM",- "UF6kPm": "Bezpośrednie","0E9k6Y": "Połącz swoje konto Google Search Console, aby wyświetlić dane o wydajności wyszukiwania, w tym najważniejsze słowa kluczowe i strony.","jioGL4": "Połącz Google Search Console","M/h5TN": "Wyświetlenia",@@ -550,7 +754,6 @@"uiy9pN": "Zdarzenia 30d","9juexR": "Szczegóły subskrypcji","fz0z4c": "Plan",- "tzMNF3": "Status","T8qVXf": "Limit zdarzeń","ekXood": "Bez limitu","5x9Sl1": "Koniec okresu",@@ -563,7 +766,6 @@"bGIAle": "Członkowie ({count})","hQZhn8": "Podszywaj się","2ZpsMl": "Brak członków",- "G/yZLu": "Usuń","nJuUfX": "Szukaj po nazwie, identyfikatorze, domenie lub e-mailu członka...","RllRQH": "Pokaż organizacje z 0 zdarzeniami (30d)","7OL11E": "Tylko powyżej limitu",@@ -578,7 +780,6 @@"uL0dMG": "Wykorzystanie usługi - ostatnie {timePeriod}","SVwJTM": "Eksport","K56Dim": "Organizacja",- "ORGv1Q": "Utworzono","JKxOsh": "Miesięczne zdarzenia","R/6nsx": "Subskrypcja","DDhP4z": "Strony",@@ -596,8 +797,6 @@"viXE32": "Prywatna","6hdNA5": "Zdarzenia (24h)","J4r/Gi": "Zdarzenia (30d)",- "Zh+5A6": "Włączone",- "OvzONl": "Wyłączone","C2EM7h": "E-mail właściciela","sEqhTf": "Nie udało się załadować danych stron. Spróbuj ponownie później.","r9Y1x6": "Szukaj po domenie lub e-mailu właściciela...",@@ -626,7 +825,6 @@"uA0DvF": "Nie udało się usunąć użytkownika z organizacji","PW+sL4": "Nie dotyczy","wittYy": "Data utworzenia",- "wL7VAE": "Akcje","bdcMGy": "Otwórz menu","6gHGy0": "Usuń z organizacji","J2wna+": "Usunąć użytkownika z organizacji?",@@ -744,19 +942,16 @@"u4673k": "Generuj klucze API, aby uzyskać dostęp do endpointów analitycznych z Twoich aplikacji","1fe3VI": "Klucze API są dostępne w planach Standard i Pro.","AkVL9j": "Nazwa klucza API",- "mRL9Vh": "Tworzenie...","jDvHYJ": "Twoje klucze API","MUaUWe": "Ładowanie kluczy API...","iX4wwR": "Nie udało się załadować kluczy API","62nsdy": "Ponów",- "EcglP9": "Klucz","IY105q": "Nie utworzono jeszcze kluczy API","wPtCEB": "Klucz API utworzony","qcTCG8": "Zapisz ten klucz API w bezpiecznym miejscu. Nie będziesz mógł go ponownie zobaczyć.","51jo4g": "Twój klucz API","+fICx5": "Ważne","TsKkxv": "Przechowuj ten klucz w bezpiecznym miejscu. Nie zostanie wyświetlony ponownie.",- "JXdbo8": "Gotowe","LuNBqj": "Hasło powinno mieć co najmniej 8 znaków","UjlqkD": "Silne hasło","EK3962": "Dobre hasło",@@ -886,7 +1081,6 @@"S5IFjk": "Utwórz zespół, aby grupować witryny i zarządzać dostępem członków.","StUScz": "{count} członków","RNCPOG": "Rejestracja",- "acrOoz": "Kontynuuj","uCk8r+": "Masz już konto?","odXlk8": "Zaloguj się","uWRAQk": "Wybierz plan",@@ -996,7 +1190,6 @@"W5IIP8": "Ulepsz do {planName}, aby odblokować {message}","4Y+tpi": "Zobacz demo tej funkcji","RL7HbL": "Poproś właściciela organizacji o ulepszenie do Pro, aby odblokować {message}",- "QashlR": "Wystąpił błąd podczas pobierania danych","jsy7pk": "Spróbuj ponownie","hyfdry": "Odsłona","/kZg9i": "Kliknięcie przycisku",@@ -1196,7 +1389,6 @@"jjBvFh": "Wykluczenia","6cBDhe": "Integracje","IP4n+n": "Osadzenia widgetu",- "rbrahO": "Zamknij","scL+IP": "Widget włączony","8pKlHk": "Włącz widget osadzenia","mhmZ+P": "Odtwarzanie sesji",@@ -1243,7 +1435,6 @@"u/vOPu": "Opłacona","jHfCjd": "Unieważniona","45hFQt": "Nieściągalna",- "W6nwjo": "Szkic","6dqYnF": "Faktury","P7PLVj": "Data","/0TOL5": "Kwota",diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex 869046d96..d8cdb7751 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -61,6 +61,7 @@"mByYl9": "Visualizações %","IuFETn": "Duração","0eoYsu": "Taxa de Rejeição",+ "QashlR": "Ocorreu um erro ao buscar dados","IxrHg4": "Filtrar {count} itens...","tL4WC1": "Carregando mais...","HPx76n": "Todos os itens carregados",@@ -74,6 +75,8 @@"XHLYdJ": "Metas","9d/EEp": "Análise de Produto","5yUsUe": "Replay",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Funis","08hqOd": "Jornadas","nL6Jl0": "Retenção",@@ -242,6 +245,212 @@"BReFYW": "Mudanças de entrada","NDoUa9": "Todos os tipos de evento ocultos","MJ2jZQ": "Total",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Meta #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Nome do evento",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Rascunho",+ "LHF3Za": "",+ "47FYwb": "Cancelar",+ "rbrahO": "Fechar",+ "cyR7Kh": "",+ "TiR/Hq": "Salvando...",+ "mRL9Vh": "Criando...",+ "X0ha1a": "",+ "JXdbo8": "Concluído",+ "acrOoz": "Continuar",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Pausar",+ "U78NhE": "",+ "wL7VAE": "Ações",+ "wEQDC6": "",+ "K3r6DQ": "Excluir",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "Remover",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Status",+ "Zh+5A6": "Ligado",+ "OvzONl": "Desligado",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Criado",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Chave",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Todas as etapas devem ter valores","jm52QG": "Por favor, insira um nome para o funil","+N7isb": "Funil salvo com sucesso",@@ -273,7 +482,6 @@"+U6ozc": "Tipo","m1czzY": "Evento","Y6DkLY": "Caminho (ex. /pricing)",- "eOj4Bs": "Nome do evento","Hp/0iW": "Digite um caminho (ex., /checkout), não uma URL completa.","Asi2Jg": "Ocultar opções avançadas","lIEejV": "Mostrar opções avançadas",@@ -287,8 +495,6 @@"tINfvW": "Use * para corresponder a um único segmento de caminho (ex., /blog/*) ou ** para corresponder a múltiplos segmentos (ex., /docs/**/intro)","ox304v": "Ocorreu um erro","KbGBQH": "Ocorreu um erro ao salvar",- "47FYwb": "Cancelar",- "TiR/Hq": "Salvando...","/liMUf": "Funil excluído com sucesso","753yX5": "Rótulo","+SDMR3": "Propriedade",@@ -298,7 +504,6 @@"SB3+JE": "Nenhum dado de funil disponível","45gABM": "Tem certeza de que deseja excluir \"{name}\"? Esta ação não pode ser desfeita.","noZdV2": "Excluindo...",- "K3r6DQ": "Excluir","GoxzAN": "Filtrar funis","qGN7M9": "Falha ao carregar funis","5/6deG": "Houve um problema ao buscar os funis. Por favor, tente novamente mais tarde.",@@ -328,16 +533,15 @@"h3ICzV": "Carregando sessões...","KjXPXZ": "{count} sessões","9iSdEj": "{count} sessão",- "tFFMkF": "Pausar","J3ca41": "Reproduzir","Ggedt8": "Mostrando apenas as primeiras {count} sessões. Mais dados podem estar disponíveis.","5WuADX": "Adicionar Meta",+ "WuHoZ9": "Conversões",+ "e/U0Xt": "Taxa de Conversão","+Ior19": "Meta de Página","rTE34i": "Meta de Evento",- "FYBPJU": "Meta #{goalId}","pW4lxD": "Padrão",- "WuHoZ9": "Conversões",- "e/U0Xt": "Taxa de Conversão",+ "99Lkvz": "","sOXElg": "Editar Meta","N/ctXb": "Clonar Meta","F3XA9+": "Excluir Meta",@@ -395,10 +599,10 @@"zuqMfZ": "Mapa","jUSc45": "Fusos Horários","NdE4Ps": "Navegadores",+ "/VnDMl": "Outro","+20FW7": "Dispositivos","aTW7It": "Sistemas Operacionais","3X4r56": "Dimensões da Tela",- "/VnDMl": "Outro","Aujn2T": "Contagem","ogKEiU": "Links Externos","VLKK35": "Cliques",@@ -407,13 +611,14 @@"pEc/5k": "Clique %","wU7PzI": "Último Clique","4KEfRY": "Títulos",- "87ZCAe": "Entradas",- "0ogV14": "Saídas",- "P6RGqE": "Nomes de host","gvOzOl": "Título da Página",+ "87ZCAe": "Entradas","vFf5xV": "Páginas de Entrada",+ "0ogV14": "Saídas","KtC97P": "Páginas de Saída",+ "P6RGqE": "Nomes de host","iF/x8v": "Referenciadores",+ "UF6kPm": "Direto","LUrJwE": "Canais","aH4De2": "Fonte","ovJ26C": "Meio",@@ -421,7 +626,6 @@"qTy5se": "Termo","Jq3FDz": "Conteúdo","grtbAW": "UTM",- "UF6kPm": "Direto","0E9k6Y": "Conecte sua conta do Google Search Console para visualizar dados de desempenho de busca, incluindo principais palavras-chave e páginas.","jioGL4": "Conectar Google Search Console","M/h5TN": "Impressões",@@ -550,7 +754,6 @@"uiy9pN": "Eventos 30d","9juexR": "Detalhes da Assinatura","fz0z4c": "Plano",- "tzMNF3": "Status","T8qVXf": "Limite de Eventos","ekXood": "Ilimitado","5x9Sl1": "Fim do Período",@@ -563,7 +766,6 @@"bGIAle": "Membros ({count})","hQZhn8": "Personificar","2ZpsMl": "Sem membros",- "G/yZLu": "Remover","nJuUfX": "Pesquisar por nome, slug, domínio ou email do membro...","RllRQH": "Mostrar orgs com 0 eventos (30d)","7OL11E": "Apenas acima do limite",@@ -578,7 +780,6 @@"uL0dMG": "Uso do Serviço - Últimos {timePeriod}","SVwJTM": "Exportar","K56Dim": "Organização",- "ORGv1Q": "Criado","JKxOsh": "Eventos Mensais","R/6nsx": "Assinatura","DDhP4z": "Sites",@@ -596,8 +797,6 @@"viXE32": "Privado","6hdNA5": "Eventos (24h)","J4r/Gi": "Eventos (30d)",- "Zh+5A6": "Ligado",- "OvzONl": "Desligado","C2EM7h": "Email do Proprietário","sEqhTf": "Falha ao carregar dados de sites. Por favor, tente novamente mais tarde.","r9Y1x6": "Pesquisar por domínio ou email do proprietário...",@@ -626,7 +825,6 @@"uA0DvF": "Falha ao remover usuário da organização","PW+sL4": "N/D","wittYy": "Criado Em",- "wL7VAE": "Ações","bdcMGy": "Abrir menu","6gHGy0": "Remover da Organização","J2wna+": "Remover usuário da organização?",@@ -744,19 +942,16 @@"u4673k": "Gere chaves de API para acessar endpoints de análise das suas aplicações","1fe3VI": "As chaves de API estão disponíveis nos planos Standard e Pro.","AkVL9j": "Nome da Chave de API",- "mRL9Vh": "Criando...","jDvHYJ": "Suas Chaves de API","MUaUWe": "Carregando chaves de API...","iX4wwR": "Falha ao carregar chaves de API","62nsdy": "Tentar Novamente",- "EcglP9": "Chave","IY105q": "Nenhuma chave de API criada ainda","wPtCEB": "Chave de API Criada","qcTCG8": "Salve esta chave de API com segurança. Você não poderá vê-la novamente.","51jo4g": "Sua Chave de API","+fICx5": "Importante","TsKkxv": "Armazene esta chave com segurança. Ela não será exibida novamente.",- "JXdbo8": "Concluído","LuNBqj": "A senha deve ter pelo menos 8 caracteres","UjlqkD": "Senha forte","EK3962": "Boa senha",@@ -886,7 +1081,6 @@"S5IFjk": "Crie um time para agrupar sites e gerenciar o acesso dos membros.","StUScz": "{count} membros","RNCPOG": "Cadastro",- "acrOoz": "Continuar","uCk8r+": "Já tem uma conta?","odXlk8": "Entrar","uWRAQk": "Escolha seu plano",@@ -996,7 +1190,6 @@"W5IIP8": "Atualize para {planName} para desbloquear {message}","4Y+tpi": "Veja uma demo desta funcionalidade","RL7HbL": "Peça ao proprietário da sua organização para atualizar para Pro para desbloquear {message}",- "QashlR": "Ocorreu um erro ao buscar dados","jsy7pk": "Tentar Novamente","hyfdry": "Visualização de página","/kZg9i": "Clique no botão",@@ -1196,7 +1389,6 @@"jjBvFh": "Exclusões","6cBDhe": "Integrações","IP4n+n": "Incorporações de Widget",- "rbrahO": "Fechar","scL+IP": "Widget Ativado","8pKlHk": "Ativar Widget de Incorporação","mhmZ+P": "Replay de Sessão",@@ -1243,7 +1435,6 @@"u/vOPu": "Pago","jHfCjd": "Anulada","45hFQt": "Incobrável",- "W6nwjo": "Rascunho","6dqYnF": "Faturas","P7PLVj": "Data","/0TOL5": "Valor",diff --git a/client/messages/uk.json b/client/messages/uk.jsonindex a301bf61f..12e2ffc3f 100644--- a/client/messages/uk.json+++ b/client/messages/uk.json@@ -61,6 +61,7 @@"mByYl9": "% переглядів сторінок","IuFETn": "Тривалість","0eoYsu": "Показник відмов",+ "QashlR": "Під час отримання даних сталася помилка","IxrHg4": "Фільтрувати {count} елементів...","tL4WC1": "Завантаження...","HPx76n": "Всі елементи завантажено",@@ -74,6 +75,8 @@"XHLYdJ": "Цілі","9d/EEp": "Продуктова аналітика","5yUsUe": "Відтворення",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "Воронки","08hqOd": "Шляхи","nL6Jl0": "Утримання",@@ -242,6 +245,212 @@"BReFYW": "Зміни полів вводу","NDoUa9": "Усі типи подій приховано","MJ2jZQ": "Усього",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "Ціль #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "Назва події",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "Чернетка",+ "LHF3Za": "",+ "47FYwb": "Скасувати",+ "rbrahO": "Закрити",+ "cyR7Kh": "",+ "TiR/Hq": "Збереження...",+ "mRL9Vh": "Створення...",+ "X0ha1a": "",+ "JXdbo8": "Готово",+ "acrOoz": "Продовжити",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "Пауза",+ "U78NhE": "",+ "wL7VAE": "Дії",+ "wEQDC6": "",+ "K3r6DQ": "Видалити",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "Статус",+ "Zh+5A6": "Увімк.",+ "OvzONl": "Вимк.",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "Створено",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "Ключ",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "Усі кроки повинні мати значення","jm52QG": "Будь ласка, введіть назву воронки","+N7isb": "Воронку успішно збережено",@@ -273,7 +482,6 @@"+U6ozc": "Тип","m1czzY": "Подія","Y6DkLY": "Шлях (наприклад, /pricing)",- "eOj4Bs": "Назва події","Hp/0iW": "Введіть шлях (наприклад, /checkout), а не повну URL-адресу.","Asi2Jg": "Приховати розширені опції","lIEejV": "Показати розширені опції",@@ -287,8 +495,6 @@"tINfvW": "Використовуйте * для збігу з одним сегментом шляху (напр., /blog/*) або ** для збігу з кількома сегментами (напр., /docs/**/intro)","ox304v": "Сталася помилка","KbGBQH": "Сталася помилка під час збереження",- "47FYwb": "Скасувати",- "TiR/Hq": "Збереження...","/liMUf": "Воронку успішно видалено","753yX5": "Мітка","+SDMR3": "Властивість",@@ -298,7 +504,6 @@"SB3+JE": "Дані воронки недоступні","45gABM": "Ви впевнені, що хочете видалити \"{name}\"? Цю дію неможливо скасувати.","noZdV2": "Видалення...",- "K3r6DQ": "Видалити","GoxzAN": "Фільтрувати воронки","qGN7M9": "Не вдалося завантажити воронки","5/6deG": "Виникла проблема під час отримання воронок. Будь ласка, спробуйте пізніше.",@@ -328,16 +533,15 @@"h3ICzV": "Завантаження сеансів...","KjXPXZ": "{count} сеансів","9iSdEj": "{count} сеанс",- "tFFMkF": "Пауза","J3ca41": "Відтворити","Ggedt8": "Показано лише перші {count} сеансів. Можуть бути доступні додаткові дані.","5WuADX": "Додати ціль",+ "WuHoZ9": "Конверсії",+ "e/U0Xt": "Коефіцієнт конверсії","+Ior19": "Цільова сторінка","rTE34i": "Цільова подія",- "FYBPJU": "Ціль #{goalId}","pW4lxD": "Шаблон",- "WuHoZ9": "Конверсії",- "e/U0Xt": "Коефіцієнт конверсії",+ "99Lkvz": "","sOXElg": "Редагувати ціль","N/ctXb": "Клонувати ціль","F3XA9+": "Видалити ціль",@@ -395,10 +599,10 @@"zuqMfZ": "Карта","jUSc45": "Часові пояси","NdE4Ps": "Браузери",+ "/VnDMl": "Інше","+20FW7": "Пристрої","aTW7It": "Операційні системи","3X4r56": "Роздільна здатність екрана",- "/VnDMl": "Інше","Aujn2T": "Кількість","ogKEiU": "Вихідні посилання","VLKK35": "Кліки",@@ -407,13 +611,14 @@"pEc/5k": "% кліків","wU7PzI": "Останній клік","4KEfRY": "Заголовки",- "87ZCAe": "Входи",- "0ogV14": "Виходи",- "P6RGqE": "Імена хостів","gvOzOl": "Заголовок сторінки",+ "87ZCAe": "Входи","vFf5xV": "Сторінки входу",+ "0ogV14": "Виходи","KtC97P": "Сторінки виходу",+ "P6RGqE": "Імена хостів","iF/x8v": "Джерела переходу",+ "UF6kPm": "Прямий (Direct)","LUrJwE": "Канали","aH4De2": "Джерело","ovJ26C": "Канал (Medium)",@@ -421,7 +626,6 @@"qTy5se": "Термін","Jq3FDz": "Контент","grtbAW": "UTM",- "UF6kPm": "Прямий (Direct)","0E9k6Y": "Підключіть акаунт Google Search Console, щоб переглядати дані про ефективність пошуку, включно з топовими ключовими словами та сторінками.","jioGL4": "Підключити Google Search Console","M/h5TN": "Покази",@@ -550,7 +754,6 @@"uiy9pN": "Події (30 днів)","9juexR": "Деталі підписки","fz0z4c": "План",- "tzMNF3": "Статус","T8qVXf": "Ліміт подій","ekXood": "Безліміт","5x9Sl1": "Кінець періоду",@@ -563,7 +766,6 @@"bGIAle": "Учасники ({count})","hQZhn8": "Імперсонація","2ZpsMl": "Немає учасників",- "G/yZLu": "","nJuUfX": "Пошук за назвою, slug, доменом або email учасника...","RllRQH": "Показати організації з 0 подій (30 днів)","7OL11E": "Лише ті, що перевищили ліміт",@@ -578,7 +780,6 @@"uL0dMG": "Використання всього сервісу - Останні {timePeriod}","SVwJTM": "Експорт","K56Dim": "Організація",- "ORGv1Q": "Створено","JKxOsh": "Щомісячні події","R/6nsx": "Підписка","DDhP4z": "Сайти",@@ -596,8 +797,6 @@"viXE32": "Приватний","6hdNA5": "Події (24 год)","J4r/Gi": "Події (30 днів)",- "Zh+5A6": "Увімк.",- "OvzONl": "Вимк.","C2EM7h": "Email власника","sEqhTf": "Не вдалося завантажити дані сайтів. Будь ласка, спробуйте пізніше.","r9Y1x6": "Шукати за доменом або email власника...",@@ -626,7 +825,6 @@"uA0DvF": "Не вдалося видалити користувача з організації","PW+sL4": "Н/Д","wittYy": "Створено",- "wL7VAE": "Дії","bdcMGy": "Відкрити меню","6gHGy0": "Видалити з організації","J2wna+": "Видалити користувача з організації?",@@ -744,19 +942,16 @@"u4673k": "Створюйте API-ключі для доступу до ендпоінтів аналітики з ваших застосунків","1fe3VI": "Ключі API доступні в планах Standard та Pro.","AkVL9j": "Назва API-ключа",- "mRL9Vh": "Створення...","jDvHYJ": "Ваші API-ключі","MUaUWe": "Завантаження API-ключів...","iX4wwR": "Не вдалося завантажити API-ключі","62nsdy": "Повторити спробу",- "EcglP9": "Ключ","IY105q": "Ще не створено жодного API-ключа","wPtCEB": "API-ключ створено","qcTCG8": "Збережіть цей API-ключ у надійному місці. Ви більше не зможете його побачити.","51jo4g": "Ваш API-ключ","+fICx5": "Важливо","TsKkxv": "Зберігайте цей ключ у безпечному місці. Він більше не відображатиметься.",- "JXdbo8": "Готово","LuNBqj": "Пароль має містити щонайменше 8 символів","UjlqkD": "Надійний пароль","EK3962": "Хороший пароль",@@ -886,7 +1081,6 @@"S5IFjk": "Створіть команду, щоб групувати сайти та керувати доступом.","StUScz": "{count} учасників","RNCPOG": "Реєстрація",- "acrOoz": "Продовжити","uCk8r+": "Вже є акаунт?","odXlk8": "Увійти","uWRAQk": "Виберіть ваш тарифний план",@@ -996,7 +1190,6 @@"W5IIP8": "Перейдіть на {planName}, щоб розблокувати {message}","4Y+tpi": "Подивитися демо цієї функції","RL7HbL": "Попросіть власника організації перейти на план Pro, щоб розблокувати {message}",- "QashlR": "Під час отримання даних сталася помилка","jsy7pk": "Спробувати ще раз","hyfdry": "Перегляд сторінки","/kZg9i": "Клік по кнопці",@@ -1196,7 +1389,6 @@"jjBvFh": "","6cBDhe": "","IP4n+n": "",- "rbrahO": "Закрити","scL+IP": "","8pKlHk": "","mhmZ+P": "Відтворення сеансів",@@ -1243,7 +1435,6 @@"u/vOPu": "Оплачено","jHfCjd": "Анульовано","45hFQt": "Безнадійний",- "W6nwjo": "Чернетка","6dqYnF": "Рахунки","P7PLVj": "Дата","/0TOL5": "Сума",diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex b39cc4ce8..9d6c58526 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -61,6 +61,7 @@"mByYl9": "页面浏览量 %","IuFETn": "时长","0eoYsu": "跳出率",+ "QashlR": "获取数据时出错","IxrHg4": "过滤 {count} 个项目...","tL4WC1": "正在加载更多...","HPx76n": "所有项目已加载",@@ -74,6 +75,8 @@"XHLYdJ": "目标","9d/EEp": "产品分析","5yUsUe": "会话回放",+ "mZDrWI": "",+ "5qmtY1": "","puhcpn": "漏斗","08hqOd": "旅程","nL6Jl0": "留存",@@ -242,6 +245,212 @@"BReFYW": "输入变更","NDoUa9": "所有事件类型已隐藏","MJ2jZQ": "总计",+ "jZu+25": "",+ "l31E69": "",+ "E/9k/a": "",+ "yl0JSO": "",+ "gyIvpP": "",+ "z2PIbo": "",+ "zZE+e+": "",+ "c6cv5o": "",+ "U3UQfB": "",+ "f5efCD": "",+ "SDTG4X": "",+ "z0076i": "",+ "iKhvJV": "",+ "XocxqF": "",+ "dv+Q6J": "",+ "rYzinM": "",+ "qkaC6i": "",+ "Gvxoji": "",+ "C4BsF8": "",+ "CZmGBZ": "",+ "9VDOG/": "",+ "k/CG+N": "",+ "dSrAoR": "",+ "/ZZy+J": "",+ "PqvkpE": "",+ "VUiN28": "",+ "VYRbh1": "",+ "DSOKGF": "",+ "ERZKPw": "",+ "4gDkIw": "",+ "5CbP3g": "",+ "ANmBWb": "",+ "iBImEo": "",+ "JfUnvy": "",+ "Q8Qw5B": "",+ "Yx6aRS": "",+ "F4tWun": "",+ "rv+WdZ": "",+ "8mBWZJ": "",+ "2Rli0c": "",+ "2S4QtW": "",+ "6bhRx4": "",+ "3kwz2Z": "",+ "O6zCyZ": "",+ "LICoyV": "",+ "NFTkNB": "",+ "h5P++h": "",+ "1HsqR2": "",+ "JWzoaP": "",+ "dOQCL8": "",+ "MYsZNO": "",+ "5U2wOH": "",+ "nDvQwt": "",+ "dCxCGt": "",+ "I5k4g/": "",+ "8O/fqy": "",+ "WYzHAI": "",+ "gpx4DX": "",+ "wIRNFx": "",+ "UHg01d": "",+ "FYBPJU": "目标 #{goalId}",+ "93jr/b": "",+ "WCs0QZ": "",+ "VUomb6": "",+ "9E7Zda": "",+ "99HM2b": "",+ "S4zxrU": "",+ "XQSLMK": "",+ "eOj4Bs": "事件名称",+ "sXo0km": "",+ "qWzbG9": "",+ "pH6sDe": "",+ "TUwf1V": "",+ "vmlGzW": "",+ "Dmxerh": "",+ "wzKC2G": "",+ "itC9lG": "",+ "XPX/Qj": "",+ "0VV/sK": "",+ "dLj+dT": "",+ "Lu6+QS": "",+ "qdOqu/": "",+ "tGuKrF": "",+ "W6nwjo": "草稿",+ "LHF3Za": "",+ "47FYwb": "取消",+ "rbrahO": "关闭",+ "cyR7Kh": "",+ "TiR/Hq": "正在保存...",+ "mRL9Vh": "正在创建...",+ "X0ha1a": "",+ "JXdbo8": "完成",+ "acrOoz": "继续",+ "H+vBOj": "",+ "1SjAqf": "",+ "NZ9+vv": "",+ "UAVBcs": "",+ "QFTqtX": "",+ "ytceSa": "",+ "vGMvPS": "",+ "XQ/KBk": "",+ "jt9BUv": "",+ "nW9O3w": "",+ "cT4fRl": "",+ "EHoeo0": "",+ "ttyUm0": "",+ "l94vPo": "",+ "qQTwNl": "",+ "IuPATc": "",+ "W1QsrY": "",+ "UBQJK/": "",+ "4IJvOg": "",+ "iHip8n": "",+ "kNp7lL": "",+ "VK7C0v": "",+ "G2HskF": "",+ "l6cRsG": "",+ "6MkXA0": "",+ "mOFG3K": "",+ "tFFMkF": "暂停",+ "U78NhE": "",+ "wL7VAE": "操作",+ "wEQDC6": "",+ "K3r6DQ": "删除",+ "poMLbD": "",+ "qzqYO3": "",+ "4YGHzj": "",+ "l2og1o": "",+ "wLuWPJ": "",+ "39mVGa": "",+ "sL8dAy": "",+ "U5hCuK": "",+ "wmdo1a": "",+ "fg8dzN": "",+ "Rp+Vr1": "",+ "lKv8ex": "",+ "wmFdws": "",+ "H/r5m6": "",+ "G/yZLu": "删除",+ "7/7DdD": "",+ "Cn4/rZ": "",+ "Vwukkb": "",+ "d1OgED": "",+ "rdE5Ca": "",+ "CoSEZb": "",+ "obVxeM": "",+ "GeY2EU": "",+ "9ctGsY": "",+ "Ctj1re": "",+ "TFVlrR": "",+ "TI5GPL": "",+ "5kpx3b": "",+ "I4Etgx": "",+ "n5XyC0": "",+ "+9SBpl": "",+ "rHJwM0": "",+ "jTMl6R": "",+ "2Nj3gm": "",+ "bAv8xK": "",+ "Dn82AL": "",+ "C2iTEH": "",+ "gnvAJX": "",+ "IX0C9y": "",+ "4QGk64": "",+ "wbsq7O": "",+ "WuGkfJ": "",+ "E/O9LL": "",+ "V52jNn": "",+ "66kGA0": "",+ "vPG+A7": "",+ "+R0VMp": "",+ "q2ZLFN": "",+ "rxCN7M": "",+ "bSCV9J": "",+ "tzMNF3": "状态",+ "Zh+5A6": "开启",+ "OvzONl": "关闭",+ "kAAlGL": "",+ "ZDpTud": "",+ "ORGv1Q": "已创建",+ "xrk6zg": "",+ "9qBH5R": "",+ "10IQpb": "",+ "gzM1em": "",+ "V+QgiY": "",+ "3mvL2Q": "",+ "AbvQFb": "",+ "EcglP9": "密钥",+ "gzX6Vt": "",+ "7CyD7e": "",+ "LzfPAG": "",+ "HcAcrp": "",+ "J4E+jp": "",+ "DIZgr3": "",+ "lu/vDB": "",+ "9uKBh7": "",+ "JX0502": "",+ "F/6VqP": "",+ "oA0ogD": "",+ "4ZtLoe": "",+ "rWPtv+": "",+ "VJWJyq": "",+ "3tP/PN": "",+ "jhVKvF": "",+ "SBUMrd": "",+ "wsKkfk": "","z6IYcX": "所有步骤都必须有值","jm52QG": "请输入漏斗名称","+N7isb": "漏斗保存成功",@@ -273,7 +482,6 @@"+U6ozc": "类型","m1czzY": "事件","Y6DkLY": "路径(例如 /pricing)",- "eOj4Bs": "事件名称","Hp/0iW": "输入一个路径(例如 /checkout),而不是完整的 URL。","Asi2Jg": "隐藏高级选项","lIEejV": "显示高级选项",@@ -287,8 +495,6 @@"tINfvW": "使用 * 匹配单个路径段(例如 /blog/*)或使用 ** 匹配多个段(例如 /docs/**/intro)","ox304v": "发生错误","KbGBQH": "保存时发生错误",- "47FYwb": "取消",- "TiR/Hq": "正在保存...","/liMUf": "漏斗删除成功","753yX5": "标签","+SDMR3": "属性",@@ -298,7 +504,6 @@"SB3+JE": "没有可用的漏斗数据","45gABM": "您确定要删除“{name}”吗?此操作无法撤销。","noZdV2": "正在删除...",- "K3r6DQ": "删除","GoxzAN": "过滤漏斗","qGN7M9": "加载漏斗失败","5/6deG": "获取漏斗时出现问题。请稍后重试。",@@ -328,16 +533,15 @@"h3ICzV": "正在加载会话...","KjXPXZ": "{count} 个会话","9iSdEj": "{count} 个会话",- "tFFMkF": "暂停","J3ca41": "播放","Ggedt8": "仅显示前 {count} 个会话。可能有更多数据可用。","5WuADX": "添加目标",+ "WuHoZ9": "转化次数",+ "e/U0Xt": "转化率","+Ior19": "页面目标","rTE34i": "事件目标",- "FYBPJU": "目标 #{goalId}","pW4lxD": "模式",- "WuHoZ9": "转化次数",- "e/U0Xt": "转化率",+ "99Lkvz": "","sOXElg": "编辑目标","N/ctXb": "克隆目标","F3XA9+": "删除目标",@@ -395,10 +599,10 @@"zuqMfZ": "地图","jUSc45": "时区","NdE4Ps": "浏览器",+ "/VnDMl": "其他","+20FW7": "设备","aTW7It": "操作系统","3X4r56": "屏幕尺寸",- "/VnDMl": "其他","Aujn2T": "计数","ogKEiU": "出站链接","VLKK35": "点击次数",@@ -407,13 +611,14 @@"pEc/5k": "点击 %","wU7PzI": "最后点击时间","4KEfRY": "标题",- "87ZCAe": "入口",- "0ogV14": "出口",- "P6RGqE": "主机名","gvOzOl": "页面标题",+ "87ZCAe": "入口","vFf5xV": "入口页面",+ "0ogV14": "出口","KtC97P": "退出页面",+ "P6RGqE": "主机名","iF/x8v": "来源网站",+ "UF6kPm": "直接访问","LUrJwE": "渠道","aH4De2": "来源","ovJ26C": "媒介",@@ -421,7 +626,6 @@"qTy5se": "关键词","Jq3FDz": "内容","grtbAW": "UTM",- "UF6kPm": "直接访问","0E9k6Y": "连接您的 Google Search Console 账户以查看搜索性能数据,包括热门关键词和页面。","jioGL4": "连接 Google Search Console","M/h5TN": "展示次数",@@ -550,7 +754,6 @@"uiy9pN": "30天事件","9juexR": "订阅详情","fz0z4c": "计划",- "tzMNF3": "状态","T8qVXf": "事件限制","ekXood": "无限制","5x9Sl1": "计费周期结束",@@ -563,7 +766,6 @@"bGIAle": "成员 ({count})","hQZhn8": "模拟身份","2ZpsMl": "无成员",- "G/yZLu": "删除","nJuUfX": "按名称、标识符、域名或成员邮箱搜索...","RllRQH": "显示 0 个事件的组织 (30天)","7OL11E": "仅超额",@@ -578,7 +780,6 @@"uL0dMG": "全服务使用情况 - 过去 {timePeriod}","SVwJTM": "导出","K56Dim": "组织",- "ORGv1Q": "已创建","JKxOsh": "每月事件","R/6nsx": "订阅","DDhP4z": "网站",@@ -596,8 +797,6 @@"viXE32": "私有","6hdNA5": "事件 (24小时)","J4r/Gi": "事件 (30天)",- "Zh+5A6": "开启",- "OvzONl": "关闭","C2EM7h": "所有者电子邮件","sEqhTf": "加载网站数据失败。请稍后重试。","r9Y1x6": "按域名或所有者电子邮件搜索...",@@ -626,7 +825,6 @@"uA0DvF": "从组织中移除用户失败","PW+sL4": "不适用","wittYy": "创建时间",- "wL7VAE": "操作","bdcMGy": "打开菜单","6gHGy0": "从组织中移除","J2wna+": "从组织中移除用户?",@@ -744,19 +942,16 @@"u4673k": "生成 API 密钥以便从您的应用程序访问分析端点","1fe3VI": "API 密钥在标准版和专业版计划中可用。","AkVL9j": "API 密钥名称",- "mRL9Vh": "正在创建...","jDvHYJ": "您的 API 密钥","MUaUWe": "正在加载 API 密钥...","iX4wwR": "加载 API 密钥失败","62nsdy": "重试",- "EcglP9": "密钥","IY105q": "尚未创建任何 API 密钥","wPtCEB": "API 密钥已创建","qcTCG8": "请安全保存此 API 密钥。您将无法再次查看它。","51jo4g": "您的 API 密钥","+fICx5": "重要","TsKkxv": "请安全地存储此密钥。它将不会再次显示。",- "JXdbo8": "完成","LuNBqj": "密码至少应为 8 个字符","UjlqkD": "强密码","EK3962": "好密码",@@ -886,7 +1081,6 @@"S5IFjk": "创建团队以对站点进行分组并管理成员访问权限。","StUScz": "{count} 名成员","RNCPOG": "注册",- "acrOoz": "继续","uCk8r+": "已经有账户了?","odXlk8": "登录","uWRAQk": "选择您的计划",@@ -996,7 +1190,6 @@"W5IIP8": "升级到 {planName} 即可解锁 {message}","4Y+tpi": "查看此功能的演示","RL7HbL": "请求您的组织所有者升级到 Pro 即可解锁 {message}",- "QashlR": "获取数据时出错","jsy7pk": "再试一次","hyfdry": "页面浏览","/kZg9i": "按钮点击",@@ -1196,7 +1389,6 @@"jjBvFh": "排除项","6cBDhe": "集成","IP4n+n": "小部件嵌入",- "rbrahO": "关闭","scL+IP": "小部件已启用","8pKlHk": "启用嵌入小部件","mhmZ+P": "会话回放",@@ -1243,7 +1435,6 @@"u/vOPu": "已付款","jHfCjd": "已作废","45hFQt": "无法收回",- "W6nwjo": "草稿","6dqYnF": "发票","P7PLVj": "日期","/0TOL5": "金额",diff --git a/client/package-lock.json b/client/package-lock.jsonindex f0399fd44..38130b5d1 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -14,6 +14,7 @@"@hookform/resolvers": "5.0.1","@icons-pack/react-simple-icons": "^13.6.0","@marsidev/react-turnstile": "^1.3.1",+ "@monaco-editor/react": "^4.7.0","@nivo/bar": "0.96.0","@nivo/calendar": "0.96.0","@nivo/line": "0.96.0",@@ -1376,6 +1377,29 @@"react-dom": "^17.0.2 || ^18.0.0 || ^19.0"}},+ "node_modules/@monaco-editor/loader": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/loader/-/loader-1.7.0.tgz",+ "integrity": "sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==",+ "license": "MIT",+ "dependencies": {+ "state-local": "^1.0.6"+ }+ },+ "node_modules/@monaco-editor/react": {+ "version": "4.7.0",+ "resolved": "https://registry.npmjs.org/@monaco-editor/react/-/react-4.7.0.tgz",+ "integrity": "sha512-cyzXQCtO47ydzxpQtCGSQGOC8Gk3ZUeBXFAxD+CWXYFo5OqZyZUonFl0DwUlTyAfRHntBfw2p3w4s9R6oe1eCA==",+ "license": "MIT",+ "dependencies": {+ "@monaco-editor/loader": "^1.5.0"+ },+ "peerDependencies": {+ "monaco-editor": ">= 0.25.0 < 1",+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.0.tgz",@@ -12283,6 +12307,12 @@"dev": true,"license": "MIT"},+ "node_modules/state-local": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/state-local/-/state-local-1.0.7.tgz",+ "integrity": "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==",+ "license": "MIT"+ },"node_modules/stop-iteration-iterator": {"version": "1.1.0","resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",diff --git a/client/package.json b/client/package.jsonindex f9f37df64..1d51b8519 100644--- a/client/package.json+++ b/client/package.json@@ -19,6 +19,7 @@"@hookform/resolvers": "5.0.1","@icons-pack/react-simple-icons": "^13.6.0","@marsidev/react-turnstile": "^1.3.1",+ "@monaco-editor/react": "^4.7.0","@nivo/bar": "0.96.0","@nivo/calendar": "0.96.0","@nivo/line": "0.96.0",diff --git a/client/src/api/analytics/endpoints/experiments.ts b/client/src/api/analytics/endpoints/experiments.tsnew file mode 100644index 000000000..3557d3679--- /dev/null+++ b/client/src/api/analytics/endpoints/experiments.ts@@ -0,0 +1,139 @@+import { authedFetch } from "../../utils";+import type {+ FeatureFlagConditionSet,+ FeatureFlagPayloadValue,+ FeatureFlagRuntime,+ FeatureFlagType,+ FeatureFlagVariant,+} from "./featureFlags";+import { CommonApiParams, toQueryParams } from "./types";++export type ExperimentStatus = "draft" | "running" | "paused" | "completed";++export type ExperimentFeatureFlag = {+ flagId: number;+ siteId: number;+ key: string;+ description: string | null;+ enabled: boolean;+ runtime: FeatureFlagRuntime;+ flagType: FeatureFlagType;+ payload?: FeatureFlagPayloadValue | null;+ variants: FeatureFlagVariant[];+ rolloutPercentage: number;+ conditionSets: FeatureFlagConditionSet[];+ version: number;+ createdAt: string;+ updatedAt: string;+};++export type ExperimentGoal = {+ goalId: number;+ siteId: number;+ name: string | null;+ goalType: "path" | "event";+ config: {+ pathPattern?: string;+ eventName?: string;+ eventPropertyKey?: string;+ eventPropertyValue?: string | number | boolean;+ propertyFilters?: Array<{+ key: string;+ value: string | number | boolean;+ }>;+ };+ createdAt: string;+};++export type Experiment = {+ experimentId: number;+ siteId: number;+ featureFlagId: number;+ primaryGoalId: number | null;+ name: string;+ description: string | null;+ hypothesis: string | null;+ status: ExperimentStatus;+ winningVariant: string | null;+ startedAt: string | null;+ endedAt: string | null;+ createdAt: string;+ updatedAt: string;+ featureFlag: ExperimentFeatureFlag;+ primaryGoal: ExperimentGoal | null;+};++export type ExperimentPayload = {+ name: string;+ description?: string | null;+ hypothesis?: string | null;+ featureFlagId: number;+ primaryGoalId?: number | null;+ status: ExperimentStatus;+ winningVariant?: string | null;+};++export type ExperimentUpdatePayload = Partial<ExperimentPayload>;++export type ExperimentVariantResult = {+ variant: string;+ sessions: number;+ exposures: number;+ conversions: number;+ conversionRate: number;+ lift: number | null;+ isControl: boolean;+};++export type ExperimentResults = {+ experiment: Experiment;+ variants: ExperimentVariantResult[];+ totalExposureSessions: number;+ totalConversions: number;+ hasGoal: boolean;+ measurement: "exposure" | "assignment";+};++export async function fetchExperiments(site: string | number): Promise<Experiment[]> {+ const response = await authedFetch<{ data: Experiment[] }>(`/sites/${site}/experiments`);+ return response.data;+}++export async function createExperiment(+ site: string | number,+ payload: ExperimentPayload+): Promise<{ success: boolean; data: Experiment }> {+ return authedFetch(`/sites/${site}/experiments`, undefined, {+ method: "POST",+ data: payload,+ });+}++export async function updateExperiment(+ site: string | number,+ experimentId: number,+ payload: ExperimentUpdatePayload+): Promise<{ success: boolean; data: Experiment }> {+ return authedFetch(`/sites/${site}/experiments/${experimentId}`, undefined, {+ method: "PUT",+ data: payload,+ });+}++export async function deleteExperiment(site: string | number, experimentId: number): Promise<{ success: boolean }> {+ return authedFetch(`/sites/${site}/experiments/${experimentId}`, undefined, {+ method: "DELETE",+ });+}++export async function fetchExperimentResults(+ site: string | number,+ experimentId: number,+ params: CommonApiParams+): Promise<ExperimentResults> {+ const response = await authedFetch<{ data: ExperimentResults }>(+ `/sites/${site}/experiments/${experimentId}/results`,+ toQueryParams(params)+ );+ return response.data;+}diff --git a/client/src/api/analytics/endpoints/featureFlags.ts b/client/src/api/analytics/endpoints/featureFlags.tsnew file mode 100644index 000000000..fcf2fee65--- /dev/null+++ b/client/src/api/analytics/endpoints/featureFlags.ts@@ -0,0 +1,118 @@+import { authedFetch } from "../../utils";++export type FeatureFlagType = "boolean" | "multivariate" | "remote_config";+export type FeatureFlagRuntime = "client" | "server" | "both";+export type FeatureFlagPayloadValue =+ | string+ | number+ | boolean+ | null+ | FeatureFlagPayloadValue[]+ | { [key: string]: FeatureFlagPayloadValue };++export type FeatureFlagRule = {+ field:+ | "hostname"+ | "pathname"+ | "query"+ | "referrer"+ | "language"+ | "country"+ | "region"+ | "city"+ | "device_type"+ | "user_id"+ | "trait";+ key?: string;+ operator: "equals" | "not_equals" | "contains" | "starts_with" | "ends_with" | "regex";+ value: string | number | boolean | Array<string | number | boolean>;+};++export type FeatureFlagVariant = {+ key: string;+ name?: string;+ rolloutPercentage: number;+ payload?: FeatureFlagPayloadValue;+};++export type FeatureFlagConditionSet = {+ name?: string;+ rules: FeatureFlagRule[];+ rolloutPercentage?: number;+ variants?: FeatureFlagVariant[];+ payload?: FeatureFlagPayloadValue | null;+};++export type FeatureFlagStats = {+ flag_key: string;+ flag_value: string;+ sessions: number;+ events: number;+ exposures: number;+};++export type FeatureFlag = {+ flagId: number;+ siteId: number;+ key: string;+ description: string | null;+ enabled: boolean;+ runtime: FeatureFlagRuntime;+ flagType: FeatureFlagType;+ payload?: FeatureFlagPayloadValue | null;+ variants: FeatureFlagVariant[];+ rolloutPercentage: number;+ rules: FeatureFlagRule[];+ conditionSets: FeatureFlagConditionSet[];+ version: number;+ createdAt: string;+ updatedAt: string;+ stats: FeatureFlagStats[];+};++export type FeatureFlagPayload = {+ key: string;+ description?: string | null;+ enabled: boolean;+ runtime: FeatureFlagRuntime;+ flagType: FeatureFlagType;+ payload?: FeatureFlagPayloadValue | null;+ variants: FeatureFlagVariant[];+ rolloutPercentage: number;+ rules: FeatureFlagRule[];+ conditionSets: FeatureFlagConditionSet[];+};++export type FeatureFlagUpdatePayload = Partial<FeatureFlagPayload>;++export async function fetchFeatureFlags(site: string | number): Promise<FeatureFlag[]> {+ const response = await authedFetch<{ data: FeatureFlag[] }>(`/sites/${site}/feature-flags`);+ return response.data;+}++export async function createFeatureFlag(+ site: string | number,+ payload: FeatureFlagPayload+): Promise<{ success: boolean; data: FeatureFlag }> {+ return authedFetch(`/sites/${site}/feature-flags`, undefined, {+ method: "POST",+ data: payload,+ });+}++export async function updateFeatureFlag(+ site: string | number,+ flagId: number,+ payload: FeatureFlagUpdatePayload+): Promise<{ success: boolean; data: FeatureFlag }> {+ return authedFetch(`/sites/${site}/feature-flags/${flagId}`, undefined, {+ method: "PUT",+ data: payload,+ });+}++export async function deleteFeatureFlag(site: string | number, flagId: number): Promise<{ success: boolean }> {+ return authedFetch(`/sites/${site}/feature-flags/${flagId}`, undefined, {+ method: "DELETE",+ });+}diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.tsindex f3965ceb5..7bf4b41cf 100644--- a/client/src/api/analytics/endpoints/index.ts+++ b/client/src/api/analytics/endpoints/index.ts@@ -63,6 +63,40 @@ export type {UpdateGoalParams,} from "./goals";+// Feature flag endpoints+export { fetchFeatureFlags, createFeatureFlag, updateFeatureFlag, deleteFeatureFlag } from "./featureFlags";+export type {+ FeatureFlag,+ FeatureFlagConditionSet,+ FeatureFlagPayload,+ FeatureFlagPayloadValue,+ FeatureFlagRule,+ FeatureFlagRuntime,+ FeatureFlagStats,+ FeatureFlagType,+ FeatureFlagUpdatePayload,+ FeatureFlagVariant,+} from "./featureFlags";++// Experiment endpoints+export {+ createExperiment,+ deleteExperiment,+ fetchExperimentResults,+ fetchExperiments,+ updateExperiment,+} from "./experiments";+export type {+ Experiment,+ ExperimentFeatureFlag,+ ExperimentGoal,+ ExperimentPayload,+ ExperimentResults,+ ExperimentStatus,+ ExperimentUpdatePayload,+ ExperimentVariantResult,+} from "./experiments";+// Funnels endpointsexport { fetchFunnels, analyzeFunnel, fetchFunnelStepSessions, saveFunnel, deleteFunnel } from "./funnels";export type {diff --git a/client/src/api/analytics/hooks/experiments/useExperiments.ts b/client/src/api/analytics/hooks/experiments/useExperiments.tsnew file mode 100644index 000000000..84175c16e--- /dev/null+++ b/client/src/api/analytics/hooks/experiments/useExperiments.ts@@ -0,0 +1,73 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ createExperiment,+ deleteExperiment,+ ExperimentPayload,+ ExperimentUpdatePayload,+ fetchExperimentResults,+ fetchExperiments,+ updateExperiment,+} from "../../endpoints";+import { buildApiParams } from "../../../utils";+import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";+import { getFilteredFilters, useStore } from "../../../../lib/store";++export function useExperiments() {+ const { site } = useStore();++ return useQuery({+ queryKey: ["experiments", site],+ queryFn: () => fetchExperiments(site),+ enabled: !!site,+ });+}++export function useExperimentResults(experimentId: number, enabled = true) {+ const { site, time, timezone } = useStore();+ const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);+ const params = buildApiParams(time, { filters: filteredFilters });++ return useQuery({+ queryKey: ["experiment-results", site, experimentId, time, filteredFilters, timezone],+ queryFn: () => fetchExperimentResults(site, experimentId, params),+ enabled: !!site && !!experimentId && enabled,+ });+}++export function useCreateExperiment() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: (payload: ExperimentPayload) => createExperiment(site, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["experiments", site] });+ },+ });+}++export function useUpdateExperiment() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: ({ experimentId, payload }: { experimentId: number; payload: ExperimentUpdatePayload }) =>+ updateExperiment(site, experimentId, payload),+ onSuccess: (_data, variables) => {+ queryClient.invalidateQueries({ queryKey: ["experiments", site] });+ queryClient.invalidateQueries({ queryKey: ["experiment-results", site, variables.experimentId] });+ },+ });+}++export function useDeleteExperiment() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: (experimentId: number) => deleteExperiment(site, experimentId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["experiments", site] });+ },+ });+}diff --git a/client/src/api/analytics/hooks/featureFlags/useFeatureFlags.ts b/client/src/api/analytics/hooks/featureFlags/useFeatureFlags.tsnew file mode 100644index 000000000..ed5ac1481--- /dev/null+++ b/client/src/api/analytics/hooks/featureFlags/useFeatureFlags.ts@@ -0,0 +1,57 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ createFeatureFlag,+ deleteFeatureFlag,+ fetchFeatureFlags,+ FeatureFlagPayload,+ FeatureFlagUpdatePayload,+ updateFeatureFlag,+} from "../../endpoints";+import { useStore } from "../../../../lib/store";++export function useFeatureFlags() {+ const { site } = useStore();++ return useQuery({+ queryKey: ["feature-flags", site],+ queryFn: () => fetchFeatureFlags(site),+ enabled: !!site,+ });+}++export function useCreateFeatureFlag() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: (payload: FeatureFlagPayload) => createFeatureFlag(site, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["feature-flags", site] });+ },+ });+}++export function useUpdateFeatureFlag() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: ({ flagId, payload }: { flagId: number; payload: FeatureFlagUpdatePayload }) =>+ updateFeatureFlag(site, flagId, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["feature-flags", site] });+ },+ });+}++export function useDeleteFeatureFlag() {+ const queryClient = useQueryClient();+ const { site } = useStore();++ return useMutation({+ mutationFn: (flagId: number) => deleteFeatureFlag(site, flagId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["feature-flags", site] });+ },+ });+}diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsxindex 33657afb4..7a9ece4bf 100644--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx@@ -5,6 +5,8 @@ import {ChartColumnDecreasing,Code,File,+ Flag,+ FlaskConical,Funnel,Gauge,Globe2,@@ -40,6 +42,8 @@ function SidebarContent() {if (hideSidebar) return null;+ const { privateKey } = getSiteRouteContext(pathname);+// Check which tab is active based on the current pathconst getTabPath = (tabName: string) => {const { siteId, privateKey } = getSiteRouteContext(pathname);@@ -128,6 +132,22 @@ function SidebarContent() {/>)}</div>+ {!privateKey && (+ <SidebarComponents.Item+ label={t("Feature Flags")}+ active={isActiveTab("feature-flags")}+ href={getTabPath("feature-flags")}+ icon={<Flag className="w-4 h-4" />}+ />+ )}+ {!privateKey && (+ <SidebarComponents.Item+ label={t("Experiments")}+ active={isActiveTab("experiments")}+ href={getTabPath("experiments")}+ icon={<FlaskConical className="w-4 h-4" />}+ />+ )}<SidebarComponents.Itemlabel={t("Funnels")}active={isActiveTab("funnels")}diff --git a/client/src/app/[site]/experiments/components/CreateExperimentWizard.tsx b/client/src/app/[site]/experiments/components/CreateExperimentWizard.tsxnew file mode 100644index 000000000..0d9f22bd2--- /dev/null+++ b/client/src/app/[site]/experiments/components/CreateExperimentWizard.tsx@@ -0,0 +1,1210 @@+"use client";++import type { Experiment, FeatureFlagVariant } from "@/api/analytics/endpoints";+import { useCreateExperiment, useUpdateExperiment } from "@/api/analytics/hooks/experiments/useExperiments";+import { useCreateFeatureFlag, useFeatureFlags } from "@/api/analytics/hooks/featureFlags/useFeatureFlags";+import { useCreateGoal } from "@/api/analytics/hooks/goals/useCreateGoal";+import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";+import { useMetric } from "@/api/analytics/hooks/useGetMetric";+import { CodeSnippet } from "@/components/CodeSnippet";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { InputWithSuggestions, type SuggestionOption } from "@/components/ui/input-with-suggestions";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { toast } from "@/components/ui/sonner";+import { Textarea } from "@/components/ui/textarea";+import { useStore } from "@/lib/store";+import { cn } from "@/lib/utils";+import { Check, FlaskConical, Flag, MousePointerClick, Plus, Target, Trash2 } from "lucide-react";+import { useExtracted } from "next-intl";+import { useEffect, useMemo, useState } from "react";+import type { ReactNode } from "react";++type WizardStep = "basics" | "assignment" | "goal" | "implementation";+type AssignmentMode = "new" | "existing";+type GoalMode = "new" | "existing" | "none";+type GoalType = "path" | "event";++type VariantDraft = {+ id: string;+ key: string;+ name: string;+ rolloutPercentage: number;+};++type VariantSourceFlag = {+ conditionSets?: Array<{+ variants?: Array<{+ key: string;+ name?: string;+ rolloutPercentage: number;+ }>;+ }>;+ variants?: Array<{+ key: string;+ name?: string;+ rolloutPercentage: number;+ }>;+};++type ImplementationState = {+ mode: "created" | "updated";+ experiment: Experiment;+ flagKey: string;+ variants: string[];+ goalMode: GoalMode;+ goalType?: GoalType;+ goalLabel?: string;+};++type WizardForm = {+ name: string;+ description: string;+ hypothesis: string;+ assignmentMode: AssignmentMode;+ existingFlagId: string;+ flagKey: string;+ flagDescription: string;+ variants: VariantDraft[];+ goalMode: GoalMode;+ existingGoalId: string;+ goalName: string;+ goalType: GoalType;+ pathPattern: string;+ eventName: string;+};++const STEPS: WizardStep[] = ["basics", "assignment", "goal", "implementation"];++const VARIANT_SEGMENT_COLORS = ["bg-accent-500", "bg-accent-400", "bg-accent-600", "bg-accent-300", "bg-accent-700"];++function createId() {+ return typeof crypto !== "undefined" && "randomUUID" in crypto+ ? crypto.randomUUID()+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`;+}++function slugify(value: string) {+ return value+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "_")+ .replace(/^_+|_+$/g, "");+}++function getVariantDraftsFromFlag(flag: VariantSourceFlag): VariantDraft[] {+ const variants = [+ ...(flag.conditionSets || []).flatMap(conditionSet => conditionSet.variants || []),+ ...(flag.variants || []),+ ];++ if (variants.length >= 2) {+ return variants.map(variant => ({+ id: createId(),+ key: variant.key,+ name: variant.name || "",+ rolloutPercentage: variant.rolloutPercentage,+ }));+ }++ return [+ { id: createId(), key: "control", name: "Control", rolloutPercentage: 50 },+ { id: createId(), key: "variant_a", name: "Variant A", rolloutPercentage: 50 },+ ];+}++function initialForm(experiment?: Experiment): WizardForm {+ if (experiment) {+ const primaryGoal = experiment.primaryGoal;++ return {+ name: experiment.name,+ description: experiment.description || "",+ hypothesis: experiment.hypothesis || "",+ assignmentMode: "existing",+ existingFlagId: String(experiment.featureFlagId),+ flagKey: experiment.featureFlag.key,+ flagDescription: experiment.featureFlag.description || "",+ variants: getVariantDraftsFromFlag(experiment.featureFlag),+ goalMode: experiment.primaryGoalId ? "existing" : "none",+ existingGoalId: experiment.primaryGoalId ? String(experiment.primaryGoalId) : "",+ goalName: primaryGoal?.name || "",+ goalType: primaryGoal?.goalType || "path",+ pathPattern: primaryGoal?.config.pathPattern || "",+ eventName: primaryGoal?.config.eventName || "",+ };+ }++ return {+ name: "",+ description: "",+ hypothesis: "",+ assignmentMode: "new",+ existingFlagId: "",+ flagKey: "",+ flagDescription: "",+ variants: [+ { id: createId(), key: "control", name: "Control", rolloutPercentage: 50 },+ { id: createId(), key: "variant_a", name: "Variant A", rolloutPercentage: 50 },+ ],+ goalMode: "new",+ existingGoalId: "",+ goalName: "",+ goalType: "path",+ pathPattern: "",+ eventName: "",+ };+}++function getVariantKeys(flag: VariantSourceFlag) {+ return [+ ...new Set([+ ...(flag.conditionSets || []).flatMap(conditionSet => conditionSet.variants?.map(variant => variant.key) || []),+ ...(flag.variants || []).map(variant => variant.key),+ ]),+ ];+}++function CodeTabs({ jsCode, tsCode }: { jsCode: string; tsCode: string }) {+ const [language, setLanguage] = useState<"js" | "ts">("js");++ return (+ <div className="grid gap-2">+ <div className="flex gap-1">+ <button+ type="button"+ onClick={() => setLanguage("js")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ language === "js"+ ? "bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"+ : "text-neutral-500 hover:bg-neutral-50 dark:text-neutral-400 dark:hover:bg-neutral-850"+ )}+ >+ JavaScript+ </button>+ <button+ type="button"+ onClick={() => setLanguage("ts")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ language === "ts"+ ? "bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"+ : "text-neutral-500 hover:bg-neutral-50 dark:text-neutral-400 dark:hover:bg-neutral-850"+ )}+ >+ TypeScript+ </button>+ </div>+ <CodeSnippet code={language === "js" ? jsCode : tsCode} language="javascript" />+ </div>+ );+}++function WizardChoice({+ selected,+ icon,+ title,+ description,+ onClick,+}: {+ selected: boolean;+ icon: ReactNode;+ title: string;+ description: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ "rounded-lg border p-3 text-left transition-colors",+ selected+ ? "border-accent-500 bg-accent-500/5 dark:border-accent-600 dark:bg-accent-600/10"+ : "border-neutral-150 bg-neutral-50/50 hover:border-neutral-200 hover:bg-neutral-100/60 dark:border-neutral-800 dark:bg-neutral-900/40 dark:hover:border-neutral-750 dark:hover:bg-neutral-900"+ )}+ >+ <div className="flex items-start gap-3">+ <div+ className={cn(+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-md",+ selected+ ? "bg-accent-500/15 text-accent-600 dark:bg-accent-500/20 dark:text-accent-400"+ : "bg-neutral-100 text-neutral-500 dark:bg-neutral-850 dark:text-neutral-400"+ )}+ >+ {icon}+ </div>+ <div className="grid gap-1">+ <span className="text-sm font-medium text-neutral-900 dark:text-neutral-50">{title}</span>+ <span className="text-xs leading-5 text-neutral-500 dark:text-neutral-400">{description}</span>+ </div>+ </div>+ </button>+ );+}++function WizardHelp({ step, isEditing }: { step: WizardStep; isEditing: boolean }) {+ const t = useExtracted();++ const content: Record<WizardStep, { title: string; body: string[] }> = {+ basics: {+ title: t("Define the question"),+ body: [+ t("Start with the behavior you want to change and the metric you expect to move."),+ t("The hypothesis is internal context for your team. It does not change assignment or tracking."),+ isEditing+ ? t("Changing these notes does not change assignment or tracking.")+ : t("New experiments are created as drafts so you can add the implementation before starting traffic."),+ ],+ },+ assignment: {+ title: t("Create the assignment"),+ body: [+ t("Experiments use multivariate feature flags to assign each visitor to one stable variant."),+ t("Calling rybbit.flag records the exposure that powers experiment results."),+ t("A full split should add up to 100 percent unless you intentionally want unassigned traffic."),+ ],+ },+ goal: {+ title: t("Pick the outcome"),+ body: [+ t("The primary goal is the conversion event or page visit used to compare variants."),+ t("Path goals work when conversion is a URL, like /thank-you. Event goals work for explicit actions."),+ t("You can skip this for now, but conversion results need a goal later."),+ ],+ },+ implementation: {+ title: t("Implement and expose"),+ body: [+ t("Use the generated flag key in your app and branch your UI or behavior by variant."),+ t("Read the flag in code before rendering the tested experience."),+ t("For event goals, fire the event when the conversion action happens."),+ ],+ },+ };++ return (+ <aside className="hidden border-l border-neutral-150 bg-neutral-50/70 p-5 dark:border-neutral-850 dark:bg-neutral-950/40 lg:block">+ <div className="sticky top-5 grid gap-3">+ <div className="flex h-9 w-9 items-center justify-center rounded-md bg-accent-500/10 text-accent-600 dark:text-accent-400">+ <FlaskConical className="h-4 w-4" />+ </div>+ <div>+ <h3 className="text-sm font-medium text-neutral-900 dark:text-neutral-50">{content[step].title}</h3>+ <div className="mt-3 grid gap-3 text-sm leading-6 text-neutral-600 dark:text-neutral-300">+ {content[step].body.map(item => (+ <p key={item}>{item}</p>+ ))}+ </div>+ </div>+ </div>+ </aside>+ );+}++export function CreateExperimentWizard({+ experiment,+ experiments,+ trigger,+ open: openProp,+ onOpenChange,+}: {+ experiment?: Experiment;+ experiments: Experiment[];+ trigger?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}) {+ const t = useExtracted();+ const { site } = useStore();+ const { data: flags } = useFeatureFlags();+ const { data: goalsData } = useGetGoals({ pageSize: 100 });+ const { data: pathsData } = useMetric({ parameter: "pathname", limit: 1000, useFilters: false });+ const { data: eventsData } = useMetric({ parameter: "event_name", limit: 1000, useFilters: false });+ const createFeatureFlagMutation = useCreateFeatureFlag();+ const createGoalMutation = useCreateGoal();+ const createExperimentMutation = useCreateExperiment();+ const updateExperimentMutation = useUpdateExperiment();+ const [internalOpen, setInternalOpen] = useState(false);+ const open = openProp ?? internalOpen;+ const [step, setStep] = useState<WizardStep>("basics");+ const [form, setForm] = useState<WizardForm>(() => initialForm(experiment));+ const [savedImplementationState, setSavedImplementationState] = useState<ImplementationState | null>(null);+ const [flagKeyTouched, setFlagKeyTouched] = useState(false);+ const [goalNameTouched, setGoalNameTouched] = useState(false);+ const isEditing = !!experiment;++ const usedFlagIds = useMemo(+ () =>+ new Set(+ experiments.filter(item => item.experimentId !== experiment?.experimentId).map(item => item.featureFlagId)+ ),+ [experiment?.experimentId, experiments]+ );+ const availableFlags = useMemo(+ () => (flags || []).filter(flag => flag.flagType === "multivariate" && !usedFlagIds.has(flag.flagId)),+ [flags, usedFlagIds]+ );+ const selectedFlag =+ availableFlags.find(flag => String(flag.flagId) === form.existingFlagId) ||+ (experiment?.featureFlagId === Number(form.existingFlagId) ? experiment.featureFlag : undefined);+ const goals = goalsData?.data || [];+ const pathSuggestions: SuggestionOption[] = (pathsData?.data || []).map(item => ({+ value: item.value,+ label: item.value,+ }));+ const eventSuggestions: SuggestionOption[] = (eventsData?.data || []).map(item => ({+ value: item.value,+ label: item.value,+ }));+ const selectedGoal =+ goals.find(goal => String(goal.goalId) === form.existingGoalId) ||+ (experiment?.primaryGoalId === Number(form.existingGoalId) ? experiment.primaryGoal : undefined);+ const activeStepIndex = STEPS.indexOf(step);+ const isSaving =+ createFeatureFlagMutation.isPending ||+ createGoalMutation.isPending ||+ createExperimentMutation.isPending ||+ updateExperimentMutation.isPending;++ useEffect(() => {+ if (!open) return;+ setStep("basics");+ setForm(initialForm(experiment));+ setSavedImplementationState(null);+ setFlagKeyTouched(!!experiment);+ setGoalNameTouched(!!experiment);+ }, [experiment?.experimentId, open]);++ useEffect(() => {+ if (form.existingFlagId || availableFlags.length === 0) return;+ setForm(current => ({ ...current, existingFlagId: String(availableFlags[0].flagId) }));+ }, [availableFlags, form.existingFlagId]);++ useEffect(() => {+ if (form.existingGoalId || goals.length === 0) return;+ setForm(current => ({ ...current, existingGoalId: String(goals[0].goalId) }));+ }, [goals, form.existingGoalId]);++ const setOpen = (next: boolean) => {+ if (openProp === undefined) setInternalOpen(next);+ onOpenChange?.(next);+ };++ const updateForm = <K extends keyof WizardForm>(key: K, value: WizardForm[K]) => {+ setForm(current => ({ ...current, [key]: value }));+ };++ const updateName = (name: string) => {+ setForm(current => ({+ ...current,+ name,+ flagKey: flagKeyTouched ? current.flagKey : slugify(name),+ goalName: goalNameTouched ? current.goalName : name ? `${name} conversion` : "",+ }));+ };++ const updateVariant = <K extends keyof VariantDraft>(id: string, key: K, value: VariantDraft[K]) => {+ setForm(current => ({+ ...current,+ variants: current.variants.map(variant => (variant.id === id ? { ...variant, [key]: value } : variant)),+ }));+ };++ const addVariant = () => {+ setForm(current => ({+ ...current,+ variants: [+ ...current.variants,+ {+ id: createId(),+ key: `variant_${current.variants.length}`,+ name: `Variant ${String.fromCharCode(64 + current.variants.length)}`,+ rolloutPercentage: 0,+ },+ ],+ }));+ };++ const removeVariant = (id: string) => {+ setForm(current => ({ ...current, variants: current.variants.filter(variant => variant.id !== id) }));+ };++ const validateStep = (stepToValidate: WizardStep) => {+ if (stepToValidate === "basics") {+ if (!form.name.trim()) return t("Name is required");+ }++ if (stepToValidate === "assignment") {+ if (form.assignmentMode === "existing" && !form.existingFlagId) {+ return t("Choose a multivariate feature flag");+ }++ if (form.assignmentMode === "new") {+ const keys = form.variants.map(variant => variant.key.trim()).filter(Boolean);+ const totalRollout = form.variants.reduce((sum, variant) => sum + Number(variant.rolloutPercentage || 0), 0);++ if (!form.flagKey.trim()) return t("Flag key is required");+ if (form.variants.length < 2) return t("Add at least two variants");+ if (keys.length !== form.variants.length) return t("Variant keys are required");+ if (new Set(keys).size !== keys.length) return t("Variant keys must be unique");+ if (totalRollout !== 100) return t("Variant traffic must add up to 100%");+ }+ }++ if (stepToValidate === "goal") {+ if (form.goalMode === "existing" && !form.existingGoalId) return t("Choose a goal");+ if (form.goalMode === "new" && form.goalType === "path" && !form.pathPattern.trim()) {+ return t("Path pattern is required");+ }+ if (form.goalMode === "new" && form.goalType === "event" && !form.eventName.trim()) {+ return t("Event name is required");+ }+ }++ return null;+ };++ const validateCurrentStep = () => validateStep(step);++ const validateExperimentConfiguration = () => {+ for (const stepToValidate of ["basics", "assignment", "goal"] as const) {+ const validationError = validateStep(stepToValidate);+ if (validationError) return validationError;+ }++ return null;+ };++ const goNext = () => {+ const validationError = validateCurrentStep();+ if (validationError) {+ toast.error(validationError);+ return;+ }++ const nextStep = STEPS[Math.min(activeStepIndex + 1, STEPS.length - 1)];+ setStep(nextStep);+ };++ const buildImplementationState = (mode: ImplementationState["mode"]): ImplementationState | null => {+ const flagKey =+ form.assignmentMode === "existing" ? selectedFlag?.key || experiment?.featureFlag.key : form.flagKey.trim();+ const variants =+ form.assignmentMode === "existing" && selectedFlag+ ? getVariantKeys(selectedFlag)+ : form.variants.map(variant => variant.key.trim()).filter(Boolean);+ const goalType =+ form.goalMode === "existing" ? selectedGoal?.goalType : form.goalMode === "new" ? form.goalType : undefined;+ const goalLabel =+ form.goalMode === "existing"+ ? selectedGoal?.goalType === "path"+ ? selectedGoal.config.pathPattern+ : selectedGoal?.config.eventName+ : form.goalMode === "new"+ ? form.goalType === "path"+ ? form.pathPattern.trim()+ : form.eventName.trim()+ : undefined;++ if (!flagKey || !experiment) return null;++ return {+ mode,+ experiment,+ flagKey,+ variants,+ goalMode: form.goalMode,+ goalType,+ goalLabel,+ };+ };++ const implementationState = savedImplementationState || (isEditing ? buildImplementationState("updated") : null);++ const submitExperiment = async () => {+ const validationError = validateExperimentConfiguration();+ if (validationError) {+ toast.error(validationError);+ return;+ }++ try {+ let featureFlagId = Number(form.existingFlagId);+ let flagKey = selectedFlag?.key || form.flagKey.trim();+ let variantKeys = selectedFlag ? getVariantKeys(selectedFlag) : form.variants.map(variant => variant.key.trim());++ if (form.assignmentMode === "new") {+ const variants: FeatureFlagVariant[] = form.variants.map(variant => ({+ key: variant.key.trim(),+ name: variant.name.trim() || undefined,+ rolloutPercentage: Number(variant.rolloutPercentage),+ }));++ const createdFlag = await createFeatureFlagMutation.mutateAsync({+ key: form.flagKey.trim(),+ description: form.flagDescription.trim() || `Assignment flag for ${form.name.trim()}`,+ enabled: true,+ runtime: "client",+ flagType: "multivariate",+ payload: null,+ variants: [],+ rolloutPercentage: 100,+ rules: [],+ conditionSets: [+ {+ name: "Default",+ rules: [],+ variants,+ },+ ],+ });++ featureFlagId = createdFlag.data.flagId;+ flagKey = createdFlag.data.key;+ variantKeys = getVariantKeys(createdFlag.data);+ }++ let primaryGoalId: number | null = form.goalMode === "existing" ? Number(form.existingGoalId) : null;+ let goalType: GoalType | undefined = selectedGoal?.goalType;+ let goalLabel =+ selectedGoal?.goalType === "path"+ ? selectedGoal.config.pathPattern+ : selectedGoal?.goalType === "event"+ ? selectedGoal.config.eventName+ : form.goalMode === "none"+ ? undefined+ : form.goalName.trim();++ if (form.goalMode === "new") {+ const createdGoal = await createGoalMutation.mutateAsync({+ siteId: Number(site),+ name: form.goalName.trim() || `${form.name.trim()} conversion`,+ goalType: form.goalType,+ config:+ form.goalType === "path" ? { pathPattern: form.pathPattern.trim() } : { eventName: form.eventName.trim() },+ });++ primaryGoalId = createdGoal.goalId;+ goalType = form.goalType;+ goalLabel = form.goalType === "path" ? form.pathPattern.trim() : form.eventName.trim();+ }++ const createdExperiment = await createExperimentMutation.mutateAsync({+ name: form.name.trim(),+ description: form.description.trim() || null,+ hypothesis: form.hypothesis.trim() || null,+ featureFlagId,+ primaryGoalId,+ status: "draft",+ });++ setSavedImplementationState({+ mode: "created",+ experiment: createdExperiment.data,+ flagKey,+ variants: variantKeys,+ goalMode: form.goalMode,+ goalType,+ goalLabel,+ });+ setStep("implementation");+ toast.success(t("Experiment created"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to save experiment"));+ }+ };++ const saveExperiment = async () => {+ const validationError = validateExperimentConfiguration();+ if (validationError) {+ toast.error(validationError);+ return;+ }++ if (!experiment) return;++ try {+ let featureFlagId = Number(form.existingFlagId);+ let flagKey = selectedFlag?.key || form.flagKey.trim();+ let variantKeys = selectedFlag ? getVariantKeys(selectedFlag) : form.variants.map(variant => variant.key.trim());++ if (form.assignmentMode === "new") {+ const variants: FeatureFlagVariant[] = form.variants.map(variant => ({+ key: variant.key.trim(),+ name: variant.name.trim() || undefined,+ rolloutPercentage: Number(variant.rolloutPercentage),+ }));++ const createdFlag = await createFeatureFlagMutation.mutateAsync({+ key: form.flagKey.trim(),+ description: form.flagDescription.trim() || `Assignment flag for ${form.name.trim()}`,+ enabled: true,+ runtime: "client",+ flagType: "multivariate",+ payload: null,+ variants: [],+ rolloutPercentage: 100,+ rules: [],+ conditionSets: [+ {+ name: "Default",+ rules: [],+ variants,+ },+ ],+ });++ featureFlagId = createdFlag.data.flagId;+ flagKey = createdFlag.data.key;+ variantKeys = getVariantKeys(createdFlag.data);+ }++ let primaryGoalId: number | null = form.goalMode === "existing" ? Number(form.existingGoalId) : null;+ let goalType: GoalType | undefined = selectedGoal?.goalType;+ let goalLabel =+ selectedGoal?.goalType === "path"+ ? selectedGoal.config.pathPattern+ : selectedGoal?.goalType === "event"+ ? selectedGoal.config.eventName+ : form.goalMode === "none"+ ? undefined+ : form.goalName.trim();++ if (form.goalMode === "new") {+ const createdGoal = await createGoalMutation.mutateAsync({+ siteId: Number(site),+ name: form.goalName.trim() || `${form.name.trim()} conversion`,+ goalType: form.goalType,+ config:+ form.goalType === "path" ? { pathPattern: form.pathPattern.trim() } : { eventName: form.eventName.trim() },+ });++ primaryGoalId = createdGoal.goalId;+ goalType = form.goalType;+ goalLabel = form.goalType === "path" ? form.pathPattern.trim() : form.eventName.trim();+ }++ const updatedExperiment = await updateExperimentMutation.mutateAsync({+ experimentId: experiment.experimentId,+ payload: {+ name: form.name.trim(),+ description: form.description.trim() || null,+ hypothesis: form.hypothesis.trim() || null,+ featureFlagId,+ primaryGoalId,+ },+ });++ setSavedImplementationState({+ mode: "updated",+ experiment: updatedExperiment.data,+ flagKey,+ variants: variantKeys,+ goalMode: form.goalMode,+ goalType,+ goalLabel,+ });+ setStep("implementation");+ toast.success(t("Experiment updated"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to save experiment"));+ }+ };++ const renderStep = () => {+ if (step === "basics") {+ return (+ <div className="grid gap-5">+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-name">{t("Experiment name")}</Label>+ <Input+ id="experiment-name"+ value={form.name}+ onChange={event => updateName(event.target.value)}+ placeholder={t("Checkout CTA test")}+ />+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-hypothesis">{t("Hypothesis")}</Label>+ <Textarea+ id="experiment-hypothesis"+ value={form.hypothesis}+ onChange={event => updateForm("hypothesis", event.target.value)}+ rows={3}+ placeholder={t("Changing the CTA copy will increase signup conversions.")}+ />+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-description">{t("Description")}</Label>+ <Textarea+ id="experiment-description"+ value={form.description}+ onChange={event => updateForm("description", event.target.value)}+ rows={3}+ placeholder={t("Optional notes for this experiment")}+ />+ </div>+ </div>+ );+ }++ if (step === "assignment") {+ const rolloutTotal = form.variants.reduce((sum, variant) => sum + Number(variant.rolloutPercentage || 0), 0);++ return (+ <div className="grid gap-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <WizardChoice+ selected={form.assignmentMode === "new"}+ icon={<Plus className="h-4 w-4" />}+ title={t("Create a new flag")}+ description={t("Best for a new experiment that needs its own assignment split.")}+ onClick={() => updateForm("assignmentMode", "new")}+ />+ <WizardChoice+ selected={form.assignmentMode === "existing"}+ icon={<Flag className="h-4 w-4" />}+ title={t("Use an existing flag")}+ description={t("Choose a multivariate flag that is not already connected to an experiment.")}+ onClick={() => updateForm("assignmentMode", "existing")}+ />+ </div>++ {form.assignmentMode === "existing" ? (+ <div className="grid gap-1.5">+ <Label>{t("Assignment flag")}</Label>+ <Select value={form.existingFlagId} onValueChange={value => updateForm("existingFlagId", value)}>+ <SelectTrigger>+ <SelectValue placeholder={t("Select a flag")} />+ </SelectTrigger>+ <SelectContent>+ {availableFlags.map(flag => (+ <SelectItem key={flag.flagId} value={String(flag.flagId)}>+ {flag.key}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {availableFlags.length === 0 && (+ <p className="text-xs text-neutral-500 dark:text-neutral-400">+ {t("No unused multivariate flags are available. Create a new flag for this experiment.")}+ </p>+ )}+ </div>+ ) : (+ <div className="grid gap-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-flag-key">{t("Flag key")}</Label>+ <Input+ id="experiment-flag-key"+ value={form.flagKey}+ onChange={event => {+ setFlagKeyTouched(true);+ updateForm("flagKey", slugify(event.target.value));+ }}+ placeholder="checkout_cta"+ className="font-mono"+ />+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-flag-description">{t("Flag description")}</Label>+ <Input+ id="experiment-flag-description"+ value={form.flagDescription}+ onChange={event => updateForm("flagDescription", event.target.value)}+ placeholder={t("Assignment flag for this experiment")}+ />+ </div>+ </div>++ <div className="grid gap-2">+ <div className="flex items-center justify-between gap-3">+ <Label>{t("Variants")}</Label>+ <span+ className={cn(+ "text-xs tabular-nums",+ rolloutTotal === 100+ ? "text-neutral-500 dark:text-neutral-400"+ : "text-amber-600 dark:text-amber-400"+ )}+ >+ {t("{rolloutTotal}% assigned", { rolloutTotal: String(rolloutTotal) })}+ </span>+ </div>+ <div className="flex h-2 gap-px overflow-hidden rounded-full bg-neutral-150 dark:bg-neutral-800">+ {form.variants.map((variant, index) =>+ Number(variant.rolloutPercentage) > 0 ? (+ <div+ key={variant.id}+ className={cn(+ "h-full first:rounded-l-full last:rounded-r-full",+ VARIANT_SEGMENT_COLORS[index % VARIANT_SEGMENT_COLORS.length]+ )}+ style={{ width: `${Math.min(100, Number(variant.rolloutPercentage))}%` }}+ title={`${variant.key || t("variant")} · ${variant.rolloutPercentage}%`}+ />+ ) : null+ )}+ </div>+ <div className="grid gap-2">+ {form.variants.map(variant => (+ <div key={variant.id} className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_5rem_2rem] gap-2">+ <Input+ value={variant.key}+ onChange={event => updateVariant(variant.id, "key", slugify(event.target.value))}+ placeholder="variant_a"+ className="font-mono"+ />+ <Input+ value={variant.name}+ onChange={event => updateVariant(variant.id, "name", event.target.value)}+ placeholder={t("Display name")}+ />+ <div className="relative">+ <Input+ type="number"+ min={0}+ max={100}+ value={variant.rolloutPercentage}+ onChange={event =>+ updateVariant(variant.id, "rolloutPercentage", Number(event.target.value || 0))+ }+ className="pr-6 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"+ />+ <span className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-xs text-neutral-500 dark:text-neutral-400">+ %+ </span>+ </div>+ <Button+ size="icon"+ variant="ghost"+ onClick={() => removeVariant(variant.id)}+ disabled={form.variants.length <= 2}+ aria-label={t("Remove variant")}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ ))}+ </div>+ <Button type="button" variant="outline" size="sm" onClick={addVariant} className="w-fit">+ <Plus className="h-4 w-4" />+ {t("Add variant")}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+ }++ if (step === "goal") {+ return (+ <div className="grid gap-5">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <WizardChoice+ selected={form.goalMode === "new"}+ icon={<Plus className="h-4 w-4" />}+ title={t("Create a new goal")}+ description={t("Define the conversion while creating the experiment.")}+ onClick={() => updateForm("goalMode", "new")}+ />+ <WizardChoice+ selected={form.goalMode === "existing"}+ icon={<Target className="h-4 w-4" />}+ title={t("Use existing")}+ description={t("Connect this experiment to a goal you already track.")}+ onClick={() => updateForm("goalMode", "existing")}+ />+ <WizardChoice+ selected={form.goalMode === "none"}+ icon={<MousePointerClick className="h-4 w-4" />}+ title={t("Skip for now")}+ description={t("Create the experiment now and add a goal later.")}+ onClick={() => updateForm("goalMode", "none")}+ />+ </div>++ {form.goalMode === "existing" && (+ <div className="grid gap-1.5">+ <Label>{t("Primary goal")}</Label>+ <Select value={form.existingGoalId} onValueChange={value => updateForm("existingGoalId", value)}>+ <SelectTrigger>+ <SelectValue placeholder={t("Select a goal")} />+ </SelectTrigger>+ <SelectContent>+ {goals.map(goal => (+ <SelectItem key={goal.goalId} value={String(goal.goalId)}>+ {goal.name || t("Goal #{goalId}", { goalId: String(goal.goalId) })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}++ {form.goalMode === "new" && (+ <div className="grid gap-5">+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-goal-name">{t("Goal name")}</Label>+ <Input+ id="experiment-goal-name"+ value={form.goalName}+ onChange={event => {+ setGoalNameTouched(true);+ updateForm("goalName", event.target.value);+ }}+ placeholder={t("Signup completed")}+ />+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <WizardChoice+ selected={form.goalType === "path"}+ icon={<Target className="h-4 w-4" />}+ title={t("Page goal")}+ description={t("Count sessions that reach a URL path.")}+ onClick={() => updateForm("goalType", "path")}+ />+ <WizardChoice+ selected={form.goalType === "event"}+ icon={<MousePointerClick className="h-4 w-4" />}+ title={t("Event goal")}+ description={t("Count sessions where your app fires a named event.")}+ onClick={() => updateForm("goalType", "event")}+ />+ </div>++ {form.goalType === "path" ? (+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-path-pattern">{t("Path pattern")}</Label>+ <InputWithSuggestions+ id="experiment-path-pattern"+ suggestions={pathSuggestions}+ value={form.pathPattern}+ onChange={event => updateForm("pathPattern", event.target.value)}+ placeholder="/signup/complete"+ />+ </div>+ ) : (+ <div className="grid gap-1.5">+ <Label htmlFor="experiment-event-name">{t("Event name")}</Label>+ <InputWithSuggestions+ id="experiment-event-name"+ suggestions={eventSuggestions}+ value={form.eventName}+ onChange={event => updateForm("eventName", event.target.value)}+ placeholder="signup_completed"+ className="font-mono"+ />+ </div>+ )}+ </div>+ )}+ </div>+ );+ }++ if (!implementationState) return null;++ const fallbackVariant = implementationState.variants[0] || "control";+ const alternateVariant = implementationState.variants.find(variant => variant !== fallbackVariant) || "variant_a";+ const variantUnion = implementationState.variants.map(variant => JSON.stringify(variant)).join(" | ");+ const jsCode = `window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag(${JSON.stringify(implementationState.flagKey)}, ${JSON.stringify(fallbackVariant)});++ if (variant === ${JSON.stringify(alternateVariant)}) {+ // Render the variant experience.+ } else {+ // Render the control experience.+ }+});`;+ const tsCode = `type ExperimentVariant = ${variantUnion || JSON.stringify(fallbackVariant)};++window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag(${JSON.stringify(implementationState.flagKey)}, ${JSON.stringify(fallbackVariant)}) as ExperimentVariant;++ switch (variant) {+ case ${JSON.stringify(alternateVariant)}:+ // Render the variant experience.+ break;+ default:+ // Render the control experience.+ break;+ }+});`;+ const eventGoalCode =+ implementationState.goalType === "event" && implementationState.goalLabel+ ? `window.rybbit.onReady((rybbit) => {+ rybbit.event(${JSON.stringify(implementationState.goalLabel)});+});`+ : null;++ return (+ <div className="grid gap-5">+ <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4 dark:border-emerald-900 dark:bg-emerald-950/30">+ <div className="flex items-start gap-3">+ <div className="mt-0.5 flex h-6 w-6 items-center justify-center rounded-full bg-emerald-500 text-white">+ <Check className="h-4 w-4" />+ </div>+ <div>+ <h3 className="text-sm font-medium text-emerald-900 dark:text-emerald-100">+ {implementationState.mode === "created"+ ? t("Experiment created as a draft")+ : t("Experiment changes saved")}+ </h3>+ <p className="mt-1 text-sm text-emerald-800 dark:text-emerald-200">+ {t("Add this code to your app, then start the experiment from the list when you are ready.")}+ </p>+ </div>+ </div>+ </div>++ <div className="grid gap-2">+ <Label>{t("Variant implementation")}</Label>+ <CodeTabs jsCode={jsCode} tsCode={tsCode} />+ </div>++ {eventGoalCode ? (+ <div className="grid gap-2">+ <Label>{t("Conversion event")}</Label>+ <CodeSnippet code={eventGoalCode} language="javascript" />+ </div>+ ) : implementationState.goalType === "path" ? (+ <p className="rounded-md border border-neutral-150 bg-neutral-50 p-3 text-sm text-neutral-600 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300">+ {t(+ "No conversion event code is needed for this path goal. Rybbit will count sessions that reach {goalLabel}.",+ {+ goalLabel: implementationState.goalLabel || "",+ }+ )}+ </p>+ ) : (+ <p className="rounded-md border border-neutral-150 bg-neutral-50 p-3 text-sm text-neutral-600 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300">+ {t("Add a primary goal later to calculate conversions for each variant.")}+ </p>+ )}+ </div>+ );+ };++ const stepTitle =+ step === "basics"+ ? t("Basics")+ : step === "assignment"+ ? t("Assignment")+ : step === "goal"+ ? t("Goal")+ : t("Implement");++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}+ <DialogContent className="flex max-h-[90vh] w-full max-w-5xl flex-col gap-0 p-0">+ <DialogTitle className="sr-only">{isEditing ? t("Edit experiment") : t("Create experiment")}</DialogTitle>++ <div className="border-b border-neutral-150 px-6 pb-4 pt-5 dark:border-neutral-850">+ <div className="mb-3 flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <span className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {isEditing ? t("Edit experiment") : t("New experiment")}+ </span>+ <span className="inline-flex items-center gap-1.5 rounded-full bg-neutral-100 px-2 py-0.5 text-xs text-neutral-500 dark:bg-neutral-850 dark:text-neutral-400">+ {isEditing ? t("Existing") : t("Draft")}+ </span>+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-2">+ {STEPS.map((item, index) => {+ const canOpenStep = item !== "implementation" || !!implementationState;+ return (+ <button+ key={item}+ type="button"+ disabled={!canOpenStep}+ onClick={() => {+ if (canOpenStep) setStep(item);+ }}+ className={cn(+ "inline-flex items-center gap-2 rounded-full px-2.5 py-1 text-xs transition-colors",+ item === step+ ? "bg-accent-500/10 text-accent-700 dark:text-accent-300"+ : index < activeStepIndex+ ? "bg-neutral-100 text-neutral-700 dark:bg-neutral-850 dark:text-neutral-200"+ : canOpenStep+ ? "bg-neutral-50 text-neutral-500 hover:bg-neutral-100 dark:bg-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-850"+ : "bg-neutral-50 text-neutral-300 dark:bg-neutral-900 dark:text-neutral-600"+ )}+ >+ <span className="flex h-4 w-4 items-center justify-center rounded-full bg-current/10 text-[10px]">+ {index < activeStepIndex || (item === "implementation" && implementationState) ? (+ <Check className="h-3 w-3" />+ ) : (+ index + 1+ )}+ </span>+ {item === "basics"+ ? t("Basics")+ : item === "assignment"+ ? t("Assignment")+ : item === "goal"+ ? t("Goal")+ : t("Implement")}+ </button>+ );+ })}+ </div>+ </div>++ <div className="grid min-h-[520px] flex-1 overflow-hidden lg:grid-cols-[minmax(0,1fr)_20rem]">+ <div className="overflow-y-auto px-6 py-5">+ <div className="mx-auto max-w-2xl">+ <div className="mb-5">+ <h2 className="text-xl font-medium tracking-tight text-neutral-900 dark:text-neutral-50">+ {stepTitle}+ </h2>+ </div>+ {renderStep()}+ </div>+ </div>+ <WizardHelp step={step} isEditing={isEditing} />+ </div>++ <div className="flex items-center justify-between border-t border-neutral-150 px-6 py-4 dark:border-neutral-850">+ <Button variant="ghost" onClick={() => setOpen(false)}>+ {step === "implementation" ? t("Close") : t("Cancel")}+ </Button>+ <div className="flex items-center gap-2">+ {activeStepIndex > 0 && step !== "implementation" && (+ <Button variant="secondary" onClick={() => setStep(STEPS[activeStepIndex - 1])}>+ {t("Back")}+ </Button>+ )}+ {step === "goal" ? (+ <Button onClick={isEditing ? saveExperiment : submitExperiment} disabled={isSaving || !site}>+ {isSaving+ ? isEditing+ ? t("Saving...")+ : t("Creating...")+ : isEditing+ ? t("Save changes")+ : t("Create experiment")}+ </Button>+ ) : step === "implementation" ? (+ <Button onClick={() => setOpen(false)}>{t("Done")}</Button>+ ) : (+ <Button onClick={goNext}>{t("Continue")}</Button>+ )}+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/client/src/app/[site]/experiments/components/ExperimentDialog.tsx b/client/src/app/[site]/experiments/components/ExperimentDialog.tsxnew file mode 100644index 000000000..7a780fdb1--- /dev/null+++ b/client/src/app/[site]/experiments/components/ExperimentDialog.tsx@@ -0,0 +1,29 @@+"use client";++import type { Experiment } from "@/api/analytics/endpoints";+import type { ReactNode } from "react";+import { CreateExperimentWizard } from "./CreateExperimentWizard";++export function ExperimentDialog({+ experiment,+ experiments,+ trigger,+ open,+ onOpenChange,+}: {+ experiment?: Experiment;+ experiments: Experiment[];+ trigger?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}) {+ return (+ <CreateExperimentWizard+ experiment={experiment}+ experiments={experiments}+ trigger={trigger}+ open={open}+ onOpenChange={onOpenChange}+ />+ );+}diff --git a/client/src/app/[site]/experiments/components/ExperimentResultsPanel.tsx b/client/src/app/[site]/experiments/components/ExperimentResultsPanel.tsxnew file mode 100644index 000000000..87709b09d--- /dev/null+++ b/client/src/app/[site]/experiments/components/ExperimentResultsPanel.tsx@@ -0,0 +1,273 @@+"use client";++import type { Experiment, ExperimentVariantResult } from "@/api/analytics/endpoints";+import { useExperimentResults } from "@/api/analytics/hooks/experiments/useExperiments";+import { cn } from "@/lib/utils";+import { Info, Target, TrendingUp, Trophy } from "lucide-react";+import { useExtracted } from "next-intl";+import type { ReactNode } from "react";+import {+ formatCompactNumber,+ formatPercent,+ getControlResult,+ getLeadingResult,+ getVariantConfidence,+ getVariantKeys,+} from "../lib/experimentHelpers";++type VariantTone = "winner" | "leading" | "control" | "variant";++function VariantTag({ tone, children }: { tone: VariantTone; children: ReactNode }) {+ const icon =+ tone === "winner" ? <Trophy className="h-3 w-3" /> : tone === "leading" ? <TrendingUp className="h-3 w-3" /> : null;++ return (+ <span+ className={cn(+ "inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] font-medium",+ tone === "winner" && "bg-emerald-500/20 text-emerald-600 dark:text-emerald-400",+ tone === "leading" && "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",+ tone === "control" && "bg-neutral-100 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400"+ )}+ >+ {icon}+ {children}+ </span>+ );+}++function VariantResultRow({+ result,+ tone,+ widthPercent,+ liftConfidence,+}: {+ result: ExperimentVariantResult;+ tone: VariantTone;+ widthPercent: number;+ liftConfidence: string | null;+}) {+ const t = useExtracted();+ const emphasized = tone === "winner" || tone === "leading";++ return (+ <div+ className={cn(+ "rounded-md border p-3 transition-colors",+ emphasized+ ? "border-emerald-500/30 bg-emerald-500/[0.04] dark:border-emerald-500/25 dark:bg-emerald-500/[0.07]"+ : "border-neutral-100 bg-neutral-50/60 dark:border-neutral-850 dark:bg-neutral-950/40"+ )}+ >+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="truncate font-mono text-sm text-neutral-900 dark:text-neutral-50">{result.variant}</span>+ {tone === "winner" && <VariantTag tone="winner">{t("Winner")}</VariantTag>}+ {tone === "leading" && <VariantTag tone="leading">{t("Leading")}</VariantTag>}+ {tone === "control" && <VariantTag tone="control">{t("Control")}</VariantTag>}+ </div>+ <div className="mt-1 text-xs tabular-nums text-neutral-500 dark:text-neutral-400">+ {t("{sessions} sessions · {conversions} conv.", {+ sessions: formatCompactNumber(result.sessions),+ conversions: formatCompactNumber(result.conversions),+ })}+ </div>+ </div>+ <div className="shrink-0 text-right">+ <div className="text-lg font-semibold tabular-nums leading-none text-neutral-900 dark:text-neutral-50">+ {formatPercent(result.conversionRate)}+ </div>+ {result.isControl ? (+ <div className="mt-1 text-xs text-neutral-400 dark:text-neutral-500">{t("Baseline")}</div>+ ) : (+ <div+ className={cn(+ "mt-1 text-xs font-medium tabular-nums",+ result.lift === null+ ? "text-neutral-400 dark:text-neutral-500"+ : result.lift >= 0+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-red-600 dark:text-red-400"+ )}+ >+ {result.lift === null ? "—" : `${result.lift >= 0 ? "+" : ""}${formatPercent(result.lift)}`}+ </div>+ )}+ {liftConfidence && (+ <div className="mt-0.5 text-[11px] text-neutral-400 dark:text-neutral-500">{liftConfidence}</div>+ )}+ </div>+ </div>++ <div className="mt-2.5 h-2 overflow-hidden rounded-full bg-neutral-150 dark:bg-neutral-800">+ <div+ className={cn(+ "h-full rounded-full transition-all",+ tone === "control"+ ? "bg-neutral-400 dark:bg-neutral-600"+ : emphasized+ ? "bg-accent-500"+ : "bg-accent-500/45"+ )}+ style={{ width: `${widthPercent}%` }}+ />+ </div>+ </div>+ );+}++export function ExperimentResultsPanel({ experiment }: { experiment: Experiment }) {+ const t = useExtracted();+ const { data, isLoading } = useExperimentResults(experiment.experimentId, !!experiment.primaryGoalId);+ const fallbackVariants = getVariantKeys(experiment);++ if (!experiment.primaryGoalId) {+ return (+ <div className="flex items-center gap-3 rounded-md border border-dashed border-neutral-200 px-4 py-3.5 dark:border-neutral-800">+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-neutral-100 text-neutral-500 dark:bg-neutral-850 dark:text-neutral-400">+ <Target className="h-4 w-4" />+ </div>+ <div className="min-w-0">+ <div className="text-sm font-medium text-neutral-800 dark:text-neutral-100">{t("No goal connected")}</div>+ <div className="text-xs text-neutral-500 dark:text-neutral-400">+ {t("Add a primary goal to measure conversions for each variant.")}+ </div>+ </div>+ </div>+ );+ }++ if (isLoading) {+ return (+ <div className="grid gap-2">+ {[0, 1].map(index => (+ <div+ key={index}+ className="rounded-md border border-neutral-100 bg-neutral-50/60 p-3 dark:border-neutral-850 dark:bg-neutral-950/40"+ >+ <div className="flex items-center justify-between">+ <div className="h-4 w-24 rounded bg-neutral-100 dark:bg-neutral-850" />+ <div className="h-5 w-12 rounded bg-neutral-100 dark:bg-neutral-850" />+ </div>+ <div className="mt-3 h-2 rounded-full bg-neutral-100 dark:bg-neutral-850" />+ </div>+ ))}+ </div>+ );+ }++ const results =+ data?.variants ||+ fallbackVariants.map(variant => ({+ variant,+ sessions: 0,+ exposures: 0,+ conversions: 0,+ conversionRate: 0,+ lift: null,+ isControl: variant === "control",+ }));++ const control = getControlResult(results);+ const leader = getLeadingResult(results);+ const leaderConfidence = leader && !leader.isControl ? getVariantConfidence(control, leader) : null;+ const maxRate = Math.max(...results.map(result => result.conversionRate), 0);+ const totalSessions = data?.totalExposureSessions ?? results.reduce((sum, result) => sum + result.sessions, 0);+ const totalConversions = data?.totalConversions ?? results.reduce((sum, result) => sum + result.conversions, 0);+ const measurement = data?.measurement ?? "exposure";++ const officialWinner = experiment.winningVariant || null;+ const isLeaderSignificant = !!leader && !!leaderConfidence?.isSignificant;++ const toneFor = (result: ExperimentVariantResult): VariantTone => {+ if (officialWinner && result.variant === officialWinner) return "winner";+ if (!officialWinner && isLeaderSignificant && leader && result.variant === leader.variant) return "leading";+ if (result.isControl) return "control";+ return "variant";+ };++ const verdict: { tone: "win" | "neutral"; icon: ReactNode; label: string } = officialWinner+ ? {+ tone: "win",+ icon: <Trophy className="h-3.5 w-3.5" />,+ label: t("Winner: {variant}", { variant: officialWinner }),+ }+ : totalConversions === 0+ ? { tone: "neutral", icon: null, label: t("No conversions yet") }+ : isLeaderSignificant && leader+ ? {+ tone: "win",+ icon: <TrendingUp className="h-3.5 w-3.5" />,+ label: t("{variant} leading", { variant: leader.variant }),+ }+ : {+ tone: "neutral",+ icon: null,+ label: experiment.status === "completed" ? t("No clear winner") : t("Gathering data"),+ };++ return (+ <div className="grid gap-2.5">+ <div className="flex items-center justify-between gap-3">+ <span+ className={cn(+ "inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium",+ verdict.tone === "win"+ ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"+ : "bg-neutral-100 text-neutral-600 dark:bg-neutral-850 dark:text-neutral-300"+ )}+ >+ {verdict.icon}+ {verdict.label}+ </span>+ <span className="text-xs tabular-nums text-neutral-500 dark:text-neutral-400">+ {t("{sessions} sessions · {conversions} conversions", {+ sessions: formatCompactNumber(totalSessions),+ conversions: formatCompactNumber(totalConversions),+ })}+ </span>+ </div>++ <div className="grid gap-2">+ {results.map(result => {+ const tone = toneFor(result);+ const widthPercent =+ result.conversionRate <= 0 || maxRate <= 0 ? 0 : Math.max(3, (result.conversionRate / maxRate) * 100);+ const confidence = result.isControl ? null : getVariantConfidence(control, result);+ const liftConfidence = result.isControl+ ? null+ : confidence+ ? confidence.isSignificant+ ? t("{confidence}% confidence", { confidence: (confidence.confidence * 100).toFixed(0) })+ : t("Not yet significant")+ : result.conversions > 0+ ? t("Gathering data")+ : null;++ return (+ <VariantResultRow+ key={result.variant}+ result={result}+ tone={tone}+ widthPercent={widthPercent}+ liftConfidence={liftConfidence}+ />+ );+ })}+ </div>++ {measurement === "assignment" && (+ <div className="flex items-start gap-2 rounded-md border border-neutral-100 bg-neutral-50/60 px-3 py-2 text-xs text-neutral-500 dark:border-neutral-850 dark:bg-neutral-950/40 dark:text-neutral-400">+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ <span>+ {t(+ 'Showing assigned visitors. Call rybbit.flag("{flagKey}") where the variant renders to measure visitors actually exposed to it.',+ { flagKey: experiment.featureFlag.key }+ )}+ </span>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/app/[site]/experiments/components/ExperimentRow.tsx b/client/src/app/[site]/experiments/components/ExperimentRow.tsxnew file mode 100644index 000000000..1d43c63dd--- /dev/null+++ b/client/src/app/[site]/experiments/components/ExperimentRow.tsx@@ -0,0 +1,169 @@+"use client";++import type { Experiment, ExperimentStatus } from "@/api/analytics/endpoints";+import { useDeleteExperiment, useUpdateExperiment } from "@/api/analytics/hooks/experiments/useExperiments";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { toast } from "@/components/ui/sonner";+import { cn } from "@/lib/utils";+import { Flag, MoreHorizontal, Pause, Pencil, Play, Square, Target, Trash2, Trophy } from "lucide-react";+import { useExtracted } from "next-intl";+import type { ReactNode } from "react";+import { useState } from "react";+import { formatRelativeTime } from "../lib/experimentHelpers";+import { ExperimentDialog } from "./ExperimentDialog";+import { ExperimentResultsPanel } from "./ExperimentResultsPanel";+import { StatusBadge } from "./StatusBadge";++function MetaChip({ icon, children }: { icon: ReactNode; children: ReactNode }) {+ return (+ <span className="inline-flex min-w-0 items-center gap-1.5 text-xs text-neutral-500 dark:text-neutral-400">+ <span className="text-neutral-400 dark:text-neutral-500">{icon}</span>+ <span className="truncate">{children}</span>+ </span>+ );+}++export function ExperimentRow({ experiment, experiments }: { experiment: Experiment; experiments: Experiment[] }) {+ const t = useExtracted();+ const deleteMutation = useDeleteExperiment();+ const updateMutation = useUpdateExperiment();+ const [editOpen, setEditOpen] = useState(false);+ const primaryGoalName =+ experiment.primaryGoal?.name || (experiment.primaryGoalId ? t("Untitled goal") : t("No goal"));++ const startedRel = formatRelativeTime(experiment.startedAt);+ const endedRel = formatRelativeTime(experiment.endedAt);+ const createdRel = formatRelativeTime(experiment.createdAt);+ const lifecycle =+ experiment.status === "completed" && endedRel+ ? t("Ended {time}", { time: endedRel })+ : experiment.startedAt && startedRel+ ? t("Started {time}", { time: startedRel })+ : createdRel+ ? t("Created {time}", { time: createdRel })+ : null;++ const handleDelete = async () => {+ if (!window.confirm(t("Delete this experiment?"))) return;++ try {+ await deleteMutation.mutateAsync(experiment.experimentId);+ toast.success(t("Experiment deleted"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to delete experiment"));+ }+ };++ const setStatus = async (status: ExperimentStatus) => {+ try {+ await updateMutation.mutateAsync({ experimentId: experiment.experimentId, payload: { status } });+ toast.success(t("Experiment updated"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to update experiment"));+ }+ };++ const isRunning = experiment.status === "running";++ return (+ <div+ className={cn(+ "overflow-hidden rounded-lg border bg-white dark:bg-neutral-900",+ isRunning ? "border-emerald-500/20 dark:border-emerald-500/15" : "border-neutral-100 dark:border-neutral-850"+ )}+ >+ <div className="flex flex-col gap-3 border-b border-neutral-100 p-4 dark:border-neutral-850 md:flex-row md:items-start md:justify-between">+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="truncate text-base font-medium text-neutral-900 dark:text-neutral-50">{experiment.name}</h3>+ <StatusBadge status={experiment.status} />+ {experiment.winningVariant && (+ <span className="inline-flex items-center gap-1 rounded-md bg-emerald-500/15 px-1.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">+ <Trophy className="h-3 w-3" />+ <span className="font-mono">{experiment.winningVariant}</span>+ </span>+ )}+ </div>+ <div className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1">+ <MetaChip icon={<Flag className="h-3.5 w-3.5" />}>+ <code className="font-mono text-neutral-700 dark:text-neutral-200">{experiment.featureFlag.key}</code>+ </MetaChip>+ <MetaChip icon={<Target className="h-3.5 w-3.5" />}>+ <span className="text-neutral-700 dark:text-neutral-200">{primaryGoalName}</span>+ </MetaChip>+ {lifecycle && <span className="text-xs text-neutral-400 dark:text-neutral-500">{lifecycle}</span>}+ </div>+ {experiment.hypothesis && (+ <p className="mt-2 max-w-3xl text-sm text-neutral-600 dark:text-neutral-300">{experiment.hypothesis}</p>+ )}+ </div>++ <div className="flex shrink-0 items-center gap-2">+ {experiment.status !== "running" && experiment.status !== "completed" && (+ <Button size="sm" onClick={() => setStatus("running")} disabled={updateMutation.isPending}>+ <Play className="h-3.5 w-3.5" />+ {t("Start")}+ </Button>+ )}+ {experiment.status === "running" && (+ <Button+ size="sm"+ variant="secondary"+ onClick={() => setStatus("paused")}+ disabled={updateMutation.isPending}+ >+ <Pause className="h-3.5 w-3.5" />+ {t("Pause")}+ </Button>+ )}+ {experiment.status !== "completed" && (+ <Button+ size="sm"+ variant="secondary"+ onClick={() => setStatus("completed")}+ disabled={updateMutation.isPending}+ >+ <Square className="h-3.5 w-3.5" />+ {t("Complete")}+ </Button>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="smIcon" variant="ghost" aria-label={t("Actions")}>+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ <DropdownMenuItem onSelect={() => setEditOpen(true)}>+ <Pencil className="mr-2 h-4 w-4" />+ {t("Edit")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={deleteMutation.isPending}+ onSelect={handleDelete}+ className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"+ >+ <Trash2 className="mr-2 h-4 w-4" />+ {t("Delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>++ <div className="p-4">+ <ExperimentResultsPanel experiment={experiment} />+ </div>++ <ExperimentDialog experiment={experiment} experiments={experiments} open={editOpen} onOpenChange={setEditOpen} />+ </div>+ );+}diff --git a/client/src/app/[site]/experiments/components/ExperimentSkeleton.tsx b/client/src/app/[site]/experiments/components/ExperimentSkeleton.tsxnew file mode 100644index 000000000..763ede79e--- /dev/null+++ b/client/src/app/[site]/experiments/components/ExperimentSkeleton.tsx@@ -0,0 +1,42 @@+function ExperimentCardSkeleton() {+ return (+ <div className="overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">+ <div className="flex items-start justify-between gap-3 border-b border-neutral-100 p-4 dark:border-neutral-850">+ <div className="grid gap-2">+ <div className="flex items-center gap-2">+ <div className="h-5 w-40 rounded bg-neutral-100 dark:bg-neutral-850" />+ <div className="h-5 w-16 rounded-md bg-neutral-100 dark:bg-neutral-850" />+ </div>+ <div className="flex gap-3">+ <div className="h-3.5 w-24 rounded bg-neutral-100 dark:bg-neutral-850" />+ <div className="h-3.5 w-20 rounded bg-neutral-100 dark:bg-neutral-850" />+ </div>+ </div>+ <div className="h-8 w-20 rounded-md bg-neutral-100 dark:bg-neutral-850" />+ </div>+ <div className="grid gap-2 p-4">+ {[0, 1].map(index => (+ <div+ key={index}+ className="rounded-md border border-neutral-100 bg-neutral-50/60 p-3 dark:border-neutral-850 dark:bg-neutral-950/40"+ >+ <div className="flex items-center justify-between">+ <div className="h-4 w-24 rounded bg-neutral-100 dark:bg-neutral-850" />+ <div className="h-5 w-12 rounded bg-neutral-100 dark:bg-neutral-850" />+ </div>+ <div className="mt-3 h-2 rounded-full bg-neutral-100 dark:bg-neutral-850" />+ </div>+ ))}+ </div>+ </div>+ );+}++export function ExperimentSkeleton() {+ return (+ <div className="grid animate-pulse gap-3">+ <ExperimentCardSkeleton />+ <ExperimentCardSkeleton />+ </div>+ );+}diff --git a/client/src/app/[site]/experiments/components/StatusBadge.tsx b/client/src/app/[site]/experiments/components/StatusBadge.tsxnew file mode 100644index 000000000..fa91e0164--- /dev/null+++ b/client/src/app/[site]/experiments/components/StatusBadge.tsx@@ -0,0 +1,30 @@+import type { ExperimentStatus } from "@/api/analytics/endpoints";+import { Badge } from "@/components/ui/badge";+import { cn } from "@/lib/utils";+import { statusLabel } from "../lib/experimentHelpers";++export function StatusBadge({ status }: { status: ExperimentStatus }) {+ const variant =+ status === "running" ? "success" : status === "completed" ? "info" : status === "paused" ? "warning" : "secondary";++ const dotColor =+ status === "running"+ ? "bg-emerald-500"+ : status === "completed"+ ? "bg-blue-500"+ : status === "paused"+ ? "bg-yellow-500"+ : "bg-neutral-400 dark:bg-neutral-500";++ return (+ <Badge variant={variant} className="gap-1.5">+ <span className="relative flex h-1.5 w-1.5">+ {status === "running" && (+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-500/60" />+ )}+ <span className={cn("relative inline-flex h-1.5 w-1.5 rounded-full", dotColor)} />+ </span>+ {statusLabel(status)}+ </Badge>+ );+}diff --git a/client/src/app/[site]/experiments/lib/experimentHelpers.ts b/client/src/app/[site]/experiments/lib/experimentHelpers.tsnew file mode 100644index 000000000..20a45febd--- /dev/null+++ b/client/src/app/[site]/experiments/lib/experimentHelpers.ts@@ -0,0 +1,124 @@+import type { Experiment, ExperimentStatus, ExperimentVariantResult } from "@/api/analytics/endpoints";+import { DateTime } from "luxon";++export type ExperimentFormState = {+ name: string;+ description: string;+ hypothesis: string;+ featureFlagId: string;+ primaryGoalId: string;+ status: ExperimentStatus;+};++export const STATUS_OPTIONS: ExperimentStatus[] = ["draft", "running", "paused", "completed"];++export const formatPercent = (value: number) => `${(value * 100).toFixed(2)}%`;++export function getVariantKeys(experiment: Experiment) {+ const keys: string[] = [];++ for (const conditionSet of experiment.featureFlag.conditionSets || []) {+ for (const variant of conditionSet.variants || []) {+ if (!keys.includes(variant.key)) keys.push(variant.key);+ }+ }++ for (const variant of experiment.featureFlag.variants || []) {+ if (!keys.includes(variant.key)) keys.push(variant.key);+ }++ return keys;+}++export function toFormState(experiment?: Experiment, fallbackFlagId?: number): ExperimentFormState {+ return {+ name: experiment?.name || "",+ description: experiment?.description || "",+ hypothesis: experiment?.hypothesis || "",+ featureFlagId: String(experiment?.featureFlagId ?? fallbackFlagId ?? ""),+ primaryGoalId: experiment?.primaryGoalId ? String(experiment.primaryGoalId) : "none",+ status: experiment?.status || "draft",+ };+}++export function statusLabel(status: ExperimentStatus) {+ const labels: Record<ExperimentStatus, string> = {+ draft: "Draft",+ running: "Running",+ paused: "Paused",+ completed: "Completed",+ };+ return labels[status];+}++export function formatCompactNumber(value: number): string {+ if (value < 1000) return value.toLocaleString();+ if (value < 1_000_000) return `${(value / 1000).toFixed(value < 10_000 ? 1 : 0)}k`;+ return `${(value / 1_000_000).toFixed(1)}M`;+}++export function formatRelativeTime(iso: string | null): string | null {+ if (!iso) return null;+ const dt = DateTime.fromISO(iso);+ return dt.isValid ? dt.toRelative() : null;+}++export function getControlResult(results: ExperimentVariantResult[]): ExperimentVariantResult | undefined {+ return results.find(result => result.isControl) || results[0];+}++export function getLeadingResult(results: ExperimentVariantResult[]): ExperimentVariantResult | undefined {+ return results.reduce<ExperimentVariantResult | undefined>((leader, result) => {+ if (result.conversionRate <= 0) return leader;+ if (!leader || result.conversionRate > leader.conversionRate) return result;+ return leader;+ }, undefined);+}++// Standard normal CDF (Zelen & Severo approximation), accurate to ~7 decimals.+function normalCdf(z: number): number {+ const t = 1 / (1 + 0.2316419 * Math.abs(z));+ const d = 0.3989422804014327 * Math.exp(-(z * z) / 2);+ const p = d * t * (0.31938153 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));+ return z >= 0 ? 1 - p : p;+}++// Derive the denominator consistent with the displayed conversion rate so the+// z-test never contradicts the rate shown to the user.+function effectiveSampleSize(result: ExperimentVariantResult): number {+ if (result.conversionRate > 0) {+ const derived = Math.round(result.conversions / result.conversionRate);+ if (Number.isFinite(derived) && derived >= result.conversions) return derived;+ }+ return result.exposures;+}++export type VariantConfidence = {+ confidence: number; // two-sided, 0..1+ isSignificant: boolean; // >= 0.95+};++const MIN_SAMPLE_FOR_STATS = 30;++// Two-proportion z-test of a variant against control. Returns null when there+// isn't enough data to say anything meaningful yet.+export function getVariantConfidence(+ control: ExperimentVariantResult | undefined,+ variant: ExperimentVariantResult+): VariantConfidence | null {+ if (!control || control.variant === variant.variant) return null;++ const nControl = effectiveSampleSize(control);+ const nVariant = effectiveSampleSize(variant);+ if (nControl < MIN_SAMPLE_FOR_STATS || nVariant < MIN_SAMPLE_FOR_STATS) return null;++ const pControl = control.conversions / nControl;+ const pVariant = variant.conversions / nVariant;+ const pPooled = (control.conversions + variant.conversions) / (nControl + nVariant);+ const standardError = Math.sqrt(pPooled * (1 - pPooled) * (1 / nControl + 1 / nVariant));+ if (standardError === 0) return null;++ const z = (pVariant - pControl) / standardError;+ const confidence = 2 * normalCdf(Math.abs(z)) - 1;+ return { confidence, isSignificant: confidence >= 0.95 };+}diff --git a/client/src/app/[site]/experiments/page.tsx b/client/src/app/[site]/experiments/page.tsxnew file mode 100644index 000000000..d06d7dfbc--- /dev/null+++ b/client/src/app/[site]/experiments/page.tsx@@ -0,0 +1,85 @@+"use client";++import { useExperiments } from "@/api/analytics/hooks/experiments/useExperiments";+import { NothingFound } from "@/components/NothingFound";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { useSetPageTitle } from "@/hooks/useSetPageTitle";+import { GOALS_PAGE_FILTERS } from "@/lib/filterGroups";+import { useStore } from "@/lib/store";+import { FlaskConical, Plus } from "lucide-react";+import { useExtracted } from "next-intl";+import { useMemo, useState } from "react";+import { SubHeader } from "../components/SubHeader/SubHeader";+import { ExperimentDialog } from "./components/ExperimentDialog";+import { ExperimentRow } from "./components/ExperimentRow";+import { ExperimentSkeleton } from "./components/ExperimentSkeleton";++export default function ExperimentsPage() {+ const t = useExtracted();+ useSetPageTitle("Experiments");+ const { site } = useStore();+ const { data: experiments, isLoading } = useExperiments();+ const [search, setSearch] = useState("");+ const [createOpen, setCreateOpen] = useState(false);++ const filteredExperiments = useMemo(() => {+ const query = search.trim().toLowerCase();+ if (!query) return experiments || [];++ return (experiments || []).filter(experiment =>+ [experiment.name, experiment.description || "", experiment.hypothesis || "", experiment.featureFlag.key].some(+ value => value.toLowerCase().includes(query)+ )+ );+ }, [experiments, search]);++ return (+ <div className="mx-auto max-w-[1400px] space-y-3 p-2 md:p-4">+ <SubHeader availableFilters={GOALS_PAGE_FILTERS} />+ <ExperimentDialog experiments={experiments || []} open={createOpen} onOpenChange={setCreateOpen} />++ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <Input+ className="w-full sm:w-64"+ isSearch+ placeholder={t("Filter experiments")}+ value={search}+ onChange={event => setSearch(event.target.value)}+ />+ <Button onClick={() => setCreateOpen(true)}>+ <Plus className="h-4 w-4" />+ {t("New experiment")}+ </Button>+ </div>++ {isLoading || !site ? (+ <ExperimentSkeleton />+ ) : filteredExperiments.length > 0 ? (+ <div className="grid gap-3">+ {filteredExperiments.map(experiment => (+ <ExperimentRow key={experiment.experimentId} experiment={experiment} experiments={experiments || []} />+ ))}+ </div>+ ) : experiments?.length ? (+ <NothingFound+ icon={<FlaskConical className="h-10 w-10" />}+ title={t("No experiments found")}+ description={t('No experiments match "{search}"', { search: search.trim() })}+ />+ ) : (+ <NothingFound+ icon={<FlaskConical className="h-10 w-10" />}+ title={t("No experiments yet")}+ description={t("Create an experiment from a multivariate feature flag and connect it to a conversion goal.")}+ action={+ <Button onClick={() => setCreateOpen(true)}>+ <Plus className="h-4 w-4" />+ {t("New experiment")}+ </Button>+ }+ />+ )}+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/ConditionSetsEditor.tsx b/client/src/app/[site]/feature-flags/components/ConditionSetsEditor.tsxnew file mode 100644index 000000000..ad71cd960--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/ConditionSetsEditor.tsx@@ -0,0 +1,254 @@+"use client";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Slider } from "@/components/ui/slider";+import type { FeatureFlagType } from "@/api/analytics/endpoints";+import { ArrowDown, ArrowUp, Braces, Plus, X } from "lucide-react";+import { useExtracted } from "next-intl";+import { useState } from "react";+import { createEmptyConditionSet } from "../lib/form";+import type { ConditionSetFormState } from "../lib/types";+import { JsonEditor } from "./JsonEditor";+import { TargetingRulesEditor } from "./TargetingRulesEditor";+import { VariantsEditor } from "./VariantsEditor";++export function ConditionSetsEditor({+ flagType,+ conditionSets,+ onChange,+}: {+ flagType: FeatureFlagType;+ conditionSets: ConditionSetFormState[];+ onChange: (conditionSets: ConditionSetFormState[]) => void;+}) {+ const t = useExtracted();+ const conditionSetLabel = flagType === "remote_config" ? t("Targeted configs") : t("Release conditions");+ const helper =+ flagType === "remote_config"+ ? t("Each condition returns its own payload. The first match wins.")+ : t("Each condition is evaluated in order. The first match wins.");++ const updateConditionSet = (id: string, patch: Partial<ConditionSetFormState>) => {+ onChange(+ conditionSets.map(conditionSet => (conditionSet.id === id ? { ...conditionSet, ...patch } : conditionSet))+ );+ };++ const removeConditionSet = (id: string) => {+ if (conditionSets.length <= 1) return;+ onChange(conditionSets.filter(conditionSet => conditionSet.id !== id));+ };++ const moveConditionSet = (index: number, direction: -1 | 1) => {+ const nextIndex = index + direction;+ if (nextIndex < 0 || nextIndex >= conditionSets.length) return;++ const next = [...conditionSets];+ const [conditionSet] = next.splice(index, 1);+ next.splice(nextIndex, 0, conditionSet);+ onChange(next);+ };++ return (+ <section className="grid gap-3">+ <div className="flex items-end justify-between gap-3">+ <div className="grid gap-1">+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {conditionSetLabel}+ </Label>+ <p className="text-xs text-neutral-500 dark:text-neutral-400">{helper}</p>+ </div>+ <Button+ type="button"+ size="sm"+ variant="secondary"+ onClick={() => onChange([...conditionSets, createEmptyConditionSet(flagType, conditionSets.length)])}+ >+ <Plus className="h-4 w-4" />+ {t("Add condition")}+ </Button>+ </div>++ <ol className="grid gap-2">+ {conditionSets.map((conditionSet, index) => {+ const isLast = index === conditionSets.length - 1;+ const isFirst = index === 0;+ return (+ <li key={conditionSet.id} className="relative flex gap-3">+ {/* Numbered rail — pt-3.5 centers chip with the name input row (p-3 body + 2px to center h-7 chip in h-8 input) */}+ <div className="flex w-7 flex-none flex-col items-center pt-3.5">+ <div className="flex h-7 w-7 items-center justify-center rounded-full bg-neutral-100 font-mono text-xs font-medium text-neutral-700 dark:bg-neutral-850 dark:text-neutral-300">+ {index + 1}+ </div>+ {!isLast && <div className="mt-1 w-px flex-1 bg-neutral-200 dark:bg-neutral-800" aria-hidden />}+ </div>++ {/* Body */}+ <div className="min-w-0 flex-1 rounded-lg bg-neutral-50/60 p-3 dark:bg-neutral-900/40">+ <div className="mb-3 flex items-center gap-1">+ <Input+ value={conditionSet.name}+ aria-label={t("Condition name")}+ placeholder={index === 0 ? t("Default") : t("Condition name")}+ onChange={event => updateConditionSet(conditionSet.id, { name: event.target.value })}+ className="h-8 border-transparent bg-transparent px-2 text-sm font-medium shadow-none hover:border-neutral-200 focus-visible:border-neutral-300 dark:bg-transparent dark:hover:border-neutral-800 dark:focus-visible:border-neutral-700"+ />+ <Button+ type="button"+ size="smIcon"+ variant="ghost"+ aria-label={t("Move up")}+ disabled={isFirst}+ onClick={() => moveConditionSet(index, -1)}+ >+ <ArrowUp className="h-4 w-4" />+ </Button>+ <Button+ type="button"+ size="smIcon"+ variant="ghost"+ aria-label={t("Move down")}+ disabled={isLast}+ onClick={() => moveConditionSet(index, 1)}+ >+ <ArrowDown className="h-4 w-4" />+ </Button>+ <Button+ type="button"+ size="smIcon"+ variant="ghost"+ aria-label={t("Remove")}+ disabled={conditionSets.length <= 1}+ onClick={() => removeConditionSet(conditionSet.id)}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>++ <div className="grid gap-4">+ <TargetingRulesEditor+ rules={conditionSet.rules}+ onChange={rules => updateConditionSet(conditionSet.id, { rules })}+ />++ {flagType === "multivariate" ? (+ <VariantsEditor+ variants={conditionSet.variants}+ onChange={variants => updateConditionSet(conditionSet.id, { variants })}+ />+ ) : (+ <div className="grid gap-3">+ {flagType === "boolean" && <RolloutControl conditionSet={conditionSet} onChange={updateConditionSet} />}++ <PayloadField+ flagType={flagType}+ value={conditionSet.payload}+ onChange={payload => updateConditionSet(conditionSet.id, { payload })}+ />+ </div>+ )}+ </div>+ </div>+ </li>+ );+ })}+ </ol>+ </section>+ );+}++function PayloadField({+ flagType,+ value,+ onChange,+}: {+ flagType: FeatureFlagType;+ value: string;+ onChange: (value: string) => void;+}) {+ const t = useExtracted();+ const isRequired = flagType === "remote_config";+ const [expanded, setExpanded] = useState(isRequired || value.trim().length > 0);++ const label = isRequired ? t("Config payload") : t("Payload");++ if (!expanded) {+ return (+ <button+ type="button"+ onClick={() => setExpanded(true)}+ className="inline-flex w-fit items-center gap-1.5 rounded-md border border-dashed border-neutral-200 px-2 py-1 text-xs text-neutral-500 transition-colors hover:border-neutral-300 hover:bg-neutral-50 hover:text-neutral-700 dark:border-neutral-800 dark:text-neutral-400 dark:hover:border-neutral-700 dark:hover:bg-neutral-900 dark:hover:text-neutral-200"+ >+ <Braces className="h-3 w-3" />+ {t("Add JSON payload")}+ <span className="text-neutral-400 dark:text-neutral-500">{t("(optional)")}</span>+ </button>+ );+ }++ return (+ <div className="grid gap-1.5">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-1.5">+ <Braces className="h-3 w-3 text-neutral-500 dark:text-neutral-400" />+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">{label}</Label>+ {!isRequired && (+ <span className="text-[10px] text-neutral-400 dark:text-neutral-500">{t("(optional)")}</span>+ )}+ </div>+ {!isRequired && (+ <button+ type="button"+ onClick={() => {+ onChange("");+ setExpanded(false);+ }}+ className="text-[10px] uppercase tracking-wider text-neutral-400 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-300"+ >+ {t("Remove")}+ </button>+ )}+ </div>+ <JsonEditor+ ariaLabel={label}+ value={value}+ onChange={onChange}+ placeholder={isRequired ? '{"theme":"dark"}' : '{"copy":"Try it now"}'}+ height={isRequired ? 160 : 120}+ />+ </div>+ );+}++function RolloutControl({+ conditionSet,+ onChange,+}: {+ conditionSet: ConditionSetFormState;+ onChange: (id: string, patch: Partial<ConditionSetFormState>) => void;+}) {+ const t = useExtracted();+ const pct = conditionSet.rolloutPercentage;++ return (+ <div className="grid gap-2">+ <div className="flex items-center justify-between gap-3">+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Rollout")} <span className="font-mono normal-case tracking-normal text-neutral-400 dark:text-neutral-500">+ — {pct === 100 ? t("everyone matched") : pct === 0 ? t("no one") : t("{pct}% of matched users", { pct: String(pct) })}+ </span>+ </Label>+ <span className="font-mono text-xs tabular-nums text-neutral-700 dark:text-neutral-200">{pct}%</span>+ </div>+ <Slider+ min={0}+ max={100}+ step={1}+ value={[pct]}+ onValueChange={value => onChange(conditionSet.id, { rolloutPercentage: value[0] ?? 0 })}+ />+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagDialog.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagDialog.tsxnew file mode 100644index 000000000..37a35b8f1--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagDialog.tsx@@ -0,0 +1,458 @@+"use client";++import { useCreateFeatureFlag, useUpdateFeatureFlag } from "@/api/analytics/hooks/featureFlags/useFeatureFlags";+import type { FeatureFlag, FeatureFlagType } from "@/api/analytics/endpoints";+import { CodeSnippet } from "@/components/CodeSnippet";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { toast } from "@/components/ui/sonner";+import { cn } from "@/lib/utils";+import { Braces, Check, SlidersHorizontal, ToggleRight } from "lucide-react";+import { useExtracted } from "next-intl";+import { useEffect, useMemo, useState } from "react";+import type { ReactNode } from "react";+import { flagTypeOptions, runtimeOptions } from "../lib/constants";+import { buildPayload, createEmptyVariant, toFormState } from "../lib/form";+import { useFlagTypeLabel, useRuntimeLabel } from "../lib/labels";+import type { FlagFormState } from "../lib/types";+import { ConditionSetsEditor } from "./ConditionSetsEditor";++const FLAG_TYPE_ICONS: Record<FeatureFlagType, typeof ToggleRight> = {+ boolean: ToggleRight,+ multivariate: SlidersHorizontal,+ remote_config: Braces,+};++function CodeTabs({ jsCode, tsCode }: { jsCode: string; tsCode: string }) {+ const [language, setLanguage] = useState<"js" | "ts">("js");++ return (+ <div className="grid gap-2">+ <div className="flex gap-1">+ <button+ type="button"+ onClick={() => setLanguage("js")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ language === "js"+ ? "bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"+ : "text-neutral-500 hover:bg-neutral-50 dark:text-neutral-400 dark:hover:bg-neutral-850"+ )}+ >+ JavaScript+ </button>+ <button+ type="button"+ onClick={() => setLanguage("ts")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ language === "ts"+ ? "bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"+ : "text-neutral-500 hover:bg-neutral-50 dark:text-neutral-400 dark:hover:bg-neutral-850"+ )}+ >+ TypeScript+ </button>+ </div>+ <CodeSnippet code={language === "js" ? jsCode : tsCode} language="javascript" />+ </div>+ );+}++function getVariantKeysFromForm(form: FlagFormState): string[] {+ const keys = form.conditionSets.flatMap(conditionSet =>+ conditionSet.variants.map(variant => variant.key.trim()).filter(Boolean)+ );+ return [...new Set(keys)];+}++function buildFlagSnippets(form: FlagFormState): { jsCode: string; tsCode: string } {+ const key = JSON.stringify(form.key.trim() || "my-flag");++ if (form.flagType === "boolean") {+ return {+ jsCode: `window.rybbit.onReady((rybbit) => {+ const enabled = rybbit.flag(${key}, false);++ if (enabled) {+ // Feature is on for this visitor.+ }+});`,+ tsCode: `window.rybbit.onReady((rybbit) => {+ const enabled: boolean = rybbit.flag(${key}, false);++ if (enabled) {+ // Feature is on for this visitor.+ }+});`,+ };+ }++ if (form.flagType === "multivariate") {+ const variants = getVariantKeysFromForm(form);+ const fallbackVariant = variants[0] || "control";+ const alternateVariant = variants.find(variant => variant !== fallbackVariant) || "variant_1";+ const variantUnion = variants.length ? variants.map(variant => JSON.stringify(variant)).join(" | ") : '"control"';++ return {+ jsCode: `window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag(${key}, ${JSON.stringify(fallbackVariant)});++ if (variant === ${JSON.stringify(alternateVariant)}) {+ // Render this variant.+ } else {+ // Render the default experience.+ }+});`,+ tsCode: `type FlagVariant = ${variantUnion};++window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag(${key}, ${JSON.stringify(fallbackVariant)}) as FlagVariant;++ switch (variant) {+ case ${JSON.stringify(alternateVariant)}:+ // Render this variant.+ break;+ default:+ // Render the default experience.+ break;+ }+});`,+ };+ }++ return {+ jsCode: `window.rybbit.onReady((rybbit) => {+ const matched = rybbit.flag(${key}, false);+ const config = rybbit.flagPayload(${key}, {});++ if (matched) {+ // Use config to drive your UI.+ }+});`,+ tsCode: `interface FlagConfig {+ // Shape your payload here.+ [key: string]: unknown;+}++window.rybbit.onReady((rybbit) => {+ const config = rybbit.flagPayload<FlagConfig>(${key}, {});++ // Use config to drive your UI.+});`,+ };+}++export function FeatureFlagDialog({+ flag,+ trigger,+ open: openProp,+ onOpenChange,+}: {+ flag?: FeatureFlag;+ trigger?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}) {+ const t = useExtracted();+ const getFlagTypeLabel = useFlagTypeLabel();+ const getRuntimeLabel = useRuntimeLabel();+ const [internalOpen, setInternalOpen] = useState(false);+ const isControlled = openProp !== undefined;+ const open = isControlled ? openProp : internalOpen;+ const setOpen = (next: boolean) => {+ if (!isControlled) setInternalOpen(next);+ onOpenChange?.(next);+ };+ const [form, setForm] = useState<FlagFormState>(() => toFormState(flag));+ const [view, setView] = useState<"form" | "implementation">("form");+ const [savedMode, setSavedMode] = useState<"created" | "updated">("created");+ const createMutation = useCreateFeatureFlag();+ const updateMutation = useUpdateFeatureFlag();+ const isEditing = !!flag;+ const isSaving = createMutation.isPending || updateMutation.isPending;++ useEffect(() => {+ if (open) {+ setForm(toFormState(flag));+ setView("form");+ }+ }, [flag, open]);++ const updateField = <K extends keyof FlagFormState>(key: K, value: FlagFormState[K]) => {+ setForm(current => ({ ...current, [key]: value }));+ };++ const handleFlagTypeChange = (flagType: FeatureFlagType) => {+ setForm(current => ({+ ...current,+ flagType,+ conditionSets: current.conditionSets.map((conditionSet, index) => ({+ ...conditionSet,+ payload: flagType === "remote_config" && !conditionSet.payload ? "{}" : conditionSet.payload,+ variants:+ flagType === "multivariate" && conditionSet.variants.length === 0+ ? [createEmptyVariant(0), createEmptyVariant(1)]+ : flagType === "multivariate"+ ? conditionSet.variants+ : [],+ rolloutPercentage: flagType === "boolean" ? conditionSet.rolloutPercentage : 100,+ name: conditionSet.name || (index === 0 ? "Default" : `Condition ${index + 1}`),+ })),+ }));+ };++ const handleSubmit = async () => {+ try {+ const payload = buildPayload(form);++ if (isEditing) {+ await updateMutation.mutateAsync({ flagId: flag.flagId, payload });+ toast.success(t("Feature flag updated"));+ setSavedMode("updated");+ } else {+ await createMutation.mutateAsync(payload);+ toast.success(t("Feature flag created"));+ setSavedMode("created");+ }++ setView("implementation");+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to save feature flag"));+ }+ };++ const typeDescriptions: Record<FeatureFlagType, string> = useMemo(+ () => ({+ boolean: t("Returns true or false"),+ multivariate: t("Split traffic across keys"),+ remote_config: t("Return a JSON payload"),+ }),+ [t]+ );++ const { jsCode, tsCode } = buildFlagSnippets(form);+ const runtimeNote =+ form.runtime === "server"+ ? t("This flag is evaluated server-side. Call the evaluate API from your backend instead of the browser script.")+ : form.runtime === "both"+ ? t("This flag also evaluates server-side. Your backend can read it from the evaluate API.")+ : null;++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ {trigger && <DialogTrigger asChild>{trigger}</DialogTrigger>}+ <DialogContent className="flex max-h-[90vh] w-full max-w-3xl flex-col gap-0 overflow-hidden p-0">+ <DialogTitle className="sr-only">+ {isEditing ? t("Edit feature flag {key}", { key: form.key }) : t("Create feature flag")}+ </DialogTitle>+ {/* Sticky header — flag identity */}+ <div className="border-b border-neutral-150 px-6 pb-4 pt-5 dark:border-neutral-850">+ <div className="mb-3 flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <span className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {isEditing ? t("Edit flag") : t("New flag")}+ </span>+ <span+ className={cn(+ "inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs",+ form.enabled+ ? "bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-400"+ : "bg-neutral-100 text-neutral-500 dark:bg-neutral-850 dark:text-neutral-400"+ )}+ >+ <span+ className={cn(+ "h-1.5 w-1.5 rounded-full",+ form.enabled ? "bg-emerald-500" : "bg-neutral-400 dark:bg-neutral-600"+ )}+ />+ {form.enabled ? t("Live") : t("Paused")}+ </span>+ </div>+ </div>++ <div className="flex items-baseline gap-2">+ <Input+ id="flag-key"+ value={form.key}+ disabled={isEditing}+ onChange={event => updateField("key", event.target.value.replace(/\s+/g, "-"))}+ placeholder="new-checkout"+ className={cn(+ "h-auto border-0 bg-transparent px-0 py-0 font-mono text-xl font-medium tracking-tight",+ "shadow-none focus-visible:ring-0 dark:bg-transparent",+ "placeholder:text-neutral-300 dark:placeholder:text-neutral-700"+ )}+ />+ </div>+ <p className="mt-1 text-xs text-neutral-500 dark:text-neutral-400">+ {t("The identifier you'll reference in code")}+ </p>+ </div>++ {/* Scrollable body */}+ <div className="flex-1 overflow-y-auto px-6 py-5">+ {view === "implementation" ? (+ <div className="grid gap-5">+ <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4 dark:border-emerald-900 dark:bg-emerald-950/30">+ <div className="flex items-start gap-3">+ <div className="mt-0.5 flex h-6 w-6 items-center justify-center rounded-full bg-emerald-500 text-white">+ <Check className="h-4 w-4" />+ </div>+ <div>+ <h3 className="text-sm font-medium text-emerald-900 dark:text-emerald-100">+ {savedMode === "created" ? t("Feature flag created") : t("Feature flag changes saved")}+ </h3>+ <p className="mt-1 text-sm text-emerald-800 dark:text-emerald-200">+ {t("Read this flag in your app to control behavior for your visitors.")}+ </p>+ </div>+ </div>+ </div>++ <div className="grid gap-2">+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Usage")}+ </Label>+ <CodeTabs jsCode={jsCode} tsCode={tsCode} />+ </div>++ {runtimeNote && (+ <p className="rounded-md border border-neutral-150 bg-neutral-50 p-3 text-sm text-neutral-600 dark:border-neutral-800 dark:bg-neutral-900/40 dark:text-neutral-300">+ {runtimeNote}+ </p>+ )}+ </div>+ ) : (+ <div className="grid gap-6">+ {/* Type selector — choice cards */}+ <section className="grid gap-2">+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Returns")}+ </Label>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">+ {flagTypeOptions.map(option => {+ const Icon = FLAG_TYPE_ICONS[option];+ const selected = form.flagType === option;+ return (+ <button+ key={option}+ type="button"+ onClick={() => handleFlagTypeChange(option)}+ className={cn(+ "group flex flex-col items-start gap-2 rounded-lg border p-3 text-left transition-colors",+ selected+ ? "border-accent-500 bg-accent-500/5 dark:border-accent-600 dark:bg-accent-600/10"+ : "border-neutral-150 bg-neutral-50/50 hover:border-neutral-200 hover:bg-neutral-100/60 dark:border-neutral-800 dark:bg-neutral-900/40 dark:hover:border-neutral-750 dark:hover:bg-neutral-900"+ )}+ >+ <div+ className={cn(+ "flex h-7 w-7 items-center justify-center rounded-md",+ selected+ ? "bg-accent-500/15 text-accent-600 dark:bg-accent-500/20 dark:text-accent-400"+ : "bg-neutral-100 text-neutral-500 dark:bg-neutral-850 dark:text-neutral-400"+ )}+ >+ <Icon className="h-4 w-4" />+ </div>+ <div className="grid gap-0.5">+ <span className="text-sm font-medium text-neutral-900 dark:text-neutral-50">+ {getFlagTypeLabel(option)}+ </span>+ <span className="text-xs text-neutral-500 dark:text-neutral-400">+ {typeDescriptions[option]}+ </span>+ </div>+ </button>+ );+ })}+ </div>+ </section>++ <ConditionSetsEditor+ flagType={form.flagType}+ conditionSets={form.conditionSets}+ onChange={conditionSets => updateField("conditionSets", conditionSets)}+ />++ {/* Meta: description */}+ <section className="grid gap-2">+ <Label+ htmlFor="flag-description"+ className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400"+ >+ {t("Description")}+ </Label>+ <Textarea+ id="flag-description"+ value={form.description}+ onChange={event => updateField("description", event.target.value)}+ rows={2}+ placeholder={t("Optional — describe what this flag controls")}+ />+ </section>+ </div>+ )}+ </div>++ {/* Sticky footer — deployment strip + actions */}+ {view === "implementation" ? (+ <div className="flex items-center justify-end gap-2 border-t border-neutral-150 px-6 py-3 dark:border-neutral-850">+ <Button onClick={() => setOpen(false)} variant="success">+ {t("Done")}+ </Button>+ </div>+ ) : (+ <div className="border-t border-neutral-150 bg-neutral-50/40 dark:border-neutral-850 dark:bg-neutral-900/40">+ <div className="flex flex-wrap items-center justify-between gap-3 px-6 py-3">+ <div className="flex flex-wrap items-center gap-4">+ <label className="flex items-center gap-2">+ <Switch checked={form.enabled} onCheckedChange={checked => updateField("enabled", checked)} />+ <span className="text-sm text-neutral-700 dark:text-neutral-300">{t("Enabled")}</span>+ </label>+ <div className="hidden h-5 w-px bg-neutral-200 dark:bg-neutral-800 sm:block" />+ <div className="flex items-center gap-2">+ <span className="text-xs text-neutral-500 dark:text-neutral-400">{t("Runtime")}</span>+ <div className="flex items-center rounded-md border border-neutral-150 bg-white p-0.5 dark:border-neutral-800 dark:bg-neutral-900">+ {runtimeOptions.map(option => {+ const selected = form.runtime === option;+ return (+ <button+ key={option}+ type="button"+ onClick={() => updateField("runtime", option)}+ className={cn(+ "rounded px-2 py-0.5 text-xs font-medium transition-colors",+ selected+ ? "bg-neutral-900 text-white dark:bg-neutral-50 dark:text-neutral-900"+ : "text-neutral-500 hover:text-neutral-700 dark:text-neutral-400 dark:hover:text-neutral-200"+ )}+ >+ {getRuntimeLabel(option)}+ </button>+ );+ })}+ </div>+ </div>+ </div>+ </div>+ <div className="flex items-center justify-end gap-2 border-t border-neutral-150 px-6 py-3 dark:border-neutral-850">+ <Button variant="ghost" onClick={() => setOpen(false)}>+ {t("Cancel")}+ </Button>+ <Button onClick={handleSubmit} disabled={isSaving || !form.key.trim()} variant="success">+ {isSaving ? t("Saving...") : isEditing ? t("Save changes") : t("Create flag")}+ </Button>+ </div>+ </div>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagSkeleton.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagSkeleton.tsxnew file mode 100644index 000000000..9b95990eb--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagSkeleton.tsx@@ -0,0 +1,17 @@+export function FeatureFlagSkeleton() {+ return (+ <div className="rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">+ {Array.from({ length: 5 }).map((_, index) => (+ <div+ key={index}+ className="flex items-center gap-4 border-b border-neutral-100 p-4 last:border-0 dark:border-neutral-850"+ >+ <div className="h-5 w-48 rounded bg-neutral-100 dark:bg-neutral-800" />+ <div className="h-5 w-20 rounded bg-neutral-100 dark:bg-neutral-800" />+ <div className="h-5 flex-1 rounded bg-neutral-100 dark:bg-neutral-800" />+ <div className="h-5 w-20 rounded bg-neutral-100 dark:bg-neutral-800" />+ </div>+ ))}+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsxnew file mode 100644index 000000000..c921e1a61--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx@@ -0,0 +1,376 @@+"use client";++import { useDeleteFeatureFlag, useUpdateFeatureFlag } from "@/api/analytics/hooks/featureFlags/useFeatureFlags";+import type { FeatureFlag } from "@/api/analytics/endpoints";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Switch } from "@/components/ui/switch";+import { TableSortIndicator } from "@/components/ui/table";+import { toast } from "@/components/ui/sonner";+import { cn } from "@/lib/utils";+import { getTimezone } from "@/lib/store";+import {+ createColumnHelper,+ flexRender,+ getCoreRowModel,+ getSortedRowModel,+ type SortingState,+ useReactTable,+} from "@tanstack/react-table";+import { Edit2, MoreHorizontal, Trash2 } from "lucide-react";+import { DateTime } from "luxon";+import { useExtracted } from "next-intl";+import { useState } from "react";+import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";+import { formatFlagValue, getConditionSetPayload } from "../lib/form";+import { useFlagTypeLabel, useRuntimeLabel } from "../lib/labels";+import { FeatureFlagDialog } from "./FeatureFlagDialog";++const columnHelper = createColumnHelper<FeatureFlag>();+const TIME_COLUMN_IDS = new Set(["createdAt", "updatedAt"]);+const isTimeColumn = (columnId: string) => TIME_COLUMN_IDS.has(columnId);++const totalSessions = (flag: FeatureFlag) => flag.stats.reduce((sum, stat) => sum + stat.sessions, 0);+const totalRules = (flag: FeatureFlag) =>+ flag.conditionSets.reduce((sum, conditionSet) => sum + conditionSet.rules.length, 0);++const computeRollout = (flag: FeatureFlag) => {+ if (flag.flagType === "remote_config") return null;+ const firstConditionSet = flag.conditionSets[0];+ if (flag.flagType === "multivariate") {+ const variants = firstConditionSet?.variants || flag.variants;+ return Math.min(+ 100,+ variants.reduce((sum, variant) => sum + variant.rolloutPercentage, 0)+ );+ }+ return firstConditionSet?.rolloutPercentage ?? flag.rolloutPercentage;+};++const SortHeader = ({ column, children }: any) => {+ const isSorted = column.getIsSorted();+ return (+ <div+ onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}+ className="flex cursor-pointer select-none items-center gap-1"+ >+ {children}+ <TableSortIndicator sortDirection={isSorted} />+ </div>+ );+};++function FlagStats({ flag }: { flag: FeatureFlag }) {+ const topStats = flag.stats.slice(0, 2);+ if (topStats.length === 0) return <span className="text-neutral-400">-</span>;++ return (+ <div className="flex flex-col gap-1">+ {topStats.map(stat => (+ <div key={`${stat.flag_value}-${stat.sessions}`} className="flex items-center gap-2 text-xs">+ <span className="max-w-24 truncate font-mono text-neutral-700 dark:text-neutral-200">+ {stat.flag_value || "(empty)"}+ </span>+ <span className="text-neutral-500 dark:text-neutral-400">{stat.sessions.toLocaleString()} sessions</span>+ </div>+ ))}+ </div>+ );+}++function FlagValueSummary({ flag }: { flag: FeatureFlag }) {+ const t = useExtracted();+ const getFlagTypeLabel = useFlagTypeLabel();+ const firstConditionSet = flag.conditionSets[0];+ const variants = firstConditionSet?.variants || flag.variants;++ if (flag.flagType === "multivariate") {+ return (+ <div className="flex max-w-56 flex-col gap-1">+ <Badge variant="outline" className="w-fit">+ {getFlagTypeLabel(flag.flagType)}+ </Badge>+ <div className="flex flex-wrap gap-1">+ {variants.slice(0, 3).map(variant => (+ <span+ key={variant.key}+ className="rounded bg-neutral-100 px-1.5 py-0.5 font-mono text-xs dark:bg-neutral-800"+ >+ {variant.key} {variant.rolloutPercentage}%+ </span>+ ))}+ {variants.length > 3 && (+ <span className="text-xs text-neutral-500 dark:text-neutral-400">+{variants.length - 3}</span>+ )}+ </div>+ </div>+ );+ }++ if (flag.flagType === "remote_config") {+ return (+ <div className="flex max-w-48 flex-col gap-1">+ <Badge variant="outline" className="w-fit">+ {getFlagTypeLabel(flag.flagType)}+ </Badge>+ <span className="truncate font-mono text-xs text-neutral-500 dark:text-neutral-400">+ {formatFlagValue(getConditionSetPayload(flag, firstConditionSet)) || t("Payload")}+ </span>+ </div>+ );+ }++ return (+ <div className="flex max-w-48 flex-col gap-1">+ <Badge variant="outline" className="w-fit">+ {getFlagTypeLabel(flag.flagType)}+ </Badge>+ {(firstConditionSet?.payload !== undefined || (flag.payload !== undefined && flag.payload !== null)) && (+ <span className="truncate font-mono text-xs text-neutral-500 dark:text-neutral-400">+ {formatFlagValue(getConditionSetPayload(flag, firstConditionSet))}+ </span>+ )}+ </div>+ );+}++function FlagRolloutSummary({ flag }: { flag: FeatureFlag }) {+ const rollout = computeRollout(flag);+ if (rollout === null) return <span className="text-neutral-400">-</span>;++ return (+ <div className="flex items-center gap-2">+ <div className="h-2 w-20 rounded-full bg-neutral-100 dark:bg-neutral-800">+ <div+ className={cn("h-2 rounded-full bg-accent-500", rollout === 0 && "bg-transparent")}+ style={{ width: `${rollout}%` }}+ />+ </div>+ <span className="text-sm tabular-nums">{rollout}%</span>+ </div>+ );+}++function RowActions({ flag }: { flag: FeatureFlag }) {+ const t = useExtracted();+ const deleteMutation = useDeleteFeatureFlag();+ const [editOpen, setEditOpen] = useState(false);++ const handleDelete = async () => {+ if (!window.confirm(t("Delete this feature flag?"))) return;+ try {+ await deleteMutation.mutateAsync(flag.flagId);+ toast.success(t("Feature flag deleted"));+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to delete feature flag"));+ }+ };++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger size="smIcon" variant="ghost" asChild>+ <Button size="smIcon" variant="ghost" aria-label={t("Actions")}>+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ <DropdownMenuItem onSelect={() => setEditOpen(true)}>+ <Edit2 className="mr-2 h-4 w-4" />+ {t("Edit")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={deleteMutation.isPending}+ onSelect={handleDelete}+ className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"+ >+ <Trash2 className="mr-2 h-4 w-4" />+ {t("Delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <FeatureFlagDialog flag={flag} open={editOpen} onOpenChange={setEditOpen} />+ </>+ );+}++export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {+ const t = useExtracted();+ const getRuntimeLabel = useRuntimeLabel();+ const updateMutation = useUpdateFeatureFlag();+ const { formatRelative, formatDateTime } = useDateTimeFormat();+ const [sorting, setSorting] = useState<SortingState>([{ id: "updatedAt", desc: true }]);++ const parseTimestamp = (value: string) => {+ const sql = DateTime.fromSQL(value, { zone: "utc" });+ const date = sql.isValid ? sql : DateTime.fromISO(value, { zone: "utc" });+ return date.setZone(getTimezone());+ };++ const renderTimeCell = (value: string) => {+ const date = parseTimestamp(value);+ if (!date.isValid) {+ return <span className="text-neutral-400">-</span>;+ }+ const formatted = formatDateTime(date, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });+ const relative = formatRelative(date);+ return (+ <div className="grid w-32 whitespace-nowrap">+ <span className="col-start-1 row-start-1 text-neutral-600 group-hover:invisible dark:text-neutral-300">+ {relative}+ </span>+ <span className="invisible col-start-1 row-start-1 text-neutral-600 group-hover:visible dark:text-neutral-300">+ {formatted}+ </span>+ </div>+ );+ };++ const columns = [+ columnHelper.accessor("key", {+ id: "key",+ header: ({ column }) => <SortHeader column={column}>{t("Flag")}</SortHeader>,+ cell: info => (+ <div className="flex items-center gap-2">+ <span className="font-mono text-sm font-medium">{info.getValue()}</span>+ <Badge variant="secondary">v{info.row.original.version}</Badge>+ </div>+ ),+ }),+ columnHelper.accessor("enabled", {+ id: "enabled",+ header: ({ column }) => <SortHeader column={column}>{t("Status")}</SortHeader>,+ cell: info => {+ const flag = info.row.original;+ return (+ <div className="flex items-center gap-2">+ <Switch+ checked={flag.enabled}+ disabled={updateMutation.isPending}+ onCheckedChange={enabled => updateMutation.mutate({ flagId: flag.flagId, payload: { enabled } })}+ />+ <Badge variant={flag.enabled ? "success" : "secondary"}>{flag.enabled ? t("On") : t("Off")}</Badge>+ <Badge variant="outline">{getRuntimeLabel(flag.runtime)}</Badge>+ </div>+ );+ },+ sortingFn: (a, b) => Number(b.original.enabled) - Number(a.original.enabled),+ }),+ columnHelper.display({+ id: "value",+ header: () => <span>{t("Value")}</span>,+ cell: info => <FlagValueSummary flag={info.row.original} />,+ }),+ columnHelper.accessor(row => computeRollout(row) ?? -1, {+ id: "rollout",+ header: ({ column }) => <SortHeader column={column}>{t("Rollout")}</SortHeader>,+ cell: info => <FlagRolloutSummary flag={info.row.original} />,+ }),+ columnHelper.accessor(row => totalRules(row), {+ id: "rules",+ header: ({ column }) => <SortHeader column={column}>{t("Rules")}</SortHeader>,+ cell: info => {+ const flag = info.row.original;+ return (+ <span className="tabular-nums">+ {flag.conditionSets.length.toLocaleString()} / {totalRules(flag).toLocaleString()}+ </span>+ );+ },+ }),+ columnHelper.accessor(row => totalSessions(row), {+ id: "traffic",+ header: ({ column }) => <SortHeader column={column}>{t("Traffic")}</SortHeader>,+ cell: info => <FlagStats flag={info.row.original} />,+ }),+ columnHelper.accessor("createdAt", {+ id: "createdAt",+ header: ({ column }) => <SortHeader column={column}>{t("Created")}</SortHeader>,+ cell: info => renderTimeCell(info.getValue()),+ }),+ columnHelper.accessor("updatedAt", {+ id: "updatedAt",+ header: ({ column }) => <SortHeader column={column}>{t("Updated")}</SortHeader>,+ cell: info => renderTimeCell(info.getValue()),+ }),+ columnHelper.display({+ id: "actions",+ header: () => <span className="sr-only">{t("Actions")}</span>,+ cell: info => (+ <div className="flex justify-end">+ <RowActions flag={info.row.original} />+ </div>+ ),+ }),+ ];++ const table = useReactTable({+ data: flags,+ columns,+ state: { sorting },+ onSortingChange: setSorting,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ sortDescFirst: true,+ });++ return (+ <div className="rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900">+ <div className="relative overflow-x-auto">+ <table className="w-full text-left text-sm">+ <thead className="bg-neutral-50 [&_tr]:border-b-0 dark:bg-neutral-850">+ {table.getHeaderGroups().map(headerGroup => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map(header => (+ <th+ key={header.id}+ scope="col"+ className={cn(+ "h-8 whitespace-nowrap px-3 text-left align-middle text-xs font-medium text-neutral-500 first:rounded-l-lg last:rounded-r-lg dark:text-neutral-400",+ header.id === "actions" && "w-12 text-right"+ )}+ style={{+ minWidth: isTimeColumn(header.id) ? "8rem" : undefined,+ }}+ >+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}+ </th>+ ))}+ </tr>+ ))}+ </thead>+ <tbody>+ {table.getRowModel().rows.length === 0 ? (+ <tr>+ <td colSpan={columns.length} className="px-3 py-8 text-center text-neutral-500 dark:text-neutral-400">+ {t("No feature flags found")}+ </td>+ </tr>+ ) : (+ table.getRowModel().rows.map(row => (+ <tr+ key={row.id}+ className="group border-b border-neutral-100 hover:bg-neutral-50 dark:border-neutral-800 dark:hover:bg-neutral-850"+ >+ {row.getVisibleCells().map(cell => (+ <td key={cell.id} className={cn("relative p-3", cell.column.id === "actions" && "text-right")}>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </td>+ ))}+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/JsonEditor.tsx b/client/src/app/[site]/feature-flags/components/JsonEditor.tsxnew file mode 100644index 000000000..4e43f9e3f--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/JsonEditor.tsx@@ -0,0 +1,71 @@+"use client";++import Editor, { type OnMount } from "@monaco-editor/react";+import { useTheme } from "next-themes";+import { useCallback } from "react";++export function JsonEditor({+ value,+ onChange,+ placeholder,+ height = 140,+ ariaLabel,+}: {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ height?: number | string;+ ariaLabel?: string;+}) {+ const { resolvedTheme } = useTheme();+ const isDark = resolvedTheme !== "light";++ const handleMount: OnMount = useCallback((editor, monaco) => {+ monaco.languages.json.jsonDefaults.setDiagnosticsOptions({+ validate: true,+ allowComments: false,+ schemaValidation: "error",+ });+ editor.updateOptions({+ lineNumbers: "off",+ minimap: { enabled: false },+ folding: false,+ lineDecorationsWidth: 4,+ lineNumbersMinChars: 0,+ glyphMargin: false,+ overviewRulerLanes: 0,+ hideCursorInOverviewRuler: true,+ overviewRulerBorder: false,+ scrollBeyondLastLine: false,+ renderLineHighlight: "none",+ scrollbar: { verticalScrollbarSize: 6, horizontalScrollbarSize: 6, alwaysConsumeMouseWheel: false },+ padding: { top: 8, bottom: 8 },+ fontSize: 12,+ fontFamily:+ 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',+ tabSize: 2,+ contextmenu: false,+ wordWrap: "on",+ });+ }, []);++ return (+ <div+ aria-label={ariaLabel}+ className="overflow-hidden rounded-md border border-neutral-150 bg-white dark:border-neutral-800 dark:bg-neutral-900"+ style={{ height }}+ >+ <Editor+ language="json"+ value={value}+ theme={isDark ? "vs-dark" : "vs"}+ onChange={next => onChange(next ?? "")}+ onMount={handleMount}+ options={{+ placeholder,+ }}+ loading={null}+ />+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/TargetingRulesEditor.tsx b/client/src/app/[site]/feature-flags/components/TargetingRulesEditor.tsxnew file mode 100644index 000000000..e21e82b08--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/TargetingRulesEditor.tsx@@ -0,0 +1,157 @@+"use client";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Filter, Plus, X } from "lucide-react";+import { useExtracted } from "next-intl";+import { Fragment } from "react";+import { ruleFieldOptions, ruleOperatorOptions } from "../lib/constants";+import { createEmptyRule } from "../lib/form";+import { useRuleFieldLabel, useRuleOperatorLabel } from "../lib/labels";+import type { RuleField, RuleFormState, RuleOperator } from "../lib/types";++export function TargetingRulesEditor({+ rules,+ onChange,+}: {+ rules: RuleFormState[];+ onChange: (rules: RuleFormState[]) => void;+}) {+ const t = useExtracted();+ const getRuleFieldLabel = useRuleFieldLabel();+ const getRuleOperatorLabel = useRuleOperatorLabel();++ const updateRule = (id: string, patch: Partial<RuleFormState>) => {+ onChange(+ rules.map(rule => {+ if (rule.id !== id) return rule;+ const next = { ...rule, ...patch };+ if (patch.field && patch.field !== "query" && patch.field !== "trait") {+ next.key = "";+ }+ return next;+ })+ );+ };++ const removeRule = (id: string) => {+ onChange(rules.filter(rule => rule.id !== id));+ };++ return (+ <div className="grid gap-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5">+ <Filter className="h-3 w-3 text-neutral-500 dark:text-neutral-400" />+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Targeting rules")}+ </Label>+ </div>+ <Button type="button" size="sm" variant="secondary" onClick={() => onChange([...rules, createEmptyRule()])}>+ <Plus className="h-4 w-4" />+ {t("Add rule")}+ </Button>+ </div>++ {rules.length === 0 ? (+ <div className="rounded-md border border-dashed border-neutral-200 px-3 py-4 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">+ <span className="font-mono text-neutral-400 dark:text-neutral-500">{"//"}</span>{" "}+ {t("Applies to everyone — add a rule to narrow targeting")}+ </div>+ ) : (+ <div className="grid gap-1.5">+ {rules.map((rule, index) => {+ const selectedField = ruleFieldOptions.find(option => option.value === rule.field);+ const requiresKey = !!selectedField?.requiresKey;++ return (+ <Fragment key={rule.id}>+ {index > 0 && (+ <div className="flex items-center gap-2 pl-1">+ <span className="font-mono text-[10px] font-semibold uppercase tracking-widest text-neutral-400 dark:text-neutral-500">+ {t("and")}+ </span>+ <div className="h-px flex-1 bg-neutral-200 dark:bg-neutral-800" />+ </div>+ )}+ <div+ className="grid grid-cols-1 items-center gap-1.5 lg:grid"+ style={{+ gridTemplateColumns: requiresKey+ ? "minmax(140px,1fr) minmax(120px,0.9fr) minmax(140px,1fr) minmax(160px,1.2fr) auto"+ : "minmax(140px,1fr) minmax(140px,1fr) minmax(160px,1.2fr) auto",+ }}+ >+ <Select+ value={rule.field}+ onValueChange={value => updateRule(rule.id, { field: value as RuleField })}+ >+ <SelectTrigger aria-label={t("Field")} className="h-8 text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ruleFieldOptions.map(option => (+ <SelectItem key={option.value} value={option.value}>+ {getRuleFieldLabel(option.value)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ {requiresKey && (+ <Input+ aria-label={t("Key")}+ value={rule.key}+ placeholder={t("key")}+ onChange={event => updateRule(rule.id, { key: event.target.value })}+ className="h-8 font-mono text-xs"+ />+ )}++ <Select+ value={rule.operator}+ onValueChange={value => updateRule(rule.id, { operator: value as RuleOperator })}+ >+ <SelectTrigger+ aria-label={t("Operator")}+ className="h-8 bg-neutral-100/60 text-xs italic text-neutral-600 dark:bg-neutral-850/60 dark:text-neutral-300"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ruleOperatorOptions.map(operator => (+ <SelectItem key={operator} value={operator}>+ {getRuleOperatorLabel(operator)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Input+ aria-label={t("Value")}+ value={rule.value}+ placeholder={t("value")}+ onChange={event => updateRule(rule.id, { value: event.target.value })}+ className="h-8 font-mono text-xs"+ />++ <Button+ type="button"+ size="smIcon"+ variant="ghost"+ aria-label={t("Remove")}+ onClick={() => removeRule(rule.id)}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ </Fragment>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/components/VariantsEditor.tsx b/client/src/app/[site]/feature-flags/components/VariantsEditor.tsxnew file mode 100644index 000000000..dd86920c3--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/VariantsEditor.tsx@@ -0,0 +1,193 @@+"use client";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Slider } from "@/components/ui/slider";+import { cn } from "@/lib/utils";+import { GitBranch, Plus, X } from "lucide-react";+import { useExtracted } from "next-intl";+import { createEmptyVariant } from "../lib/form";+import type { VariantFormState } from "../lib/types";+import { JsonEditor } from "./JsonEditor";++const VARIANT_PALETTE = [+ "bg-accent-500 dark:bg-accent-600",+ "bg-sky-500 dark:bg-sky-600",+ "bg-amber-500 dark:bg-amber-500",+ "bg-violet-500 dark:bg-violet-500",+ "bg-rose-500 dark:bg-rose-500",+ "bg-teal-500 dark:bg-teal-500",+];++const VARIANT_DOT_PALETTE = [+ "bg-accent-500 dark:bg-accent-500",+ "bg-sky-500",+ "bg-amber-500",+ "bg-violet-500",+ "bg-rose-500",+ "bg-teal-500",+];++export function VariantsEditor({+ variants,+ onChange,+}: {+ variants: VariantFormState[];+ onChange: (variants: VariantFormState[]) => void;+}) {+ const t = useExtracted();+ const totalRollout = variants.reduce((sum, variant) => sum + variant.rolloutPercentage, 0);+ const over = totalRollout > 100;+ const under = totalRollout < 100;++ const updateVariant = (id: string, patch: Partial<VariantFormState>) => {+ onChange(variants.map(variant => (variant.id === id ? { ...variant, ...patch } : variant)));+ };++ const removeVariant = (id: string) => {+ onChange(variants.filter(variant => variant.id !== id));+ };++ return (+ <div className="grid gap-3">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5">+ <GitBranch className="h-3 w-3 text-neutral-500 dark:text-neutral-400" />+ <Label className="text-xs uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Variants")}+ </Label>+ </div>+ <div className="flex items-center gap-2">+ <span+ className={cn(+ "font-mono text-xs tabular-nums",+ over+ ? "text-red-500 dark:text-red-400"+ : under+ ? "text-amber-600 dark:text-amber-400"+ : "text-emerald-600 dark:text-emerald-400"+ )}+ >+ {totalRollout}%+ </span>+ <Button+ type="button"+ size="sm"+ variant="secondary"+ onClick={() => onChange([...variants, createEmptyVariant(variants.length)])}+ >+ <Plus className="h-4 w-4" />+ {t("Add variant")}+ </Button>+ </div>+ </div>++ {/* Stacked rollout bar */}+ {variants.length > 0 && (+ <div className="grid gap-1.5">+ <div className="flex h-2 w-full overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-850">+ {variants.map((variant, index) => {+ const width = Math.min(100, Math.max(0, variant.rolloutPercentage));+ if (width === 0) return null;+ return (+ <div+ key={variant.id}+ className={cn("h-full transition-[width]", VARIANT_PALETTE[index % VARIANT_PALETTE.length])}+ style={{ width: `${(width / Math.max(totalRollout, 100)) * 100}%` }}+ title={`${variant.key || variant.name || `Variant ${index + 1}`} • ${width}%`}+ />+ );+ })}+ </div>+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-neutral-500 dark:text-neutral-400">+ {variants.map((variant, index) => (+ <span key={variant.id} className="inline-flex items-center gap-1.5">+ <span+ className={cn("h-1.5 w-1.5 rounded-full", VARIANT_DOT_PALETTE[index % VARIANT_DOT_PALETTE.length])}+ />+ <span className="font-mono text-neutral-700 dark:text-neutral-200">+ {variant.key || `variant_${index + 1}`}+ </span>+ <span className="tabular-nums">{variant.rolloutPercentage}%</span>+ </span>+ ))}+ </div>+ </div>+ )}++ <div className="grid gap-2">+ {variants.map((variant, index) => (+ <div+ key={variant.id}+ className="grid gap-3 rounded-md border border-neutral-150 bg-white p-3 dark:border-neutral-800 dark:bg-neutral-900"+ >+ <div className="grid grid-cols-1 items-center gap-2 md:grid-cols-[auto_minmax(120px,1fr)_minmax(120px,1fr)_2rem]">+ <span+ className={cn(+ "h-2.5 w-2.5 rounded-full",+ VARIANT_DOT_PALETTE[index % VARIANT_DOT_PALETTE.length]+ )}+ aria-hidden+ />+ <Input+ aria-label={t("Variant key")}+ value={variant.key}+ placeholder={t("variant_key")}+ onChange={event => updateVariant(variant.id, { key: event.target.value })}+ className="h-8 font-mono text-xs"+ />+ <Input+ aria-label={t("Variant name")}+ value={variant.name}+ placeholder={t("Display name")}+ onChange={event => updateVariant(variant.id, { name: event.target.value })}+ className="h-8 text-xs"+ />+ <Button+ type="button"+ size="smIcon"+ variant="ghost"+ aria-label={t("Remove")}+ onClick={() => removeVariant(variant.id)}+ >+ <X className="h-4 w-4" />+ </Button>+ </div>++ <div className="grid gap-2">+ <div className="flex items-center justify-between">+ <Label className="text-[11px] uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Rollout")}+ </Label>+ <span className="font-mono text-xs tabular-nums text-neutral-700 dark:text-neutral-200">+ {variant.rolloutPercentage}%+ </span>+ </div>+ <Slider+ min={0}+ max={100}+ step={1}+ value={[variant.rolloutPercentage]}+ onValueChange={value => updateVariant(variant.id, { rolloutPercentage: value[0] ?? 0 })}+ />+ </div>++ <div className="grid gap-1.5">+ <Label className="text-[11px] uppercase tracking-wider text-neutral-500 dark:text-neutral-400">+ {t("Payload")}+ </Label>+ <JsonEditor+ ariaLabel={t("Payload")}+ value={variant.payload}+ onChange={payload => updateVariant(variant.id, { payload })}+ placeholder='{"copy":"Try it now"}'+ height={110}+ />+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/client/src/app/[site]/feature-flags/lib/constants.ts b/client/src/app/[site]/feature-flags/lib/constants.tsnew file mode 100644index 000000000..1400a5dd3--- /dev/null+++ b/client/src/app/[site]/feature-flags/lib/constants.ts@@ -0,0 +1,28 @@+import type { FeatureFlagRuntime, FeatureFlagType } from "@/api/analytics/endpoints";+import type { RuleField, RuleOperator } from "./types";++export const flagTypeOptions: FeatureFlagType[] = ["boolean", "multivariate", "remote_config"];+export const runtimeOptions: FeatureFlagRuntime[] = ["client", "server", "both"];++export const ruleFieldOptions: Array<{ value: RuleField; requiresKey?: boolean }> = [+ { value: "hostname" },+ { value: "pathname" },+ { value: "query", requiresKey: true },+ { value: "referrer" },+ { value: "language" },+ { value: "country" },+ { value: "region" },+ { value: "city" },+ { value: "device_type" },+ { value: "user_id" },+ { value: "trait", requiresKey: true },+];++export const ruleOperatorOptions: RuleOperator[] = [+ "equals",+ "not_equals",+ "contains",+ "starts_with",+ "ends_with",+ "regex",+];diff --git a/client/src/app/[site]/feature-flags/lib/form.ts b/client/src/app/[site]/feature-flags/lib/form.tsnew file mode 100644index 000000000..2acc9812c--- /dev/null+++ b/client/src/app/[site]/feature-flags/lib/form.ts@@ -0,0 +1,261 @@+import type {+ FeatureFlag,+ FeatureFlagPayload,+ FeatureFlagPayloadValue,+ FeatureFlagRule,+ FeatureFlagType,+} from "@/api/analytics/endpoints";+import type { ConditionSetFormState, FlagFormState, RuleFormState, VariantFormState } from "./types";++function createRuleId() {+ return typeof crypto !== "undefined" && "randomUUID" in crypto+ ? crypto.randomUUID()+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`;+}++export function createEmptyRule(): RuleFormState {+ return {+ id: createRuleId(),+ field: "pathname",+ key: "",+ operator: "equals",+ value: "",+ };+}++export function createEmptyVariant(index: number): VariantFormState {+ return {+ id: createRuleId(),+ key: index === 0 ? "control" : `variant_${index}`,+ name: "",+ rolloutPercentage: index < 2 ? 50 : 0,+ payload: "",+ };+}++export function createEmptyConditionSet(flagType: FeatureFlagType, index: number): ConditionSetFormState {+ return {+ id: createRuleId(),+ name: index === 0 ? "Default" : `Condition ${index + 1}`,+ rules: [],+ rolloutPercentage: 100,+ variants: flagType === "multivariate" ? [createEmptyVariant(0), createEmptyVariant(1)] : [],+ payload: flagType === "remote_config" ? "{}" : "",+ };+}++export function createEmptyForm(): FlagFormState {+ return {+ key: "",+ description: "",+ enabled: true,+ runtime: "client",+ flagType: "boolean",+ conditionSets: [createEmptyConditionSet("boolean", 0)],+ };+}++export function formatFlagValue(value: unknown) {+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ if (value === null || value === undefined) return "";+ return JSON.stringify(value);+}++function formatPayloadValue(value: FeatureFlagPayloadValue | null | undefined) {+ if (value === undefined || value === null) return "";+ return JSON.stringify(value, null, 2);+}++export function getConditionSetPayload(+ flag: FeatureFlag,+ conditionSet: FeatureFlag["conditionSets"][number] | undefined+) {+ return conditionSet && conditionSet.payload !== undefined ? conditionSet.payload : flag.payload;+}++function parseOptionalPayload(value: string): FeatureFlagPayloadValue | undefined {+ const trimmed = value.trim();+ if (!trimmed) return undefined;+ return JSON.parse(trimmed) as FeatureFlagPayloadValue;+}++function parseRequiredPayload(value: string): FeatureFlagPayloadValue {+ const parsed = parseOptionalPayload(value);+ if (parsed === undefined) {+ throw new Error("Payload is required");+ }+ return parsed;+}++function formatRuleValue(value: FeatureFlagRule["value"]) {+ if (Array.isArray(value)) return JSON.stringify(value);+ return String(value);+}++function parseRuleValue(value: string): FeatureFlagRule["value"] {+ const trimmed = value.trim();+ if (trimmed.startsWith("[")) {+ const parsed = JSON.parse(trimmed);+ if (+ Array.isArray(parsed) &&+ parsed.every(item => typeof item === "string" || typeof item === "number" || typeof item === "boolean")+ ) {+ return parsed;+ }+ throw new Error("Rule arrays can only contain strings, numbers, or booleans");+ }+ return trimmed;+}++function toRuleFormState(rule: FeatureFlagRule): RuleFormState {+ return {+ id: createRuleId(),+ field: rule.field,+ key: rule.key || "",+ operator: rule.operator,+ value: formatRuleValue(rule.value),+ };+}++function toVariantFormState(variant: FeatureFlag["variants"][number]): VariantFormState {+ return {+ id: createRuleId(),+ key: variant.key,+ name: variant.name || "",+ rolloutPercentage: variant.rolloutPercentage,+ payload: formatPayloadValue(variant.payload),+ };+}++function toConditionSetFormState(+ conditionSet: FeatureFlag["conditionSets"][number],+ flagType: FeatureFlagType,+ index: number+): ConditionSetFormState {+ return {+ id: createRuleId(),+ name: conditionSet.name || (index === 0 ? "Default" : `Condition ${index + 1}`),+ rules: (conditionSet.rules || []).map(toRuleFormState),+ rolloutPercentage: conditionSet.rolloutPercentage ?? 100,+ variants:+ conditionSet.variants && conditionSet.variants.length > 0+ ? conditionSet.variants.map(toVariantFormState)+ : flagType === "multivariate"+ ? [createEmptyVariant(0), createEmptyVariant(1)]+ : [],+ payload: formatPayloadValue(conditionSet.payload),+ };+}++function fallbackConditionSetFromFlag(flag: FeatureFlag): ConditionSetFormState {+ return {+ id: createRuleId(),+ name: "Default",+ rules: (flag.rules || []).map(toRuleFormState),+ rolloutPercentage: flag.rolloutPercentage,+ variants: flag.flagType === "multivariate" ? (flag.variants || []).map(toVariantFormState) : [],+ payload: formatPayloadValue(flag.payload),+ };+}++export function toFormState(flag?: FeatureFlag): FlagFormState {+ if (!flag) return createEmptyForm();++ return {+ key: flag.key,+ description: flag.description || "",+ enabled: flag.enabled,+ runtime: flag.runtime,+ flagType: flag.flagType,+ conditionSets:+ flag.conditionSets && flag.conditionSets.length > 0+ ? flag.conditionSets.map((conditionSet, index) => toConditionSetFormState(conditionSet, flag.flagType, index))+ : [fallbackConditionSetFromFlag(flag)],+ };+}++export function buildPayload(form: FlagFormState): FeatureFlagPayload {+ const buildRules = (rules: RuleFormState[]) =>+ rules.map(rule => {+ const requiresKey = rule.field === "query" || rule.field === "trait";+ if (requiresKey && !rule.key.trim()) {+ throw new Error("Rule key is required");+ }+ if (!rule.value.trim()) {+ throw new Error("Rule value is required");+ }++ return {+ field: rule.field,+ key: requiresKey ? rule.key.trim() : undefined,+ operator: rule.operator,+ value: parseRuleValue(rule.value),+ };+ });++ const buildVariants = (variants: VariantFormState[]) =>+ variants.map(variant => ({+ key: variant.key.trim(),+ name: variant.name.trim() || undefined,+ rolloutPercentage: variant.rolloutPercentage,+ payload: parseOptionalPayload(variant.payload),+ }));++ const validateVariants = (variants: ReturnType<typeof buildVariants>) => {+ const variantKeys = new Set(variants.map(variant => variant.key));+ const variantRolloutTotal = variants.reduce((sum, variant) => sum + variant.rolloutPercentage, 0);++ if (variants.length < 2) {+ throw new Error("Multiple variant flags need at least two variants");+ }+ if (variants.some(variant => !variant.key)) {+ throw new Error("Variant key is required");+ }+ if (variantKeys.size !== variants.length) {+ throw new Error("Variant keys must be unique");+ }+ if (variantRolloutTotal > 100) {+ throw new Error("Variant rollout percentages cannot exceed 100");+ }+ };++ const conditionSets = form.conditionSets.map(conditionSet => {+ if (+ !Number.isInteger(conditionSet.rolloutPercentage) ||+ conditionSet.rolloutPercentage < 0 ||+ conditionSet.rolloutPercentage > 100+ ) {+ throw new Error("Rollout must be between 0 and 100");+ }++ const variants = form.flagType === "multivariate" ? buildVariants(conditionSet.variants) : [];+ if (form.flagType === "multivariate") {+ validateVariants(variants);+ }++ return {+ name: conditionSet.name.trim() || undefined,+ rules: buildRules(conditionSet.rules),+ rolloutPercentage: form.flagType === "boolean" ? conditionSet.rolloutPercentage : undefined,+ variants: form.flagType === "multivariate" ? variants : undefined,+ payload:+ form.flagType === "remote_config"+ ? parseRequiredPayload(conditionSet.payload)+ : parseOptionalPayload(conditionSet.payload),+ };+ });++ return {+ key: form.key.trim(),+ description: form.description.trim() || null,+ enabled: form.enabled,+ runtime: form.runtime,+ flagType: form.flagType,+ payload: null,+ variants: [],+ rolloutPercentage: 100,+ rules: [],+ conditionSets,+ };+}diff --git a/client/src/app/[site]/feature-flags/lib/labels.ts b/client/src/app/[site]/feature-flags/lib/labels.tsnew file mode 100644index 000000000..ff4d0b6df--- /dev/null+++ b/client/src/app/[site]/feature-flags/lib/labels.ts@@ -0,0 +1,100 @@+"use client";++import type { FeatureFlagRuntime, FeatureFlagType } from "@/api/analytics/endpoints";+import { useExtracted } from "next-intl";+import { useCallback } from "react";+import type { RuleField, RuleOperator } from "./types";++export function useFlagTypeLabel() {+ const t = useExtracted();++ return useCallback(+ (flagType: FeatureFlagType) => {+ switch (flagType) {+ case "boolean":+ return t("Boolean");+ case "multivariate":+ return t("Multiple variants");+ case "remote_config":+ return t("Remote config");+ }+ },+ [t]+ );+}++export function useRuntimeLabel() {+ const t = useExtracted();++ return useCallback(+ (runtime: FeatureFlagRuntime) => {+ switch (runtime) {+ case "client":+ return t("Client");+ case "server":+ return t("Server");+ case "both":+ return t("Both");+ }+ },+ [t]+ );+}++export function useRuleFieldLabel() {+ const t = useExtracted();++ return useCallback(+ (field: RuleField) => {+ switch (field) {+ case "hostname":+ return t("Hostname");+ case "pathname":+ return t("Pathname");+ case "query":+ return t("Query parameter");+ case "referrer":+ return t("Referrer");+ case "language":+ return t("Language");+ case "country":+ return t("Country");+ case "region":+ return t("Region");+ case "city":+ return t("City");+ case "device_type":+ return t("Device type");+ case "user_id":+ return t("User ID");+ case "trait":+ return t("User trait");+ }+ },+ [t]+ );+}++export function useRuleOperatorLabel() {+ const t = useExtracted();++ return useCallback(+ (operator: RuleOperator) => {+ switch (operator) {+ case "equals":+ return t("Equals");+ case "not_equals":+ return t("Does not equal");+ case "contains":+ return t("Contains");+ case "starts_with":+ return t("Starts with");+ case "ends_with":+ return t("Ends with");+ case "regex":+ return t("Regex");+ }+ },+ [t]+ );+}diff --git a/client/src/app/[site]/feature-flags/lib/types.ts b/client/src/app/[site]/feature-flags/lib/types.tsnew file mode 100644index 000000000..8b04ea024--- /dev/null+++ b/client/src/app/[site]/feature-flags/lib/types.ts@@ -0,0 +1,38 @@+import type { FeatureFlagRule, FeatureFlagRuntime, FeatureFlagType } from "@/api/analytics/endpoints";++export type FlagFormState = {+ key: string;+ description: string;+ enabled: boolean;+ runtime: FeatureFlagRuntime;+ flagType: FeatureFlagType;+ conditionSets: ConditionSetFormState[];+};++export type RuleField = FeatureFlagRule["field"];+export type RuleOperator = FeatureFlagRule["operator"];++export type RuleFormState = {+ id: string;+ field: RuleField;+ key: string;+ operator: RuleOperator;+ value: string;+};++export type VariantFormState = {+ id: string;+ key: string;+ name: string;+ rolloutPercentage: number;+ payload: string;+};++export type ConditionSetFormState = {+ id: string;+ name: string;+ rules: RuleFormState[];+ rolloutPercentage: number;+ variants: VariantFormState[];+ payload: string;+};diff --git a/client/src/app/[site]/feature-flags/page.tsx b/client/src/app/[site]/feature-flags/page.tsxnew file mode 100644index 000000000..1646c8112--- /dev/null+++ b/client/src/app/[site]/feature-flags/page.tsx@@ -0,0 +1,73 @@+"use client";++import { useFeatureFlags } from "@/api/analytics/hooks/featureFlags/useFeatureFlags";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { NothingFound } from "@/components/NothingFound";+import { useSetPageTitle } from "@/hooks/useSetPageTitle";+import { Flag, Plus } from "lucide-react";+import { useExtracted } from "next-intl";+import { useMemo, useState } from "react";+import { FeatureFlagDialog } from "./components/FeatureFlagDialog";+import { FeatureFlagSkeleton } from "./components/FeatureFlagSkeleton";+import { FeatureFlagTable } from "./components/FeatureFlagTable";++export default function FeatureFlagsPage() {+ const t = useExtracted();+ useSetPageTitle("Feature Flags");+ const { data: flags, isLoading } = useFeatureFlags();+ const [search, setSearch] = useState("");++ const filteredFlags = useMemo(() => {+ const query = search.trim().toLowerCase();+ if (!query) return flags || [];+ return (flags || []).filter(flag =>+ [flag.key, flag.description || ""].some(value => value.toLowerCase().includes(query))+ );+ }, [flags, search]);++ return (+ <div className="mx-auto max-w-[1400px] space-y-3 p-2 md:p-4">+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <Input+ className="w-full sm:w-64"+ isSearch+ placeholder={t("Filter feature flags")}+ value={search}+ onChange={event => setSearch(event.target.value)}+ />+ <FeatureFlagDialog+ trigger={+ <Button>+ <Plus className="h-4 w-4" />+ {t("New flag")}+ </Button>+ }+ />+ </div>++ {isLoading ? (+ <FeatureFlagSkeleton />+ ) : filteredFlags.length > 0 ? (+ <FeatureFlagTable flags={filteredFlags} />+ ) : flags?.length ? (+ <NothingFound icon={<Flag className="h-10 w-10" />} title={t("No feature flags found")} />+ ) : (+ <NothingFound+ icon={<Flag className="h-10 w-10" />}+ title={t("No feature flags yet")}+ action={+ <FeatureFlagDialog+ trigger={+ <Button>+ <Plus className="h-4 w-4" />+ {t("New flag")}+ </Button>+ }+ />+ }+ />+ )}+ </div>+ );+}diff --git a/client/src/lib/rybbit.d.ts b/client/src/lib/rybbit.d.tsindex 0c8e87552..a17198d21 100644--- a/client/src/lib/rybbit.d.ts+++ b/client/src/lib/rybbit.d.ts@@ -42,6 +42,39 @@ interface Rybbit {* @param target Optional target attribute of the link*/trackOutbound: (url: string, text?: string, target?: string) => void;++ /**+ * Evaluates a feature flag and returns its value. Reading a flag records a+ * feature flag exposure once per flag value/version.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flag: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns the payload for a feature flag or its selected variant.+ * Use this for remote config and multivariate payloads.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flagPayload: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns all evaluated flag values keyed by flag key+ */+ flags: () => Record<string, unknown>;++ /**+ * Returns all available flag payloads keyed by flag key+ */+ flagPayloads: () => Record<string, unknown>;++ /**+ * Runs a callback once the tracking script and feature flags are ready.+ * Use this before reading flags during page initialization.+ * @param callback Receives the ready rybbit instance+ */+ onReady: (callback: (rybbit: Rybbit) => void) => void;}declare global {diff --git a/client/src/lib/siteRoute.ts b/client/src/lib/siteRoute.tsindex dbd0b6fe0..ff041c3af 100644--- a/client/src/lib/siteRoute.ts+++ b/client/src/lib/siteRoute.ts@@ -13,6 +13,8 @@ export const SYNCED_ANALYTICS_ROUTES = new Set(["errors","pages","replay",+ "feature-flags",+ "experiments",]);export type SiteRouteContext = {diff --git a/docs/content/docs/api/sending-events.mdx b/docs/content/docs/api/sending-events.mdxindex 6d5c6e222..4f02479b3 100644--- a/docs/content/docs/api/sending-events.mdx+++ b/docs/content/docs/api/sending-events.mdx@@ -157,6 +157,11 @@ All parameters are sent in the request body as JSON.type: 'string',typeDescription: 'Max 2048 chars (4096 for error events)',},+ feature_flags: {+ description: 'Optional map of feature flag keys to assigned values. Useful for server-side flag evaluation and filtering analytics by flag value.',+ type: 'Record<string, string>',+ typeDescription: 'Keys max 100 chars, values max 2048 chars',+ },}}/>diff --git a/docs/content/docs/experiments.mdx b/docs/content/docs/experiments.mdxnew file mode 100644index 000000000..8cd11dfb6--- /dev/null+++ b/docs/content/docs/experiments.mdx@@ -0,0 +1,173 @@+---+title: Experiments+description: Run A/B tests on feature flag variants and measure conversion lift+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { Step, Steps } from 'fumadocs-ui/components/steps';++Experiments are A/B tests built on top of Rybbit. Each experiment splits your visitors across the variants of a [multivariate feature flag](/docs/feature-flags), then measures how often each variant completes a [conversion goal](/docs/goals). Rybbit calculates the conversion rate for every variant, the **lift** relative to your control, and how confident you can be that the difference is real.++<Callout type="info">+An experiment ties together two features you may already use: a **multivariate feature flag** decides which variant each visitor sees, and a **goal** defines the conversion you are optimizing for. If you understand those two pieces, you understand experiments.+</Callout>++## How Experiments Work++An experiment has three moving parts:++| Part | What it does |+| --- | --- |+| **Assignment** | A multivariate feature flag assigns each visitor to one stable variant (for example `control` or `variant_a`) based on its rollout percentages. |+| **Exposure** | When your code reads the flag with `rybbit.flag()`, Rybbit records an exposure for that variant. Exposures are the denominator for each variant's conversion rate. |+| **Conversion** | The experiment's primary goal — a page visit or a custom event — counts as a conversion for whichever variant the visitor was assigned. |++Because assignment is sticky for a given visitor, a person sees the same variant on repeat visits, which keeps your results consistent.++## Creating an Experiment++Open your site in the Rybbit dashboard, go to **Experiments**, and click **New experiment**. A guided wizard walks you through each step.++<Steps>+<Step>+### Basics++Give the experiment a **name** and, optionally, a **hypothesis** and **description**. The hypothesis is internal context for your team — something like *"Changing the CTA copy will increase signups."* It does not affect assignment or tracking.++New experiments are created as **drafts** so you can add the implementation code before any traffic is split.+</Step>++<Step>+### Assignment++Choose how visitors are split into variants:++- **Create a new flag** — Define a new multivariate flag with its own variants and rollout split. Each variant needs a unique key, and the rollout percentages must add up to **100%**.+- **Use an existing flag** — Pick a multivariate flag that is not already attached to another experiment.++<Callout type="info">+Each experiment uses its own multivariate flag. The flag's variant keys (such as `control` and `variant_a`) are what you branch on in code.+</Callout>+</Step>++<Step>+### Goal++Pick the conversion you want to compare variants against:++- **Create a new goal** — Define a **page goal** (a URL path such as `/signup/complete`) or an **event goal** (a custom event such as `signup_completed`). The form provides autocomplete suggestions based on paths and events already seen on your site.+- **Use an existing goal** — Connect a goal you already track.+- **Skip for now** — Create the experiment without a goal and add one later. Conversion results require a goal.+</Step>++<Step>+### Review and Implement++Review the assignment flag and goal, then create the experiment. Rybbit creates any new flag or goal you configured, connects them, and shows you the **implementation code** for the flag. The experiment stays in **draft** until you start it from the experiment list.+</Step>+</Steps>++## Implementing in Code++Read the experiment's flag in your app and branch your UI or behavior on the returned variant. Reading the flag also records the exposure that powers your results, so make sure it runs wherever the tested experience is shown.++<Tabs items={['JavaScript', 'TypeScript']}>+<Tab value="JavaScript">+```javascript+window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag("checkout_cta", "control");++ if (variant === "variant_a") {+ // Render the variant experience.+ } else {+ // Render the control experience.+ }+});+```+</Tab>+<Tab value="TypeScript">+```typescript+type ExperimentVariant = "control" | "variant_a";++window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag("checkout_cta", "control") as ExperimentVariant;++ switch (variant) {+ case "variant_a":+ // Render the variant experience.+ break;+ default:+ // Render the control experience.+ break;+ }+});+```+</Tab>+</Tabs>++If your primary goal is an **event goal**, fire that event when the conversion action happens:++```javascript+window.rybbit.onReady((rybbit) => {+ rybbit.event("signup_completed");+});+```++**Page goals** need no extra code — Rybbit counts sessions that reach the goal's path automatically.++<Callout type="info">+Use a stable variant for the `rybbit.flag()` fallback (usually `"control"`) so visitors still get a sensible experience before the flag resolves or if the experiment is paused.+</Callout>++## Reading Results++Each experiment shows a results panel comparing every variant. Results respect the global date range and filters applied on the page.++| Metric | Description |+| --- | --- |+| **Variant** | The variant key, with the **Control** marked as the baseline. |+| **Sessions** | Sessions exposed to that variant, alongside the number that converted. |+| **Conversion rate** | Conversions divided by exposures for that variant. |+| **Lift** | The percentage change in conversion rate relative to the control. Positive lift is shown in green, negative in red. |+| **Confidence** | How confident Rybbit is that the variant's difference from the control is real, based on a two-proportion comparison. |++Rybbit summarizes the state of each experiment at a glance:++- **Gathering data** — Not enough exposures or conversions yet to draw a conclusion.+- **Leading** — A variant is outperforming the control with at least **95% confidence**.+- **Winner** — The variant recorded as the winner once the experiment is decided.++<Callout type="warn">+Avoid stopping an experiment the moment a variant looks ahead. Let it run until it reaches 95% confidence with a meaningful number of conversions, otherwise early noise can masquerade as a real difference.+</Callout>++## Experiment Lifecycle++Experiments move through four statuses, which you control from the experiment list:++| Status | Meaning |+| --- | --- |+| **Draft** | Created but not yet collecting results. Add your implementation code here. |+| **Running** | Actively splitting traffic and recording exposures and conversions. |+| **Paused** | Temporarily stopped. Visitors keep their existing assignments. |+| **Completed** | Finished. Use this once you have a result and have shipped (or rolled back) the change. |++Use **Start**, **Pause**, and **Complete** on each experiment to move between states.++## Best Practices++- Change one thing at a time so you can attribute any lift to a single difference.+- Make sure your variant rollout percentages add up to 100% unless you intentionally want unassigned traffic.+- Read the flag wherever the tested experience renders so every exposed visitor is counted.+- Pick a primary goal that directly reflects the outcome you care about, not a proxy metric.+- Wait for 95% confidence and a healthy sample size before declaring a winner.+- After completing an experiment, ship the winning variant and remove the flag branch to keep your code clean.++---++**Related Documentation:**+- [Feature Flags](/docs/feature-flags) — The assignment mechanism behind experiments+- [Goals](/docs/goals) — Define the conversion an experiment measures+- [Track Events](/docs/track-events) — Fire custom events for event goals+- [Tracking Script](/docs/script) — Load the script and use `onReady()`diff --git a/docs/content/docs/feature-flags.mdx b/docs/content/docs/feature-flags.mdxnew file mode 100644index 000000000..b0c2c32d0--- /dev/null+++ b/docs/content/docs/feature-flags.mdx@@ -0,0 +1,363 @@+---+title: Feature Flags+description: Roll out features, serve remote config, and target variants in Rybbit+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';+import { TypeTable } from 'fumadocs-ui/components/type-table';++Feature flags let you change product behavior without deploying new code. In Rybbit, a flag can be evaluated in the browser, on your server, or in both places. Flag assignments are also attached to analytics events so you can filter and compare behavior by flag value.++<Callout type="info">+Feature flags are different from [tags](/docs/tagging). Tags label traffic that you already routed yourself. Feature flags decide which value a visitor receives at runtime.+</Callout>++## Create a Flag++1. Open your site in the Rybbit dashboard.+2. Go to **Feature Flags**.+3. Click **New flag**.+4. Choose a stable **key**, such as `new_checkout` or `pricing_banner`.+5. Select the flag type, runtime, and targeting conditions.+6. Enable the flag when you are ready for it to evaluate as active.++The **key** is the public identifier used in code. Treat it as the flag name and avoid changing it after the flag is in use.++## Flag Types++| Type | Returns | Best for |+| --- | --- | --- |+| **Boolean** | `true` or `false` | Releasing a feature on/off, gradual rollouts, allowlists |+| **Multiple variants** | A variant key like `"control"` or `"variant_a"` | Comparing more than one experience or configuration |+| **Remote config** | `true` plus a payload from `flagPayload()` | Shipping structured config such as copy, colors, limits, or JSON settings |++### Boolean Flags++Boolean flags support a rollout percentage for each condition set. If the visitor matches the condition set and falls inside the rollout bucket, `window.rybbit.flag()` returns `true`.++```javascript+window.rybbit.onReady((rybbit) => {+ const enabled = rybbit.flag("new_checkout", false);++ if (enabled) {+ showNewCheckout();+ }+});+```++### Multiple Variants++Multiple variant flags return the selected variant key. Each variant has its own rollout percentage and optional payload.++```javascript+window.rybbit.onReady((rybbit) => {+ const variant = rybbit.flag("homepage_cta", "control");++ if (variant === "variant_a") {+ renderAlternateCTA();+ }+});+```++Variant rollout percentages are evaluated in order. If the visitor falls outside the total allocated percentage, the flag returns `false`.++### Remote Config++Remote config flags are useful when you want Rybbit to choose a JSON payload. For remote config, `flag()` returns whether a config matched, and `flagPayload()` returns the actual config.++```javascript+window.rybbit.onReady((rybbit) => {+ const config = rybbit.flagPayload("checkout_config", {+ buttonText: "Continue",+ theme: "default",+ });++ renderCheckout(config);+});+```++Remote config can still use targeting. This lets you serve one config to beta users, another config to a country, and a default config to everyone else.++## Runtime++Each flag has a runtime:++| Runtime | Evaluated by | Use when |+| --- | --- | --- |+| **Client** | The browser tracking script | UI changes, frontend copy, client-only experiments |+| **Server** | Your backend through the API | Backend behavior, pricing logic, data access, anything private |+| **Both** | Browser and server | Both sides need the same decision |++<Callout type="warn">+Do not put secrets in client or both-runtime flag payloads. Browser-evaluated flags and payloads are visible to the user.+</Callout>++## Targeting and Condition Sets++Flags use ordered condition sets. Each set contains targeting rules plus the rollout, variants, or payload for users who match that set.++Evaluation works like this:++1. Rybbit checks condition sets from top to bottom.+2. The first condition set whose rules all match is selected.+3. Rybbit applies the rollout, variant allocation, or remote config payload from that selected set.+4. Later condition sets are not evaluated.++This means condition set order matters. Put narrow segments first and broad defaults last.++<Callout type="warn">+If a visitor matches a boolean condition set but falls outside that set's rollout percentage, Rybbit returns `false` and does not continue to later condition sets.+</Callout>++### Targeting Fields++| Field | Description |+| --- | --- |+| Hostname | Current hostname, such as `example.com` |+| Pathname | Current path, such as `/pricing` |+| Query parameter | A specific URL query parameter |+| Referrer | The document referrer |+| Language | Browser language, such as `en-US` |+| Country | Visitor country resolved from IP |+| Region | Visitor region resolved from IP |+| City | Visitor city resolved from IP |+| Device type | Device category derived from user agent and screen size |+| User ID | The identified user ID, falling back to the anonymous visitor ID |+| User trait | A trait set through `identify()` or `setTraits()` |++### Operators++Targeting rules support:++- `equals`+- `not_equals`+- `contains`+- `starts_with`+- `ends_with`+- `regex`++All rules in a condition set must match. Multiple condition sets act as ordered alternatives.++## Browser Runtime++The tracking script automatically evaluates client and both-runtime flags when it loads. It sends context such as anonymous visitor ID, identified user ID, URL, referrer, language, screen size, IP-derived location, and saved user traits.++Use `onReady()` before reading flags if you need the evaluated value during page initialization:++```javascript+window.rybbit.onReady((rybbit) => {+ const enabled = rybbit.flag("new_checkout", false);+ const payload = rybbit.flagPayload("new_checkout", {});+});+```++Available browser methods:++<TypeTable+ type={{+ "flag(key, fallback)": {+ description: "Returns a single flag value. Reading a flag also records a feature flag exposure event once per flag value/version.",+ type: "function",+ },+ "flagPayload(key, fallback)": {+ description: "Returns the payload for a flag or variant. Use this for remote config and multivariate payloads.",+ type: "function",+ },+ "flags()": {+ description: "Returns all evaluated flag values keyed by flag key.",+ type: "function",+ },+ "flagPayloads()": {+ description: "Returns all available flag payloads keyed by flag key.",+ type: "function",+ },+ }}+/>++Assignments are included on analytics events as a feature flag map. This lets you filter dashboard reports by flag key and value.++### Identify and Traits++If you call `identify()` or `setTraits()`, the browser runtime refreshes feature flags using the updated user context.++```javascript+window.rybbit.identify("user_123", {+ plan: "pro",+ beta: true,+});+```++You can then target flags using **User ID** or **User trait** rules.++## Server Runtime++Use server runtime for decisions that should not happen in the browser. The server endpoint returns server and both-runtime flags only.++```+POST /api/sites/:siteId/feature-flags/evaluate+```++### Request++<TypeTable+ type={{+ anonymousId: {+ description: "Stable anonymous visitor ID used for rollout bucketing. Keep this stable for sticky assignments.",+ type: "string",+ required: true,+ },+ identifiedUserId: {+ description: "Logged-in user ID. Enables user ID rules and loads saved user traits.",+ type: "string",+ },+ hostname: {+ description: "Hostname used by hostname targeting rules.",+ type: "string",+ },+ pathname: {+ description: "Path used by pathname targeting rules.",+ type: "string",+ },+ query: {+ description: "Parsed query parameter object used by query targeting rules.",+ type: "Record<string, string>",+ },+ querystring: {+ description: "Raw query string. Used if query is not provided.",+ type: "string",+ },+ referrer: {+ description: "Referrer used by referrer targeting rules.",+ type: "string",+ },+ language: {+ description: "Language code used by language targeting rules.",+ type: "string",+ },+ screenWidth: {+ description: "Screen width used with user agent parsing to derive device type.",+ type: "number",+ },+ screenHeight: {+ description: "Screen height used with user agent parsing to derive device type.",+ type: "number",+ },+ }}+/>++<Tabs items={['cURL', 'JavaScript']}>+ <Tab value="cURL">+```bash+curl -X POST "https://app.rybbit.io/api/sites/123/feature-flags/evaluate" \+ -H "Authorization: Bearer rb_your_api_key_here" \+ -H "Content-Type: application/json" \+ -d '{+ "anonymousId": "visitor_abc",+ "identifiedUserId": "user_123",+ "hostname": "example.com",+ "pathname": "/checkout",+ "query": { "plan": "pro" },+ "language": "en-US",+ "screenWidth": 1440,+ "screenHeight": 900+ }'+```+ </Tab>+ <Tab value="JavaScript">+```javascript+const response = await fetch(+ "https://app.rybbit.io/api/sites/123/feature-flags/evaluate",+ {+ method: "POST",+ headers: {+ Authorization: "Bearer rb_your_api_key_here",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonymousId: "visitor_abc",+ identifiedUserId: "user_123",+ hostname: "example.com",+ pathname: "/checkout",+ query: { plan: "pro" },+ language: "en-US",+ screenWidth: 1440,+ screenHeight: 900,+ }),+ }+);++const data = await response.json();+const newCheckout = data.flags.new_checkout?.value === true;+```+ </Tab>+</Tabs>++### Response++```json+{+ "flags": {+ "new_checkout": {+ "key": "new_checkout",+ "value": true,+ "flagType": "boolean",+ "payload": { "copy": "Try it now" },+ "conditionSet": "Default",+ "version": 3,+ "reason": "rollout",+ "matched": true,+ "rolloutPercentage": 100+ }+ },+ "generatedAt": "2026-05-27T12:00:00.000Z"+}+```++Assignment fields:++| Field | Description |+| --- | --- |+| `value` | The evaluated flag value. Boolean flags return `true` or `false`; multiple variant flags return a variant key or `false`; remote config returns `true` when matched. |+| `payload` | Optional payload from the selected condition set or selected variant. |+| `variant` | Selected variant key for multiple variant flags. |+| `conditionSet` | Name of the condition set that matched. |+| `reason` | Why the assignment was produced, such as `rollout`, `variant`, `remote_config`, `fallthrough`, `target_mismatch`, or `disabled`. |+| `matched` | Whether the flag produced an active match. |+| `rolloutPercentage` | The rollout percentage that was evaluated. |+| `version` | Flag version. Increments when the flag is edited. |++## Analytics and Filtering++Feature flag assignments are stored on events. Browser-tracked events include evaluated client flags automatically. Server-side events can include a `feature_flags` object in the [HTTP API](/docs/api/sending-events) payload:++```json+{+ "site_id": "123",+ "type": "custom_event",+ "event_name": "purchase",+ "pathname": "/checkout",+ "feature_flags": {+ "new_checkout": "true",+ "homepage_cta": "variant_a"+ }+}+```++Use feature flag filters in the dashboard to compare behavior between flag values.++## Best Practices++- Keep flag keys stable and descriptive, such as `new_checkout` or `pricing_page_copy`.+- Use **Client** runtime only for values that are safe to expose in the browser.+- Use **Server** runtime for permission checks, pricing logic, and private backend behavior.+- Put specific condition sets before broad default condition sets.+- Keep remote config payloads small and JSON-serializable.+- Use a stable `anonymousId` for server-side evaluation so rollout assignments remain sticky.+- Remove stale flags after rollout is complete to keep your dashboard and codebase clean.++**Related Documentation:**+- [Tracking Script](/docs/script)+- [Identify Users](/docs/identify-users)+- [Tagging](/docs/tagging)+- [API - Sending Events](/docs/api/sending-events)diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex 8a1bc1956..da451651f 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -12,6 +12,7 @@"autocapture","identify-users","tagging",+ "feature-flags","guides","proxy-guide","sdks",@@ -21,6 +22,7 @@"bot-detection","goals","funnels",+ "experiments","embeds","feature-guides","---Self-hosting---",diff --git a/docs/content/docs/script.mdx b/docs/content/docs/script.mdxindex 9e8ca401d..fb23cfd0c 100644--- a/docs/content/docs/script.mdx+++ b/docs/content/docs/script.mdx@@ -44,6 +44,28 @@ These are the attributes you can pass to the script tag.| `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). |+### Feature Flags++The tracking script automatically evaluates client and both-runtime feature flags when it loads. Read evaluated flags from `window.rybbit` after the script is ready:++```javascript+window.rybbit.onReady((rybbit) => {+ const enabled = rybbit.flag("new_checkout", false);+ const config = rybbit.flagPayload("checkout_config", {});+});+```++Available methods:++| Method | Description |+| --- | --- |+| `flag(key, fallback)` | Returns a boolean, variant key, or fallback value. Also records a feature flag exposure once per flag value/version. |+| `flagPayload(key, fallback)` | Returns the payload for a flag, variant, or remote config. |+| `flags()` | Returns all evaluated flag values. |+| `flagPayloads()` | Returns all available flag payloads. |++See [Feature Flags](/docs/feature-flags) for targeting rules, remote config, and server-side evaluation.+### Session Replay AttributesThese attributes configure rrweb session replay behavior. They only apply when session replay is enabled in your site settings.diff --git a/docs/content/docs/tagging.mdx b/docs/content/docs/tagging.mdxindex 5487308a0..8940dd032 100644--- a/docs/content/docs/tagging.mdx+++ b/docs/content/docs/tagging.mdx@@ -5,6 +5,8 @@ description: How to use tags to label and segment analytics data in RybbitTags 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.+If you need Rybbit to choose a value at runtime, gradually roll out a feature, or serve remote config, use [Feature Flags](/docs/feature-flags) instead.+## How It WorksAdd 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.diff --git a/docs/content/docs/track-events.mdx b/docs/content/docs/track-events.mdxindex 05bfb0e11..8001a83fb 100644--- a/docs/content/docs/track-events.mdx+++ b/docs/content/docs/track-events.mdx@@ -104,6 +104,39 @@ interface Rybbit {* @param target Optional target attribute of the link*/trackOutbound: (url: string, text?: string, target?: string) => void;++ /**+ * Evaluates a feature flag and returns its value. Reading a flag records a+ * feature flag exposure once per flag value/version.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flag: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns the payload for a feature flag or its selected variant.+ * Use this for remote config and multivariate payloads.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flagPayload: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns all evaluated flag values keyed by flag key+ */+ flags: () => Record<string, unknown>;++ /**+ * Returns all available flag payloads keyed by flag key+ */+ flagPayloads: () => Record<string, unknown>;++ /**+ * Runs a callback once the tracking script and feature flags are ready.+ * Use this before reading flags during page initialization.+ * @param callback Receives the ready rybbit instance+ */+ onReady: (callback: (rybbit: Rybbit) => void) => void;}declare global {diff --git a/docs/src/components/rybbit.d.ts b/docs/src/components/rybbit.d.tsindex 0c8e87552..a17198d21 100644--- a/docs/src/components/rybbit.d.ts+++ b/docs/src/components/rybbit.d.ts@@ -42,6 +42,39 @@ interface Rybbit {* @param target Optional target attribute of the link*/trackOutbound: (url: string, text?: string, target?: string) => void;++ /**+ * Evaluates a feature flag and returns its value. Reading a flag records a+ * feature flag exposure once per flag value/version.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flag: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns the payload for a feature flag or its selected variant.+ * Use this for remote config and multivariate payloads.+ * @param key The flag key+ * @param fallback Value returned before flags resolve or if the flag is inactive+ */+ flagPayload: <T = unknown>(key: string, fallback?: T) => T;++ /**+ * Returns all evaluated flag values keyed by flag key+ */+ flags: () => Record<string, unknown>;++ /**+ * Returns all available flag payloads keyed by flag key+ */+ flagPayloads: () => Record<string, unknown>;++ /**+ * Runs a callback once the tracking script and feature flags are ready.+ * Use this before reading flags during page initialization.+ * @param callback Receives the ready rybbit instance+ */+ onReady: (callback: (rybbit: Rybbit) => void) => void;}declare global {diff --git a/server/drizzle/0006_orange_thunderbird.sql b/server/drizzle/0006_orange_thunderbird.sqlnew file mode 100644index 000000000..09e87c153--- /dev/null+++ b/server/drizzle/0006_orange_thunderbird.sql@@ -0,0 +1,77 @@+CREATE TABLE IF NOT EXISTS "experiments" (+ "experiment_id" serial PRIMARY KEY NOT NULL,+ "site_id" integer NOT NULL,+ "feature_flag_id" integer NOT NULL,+ "primary_goal_id" integer,+ "name" text NOT NULL,+ "description" text,+ "hypothesis" text,+ "status" text DEFAULT 'draft' NOT NULL,+ "winning_variant" text,+ "started_at" timestamp,+ "ended_at" timestamp,+ "created_at" timestamp DEFAULT now() NOT NULL,+ "updated_at" timestamp DEFAULT now() NOT NULL,+ CONSTRAINT "experiments_site_flag_unique" UNIQUE("site_id","feature_flag_id"),+ CONSTRAINT "experiments_status_check" CHECK (status IN ('draft', 'running', 'paused', 'completed'))+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "feature_flags" (+ "flag_id" serial PRIMARY KEY NOT NULL,+ "site_id" integer NOT NULL,+ "key" text NOT NULL,+ "description" text,+ "enabled" boolean DEFAULT false NOT NULL,+ "runtime" text DEFAULT 'client' NOT NULL,+ "flag_type" text DEFAULT 'boolean' NOT NULL,+ "payload" jsonb,+ "variants" jsonb DEFAULT '[]'::jsonb NOT NULL,+ "rollout_percentage" integer DEFAULT 100 NOT NULL,+ "rules" jsonb DEFAULT '[]'::jsonb NOT NULL,+ "condition_sets" jsonb DEFAULT '[]'::jsonb NOT NULL,+ "salt" text DEFAULT md5(random()::text || clock_timestamp()::text) NOT NULL,+ "version" integer DEFAULT 1 NOT NULL,+ "created_at" timestamp DEFAULT now() NOT NULL,+ "updated_at" timestamp DEFAULT now() NOT NULL,+ CONSTRAINT "feature_flags_site_key_unique" UNIQUE("site_id","key"),+ CONSTRAINT "feature_flags_rollout_check" CHECK (rollout_percentage >= 0 AND rollout_percentage <= 100),+ CONSTRAINT "feature_flags_runtime_check" CHECK (runtime IN ('client', 'server', 'both')),+ CONSTRAINT "feature_flags_type_check" CHECK (flag_type IN ('boolean', 'multivariate', 'remote_config'))+);+--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.table_constraints+ WHERE constraint_name = 'experiments_site_id_sites_site_id_fk'+ ) THEN+ ALTER TABLE "experiments" ADD CONSTRAINT "experiments_site_id_sites_site_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("site_id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.table_constraints+ WHERE constraint_name = 'experiments_feature_flag_id_feature_flags_flag_id_fk'+ ) THEN+ ALTER TABLE "experiments" ADD CONSTRAINT "experiments_feature_flag_id_feature_flags_flag_id_fk" FOREIGN KEY ("feature_flag_id") REFERENCES "public"."feature_flags"("flag_id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.table_constraints+ WHERE constraint_name = 'experiments_primary_goal_id_goals_goal_id_fk'+ ) THEN+ ALTER TABLE "experiments" ADD CONSTRAINT "experiments_primary_goal_id_goals_goal_id_fk" FOREIGN KEY ("primary_goal_id") REFERENCES "public"."goals"("goal_id") ON DELETE set null ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.table_constraints+ WHERE constraint_name = 'feature_flags_site_id_sites_site_id_fk'+ ) THEN+ ALTER TABLE "feature_flags" ADD CONSTRAINT "feature_flags_site_id_sites_site_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("site_id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "experiments_site_idx" ON "experiments" USING btree ("site_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "experiments_feature_flag_idx" ON "experiments" USING btree ("feature_flag_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "experiments_primary_goal_idx" ON "experiments" USING btree ("primary_goal_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "feature_flags_site_idx" ON "feature_flags" USING btree ("site_id");diff --git a/server/drizzle/meta/0006_snapshot.json b/server/drizzle/meta/0006_snapshot.jsonnew file mode 100644index 000000000..efd5d4771--- /dev/null+++ b/server/drizzle/meta/0006_snapshot.json@@ -0,0 +1,3255 @@+{+ "id": "662aeef8-8f3e-4c11-becb-a2cef1b972ef",+ "prevId": "2f7fdcb4-ca39-48b2-965a-bb095d262fa6",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "accountId": {+ "name": "accountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "providerId": {+ "name": "providerId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idToken": {+ "name": "idToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_userId_user_id_fk": {+ "name": "account_userId_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.active_sessions": {+ "name": "active_sessions",+ "schema": "",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "last_activity": {+ "name": "last_activity",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_regions": {+ "name": "agent_regions",+ "schema": "",+ "columns": {+ "code": {+ "name": "code",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_url": {+ "name": "endpoint_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "last_health_check": {+ "name": "last_health_check",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "is_healthy": {+ "name": "is_healthy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "referenceId": {+ "name": "referenceId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refillInterval": {+ "name": "refillInterval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refillAmount": {+ "name": "refillAmount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRefillAt": {+ "name": "lastRefillAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "rateLimitEnabled": {+ "name": "rateLimitEnabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "rateLimitTimeWindow": {+ "name": "rateLimitTimeWindow",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "rateLimitMax": {+ "name": "rateLimitMax",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "requestCount": {+ "name": "requestCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRequest": {+ "name": "lastRequest",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "configId": {+ "name": "configId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "apikey_referenceId_user_id_fk": {+ "name": "apikey_referenceId_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": [+ "referenceId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cancellation_feedback": {+ "name": "cancellation_feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason_details": {+ "name": "reason_details",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_shown": {+ "name": "retention_offer_shown",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_accepted": {+ "name": "retention_offer_accepted",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "plan_name_at_cancellation": {+ "name": "plan_name_at_cancellation",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_event_count_at_cancellation": {+ "name": "monthly_event_count_at_cancellation",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.experiments": {+ "name": "experiments",+ "schema": "",+ "columns": {+ "experiment_id": {+ "name": "experiment_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "feature_flag_id": {+ "name": "feature_flag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "primary_goal_id": {+ "name": "primary_goal_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "hypothesis": {+ "name": "hypothesis",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "winning_variant": {+ "name": "winning_variant",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "experiments_site_idx": {+ "name": "experiments_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_feature_flag_idx": {+ "name": "experiments_feature_flag_idx",+ "columns": [+ {+ "expression": "feature_flag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_primary_goal_idx": {+ "name": "experiments_primary_goal_idx",+ "columns": [+ {+ "expression": "primary_goal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "experiments_site_id_sites_site_id_fk": {+ "name": "experiments_site_id_sites_site_id_fk",+ "tableFrom": "experiments",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",+ "tableFrom": "experiments",+ "tableTo": "feature_flags",+ "columnsFrom": [+ "feature_flag_id"+ ],+ "columnsTo": [+ "flag_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_primary_goal_id_goals_goal_id_fk": {+ "name": "experiments_primary_goal_id_goals_goal_id_fk",+ "tableFrom": "experiments",+ "tableTo": "goals",+ "columnsFrom": [+ "primary_goal_id"+ ],+ "columnsTo": [+ "goal_id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "experiments_site_flag_unique": {+ "name": "experiments_site_flag_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "feature_flag_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "experiments_status_check": {+ "name": "experiments_status_check",+ "value": "status IN ('draft', 'running', 'paused', 'completed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.feature_flags": {+ "name": "feature_flags",+ "schema": "",+ "columns": {+ "flag_id": {+ "name": "flag_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "runtime": {+ "name": "runtime",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'client'"+ },+ "flag_type": {+ "name": "flag_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'boolean'"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "variants": {+ "name": "variants",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "rollout_percentage": {+ "name": "rollout_percentage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "rules": {+ "name": "rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "condition_sets": {+ "name": "condition_sets",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "salt": {+ "name": "salt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "md5(random()::text || clock_timestamp()::text)"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feature_flags_site_idx": {+ "name": "feature_flags_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "feature_flags_site_id_sites_site_id_fk": {+ "name": "feature_flags_site_id_sites_site_id_fk",+ "tableFrom": "feature_flags",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "feature_flags_site_key_unique": {+ "name": "feature_flags_site_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "feature_flags_rollout_check": {+ "name": "feature_flags_rollout_check",+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"+ },+ "feature_flags_runtime_check": {+ "name": "feature_flags_runtime_check",+ "value": "runtime IN ('client', 'server', 'both')"+ },+ "feature_flags_type_check": {+ "name": "feature_flags_type_check",+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"+ }+ },+ "isRLSEnabled": false+ },+ "public.funnels": {+ "name": "funnels",+ "schema": "",+ "columns": {+ "report_id": {+ "name": "report_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "data": {+ "name": "data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "funnels_site_id_sites_site_id_fk": {+ "name": "funnels_site_id_sites_site_id_fk",+ "tableFrom": "funnels",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "funnels_user_id_user_id_fk": {+ "name": "funnels_user_id_user_id_fk",+ "tableFrom": "funnels",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.goals": {+ "name": "goals",+ "schema": "",+ "columns": {+ "goal_id": {+ "name": "goal_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_type": {+ "name": "goal_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "goals_site_id_sites_site_id_fk": {+ "name": "goals_site_id_sites_site_id_fk",+ "tableFrom": "goals",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_property_url": {+ "name": "gsc_property_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "gsc_connections_site_id_sites_site_id_fk": {+ "name": "gsc_connections_site_id_sites_site_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_status": {+ "name": "import_status",+ "schema": "",+ "columns": {+ "import_id": {+ "name": "import_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "platform": {+ "name": "platform",+ "type": "import_platform_enum",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": true+ },+ "imported_events": {+ "name": "imported_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "skipped_events": {+ "name": "skipped_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "invalid_events": {+ "name": "invalid_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "import_status_site_id_sites_site_id_fk": {+ "name": "import_status_site_id_sites_site_id_fk",+ "tableFrom": "import_status",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "import_status_organization_id_organization_id_fk": {+ "name": "import_status_organization_id_organization_id_fk",+ "tableFrom": "import_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "inviterId": {+ "name": "inviterId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "site_ids": {+ "name": "site_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "invitation_inviterId_user_id_fk": {+ "name": "invitation_inviterId_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviterId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "invitation_organizationId_organization_id_fk": {+ "name": "invitation_organizationId_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "invitation_teamId_team_id_fk": {+ "name": "invitation_teamId_team_id_fk",+ "tableFrom": "invitation",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "member_organizationId_organization_id_fk": {+ "name": "member_organizationId_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "member_userId_user_id_fk": {+ "name": "member_userId_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member_site_access": {+ "name": "member_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "member_id": {+ "name": "member_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "member_site_access_member_idx": {+ "name": "member_site_access_member_idx",+ "columns": [+ {+ "expression": "member_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_site_access_site_idx": {+ "name": "member_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_site_access_member_id_member_id_fk": {+ "name": "member_site_access_member_id_member_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "member",+ "columnsFrom": [+ "member_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_site_id_sites_site_id_fk": {+ "name": "member_site_access_site_id_sites_site_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_created_by_user_id_fk": {+ "name": "member_site_access_created_by_user_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "member_site_access_unique": {+ "name": "member_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "member_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification_channels": {+ "name": "notification_channels",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_ids": {+ "name": "monitor_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_events": {+ "name": "trigger_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[\"down\",\"recovery\"]'::jsonb"+ },+ "cooldown_minutes": {+ "name": "cooldown_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 5+ },+ "last_notified_at": {+ "name": "last_notified_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_channels_organization_id_organization_id_fk": {+ "name": "notification_channels_organization_id_organization_id_fk",+ "tableFrom": "notification_channels",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "notification_channels_created_by_user_id_fk": {+ "name": "notification_channels_created_by_user_id_fk",+ "tableFrom": "notification_channels",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "approachingLimitNotifiedPeriodStart": {+ "name": "approachingLimitNotifiedPeriodStart",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "planOverride": {+ "name": "planOverride",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "custom_plan": {+ "name": "custom_plan",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ipAddress": {+ "name": "ipAddress",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userAgent": {+ "name": "userAgent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "impersonatedBy": {+ "name": "impersonatedBy",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeOrganizationId": {+ "name": "activeOrganizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeTeamId": {+ "name": "activeTeamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_userId_user_id_fk": {+ "name": "session_userId_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sites": {+ "name": "sites",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "site_id": {+ "name": "site_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "embed_enabled": {+ "name": "embed_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "saltUserIds": {+ "name": "saltUserIds",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "blockBots": {+ "name": "blockBots",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "excluded_ips": {+ "name": "excluded_ips",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_countries": {+ "name": "excluded_countries",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "sessionReplay": {+ "name": "sessionReplay",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "webVitals": {+ "name": "webVitals",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackErrors": {+ "name": "trackErrors",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackOutbound": {+ "name": "trackOutbound",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackUrlParams": {+ "name": "trackUrlParams",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackInitialPageView": {+ "name": "trackInitialPageView",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackSpaNavigation": {+ "name": "trackSpaNavigation",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackIp": {+ "name": "trackIp",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackButtonClicks": {+ "name": "trackButtonClicks",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackCopy": {+ "name": "trackCopy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackFormInteractions": {+ "name": "trackFormInteractions",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "api_key": {+ "name": "api_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "private_link_key": {+ "name": "private_link_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tags": {+ "name": "tags",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "sites_created_by_user_id_fk": {+ "name": "sites_created_by_user_id_fk",+ "tableFrom": "sites",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "sites_organization_id_organization_id_fk": {+ "name": "sites_organization_id_organization_id_fk",+ "tableFrom": "sites",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "team_organizationId_organization_id_fk": {+ "name": "team_organizationId_organization_id_fk",+ "tableFrom": "team",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.teamMember": {+ "name": "teamMember",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "teamMember_teamId_team_id_fk": {+ "name": "teamMember_teamId_team_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "teamMember_userId_user_id_fk": {+ "name": "teamMember_userId_user_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_site_access": {+ "name": "team_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_site_access_team_idx": {+ "name": "team_site_access_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_site_access_site_idx": {+ "name": "team_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_site_access_team_id_team_id_fk": {+ "name": "team_site_access_team_id_team_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_site_access_site_id_sites_site_id_fk": {+ "name": "team_site_access_site_id_sites_site_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_site_access_unique": {+ "name": "team_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry": {+ "name": "telemetry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "instance_id": {+ "name": "instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "timestamp": {+ "name": "timestamp",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "table_counts": {+ "name": "table_counts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "clickhouse_size_gb": {+ "name": "clickhouse_size_gb",+ "type": "real",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_alert_history": {+ "name": "uptime_alert_history",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "alert_id": {+ "name": "alert_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "triggered_at": {+ "name": "triggered_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "alert_data": {+ "name": "alert_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_alert_history_alert_id_uptime_alerts_id_fk": {+ "name": "uptime_alert_history_alert_id_uptime_alerts_id_fk",+ "tableFrom": "uptime_alert_history",+ "tableTo": "uptime_alerts",+ "columnsFrom": [+ "alert_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_alert_history_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_alert_history_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_alert_history",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_alerts": {+ "name": "uptime_alerts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "alert_type": {+ "name": "alert_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "alert_config": {+ "name": "alert_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "conditions": {+ "name": "conditions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_alerts_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_alerts_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_alerts",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_incidents": {+ "name": "uptime_incidents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_type": {+ "name": "last_error_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failure_count": {+ "name": "failure_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_incidents_organization_id_organization_id_fk": {+ "name": "uptime_incidents_organization_id_organization_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_incidents_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_incidents_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "uptime_incidents_acknowledged_by_user_id_fk": {+ "name": "uptime_incidents_acknowledged_by_user_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "uptime_incidents_resolved_by_user_id_fk": {+ "name": "uptime_incidents_resolved_by_user_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_monitor_status": {+ "name": "uptime_monitor_status",+ "schema": "",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "current_status": {+ "name": "current_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'unknown'"+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "consecutive_successes": {+ "name": "consecutive_successes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "uptime_percentage_24h": {+ "name": "uptime_percentage_24h",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "uptime_percentage_7d": {+ "name": "uptime_percentage_7d",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "uptime_percentage_30d": {+ "name": "uptime_percentage_30d",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "average_response_time_24h": {+ "name": "average_response_time_24h",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {+ "uptime_monitor_status_updated_at_idx": {+ "name": "uptime_monitor_status_updated_at_idx",+ "columns": [+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "uptime_monitor_status_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_monitor_status",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "uptime_monitor_status_current_status_check": {+ "name": "uptime_monitor_status_current_status_check",+ "value": "current_status IN ('up', 'down', 'unknown')"+ },+ "uptime_monitor_status_uptime_24h_check": {+ "name": "uptime_monitor_status_uptime_24h_check",+ "value": "uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100"+ },+ "uptime_monitor_status_uptime_7d_check": {+ "name": "uptime_monitor_status_uptime_7d_check",+ "value": "uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100"+ },+ "uptime_monitor_status_uptime_30d_check": {+ "name": "uptime_monitor_status_uptime_30d_check",+ "value": "uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100"+ }+ },+ "isRLSEnabled": false+ },+ "public.uptime_monitors": {+ "name": "uptime_monitors",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_type": {+ "name": "monitor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "interval_seconds": {+ "name": "interval_seconds",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "http_config": {+ "name": "http_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "tcp_config": {+ "name": "tcp_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "validation_rules": {+ "name": "validation_rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "monitoring_type": {+ "name": "monitoring_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'local'"+ },+ "selected_regions": {+ "name": "selected_regions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[\"local\"]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_monitors_organization_id_organization_id_fk": {+ "name": "uptime_monitors_organization_id_organization_id_fk",+ "tableFrom": "uptime_monitors",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_monitors_created_by_user_id_fk": {+ "name": "uptime_monitors_created_by_user_id_fk",+ "tableFrom": "uptime_monitors",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "displayUsername": {+ "name": "displayUsername",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "banReason": {+ "name": "banReason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banExpires": {+ "name": "banExpires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "sendAutoEmailReports": {+ "name": "sendAutoEmailReports",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "scheduled_tip_email_ids": {+ "name": "scheduled_tip_email_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ },+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_aliases": {+ "name": "user_aliases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "anonymous_id": {+ "name": "anonymous_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_aliases_user_idx": {+ "name": "user_aliases_user_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_aliases_anon_idx": {+ "name": "user_aliases_anon_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "anonymous_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_aliases_site_id_sites_site_id_fk": {+ "name": "user_aliases_site_id_sites_site_id_fk",+ "tableFrom": "user_aliases",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_aliases_site_anon_unique": {+ "name": "user_aliases_site_anon_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "anonymous_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_profiles": {+ "name": "user_profiles",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "traits": {+ "name": "traits",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_profiles_site_idx": {+ "name": "user_profiles_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_profiles_site_id_sites_site_id_fk": {+ "name": "user_profiles_site_id_sites_site_id_fk",+ "tableFrom": "user_profiles",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "user_profiles_site_id_user_id_pk": {+ "name": "user_profiles_site_id_user_id_pk",+ "columns": [+ "site_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {+ "public.import_platform_enum": {+ "name": "import_platform_enum",+ "schema": "public",+ "values": [+ "umami",+ "simple_analytics",+ "plausible"+ ]+ }+ },+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.jsonindex 4a4ffe02a..05679b82e 100644--- a/server/drizzle/meta/_journal.json+++ b/server/drizzle/meta/_journal.json@@ -43,6 +43,13 @@"when": 1778551960948,"tag": "0005_sticky_gressill","breakpoints": true+ },+ {+ "idx": 6,+ "version": "7",+ "when": 1779981165610,+ "tag": "0006_orange_thunderbird",+ "breakpoints": true}]}\ No newline at end of filediff --git a/server/package-lock.json b/server/package-lock.jsonindex 8f881dad6..0b48ac3bb 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -42,6 +42,7 @@"react-dom": "19.2.1","resend": "^4.5.1","rrweb": "^2.0.0-alpha.20",+ "safe-regex2": "^5.0.0","sqlstring": "2.3.3","stripe": "18.1.0","twilio": "^5.8.0",diff --git a/server/package.json b/server/package.jsonindex ba2b749f3..75d2be589 100644--- a/server/package.json+++ b/server/package.json@@ -61,6 +61,7 @@"react-dom": "19.2.1","resend": "^4.5.1","rrweb": "^2.0.0-alpha.20",+ "safe-regex2": "^5.0.0","sqlstring": "2.3.3","stripe": "18.1.0","twilio": "^5.8.0",diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 7501b7b88..f14be96cc 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -67,6 +67,71 @@}// config.ts+ function createVisitorId() {+ try {+ if (crypto?.randomUUID) {+ return crypto.randomUUID();+ }+ } catch (e2) {+ }+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;+ }+ function getOrCreateVisitorId(namespace) {+ const key = `${namespace}-visitor-id`;+ try {+ const stored = localStorage.getItem(key);+ if (stored) return stored;+ const visitorId = createVisitorId();+ localStorage.setItem(key, visitorId);+ return visitorId;+ } catch (e2) {+ return createVisitorId();+ }+ }+ function getIdentifiedUserId(namespace) {+ try {+ return localStorage.getItem(`${namespace}-user-id`) || void 0;+ } catch (e2) {+ return void 0;+ }+ }+ function getEvaluationPathname(url) {+ if (url.hash && url.hash.startsWith("#/")) {+ return url.hash.substring(1);+ }+ return url.pathname;+ }+ async function fetchFeatureFlags(analyticsHost, siteId, namespace, visitorId) {+ try {+ const url = new URL(window.location.href);+ const response = await fetch(`${analyticsHost}/site/${siteId}/feature-flags/evaluate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json"+ },+ credentials: "omit",+ body: JSON.stringify({+ anonymousId: visitorId,+ identifiedUserId: getIdentifiedUserId(namespace),+ hostname: url.hostname,+ pathname: getEvaluationPathname(url),+ querystring: url.search,+ query: Object.fromEntries(url.searchParams.entries()),+ referrer: document.referrer,+ language: navigator.language,+ screenWidth: screen.width,+ screenHeight: screen.height+ })+ });+ if (!response.ok) {+ return {};+ }+ const data = await response.json();+ return data?.flags && typeof data.flags === "object" ? data.flags : {};+ } catch (e2) {+ return {};+ }+ }async function parseScriptConfig(scriptTag) {const src = scriptTag.getAttribute("src");if (!src) {@@ -84,6 +149,7 @@return null;}const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";+ const visitorId = getOrCreateVisitorId(namespace);const skipPatterns = parseJsonSafely(scriptTag.getAttribute("data-skip-patterns"), []);const maskPatterns = parseJsonSafely(scriptTag.getAttribute("data-mask-patterns"), []);const sessionReplayMaskTextSelectors = parseJsonSafely(@@ -115,6 +181,7 @@namespace,analyticsHost,siteId,+ visitorId,debounceDuration,sessionReplayBatchSize,sessionReplayBatchInterval,@@ -133,6 +200,7 @@trackCopy: false,trackFormInteractions: false,tag,+ featureFlags: {},// rrweb session replay options (undefined means use rrweb defaults)sessionReplayBlockClass,sessionReplayBlockSelector,@@ -146,6 +214,7 @@sessionReplaySlimDOMOptions,sessionReplaySampleRate};+ let resolvedConfig = defaultConfig;try {const configUrl = `${analyticsHost}/site/tracking-config/${siteId}`;const response = await fetch(configUrl, {@@ -155,7 +224,7 @@});if (response.ok) {const apiConfig = await response.json();- return {+ resolvedConfig = {...defaultConfig,// Map API field names to script config field namesautoTrackPageview: apiConfig.trackInitialPageView ?? defaultConfig.autoTrackPageview,@@ -171,12 +240,12 @@};} else {console.warn("Failed to fetch tracking config from API, using defaults");- return defaultConfig;}} catch (error) {console.warn("Error fetching tracking config:", error);- return defaultConfig;}+ resolvedConfig.featureFlags = await fetchFeatureFlags(analyticsHost, siteId, namespace, visitorId);+ return resolvedConfig;}// sessionReplay.ts@@ -472,15 +541,26 @@const canvas = document.createElement("canvas");const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");if (gl) {- const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");- if (debugInfo) {- const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);- if (typeof renderer === "string" && renderer.includes("SwiftShader")) {- addSignal(CLIENT_BOT_SIGNAL_MASKS.swiftShader, 1);+ const rendererParts = [];+ const rendererRaw = gl.getParameter(gl.RENDERER);+ if (typeof rendererRaw === "string") {+ rendererParts.push(rendererRaw);+ }+ try {+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");+ if (debugInfo) {+ const unmaskedRaw = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);+ if (typeof unmaskedRaw === "string") {+ rendererParts.push(unmaskedRaw);+ }}+ } catch {+ }+ if (rendererParts.join(" ").toLowerCase().includes("swiftshader")) {+ addSignal(CLIENT_BOT_SIGNAL_MASKS.swiftShader, 1);}}- } catch (e2) {+ } catch {}if ((!navigator.plugins || navigator.plugins.length === 0) && isChromeLike) {addSignal(CLIENT_BOT_SIGNAL_MASKS.emptyPlugins, 1);@@ -503,12 +583,66 @@this.customUserId = null;this.errorDedupeCache = /* @__PURE__ */ new Map();this.errorDedupeLastCleanup = 0;+ this.exposedFeatureFlags = /* @__PURE__ */ new Set();this.config = config;this.loadUserId();if (config.enableSessionReplay) {this.initializeSessionReplay();}}+ serializeFeatureFlagValue(value) {+ if (value === null || value === void 0) return "";+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ try {+ return JSON.stringify(value);+ } catch (e2) {+ return "";+ }+ }+ getFeatureFlagEventPayload() {+ const payload = {};+ for (const [key, assignment] of Object.entries(this.config.featureFlags || {})) {+ payload[key] = this.serializeFeatureFlagValue(assignment.value);+ }+ return payload;+ }+ getCurrentUrlContext() {+ const url = new URL(window.location.href);+ const pathname = url.hash && url.hash.startsWith("#/") ? url.hash.substring(1) : url.pathname;+ return {+ hostname: url.hostname,+ pathname,+ querystring: url.search,+ query: Object.fromEntries(url.searchParams.entries()),+ referrer: document.referrer,+ language: navigator.language,+ screenWidth: screen.width,+ screenHeight: screen.height+ };+ }+ async refreshFeatureFlags() {+ try {+ const response = await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json"+ },+ body: JSON.stringify({+ anonymousId: this.config.visitorId,+ identifiedUserId: this.customUserId || void 0,+ ...this.getCurrentUrlContext()+ }),+ mode: "cors",+ credentials: "omit",+ keepalive: true+ });+ if (!response.ok) return;+ const data = await response.json();+ this.config.featureFlags = data?.flags && typeof data.flags === "object" ? data.flags : {};+ } catch (e2) {+ }+ }loadUserId() {try {const storedUserId = localStorage.getItem(`${this.config.namespace}-user-id`);@@ -579,6 +713,10 @@if (this.config.tag) {payload.tag = this.config.tag;}+ const featureFlagPayload = this.getFeatureFlagEventPayload();+ if (Object.keys(featureFlagPayload).length > 0) {+ payload.feature_flags = featureFlagPayload;+ }return payload;}async sendTrackingData(payload) {@@ -605,7 +743,15 @@if (!basePayload) {return;}- const typesWithProperties = ["custom_event", "outbound", "error", "button_click", "copy", "form_submit", "input_change"];+ const typesWithProperties = [+ "custom_event",+ "outbound",+ "error",+ "button_click",+ "copy",+ "form_submit",+ "input_change"+ ];const payload = {...basePayload,type: eventType,@@ -620,6 +766,40 @@trackEvent(name, properties = {}) {this.track("custom_event", name, properties);}+ getFeatureFlag(key, fallback) {+ const assignment = this.config.featureFlags?.[key];+ if (!assignment) {+ return fallback;+ }+ const exposureKey = `${key}:${assignment.version}:${this.serializeFeatureFlagValue(assignment.value)}`;+ if (!this.exposedFeatureFlags.has(exposureKey)) {+ this.exposedFeatureFlags.add(exposureKey);+ this.trackEvent("feature_flag_exposure", {+ key,+ value: this.serializeFeatureFlagValue(assignment.value),+ version: assignment.version,+ reason: assignment.reason+ });+ }+ return assignment.value;+ }+ getFeatureFlags() {+ return Object.fromEntries(+ Object.entries(this.config.featureFlags || {}).map(([key, assignment]) => [key, assignment.value])+ );+ }+ getFeatureFlagPayload(key, fallback) {+ const assignment = this.config.featureFlags?.[key];+ if (!assignment || assignment.payload === void 0) {+ return fallback;+ }+ return assignment.payload;+ }+ getFeatureFlagPayloads() {+ return Object.fromEntries(+ Object.entries(this.config.featureFlags || {}).filter(([, assignment]) => assignment.payload !== void 0).map(([key, assignment]) => [key, assignment.payload])+ );+ }trackOutbound(url, text = "", target = "_self") {this.track("outbound", "", { url, text, target });}@@ -732,7 +912,7 @@} catch (e2) {console.warn("Could not persist user ID to localStorage");}- this.sendIdentifyEvent(this.customUserId, traits, true);+ void this.sendIdentifyEvent(this.customUserId, traits, true).then(() => this.refreshFeatureFlags());if (this.sessionReplayRecorder) {this.sessionReplayRecorder.updateUserId(this.customUserId);}@@ -747,7 +927,7 @@console.warn("Cannot set traits without identifying user first. Call identify() first.");return;}- this.sendIdentifyEvent(userId, traits, false);+ void this.sendIdentifyEvent(userId, traits, false).then(() => this.refreshFeatureFlags());}async sendIdentifyEvent(userId, traits, isNewIdentify = true) {try {@@ -775,6 +955,7 @@localStorage.removeItem(`${this.config.namespace}-user-id`);} catch (e2) {}+ void this.refreshFeatureFlags();}getUserId() {return this.customUserId;@@ -797,6 +978,7 @@}// Handle page changes for SPAonPageChange() {+ void this.refreshFeatureFlags();if (this.sessionReplayRecorder) {this.sessionReplayRecorder.onPageChange();}@@ -1310,6 +1492,12 @@clearUserId: () => {},getUserId: () => null,+ flag: (_key, fallback) => fallback,+ flagPayload: (_key, fallback) => fallback,+ flags: () => ({}),+ flagPayloads: () => ({}),+ onReady: () => {+ },startSessionReplay: () => {},stopSessionReplay: () => {@@ -1331,6 +1519,11 @@setTraits: queueMethod("setTraits"),clearUserId: queueMethod("clearUserId"),getUserId: () => null,+ flag: (_key, fallback) => fallback,+ flagPayload: (_key, fallback) => fallback,+ flags: () => ({}),+ flagPayloads: () => ({}),+ onReady: queueMethod("onReady"),startSessionReplay: queueMethod("startSessionReplay"),stopSessionReplay: queueMethod("stopSessionReplay"),isSessionReplayActive: () => false@@ -1437,6 +1630,11 @@setTraits: (traits) => tracker.setTraits(traits),clearUserId: () => tracker.clearUserId(),getUserId: () => tracker.getUserId(),+ flag: (key, fallback) => tracker.getFeatureFlag(key, fallback),+ flagPayload: (key, fallback) => tracker.getFeatureFlagPayload(key, fallback),+ flags: () => tracker.getFeatureFlags(),+ flagPayloads: () => tracker.getFeatureFlagPayloads(),+ onReady: (callback) => callback(window[config.namespace]),startSessionReplay: () => tracker.startSessionReplay(),stopSessionReplay: () => tracker.stopSessionReplay(),isSessionReplayActive: () => tracker.isSessionReplayActive()diff --git a/server/public/script.js b/server/public/script.jsindex 905957653..e7d1a1869 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var Ne=Object.defineProperty;var Oe=(n,e,t)=>e in n?Ne(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>Oe(n,typeof e!="symbol"?e+"":e,t);function De(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 o=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+o+"$")}function W(n,e){for(let t of e)try{if(De(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function oe(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 E(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 ce(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=E(n.getAttribute("data-skip-patterns"),[]),o=E(n.getAttribute("data-mask-patterns"),[]),l=E(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,g=n.getAttribute("data-replay-block-class")||void 0,C=n.getAttribute("data-replay-block-selector")||void 0,f=n.getAttribute("data-replay-ignore-class")||void 0,a=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"),S=p!==null?p!=="false":void 0,w=n.getAttribute("data-replay-mask-input-options"),U=w?E(w,{password:!0,email:!0}):void 0,te=n.getAttribute("data-replay-collect-fonts"),_e=te!==null?te!=="false":void 0,re=n.getAttribute("data-replay-sampling"),Me=re?E(re,{}):void 0,ne=n.getAttribute("data-replay-slim-dom-options"),Le=ne?E(ne,{}):void 0,ie=n.getAttribute("data-replay-sample-rate"),Be=ie?Math.min(100,Math.max(0,parseInt(ie,10))):void 0,xe=n.getAttribute("data-tag")||"",m={namespace:i,analyticsHost:t,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:l,skipPatterns:s,maskPatterns:o,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:xe,sessionReplayBlockClass:g,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:f,sessionReplayIgnoreSelector:a,sessionReplayMaskTextClass:c,sessionReplayMaskAllInputs:S,sessionReplayMaskInputOptions:U,sessionReplayCollectFonts:_e,sessionReplaySampling:Me,sessionReplaySlimDOMOptions:Le,sessionReplaySampleRate:Be};try{let F=`${t}/site/tracking-config/${r}`,se=await fetch(F,{method:"GET",credentials:"omit"});if(se.ok){let b=await se.json();return{...m,autoTrackPageview:b.trackInitialPageView??m.autoTrackPageview,autoTrackSpa:b.trackSpaNavigation??m.autoTrackSpa,trackQuerystring:b.trackUrlParams??m.trackQuerystring,trackOutbound:b.trackOutbound??m.trackOutbound,enableWebVitals:b.webVitals??m.enableWebVitals,trackErrors:b.trackErrors??m.trackErrors,enableSessionReplay:b.sessionReplay??m.enableSessionReplay,trackButtonClicks:b.trackButtonClicks??m.trackButtonClicks,trackCopy:b.trackCopy??m.trackCopy,trackFormInteractions:b.trackFormInteractions??m.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),m}catch(F){return console.warn("Error fetching tracking config:",F),m}}var le="rybbit-replay-sampled";function He(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(le);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(le,t?"1":"0"),t}catch{return Math.random()*100<n}}var _=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&&!He(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 y={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512},ue=null,Ue=10;function de(){return he().score}function pe(){return he().mask}function he(){return ue??(ue=Fe()),ue}function Fe(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),o=Number(window.screen?.width),l=Number(window.screen?.height),d=Number(window.outerWidth),u=Number(window.outerHeight),h=Number(window.innerWidth),g=Number(window.innerHeight),f=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||f)&&t(y.automationApi,3),(u===0||d===0)&&t(y.zeroOuterDimensions,2),(!Number.isFinite(o)||!Number.isFinite(l)||o<=0||l<=0||o>1e5||l>1e5)&&t(y.impossibleDimensions,3),s&&o===800&&l===600&&t(y.defaultViewport800x600,3),s&&o===1024&&l===768&&t(y.defaultViewport1024x768,3),Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(h)&&Number.isFinite(g)&&d>0&&u>0&&h>0&&g>0&&(d+8<h||u+8<g)&&t(y.outerDimensionsWeird,2);let a=!1;!window.chrome&&i&&(t(y.missingChrome,1),a=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p){let S=p.getExtension("WEBGL_debug_renderer_info");if(S){let w=p.getParameter(S.UNMASKED_RENDERER_WEBGL);typeof w=="string"&&w.includes("SwiftShader")&&t(y.swiftShader,1)}}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(y.emptyPlugins,1),a=!0),a&&t(y.pluginApiAbsence,0)}catch{}return{score:Math.min(n,Ue),mask:e}}var M=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 _(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)),W(t,this.config.skipPatterns))return null;let r=W(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,_bs:de(),_bsm:pe()};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 o={...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(o)}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||"",o=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(o&&!o.includes(i))return;let d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),h=6e4,g=this.errorDedupeCache.get(d);if(g&&u-g<h)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>h){for(let[a,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(a);this.errorDedupeLastCleanup=u}let f={message:e.message?.substring(0,500)||"Unknown error",stack:o.substring(0,2e3)||""};if(s&&(f.fileName=s),t.lineno){let a=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;a&&a!==0&&(f.lineNumber=a)}if(t.colno){let a=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;a&&a!==0&&(f.columnNumber=a)}for(let a in t)!["lineno","colno"].includes(a)&&t[a]!==void 0&&(f[a]=t[a]);this.track("error",e.name||"Error",f)}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 Re=-1,P=n=>{addEventListener("pageshow",(e=>{e.persisted&&(Re=e.timeStamp,n(e))}),!0)},v=(n,e,t,r)=>{let i,s;return o=>{e.value>=0&&(o||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)))}},q=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Q=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},I=()=>Q()?.activationStart??0,k=(n,e=-1)=>{let t=Q(),r="navigate";return Re>=0?r="back-forward-cache":t&&(document.prerendering||I()>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}},z=new WeakMap;function Y(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var $=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},A=(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{}},Z=n=>{let e=!1;return()=>{e||(n(),e=!0)}},T=-1,Se=new Set,ge=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,G=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Se)e();isFinite(T)||(T=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",G,!0))}},B=()=>{if(T<0){let n=I();T=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??ge(),addEventListener("visibilitychange",G,!0),addEventListener("prerenderingchange",G,!0),P((()=>{setTimeout((()=>{T=ge()}))}))}return{get firstHiddenTime(){return T},onHidden(n){Se.add(n)}}},x=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},me=[1800,3e3],ee=(n,e={})=>{x((()=>{let t=B(),r,i=k("FCP"),s=A("paint",(o=>{for(let l of o)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-I(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,me,e.reportAllChanges),P((o=>{i=k("FCP"),r=v(n,i,me,e.reportAllChanges),q((()=>{i.value=performance.now()-o.timeStamp,r(!0)}))})))}))},fe=[.1,.25],Ee=(n,e={})=>{let t=B();ee(Z((()=>{let r,i=k("CLS",0),s=Y(e,$),o=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=A("layout-shift",o);l&&(r=v(n,i,fe,e.reportAllChanges),t.onHidden((()=>{o(l.takeRecords()),r(!0)})),P((()=>{s.i=0,i=k("CLS",0),r=v(n,i,fe,e.reportAllChanges),q((()=>r()))})),setTimeout(r))})))},Ce=0,V=1/0,L=0,We=n=>{for(let e of n)e.interactionId&&(V=Math.min(V,e.interactionId),L=Math.max(L,e.interactionId),Ce=L?(L-V)/7+1:0)},K,be=()=>K?Ce:performance.interactionCount??0,ze=()=>{"interactionCount"in performance||K||(K=A("event",We,{type:"event",buffered:!0,durationThreshold:0}))},ye=0,j=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){ye=be(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((be()-ye)/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)}}},Te=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=Z(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},ve=[200,500],Pe=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();x((()=>{ze();let r,i=k("INP"),s=Y(e,j),o=d=>{Te((()=>{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=A("event",o,{durationThreshold:e.durationThreshold??40});r=v(n,i,ve,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{o(l.takeRecords()),r(!0)})),P((()=>{s.v(),i=k("INP"),r=v(n,i,ve,e.reportAllChanges)})))}))},J=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},ke=[2500,4e3],Ie=(n,e={})=>{x((()=>{let t=B(),r,i=k("LCP"),s=Y(e,J),o=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-I(),0),i.entries=[u],r())},l=A("largest-contentful-paint",o);if(l){r=v(n,i,ke,e.reportAllChanges);let d=Z((()=>{o(l.takeRecords()),l.disconnect(),r(!0)})),u=h=>{h.isTrusted&&(Te(d),removeEventListener(h.type,u,{capture:!0}))};for(let h of["keydown","click","visibilitychange"])addEventListener(h,u,{capture:!0});P((h=>{i=k("LCP"),r=v(n,i,ke,e.reportAllChanges),q((()=>{i.value=performance.now()-h.timeStamp,r(!0)}))}))}}))},we=[800,1800],X=n=>{document.prerendering?x((()=>X(n))):document.readyState!=="complete"?addEventListener("load",(()=>X(n)),!0):setTimeout(n)},Ae=(n,e={})=>{let t=k("TTFB"),r=v(n,t,we,e.reportAllChanges);X((()=>{let i=Q();i&&(t.value=Math.max(i.responseStart-I(),0),t.entries=[i],r(!0),P((()=>{t=k("TTFB",0),r=v(n,t,we,e.reportAllChanges),r(!0)})))}))};var N=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{Ie(this.collectMetric.bind(this)),Ee(this.collectMetric.bind(this)),Pe(this.collectMetric.bind(this)),ee(this.collectMetric.bind(this)),Ae(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 O=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 D=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 o={text:t.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(o)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var H=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 o=t.type?.toLowerCase();if(o==="hidden"||o==="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=a=>(...c)=>{r.push([a,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 ce(n);if(!s)return;let o=new M(s);s.enableWebVitals&&new N(c=>{o.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new O(o,s),l.initialize()),s.trackCopy&&(d=new D(o),d.initialize()),s.trackFormInteractions&&(u=new H(o,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",a=>{o.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let c=a.reason instanceof Error?a.reason:new Error(String(a.reason));o.trackError(c,{type:"unhandledrejection"})}));let h=()=>o.trackPageview(),g=s.debounceDuration>0?oe(h,s.debounceDuration):h;function C(){if(document.addEventListener("click",function(a){let c=a.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let S={};for(let w of c.attributes)if(w.name.startsWith("data-rybbit-prop-")){let U=w.name.replace("data-rybbit-prop-","");S[U]=w.value}o.trackEvent(p,S)}break}c=c.parentElement}if(s.trackOutbound){let p=a.target.closest("a");p?.href&&ae(p.href)&&o.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let a=history.pushState,c=history.replaceState;history.pushState=function(...p){a.apply(this,p),g(),o.onPageChange()},history.replaceState=function(...p){c.apply(this,p),g(),o.onPageChange()},window.addEventListener("popstate",()=>{g(),o.onPageChange()}),window.addEventListener("hashchange",()=>{g(),o.onPageChange()})}}window[s.namespace]={pageview:()=>o.trackPageview(),event:(a,c={})=>o.trackEvent(a,c),error:(a,c={})=>o.trackError(a,c),trackOutbound:(a,c="",p="_self")=>o.trackOutbound(a,c,p),identify:(a,c)=>o.identify(a,c),setTraits:a=>o.setTraits(a),clearUserId:()=>o.clearUserId(),getUserId:()=>o.getUserId(),startSessionReplay:()=>o.startSessionReplay(),stopSessionReplay:()=>o.stopSessionReplay(),isSessionReplayActive:()=>o.isSessionReplayActive()};let f=window[s.namespace];for(let[a,c]of r)f[a](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),o.cleanup()}),s.autoTrackPageview&&o.trackPageview()})();})();+"use strict";(()=>{var De=Object.defineProperty;var Ue=(n,e,t)=>e in n?De(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>Ue(n,typeof e!="symbol"?e+"":e,t);function He(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 $(n,e){for(let t of e)try{if(He(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ce(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function le(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function E(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}}function ue(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function We(n){let e=`${n}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let r=ue();return localStorage.setItem(e,r),r}catch{return ue()}}function Ve(n){try{return localStorage.getItem(`${n}-user-id`)||void 0}catch{return}}function $e(n){return n.hash&&n.hash.startsWith("#/")?n.hash.substring(1):n.pathname}async function ze(n,e,t,r){try{let i=new URL(window.location.href),s=await fetch(`${n}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({anonymousId:r,identifiedUserId:Ve(t),hostname:i.hostname,pathname:$e(i),querystring:i.search,query:Object.fromEntries(i.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!s.ok)return{};let a=await s.json();return a?.flags&&typeof a.flags=="object"?a.flags:{}}catch{return{}}}async function de(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=We(i),a=E(n.getAttribute("data-skip-patterns"),[]),l=E(n.getAttribute("data-mask-patterns"),[]),d=E(n.getAttribute("data-replay-mask-text-selectors"),[]),u=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,g=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,C=n.getAttribute("data-replay-block-class")||void 0,m=n.getAttribute("data-replay-block-selector")||void 0,o=n.getAttribute("data-replay-ignore-class")||void 0,c=n.getAttribute("data-replay-ignore-selector")||void 0,p=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),S=w!==null?w!=="false":void 0,T=n.getAttribute("data-replay-mask-input-options"),F=T?E(T,{password:!0,email:!0}):void 0,ne=n.getAttribute("data-replay-collect-fonts"),Le=ne!==null?ne!=="false":void 0,ie=n.getAttribute("data-replay-sampling"),Be=ie?E(ie,{}):void 0,se=n.getAttribute("data-replay-slim-dom-options"),xe=se?E(se,{}):void 0,ae=n.getAttribute("data-replay-sample-rate"),Oe=ae?Math.min(100,Math.max(0,parseInt(ae,10))):void 0,Ne=n.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:r,visitorId:s,debounceDuration:u,sessionReplayBatchSize:g,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:d,skipPatterns:a,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Ne,featureFlags:{},sessionReplayBlockClass:C,sessionReplayBlockSelector:m,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:c,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:S,sessionReplayMaskInputOptions:F,sessionReplayCollectFonts:Le,sessionReplaySampling:Be,sessionReplaySlimDOMOptions:xe,sessionReplaySampleRate:Oe},W=f;try{let V=`${t}/site/tracking-config/${r}`,oe=await fetch(V,{method:"GET",credentials:"omit"});if(oe.ok){let y=await oe.json();W={...f,autoTrackPageview:y.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:y.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:y.trackUrlParams??f.trackQuerystring,trackOutbound:y.trackOutbound??f.trackOutbound,enableWebVitals:y.webVitals??f.enableWebVitals,trackErrors:y.trackErrors??f.trackErrors,enableSessionReplay:y.sessionReplay??f.enableSessionReplay,trackButtonClicks:y.trackButtonClicks??f.trackButtonClicks,trackCopy:y.trackCopy??f.trackCopy,trackFormInteractions:y.trackFormInteractions??f.trackFormInteractions}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(V){console.warn("Error fetching tracking config:",V)}return W.featureFlags=await ze(t,r,i,s),W}var pe="rybbit-replay-sampled";function je(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(pe);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(pe,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&&!je(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 b={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512},ge=null,Ge=10;function he(){return me().score}function fe(){return me().mask}function me(){return ge??(ge=Ke()),ge}function Ke(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),a=Number(window.screen?.width),l=Number(window.screen?.height),d=Number(window.outerWidth),u=Number(window.outerHeight),g=Number(window.innerWidth),h=Number(window.innerHeight),m=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||m)&&t(b.automationApi,3),(u===0||d===0)&&t(b.zeroOuterDimensions,2),(!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0||a>1e5||l>1e5)&&t(b.impossibleDimensions,3),s&&a===800&&l===600&&t(b.defaultViewport800x600,3),s&&a===1024&&l===768&&t(b.defaultViewport1024x768,3),Number.isFinite(d)&&Number.isFinite(u)&&Number.isFinite(g)&&Number.isFinite(h)&&d>0&&u>0&&g>0&&h>0&&(d+8<g||u+8<h)&&t(b.outerDimensionsWeird,2);let o=!1;!window.chrome&&i&&(t(b.missingChrome,1),o=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p){let w=[],S=p.getParameter(p.RENDERER);typeof S=="string"&&w.push(S);try{let T=p.getExtension("WEBGL_debug_renderer_info");if(T){let F=p.getParameter(T.UNMASKED_RENDERER_WEBGL);typeof F=="string"&&w.push(F)}}catch{}w.join(" ").toLowerCase().includes("swiftshader")&&t(b.swiftShader,1)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(b.emptyPlugins,1),o=!0),o&&t(b.pluginApiAbsence,0)}catch{}return{score:Math.min(n,Ge),mask:e}}var L=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}getFeatureFlagEventPayload(){let e={};for(let[t,r]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(r.value);return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=e.hash&&e.hash.startsWith("#/")?e.hash.substring(1):e.pathname;return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){try{let e=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0});if(!e.ok)return;let t=await e.json();this.config.featureFlags=t?.flags&&typeof t.flags=="object"?t.flags:{}}catch{}}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)),$(t,this.config.skipPatterns))return null;let r=$(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,_bs:he(),_bsm:fe()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),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)}getFeatureFlag(e,t){let r=this.config.featureFlags?.[e];if(!r)return t;let i=`${e}:${r.version}:${this.serializeFeatureFlagValue(r.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(r.value),version:r.version,reason:r.reason})),r.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let r=this.config.featureFlags?.[e];return!r||r.payload===void 0?t:r.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}trackOutbound(e,t="",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(),g=6e4,h=this.errorDedupeCache.get(d);if(h&&u-h<g)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>g){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let m={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(m.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(m.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(m.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(m[o]=t[o]);this.track("error",e.name||"Error",m)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}identify(e,t){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0).then(()=>this.refreshFeatureFlags()),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let t=this.customUserId;if(!t){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(t,e,!1).then(()=>this.refreshFeatureFlags())}async sendIdentifyEvent(e,t,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{}this.refreshFeatureFlags()}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Ee=-1,I=n=>{addEventListener("pageshow",(e=>{e.persisted&&(Ee=e.timeStamp,n(e))}),!0)},v=(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)))}},Y=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Z=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},_=()=>Z()?.activationStart??0,k=(n,e=-1)=>{let t=Z(),r="navigate";return Ee>=0?r="back-forward-cache":t&&(document.prerendering||_()>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}},z=new WeakMap;function ee(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var G=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},A=(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{}},te=n=>{let e=!1;return()=>{e||(n(),e=!0)}},P=-1,Ce=new Set,ye=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,K=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Ce)e();isFinite(P)||(P=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",K,!0))}},x=()=>{if(P<0){let n=_();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??ye(),addEventListener("visibilitychange",K,!0),addEventListener("prerenderingchange",K,!0),I((()=>{setTimeout((()=>{P=ye()}))}))}return{get firstHiddenTime(){return P},onHidden(n){Ce.add(n)}}},O=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},be=[1800,3e3],re=(n,e={})=>{O((()=>{let t=x(),r,i=k("FCP"),s=A("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-_(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,be,e.reportAllChanges),I((a=>{i=k("FCP"),r=v(n,i,be,e.reportAllChanges),Y((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},ve=[.1,.25],Pe=(n,e={})=>{let t=x();re(te((()=>{let r,i=k("CLS",0),s=ee(e,G),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=A("layout-shift",a);l&&(r=v(n,i,ve,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.i=0,i=k("CLS",0),r=v(n,i,ve,e.reportAllChanges),Y((()=>r()))})),setTimeout(r))})))},Ie=0,j=1/0,B=0,Je=n=>{for(let e of n)e.interactionId&&(j=Math.min(j,e.interactionId),B=Math.max(B,e.interactionId),Ie=B?(B-j)/7+1:0)},J,ke=()=>J?Ie:performance.interactionCount??0,qe=()=>{"interactionCount"in performance||J||(J=A("event",Je,{type:"event",buffered:!0,durationThreshold:0}))},we=0,q=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){we=ke(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((ke()-we)/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)}}},_e=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=te(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},Re=[200,500],Ae=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=x();O((()=>{qe();let r,i=k("INP"),s=ee(e,q),a=d=>{_e((()=>{for(let g of d)s.h(g);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=A("event",a,{durationThreshold:e.durationThreshold??40});r=v(n,i,Re,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),I((()=>{s.v(),i=k("INP"),r=v(n,i,Re,e.reportAllChanges)})))}))},X=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},Se=[2500,4e3],Fe=(n,e={})=>{O((()=>{let t=x(),r,i=k("LCP"),s=ee(e,X),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-_(),0),i.entries=[u],r())},l=A("largest-contentful-paint",a);if(l){r=v(n,i,Se,e.reportAllChanges);let d=te((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=g=>{g.isTrusted&&(_e(d),removeEventListener(g.type,u,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,u,{capture:!0});I((g=>{i=k("LCP"),r=v(n,i,Se,e.reportAllChanges),Y((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},Te=[800,1800],Q=n=>{document.prerendering?O((()=>Q(n))):document.readyState!=="complete"?addEventListener("load",(()=>Q(n)),!0):setTimeout(n)},Me=(n,e={})=>{let t=k("TTFB"),r=v(n,t,Te,e.reportAllChanges);Q((()=>{let i=Z();i&&(t.value=Math.max(i.responseStart-_(),0),t.entries=[i],r(!0),I((()=>{t=k("TTFB",0),r=v(n,t,Te,e.reportAllChanges),r(!0)})))}))};var N=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{Fe(this.collectMetric.bind(this)),Pe(this.collectMetric.bind(this)),Ae(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),Me(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 U=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 H=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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await de(n);if(!s)return;let a=new L(s);s.enableWebVitals&&new N(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 U(a),d.initialize()),s.trackFormInteractions&&(u=new H(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 g=()=>a.trackPageview(),h=s.debounceDuration>0?ce(g,s.debounceDuration):g;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 w={};for(let S of c.attributes)if(S.name.startsWith("data-rybbit-prop-")){let T=S.name.replace("data-rybbit-prop-","");w[T]=S.value}a.trackEvent(p,w)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&le(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),h(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),h(),a.onPageChange()},window.addEventListener("popstate",()=>{h(),a.onPageChange()}),window.addEventListener("hashchange",()=>{h(),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(),flag:(o,c)=>a.getFeatureFlag(o,c),flagPayload:(o,c)=>a.getFeatureFlagPayload(o,c),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let m=window[s.namespace];for(let[o,c]of r)m[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.tsindex ce42381b7..5ac099af3 100644--- a/server/src/analytics-script/config.test.ts+++ b/server/src/analytics-script/config.test.ts@@ -13,6 +13,7 @@ describe("parseScriptConfig", () => {mockScriptTag = document.createElement("script");consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ localStorage.clear();vi.clearAllMocks();});@@ -26,18 +27,35 @@ describe("parseScriptConfig", () => {mockScriptTag.setAttribute("data-site-id", "123");// Mock successful API response- (global.fetch as any).mockResolvedValueOnce({- ok: true,- json: async () => ({- sessionReplay: true,- webVitals: true,- trackErrors: false,- trackOutbound: true,- trackUrlParams: false,- trackInitialPageView: true,- trackSpaNavigation: false,- }),- });+ (global.fetch as any)+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ sessionReplay: true,+ webVitals: true,+ trackErrors: false,+ trackOutbound: true,+ trackUrlParams: false,+ trackInitialPageView: true,+ trackSpaNavigation: false,+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ flags: {+ new_checkout: {+ key: "new_checkout",+ value: true,+ flagType: "boolean",+ version: 1,+ reason: "rollout",+ matched: true,+ rolloutPercentage: 100,+ },+ },+ }),+ });const config = await parseScriptConfig(mockScriptTag);@@ -45,6 +63,7 @@ describe("parseScriptConfig", () => {namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",+ visitorId: expect.any(String),debounceDuration: 500,autoTrackPageview: true, // trackInitialPageView from APIautoTrackSpa: false, // trackSpaNavigation from API@@ -57,6 +76,17 @@ describe("parseScriptConfig", () => {trackCopy: false,trackFormInteractions: false,tag: "",+ featureFlags: {+ new_checkout: {+ key: "new_checkout",+ value: true,+ flagType: "boolean",+ version: 1,+ reason: "rollout",+ matched: true,+ rolloutPercentage: 100,+ },+ },skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,@@ -98,6 +128,7 @@ describe("parseScriptConfig", () => {namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",+ visitorId: expect.any(String),debounceDuration: 500,autoTrackPageview: true,autoTrackSpa: true,@@ -110,6 +141,7 @@ describe("parseScriptConfig", () => {trackCopy: false,trackFormInteractions: false,tag: "",+ featureFlags: {},skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,@@ -144,6 +176,7 @@ describe("parseScriptConfig", () => {namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",+ visitorId: expect.any(String),debounceDuration: 500,autoTrackPageview: true,autoTrackSpa: true,@@ -156,6 +189,7 @@ describe("parseScriptConfig", () => {trackCopy: false,trackFormInteractions: false,tag: "",+ featureFlags: {},skipPatterns: [],maskPatterns: [],sessionReplayBatchInterval: 5000,diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex 541dd124e..38fb7d402 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -1,6 +1,88 @@import { ScriptConfig } from "./types.js";import { parseJsonSafely } from "./utils.js";+function createVisitorId(): string {+ try {+ if (crypto?.randomUUID) {+ return crypto.randomUUID();+ }+ } catch (e) {+ // crypto may be unavailable in older browsers+ }++ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;+}++function getOrCreateVisitorId(namespace: string): string {+ const key = `${namespace}-visitor-id`;++ try {+ const stored = localStorage.getItem(key);+ if (stored) return stored;++ const visitorId = createVisitorId();+ localStorage.setItem(key, visitorId);+ return visitorId;+ } catch (e) {+ return createVisitorId();+ }+}++function getIdentifiedUserId(namespace: string): string | undefined {+ try {+ return localStorage.getItem(`${namespace}-user-id`) || undefined;+ } catch (e) {+ return undefined;+ }+}++function getEvaluationPathname(url: URL): string {+ if (url.hash && url.hash.startsWith("#/")) {+ return url.hash.substring(1);+ }++ return url.pathname;+}++async function fetchFeatureFlags(+ analyticsHost: string,+ siteId: string,+ namespace: string,+ visitorId: string+): Promise<ScriptConfig["featureFlags"]> {+ try {+ const url = new URL(window.location.href);+ const response = await fetch(`${analyticsHost}/site/${siteId}/feature-flags/evaluate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ credentials: "omit",+ body: JSON.stringify({+ anonymousId: visitorId,+ identifiedUserId: getIdentifiedUserId(namespace),+ hostname: url.hostname,+ pathname: getEvaluationPathname(url),+ querystring: url.search,+ query: Object.fromEntries(url.searchParams.entries()),+ referrer: document.referrer,+ language: navigator.language,+ screenWidth: screen.width,+ screenHeight: screen.height,+ }),+ });++ if (!response.ok) {+ return {};+ }++ const data = await response.json();+ return data?.flags && typeof data.flags === "object" ? data.flags : {};+ } catch (e) {+ return {};+ }+}+/*** Parse minimal script configuration from the script tag attributes* Most configuration will be fetched from the API@@ -25,6 +107,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S}const namespace = scriptTag.getAttribute("data-namespace") || "rybbit";+ const visitorId = getOrCreateVisitorId(namespace);// These can be overridden via data attributes for testing/debuggingconst skipPatterns = parseJsonSafely<string[]>(scriptTag.getAttribute("data-skip-patterns"), []);@@ -54,9 +137,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<Sconst sessionReplayMaskTextClass = scriptTag.getAttribute("data-replay-mask-text-class") || undefined;const maskAllInputsAttr = scriptTag.getAttribute("data-replay-mask-all-inputs");- const sessionReplayMaskAllInputs = maskAllInputsAttr !== null- ? maskAllInputsAttr !== "false"- : undefined;+ const sessionReplayMaskAllInputs = maskAllInputsAttr !== null ? maskAllInputsAttr !== "false" : undefined;const maskInputOptionsAttr = scriptTag.getAttribute("data-replay-mask-input-options");const sessionReplayMaskInputOptions = maskInputOptionsAttr@@ -64,14 +145,10 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S: undefined;const collectFontsAttr = scriptTag.getAttribute("data-replay-collect-fonts");- const sessionReplayCollectFonts = collectFontsAttr !== null- ? collectFontsAttr !== "false"- : undefined;+ const sessionReplayCollectFonts = collectFontsAttr !== null ? collectFontsAttr !== "false" : undefined;const samplingAttr = scriptTag.getAttribute("data-replay-sampling");- const sessionReplaySampling = samplingAttr- ? parseJsonSafely<Record<string, any>>(samplingAttr, {})- : undefined;+ const sessionReplaySampling = samplingAttr ? parseJsonSafely<Record<string, any>>(samplingAttr, {}) : undefined;const slimDOMAttr = scriptTag.getAttribute("data-replay-slim-dom-options");const sessionReplaySlimDOMOptions = slimDOMAttr@@ -79,9 +156,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S: undefined;const sampleRateAttr = scriptTag.getAttribute("data-replay-sample-rate");- const sessionReplaySampleRate = sampleRateAttr- ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10)))- : undefined;+ const sessionReplaySampleRate = sampleRateAttr ? Math.min(100, Math.max(0, parseInt(sampleRateAttr, 10))) : undefined;const tag = scriptTag.getAttribute("data-tag") || "";@@ -90,6 +165,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<Snamespace,analyticsHost,siteId,+ visitorId,debounceDuration,sessionReplayBatchSize,sessionReplayBatchInterval,@@ -108,6 +184,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<StrackCopy: false,trackFormInteractions: false,tag,+ featureFlags: {},// rrweb session replay options (undefined means use rrweb defaults)sessionReplayBlockClass,sessionReplayBlockSelector,@@ -122,6 +199,8 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<SsessionReplaySampleRate,};+ let resolvedConfig = defaultConfig;+try {// Fetch configuration from APIconst configUrl = `${analyticsHost}/site/tracking-config/${siteId}`;@@ -135,7 +214,7 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<Sconst apiConfig = await response.json();// Merge API config with defaults, API config takes precedence- return {+ resolvedConfig = {...defaultConfig,// Map API field names to script config field namesautoTrackPageview: apiConfig.trackInitialPageView ?? defaultConfig.autoTrackPageview,@@ -152,11 +231,12 @@ export async function parseScriptConfig(scriptTag: HTMLScriptElement): Promise<S} else {// If API call fails, log warning and use defaultsconsole.warn("Failed to fetch tracking config from API, using defaults");- return defaultConfig;}} catch (error) {// If network error, log and use defaultsconsole.warn("Error fetching tracking config:", error);- return defaultConfig;}++ resolvedConfig.featureFlags = await fetchFeatureFlags(analyticsHost, siteId, namespace, visitorId);+ return resolvedConfig;}diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.tsindex a0fffb2d8..e6a30262e 100644--- a/server/src/analytics-script/index.ts+++ b/server/src/analytics-script/index.ts@@ -38,6 +38,11 @@ declare global {setTraits: () => {},clearUserId: () => {},getUserId: () => null,+ flag: (_key: string, fallback?: unknown) => fallback,+ flagPayload: (_key: string, fallback?: unknown) => fallback,+ flags: () => ({}),+ flagPayloads: () => ({}),+ onReady: () => {},startSessionReplay: () => {},stopSessionReplay: () => {},isSessionReplayActive: () => false,@@ -48,8 +53,11 @@ declare global {// Expose stub API immediately to queue calls made before config is readytype QueueEntry = [string, any[]];const earlyQueue: QueueEntry[] = [];- const queueMethod = (method: string) =>- (...args: any[]) => { earlyQueue.push([method, args]); };+ const queueMethod =+ (method: string) =>+ (...args: any[]) => {+ earlyQueue.push([method, args]);+ };window[namespace] = {pageview: queueMethod("pageview"),@@ -60,6 +68,11 @@ declare global {setTraits: queueMethod("setTraits"),clearUserId: queueMethod("clearUserId"),getUserId: () => null,+ flag: (_key: string, fallback?: unknown) => fallback,+ flagPayload: (_key: string, fallback?: unknown) => fallback,+ flags: () => ({}),+ flagPayloads: () => ({}),+ onReady: queueMethod("onReady"),startSessionReplay: queueMethod("startSessionReplay"),stopSessionReplay: queueMethod("stopSessionReplay"),isSessionReplayActive: () => false,@@ -203,6 +216,11 @@ declare global {setTraits: (traits: Record<string, unknown>) => tracker.setTraits(traits),clearUserId: () => tracker.clearUserId(),getUserId: () => tracker.getUserId(),+ flag: <T = unknown>(key: string, fallback?: T) => tracker.getFeatureFlag<T>(key, fallback),+ flagPayload: <T = unknown>(key: string, fallback?: T) => tracker.getFeatureFlagPayload<T>(key, fallback),+ flags: () => tracker.getFeatureFlags(),+ flagPayloads: () => tracker.getFeatureFlagPayloads(),+ onReady: (callback: (api: RybbitAPI) => void) => callback(window[config.namespace]),startSessionReplay: () => tracker.startSessionReplay(),stopSessionReplay: () => tracker.stopSessionReplay(),isSessionReplayActive: () => tracker.isSessionReplayActive(),@@ -228,4 +246,4 @@ declare global {if (config!.autoTrackPageview) {tracker.trackPageview();}-})();\ No newline at end of file+})();diff --git a/server/src/analytics-script/tracking.test.ts b/server/src/analytics-script/tracking.test.tsindex cc86b0e33..bae626502 100644--- a/server/src/analytics-script/tracking.test.ts+++ b/server/src/analytics-script/tracking.test.ts@@ -86,6 +86,7 @@ describe("Tracker", () => {namespace: "rybbit",analyticsHost: "https://analytics.example.com",siteId: "123",+ visitorId: "visitor-123",debounceDuration: 0,autoTrackPageview: true,autoTrackSpa: true,@@ -103,6 +104,7 @@ describe("Tracker", () => {trackCopy: false,trackFormInteractions: false,tag: "",+ featureFlags: {},};tracker = new Tracker(config);@@ -183,6 +185,26 @@ describe("Tracker", () => {const payload = tracker.createBasePayload();expect(payload?.user_id).toBe("user-123");});++ it("should include evaluated feature flags in payloads", () => {+ config.featureFlags = {+ new_checkout: {+ key: "new_checkout",+ value: true,+ flagType: "boolean",+ payload: { copy: "Try it now" },+ version: 1,+ reason: "rollout",+ matched: true,+ rolloutPercentage: 100,+ },+ };+ tracker = new Tracker(config);++ const payload = tracker.createBasePayload();+ expect(payload?.feature_flags).toEqual({ new_checkout: "true" });+ expect(tracker.getFeatureFlagPayload("new_checkout")).toEqual({ copy: "Try it now" });+ });});describe("tracking methods", () => {@@ -216,6 +238,36 @@ describe("Tracker", () => {expect(body.properties).toBe(JSON.stringify({ button: "submit" }));});+ it("should track feature flag exposure once when a flag is read", () => {+ config.featureFlags = {+ new_checkout: {+ key: "new_checkout",+ value: true,+ flagType: "boolean",+ version: 1,+ reason: "rollout",+ matched: true,+ rolloutPercentage: 100,+ },+ };+ tracker = new Tracker(config);+ vi.mocked(global.fetch).mockClear();++ expect(tracker.getFeatureFlag("new_checkout", false)).toBe(true);+ expect(tracker.getFeatureFlag("new_checkout", false)).toBe(true);++ expect(global.fetch).toHaveBeenCalledTimes(1);+ const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);+ expect(body.type).toBe("custom_event");+ expect(body.event_name).toBe("feature_flag_exposure");+ expect(JSON.parse(body.properties)).toMatchObject({+ key: "new_checkout",+ value: "true",+ version: 1,+ reason: "rollout",+ });+ });+it("should validate custom event name", () => {const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex 58b9801e3..9fd3a0d50 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -1,4 +1,14 @@-import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData, SessionReplayBatch, ButtonClickProperties, CopyProperties, FormSubmitProperties, InputChangeProperties } from "./types.js";+import {+ BasePayload,+ ScriptConfig,+ TrackingPayload,+ WebVitalsData,+ SessionReplayBatch,+ ButtonClickProperties,+ CopyProperties,+ FormSubmitProperties,+ InputChangeProperties,+} from "./types.js";import { findMatchingPattern } from "./utils.js";import { SessionReplayRecorder } from "./sessionReplay.js";import { getBotScore, getBotSignalMask } from "./botSignals.js";@@ -9,6 +19,7 @@ export class Tracker {private sessionReplayRecorder?: SessionReplayRecorder;private errorDedupeCache: Map<string, number> = new Map();private errorDedupeLastCleanup = 0;+ private exposedFeatureFlags = new Set<string>();constructor(config: ScriptConfig) {this.config = config;this.loadUserId();@@ -18,6 +29,69 @@ export class Tracker {}}+ private serializeFeatureFlagValue(value: unknown): string {+ if (value === null || value === undefined) return "";+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);++ try {+ return JSON.stringify(value);+ } catch (e) {+ return "";+ }+ }++ private getFeatureFlagEventPayload(): Record<string, string> {+ const payload: Record<string, string> = {};++ for (const [key, assignment] of Object.entries(this.config.featureFlags || {})) {+ payload[key] = this.serializeFeatureFlagValue(assignment.value);+ }++ return payload;+ }++ private getCurrentUrlContext() {+ const url = new URL(window.location.href);+ const pathname = url.hash && url.hash.startsWith("#/") ? url.hash.substring(1) : url.pathname;++ return {+ hostname: url.hostname,+ pathname,+ querystring: url.search,+ query: Object.fromEntries(url.searchParams.entries()),+ referrer: document.referrer,+ language: navigator.language,+ screenWidth: screen.width,+ screenHeight: screen.height,+ };+ }++ private async refreshFeatureFlags(): Promise<void> {+ try {+ const response = await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ anonymousId: this.config.visitorId,+ identifiedUserId: this.customUserId || undefined,+ ...this.getCurrentUrlContext(),+ }),+ mode: "cors",+ credentials: "omit",+ keepalive: true,+ });++ if (!response.ok) return;+ const data = await response.json();+ this.config.featureFlags = data?.flags && typeof data.flags === "object" ? data.flags : {};+ } catch (e) {+ // Feature flag refresh is best-effort and should never affect analytics collection.+ }+ }+private loadUserId(): void {try {const storedUserId = localStorage.getItem(`${this.config.namespace}-user-id`);@@ -99,6 +173,11 @@ export class Tracker {payload.tag = this.config.tag;}+ const featureFlagPayload = this.getFeatureFlagEventPayload();+ if (Object.keys(featureFlagPayload).length > 0) {+ payload.feature_flags = featureFlagPayload;+ }+return payload;}@@ -129,14 +208,20 @@ export class Tracker {return; // Skip tracking}- const typesWithProperties = ["custom_event", "outbound", "error", "button_click", "copy", "form_submit", "input_change"];+ const typesWithProperties = [+ "custom_event",+ "outbound",+ "error",+ "button_click",+ "copy",+ "form_submit",+ "input_change",+ ];const payload: TrackingPayload = {...basePayload,type: eventType,event_name: eventName,- properties: typesWithProperties.includes(eventType)- ? JSON.stringify(properties)- : undefined,+ properties: typesWithProperties.includes(eventType) ? JSON.stringify(properties) : undefined,};this.sendTrackingData(payload);@@ -150,6 +235,51 @@ export class Tracker {this.track("custom_event", name, properties);}+ getFeatureFlag<T = unknown>(key: string, fallback?: T): T {+ const assignment = this.config.featureFlags?.[key];++ if (!assignment) {+ return fallback as T;+ }++ const exposureKey = `${key}:${assignment.version}:${this.serializeFeatureFlagValue(assignment.value)}`;+ if (!this.exposedFeatureFlags.has(exposureKey)) {+ this.exposedFeatureFlags.add(exposureKey);+ this.trackEvent("feature_flag_exposure", {+ key,+ value: this.serializeFeatureFlagValue(assignment.value),+ version: assignment.version,+ reason: assignment.reason,+ });+ }++ return assignment.value as T;+ }++ getFeatureFlags(): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(this.config.featureFlags || {}).map(([key, assignment]) => [key, assignment.value])+ );+ }++ getFeatureFlagPayload<T = unknown>(key: string, fallback?: T): T {+ const assignment = this.config.featureFlags?.[key];++ if (!assignment || assignment.payload === undefined) {+ return fallback as T;+ }++ return assignment.payload as T;+ }++ getFeatureFlagPayloads(): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(this.config.featureFlags || {})+ .filter(([, assignment]) => assignment.payload !== undefined)+ .map(([key, assignment]) => [key, assignment.payload])+ );+ }+trackOutbound(url: string, text: string = "", target: string = "_self"): void {this.track("outbound", "", { url, text, target });}@@ -303,7 +433,7 @@ export class Tracker {}// Send identify event to server (creates alias and stores traits)- this.sendIdentifyEvent(this.customUserId, traits, true);+ void this.sendIdentifyEvent(this.customUserId, traits, true).then(() => this.refreshFeatureFlags());// Update session replay recorder with new user IDif (this.sessionReplayRecorder) {@@ -323,7 +453,7 @@ export class Tracker {return;}- this.sendIdentifyEvent(userId, traits, false);+ void this.sendIdentifyEvent(userId, traits, false).then(() => this.refreshFeatureFlags());}private async sendIdentifyEvent(@@ -358,6 +488,7 @@ export class Tracker {} catch (e) {// localStorage not available}+ void this.refreshFeatureFlags();}getUserId(): string | null {@@ -385,6 +516,8 @@ export class Tracker {// Handle page changes for SPAonPageChange(): void {+ void this.refreshFeatureFlags();+if (this.sessionReplayRecorder) {this.sessionReplayRecorder.onPageChange();}diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 9a439449b..c2fb34d7b 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -2,6 +2,7 @@ export interface ScriptConfig {namespace: string;analyticsHost: string;siteId: string;+ visitorId: string;debounceDuration: number;autoTrackPageview: boolean;autoTrackSpa: boolean;@@ -31,6 +32,20 @@ export interface ScriptConfig {trackCopy: boolean;trackFormInteractions: boolean;tag: string;+ featureFlags: Record<string, FeatureFlagAssignment>;+}++export interface FeatureFlagAssignment {+ key: string;+ value: unknown;+ flagType: "boolean" | "multivariate" | "remote_config";+ payload?: unknown;+ variant?: string;+ conditionSet?: string;+ version: number;+ reason: "disabled" | "target_mismatch" | "rollout" | "variant" | "remote_config" | "fallthrough";+ matched: boolean;+ rolloutPercentage: number;}export interface BasePayload {@@ -45,12 +60,22 @@ export interface BasePayload {referrer: string;user_id?: string;tag?: string;+ feature_flags?: Record<string, string>;_bs?: number; // Client-side weighted bot detection score_bsm?: number; // Client-side bot detection signal bitmask}export interface TrackingPayload extends BasePayload {- type: "pageview" | "custom_event" | "outbound" | "performance" | "error" | "button_click" | "copy" | "form_submit" | "input_change";+ type:+ | "pageview"+ | "custom_event"+ | "outbound"+ | "performance"+ | "error"+ | "button_click"+ | "copy"+ | "form_submit"+ | "input_change";event_name?: string;properties?: string;// Web vitals metrics@@ -116,6 +141,11 @@ export interface RybbitAPI {setTraits: (traits: Record<string, unknown>) => void;clearUserId: () => void;getUserId: () => string | null;+ flag: <T = unknown>(key: string, fallback?: T) => T;+ flagPayload: <T = unknown>(key: string, fallback?: T) => T;+ flags: () => Record<string, unknown>;+ flagPayloads: () => Record<string, unknown>;+ onReady: (callback: (api: RybbitAPI) => void) => void;startSessionReplay: () => void;stopSessionReplay: () => void;isSessionReplayActive: () => boolean;diff --git a/server/src/api/analytics/utils/getFilterStatement.test.ts b/server/src/api/analytics/utils/getFilterStatement.test.tsindex 8a6f15efa..881364c4c 100644--- a/server/src/api/analytics/utils/getFilterStatement.test.ts+++ b/server/src/api/analytics/utils/getFilterStatement.test.ts@@ -36,6 +36,12 @@ describe("getSqlParam", () => {});});+ describe("Feature flag parameters", () => {+ it("should handle feature_flag:key", () => {+ expect(getSqlParam("feature_flag:new_checkout" as FilterParameter)).toBe("feature_flags['new_checkout']");+ });+ });+describe("Special parameters", () => {it("should handle referrer", () => {expect(getSqlParam("referrer")).toBe("domainWithoutWWW(referrer)");diff --git a/server/src/api/analytics/utils/getFilterStatement.ts b/server/src/api/analytics/utils/getFilterStatement.tsindex dc4a5a41c..97b1c883c 100644--- a/server/src/api/analytics/utils/getFilterStatement.ts+++ b/server/src/api/analytics/utils/getFilterStatement.ts@@ -53,6 +53,11 @@ const wrapLikeValue = (type: FilterType, value: string | number): string => {};export const getSqlParam = (parameter: FilterParameter) => {+ if (parameter.startsWith("feature_flag:")) {+ const key = parameter.substring("feature_flag:".length);+ return `feature_flags[${SqlString.escape(key)}]`;+ }+// Handle URL parameters through the url_parameters mapif (parameter.startsWith("utm_") || parameter.startsWith("url_param:")) {// For explicit url_param: prefix (e.g., url_param:campaign_id)diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.tsindex e732b08a3..0b5f86181 100644--- a/server/src/api/analytics/utils/query-validation.ts+++ b/server/src/api/analytics/utils/query-validation.ts@@ -1,4 +1,4 @@-import { FilterParams } from "@rybbit/shared";+import { FilterParameter, FilterParams } from "@rybbit/shared";import { z } from "zod";// =============================================================================@@ -254,7 +254,7 @@ const filterTypeSchema = z.enum([/*** Schema for filter parameter values*/-export const filterParamSchema = z.enum([+const baseFilterParamSchema = z.enum(["browser","operating_system","language",@@ -286,6 +286,11 @@ export const filterParamSchema = z.enum(["tag",]);+export const filterParamSchema: z.ZodType<FilterParameter> = z.union([+ baseFilterParamSchema,+ z.string().regex(/^feature_flag:[A-Za-z][A-Za-z0-9_.:-]{0,99}$/),+]) as z.ZodType<FilterParameter>;+/*** Schema for filter objects*/diff --git a/server/src/api/experiments/createExperiment.ts b/server/src/api/experiments/createExperiment.tsnew file mode 100644index 000000000..df332f26b--- /dev/null+++ b/server/src/api/experiments/createExperiment.ts@@ -0,0 +1,60 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { z } from "zod";+import { db } from "../../db/postgres/postgres.js";+import { experiments } from "../../db/postgres/schema.js";+import { experimentBodySchema, type ExperimentBody } from "./schemas.js";+import {+ getDuplicateExperimentMessage,+ getExperimentWithRelations,+ parseSiteId,+ serializeExperiment,+ timestampsForStatus,+ validateExperimentReferences,+} from "./utils.js";++export async function createExperiment(+ request: FastifyRequest<{+ Params: { siteId: string };+ Body: ExperimentBody;+ }>,+ reply: FastifyReply+) {+ try {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const body = experimentBodySchema.parse(request.body);+ const references = await validateExperimentReferences(siteId, body);++ if ("error" in references) {+ return reply.status(400).send({ error: references.error });+ }++ const [created] = await db+ .insert(experiments)+ .values({+ siteId,+ featureFlagId: body.featureFlagId,+ primaryGoalId: body.primaryGoalId ?? null,+ name: body.name,+ description: body.description || null,+ hypothesis: body.hypothesis || null,+ status: body.status,+ winningVariant: body.winningVariant || null,+ ...timestampsForStatus(body.status),+ })+ .returning({ experimentId: experiments.experimentId });++ const record = await getExperimentWithRelations(siteId, created.experimentId);+ return reply.status(201).send({ success: true, data: record ? serializeExperiment(record) : created });+ } catch (error) {+ const duplicateMessage = getDuplicateExperimentMessage(error);+ if (duplicateMessage) {+ return reply.status(409).send({ error: duplicateMessage });+ }+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to create experiment" });+ }+}diff --git a/server/src/api/experiments/deleteExperiment.ts b/server/src/api/experiments/deleteExperiment.tsnew file mode 100644index 000000000..f3c051777--- /dev/null+++ b/server/src/api/experiments/deleteExperiment.ts@@ -0,0 +1,29 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { and, eq } from "drizzle-orm";+import { db } from "../../db/postgres/postgres.js";+import { experiments } from "../../db/postgres/schema.js";+import { parseExperimentId, parseSiteId } from "./utils.js";++export async function deleteExperiment(+ request: FastifyRequest<{+ Params: { siteId: string; experimentId: string };+ }>,+ reply: FastifyReply+) {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const experimentId = parseExperimentId(request.params.experimentId, reply);+ if (!experimentId) return;++ const [deleted] = await db+ .delete(experiments)+ .where(and(eq(experiments.siteId, siteId), eq(experiments.experimentId, experimentId)))+ .returning({ experimentId: experiments.experimentId });++ if (!deleted) {+ return reply.status(404).send({ error: "Experiment not found" });+ }++ return reply.send({ success: true });+}diff --git a/server/src/api/experiments/getExperimentResults.ts b/server/src/api/experiments/getExperimentResults.tsnew file mode 100644index 000000000..de5bcefcf--- /dev/null+++ b/server/src/api/experiments/getExperimentResults.ts@@ -0,0 +1,173 @@+import { FastifyReply, FastifyRequest } from "fastify";+import type { FilterParams } from "@rybbit/shared";+import SqlString from "sqlstring";+import { z } from "zod";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { buildGoalCondition } from "../analytics/goals/goalConditions.js";+import { getFilterStatement } from "../analytics/utils/getFilterStatement.js";+import { getTimeStatement, processResults } from "../analytics/utils/utils.js";+import type { ExperimentResultRow } from "./types.js";+import {+ buildExperimentResults,+ getExperimentVariantKeys,+ getExperimentWithRelations,+ parseExperimentId,+ parseSiteId,+ serializeExperiment,+} from "./utils.js";++export async function getExperimentResults(+ request: FastifyRequest<{+ Params: { siteId: string; experimentId: string };+ Querystring: FilterParams;+ }>,+ reply: FastifyReply+) {+ try {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const experimentId = parseExperimentId(request.params.experimentId, reply);+ if (!experimentId) return;++ const record = await getExperimentWithRelations(siteId, experimentId);+ if (!record) {+ return reply.status(404).send({ error: "Experiment not found" });+ }++ const variants = getExperimentVariantKeys(record.featureFlag);+ const goalCondition = record.primaryGoal ? buildGoalCondition(record.primaryGoal) : null;++ if (!record.primaryGoal || !goalCondition) {+ return reply.send({+ data: {+ experiment: serializeExperiment(record),+ variants: buildExperimentResults(variants, []),+ totalExposureSessions: 0,+ totalConversions: 0,+ hasGoal: false,+ measurement: "exposure",+ },+ });+ }++ const timeStatement = getTimeStatement(request.query);+ const filterStatement = request.query.filters+ ? getFilterStatement(request.query.filters as string, siteId, timeStatement)+ : "";+ const escapedSiteId = SqlString.escape(siteId);+ const escapedFlagKey = SqlString.escape(record.featureFlag.key);++ // One row per session that completed the goal, scoped to the same time+ // window and filters the goals page uses, so experiment conversions can+ // never exceed the goal's own count. Aggregating per session also keeps the+ // join below one-to-one, so exposure counts aren't inflated.+ const goalSessionsCte = `+ goal_sessions AS (+ SELECT+ session_id,+ max(timestamp) AS last_goal_at+ FROM events+ WHERE site_id = ${escapedSiteId}+ AND (${goalCondition})+ ${timeStatement}+ ${filterStatement}+ GROUP BY session_id+ )`;++ // Exposure-based: counts only sessions that explicitly read the flag via+ // rybbit.flag(), which emits a feature_flag_exposure event. This is the+ // statistically correct unit of analysis for an experiment.+ const exposureQuery = `+ WITH+ exposure_sessions AS (+ SELECT+ session_id,+ JSONExtractString(toString(props), 'value') AS variant,+ min(timestamp) AS exposed_at,+ count() AS exposures+ FROM events+ WHERE site_id = ${escapedSiteId}+ AND type = 'custom_event'+ AND event_name = 'feature_flag_exposure'+ AND JSONExtractString(toString(props), 'key') = ${escapedFlagKey}+ AND JSONExtractString(toString(props), 'value') != ''+ ${timeStatement}+ ${filterStatement}+ GROUP BY session_id, variant+ ),+ ${goalSessionsCte}+ SELECT+ e.variant AS variant,+ uniqExact(e.session_id) AS sessions,+ sum(e.exposures) AS exposures,+ uniqExactIf(e.session_id, g.last_goal_at >= e.exposed_at) AS conversions+ FROM exposure_sessions e+ LEFT JOIN goal_sessions g ON g.session_id = e.session_id+ GROUP BY e.variant+ ORDER BY e.variant ASC+ `;++ const exposureResult = await clickhouse.query({ query: exposureQuery, format: "JSONEachRow" });+ let rows = await processResults<ExperimentResultRow>(exposureResult);+ let measurement: "exposure" | "assignment" = "exposure";++ // Fallback: if no exposures were recorded (the app never calls rybbit.flag+ // for this key), count sessions that were assigned the variant via the+ // feature_flags map attached to every event. Looser, but avoids a confusing+ // empty result when the flag is clearly assigning traffic.+ const hasExposures = rows.some(row => Number(row.sessions) > 0);+ if (!hasExposures) {+ const assignmentQuery = `+ WITH+ assignment_sessions AS (+ SELECT+ session_id,+ feature_flags[${escapedFlagKey}] AS variant,+ min(timestamp) AS assigned_at+ FROM events+ WHERE site_id = ${escapedSiteId}+ AND feature_flags[${escapedFlagKey}] != ''+ ${timeStatement}+ ${filterStatement}+ GROUP BY session_id, variant+ ),+ ${goalSessionsCte}+ SELECT+ a.variant AS variant,+ uniqExact(a.session_id) AS sessions,+ uniqExact(a.session_id) AS exposures,+ uniqExactIf(a.session_id, g.last_goal_at >= a.assigned_at) AS conversions+ FROM assignment_sessions a+ LEFT JOIN goal_sessions g ON g.session_id = a.session_id+ GROUP BY a.variant+ ORDER BY a.variant ASC+ `;++ const assignmentResult = await clickhouse.query({ query: assignmentQuery, format: "JSONEachRow" });+ const assignmentRows = await processResults<ExperimentResultRow>(assignmentResult);+ if (assignmentRows.some(row => Number(row.sessions) > 0)) {+ rows = assignmentRows;+ measurement = "assignment";+ }+ }++ const variantResults = buildExperimentResults(variants, rows);++ return reply.send({+ data: {+ experiment: serializeExperiment(record),+ variants: variantResults,+ totalExposureSessions: variantResults.reduce((sum, variant) => sum + variant.sessions, 0),+ totalConversions: variantResults.reduce((sum, variant) => sum + variant.conversions, 0),+ hasGoal: true,+ measurement,+ },+ });+ } catch (error) {+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to get experiment results" });+ }+}diff --git a/server/src/api/experiments/getExperiments.ts b/server/src/api/experiments/getExperiments.tsnew file mode 100644index 000000000..4c2f81810--- /dev/null+++ b/server/src/api/experiments/getExperiments.ts@@ -0,0 +1,31 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { desc, eq } from "drizzle-orm";+import { db } from "../../db/postgres/postgres.js";+import { experiments, featureFlags, goals } from "../../db/postgres/schema.js";+import { parseSiteId, serializeExperiment } from "./utils.js";++export async function getExperiments(+ request: FastifyRequest<{+ Params: { siteId: string };+ }>,+ reply: FastifyReply+) {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const rows = await db+ .select({+ experiment: experiments,+ featureFlag: featureFlags,+ primaryGoal: goals,+ })+ .from(experiments)+ .innerJoin(featureFlags, eq(experiments.featureFlagId, featureFlags.flagId))+ .leftJoin(goals, eq(experiments.primaryGoalId, goals.goalId))+ .where(eq(experiments.siteId, siteId))+ .orderBy(desc(experiments.updatedAt));++ return reply.send({+ data: rows.map(serializeExperiment),+ });+}diff --git a/server/src/api/experiments/index.ts b/server/src/api/experiments/index.tsnew file mode 100644index 000000000..72dd548ef--- /dev/null+++ b/server/src/api/experiments/index.ts@@ -0,0 +1,5 @@+export { createExperiment } from "./createExperiment.js";+export { deleteExperiment } from "./deleteExperiment.js";+export { getExperimentResults } from "./getExperimentResults.js";+export { getExperiments } from "./getExperiments.js";+export { updateExperiment } from "./updateExperiment.js";diff --git a/server/src/api/experiments/schemas.ts b/server/src/api/experiments/schemas.tsnew file mode 100644index 000000000..7746b2973--- /dev/null+++ b/server/src/api/experiments/schemas.ts@@ -0,0 +1,20 @@+import { z } from "zod";++export const experimentStatusSchema = z.enum(["draft", "running", "paused", "completed"]);++export const experimentBodySchema = z.object({+ name: z.string().trim().min(1).max(160),+ description: z.string().trim().max(1000).optional().nullable(),+ hypothesis: z.string().trim().max(1000).optional().nullable(),+ featureFlagId: z.number().int().positive(),+ primaryGoalId: z.number().int().positive().optional().nullable(),+ status: experimentStatusSchema.default("draft"),+ winningVariant: z.string().trim().max(100).optional().nullable(),+});++export const experimentUpdateSchema = experimentBodySchema.partial().refine(data => Object.keys(data).length > 0, {+ message: "At least one field must be provided",+});++export type ExperimentBody = z.infer<typeof experimentBodySchema>;+export type ExperimentUpdate = z.infer<typeof experimentUpdateSchema>;diff --git a/server/src/api/experiments/types.ts b/server/src/api/experiments/types.tsnew file mode 100644index 000000000..6f8d0293d--- /dev/null+++ b/server/src/api/experiments/types.ts@@ -0,0 +1,18 @@+import { experiments, featureFlags, goals } from "../../db/postgres/schema.js";++export type ExperimentRecord = typeof experiments.$inferSelect;+export type FeatureFlagRecord = typeof featureFlags.$inferSelect;+export type GoalRecord = typeof goals.$inferSelect;++export type ExperimentWithRelations = {+ experiment: ExperimentRecord;+ featureFlag: FeatureFlagRecord;+ primaryGoal: GoalRecord | null;+};++export type ExperimentResultRow = {+ variant: string;+ sessions: number;+ exposures: number;+ conversions: number;+};diff --git a/server/src/api/experiments/updateExperiment.ts b/server/src/api/experiments/updateExperiment.tsnew file mode 100644index 000000000..57424db46--- /dev/null+++ b/server/src/api/experiments/updateExperiment.ts@@ -0,0 +1,83 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { and, eq } from "drizzle-orm";+import { z } from "zod";+import { db } from "../../db/postgres/postgres.js";+import { experiments } from "../../db/postgres/schema.js";+import { experimentUpdateSchema, type ExperimentUpdate } from "./schemas.js";+import {+ getDuplicateExperimentMessage,+ getExperimentWithRelations,+ parseExperimentId,+ parseSiteId,+ serializeExperiment,+ timestampsForStatus,+ validateExperimentReferences,+} from "./utils.js";++export async function updateExperiment(+ request: FastifyRequest<{+ Params: { siteId: string; experimentId: string };+ Body: ExperimentUpdate;+ }>,+ reply: FastifyReply+) {+ try {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const experimentId = parseExperimentId(request.params.experimentId, reply);+ if (!experimentId) return;++ const existing = await db.query.experiments.findFirst({+ where: and(eq(experiments.siteId, siteId), eq(experiments.experimentId, experimentId)),+ });++ if (!existing) {+ return reply.status(404).send({ error: "Experiment not found" });+ }++ const body = experimentUpdateSchema.parse(request.body);++ if (body.featureFlagId !== undefined || body.primaryGoalId !== undefined) {+ const references = await validateExperimentReferences(siteId, {+ featureFlagId: body.featureFlagId ?? existing.featureFlagId,+ primaryGoalId: body.primaryGoalId === undefined ? existing.primaryGoalId : body.primaryGoalId,+ });++ if ("error" in references) {+ return reply.status(400).send({ error: references.error });+ }+ }++ const updateData: Partial<typeof experiments.$inferInsert> = {+ ...body,+ description: body.description === undefined ? undefined : body.description || null,+ hypothesis: body.hypothesis === undefined ? undefined : body.hypothesis || null,+ primaryGoalId: body.primaryGoalId === undefined ? undefined : body.primaryGoalId,+ winningVariant: body.winningVariant === undefined ? undefined : body.winningVariant || null,+ updatedAt: new Date().toISOString(),+ };++ if (body.status !== undefined) {+ Object.assign(updateData, timestampsForStatus(body.status, existing));+ }++ const [updated] = await db+ .update(experiments)+ .set(updateData)+ .where(and(eq(experiments.siteId, siteId), eq(experiments.experimentId, experimentId)))+ .returning({ experimentId: experiments.experimentId });++ const record = await getExperimentWithRelations(siteId, updated.experimentId);+ return reply.send({ success: true, data: record ? serializeExperiment(record) : updated });+ } catch (error) {+ const duplicateMessage = getDuplicateExperimentMessage(error);+ if (duplicateMessage) {+ return reply.status(409).send({ error: duplicateMessage });+ }+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to update experiment" });+ }+}diff --git a/server/src/api/experiments/utils.ts b/server/src/api/experiments/utils.tsnew file mode 100644index 000000000..f2968bd34--- /dev/null+++ b/server/src/api/experiments/utils.ts@@ -0,0 +1,153 @@+import { FastifyReply } from "fastify";+import { and, eq } from "drizzle-orm";+import { db } from "../../db/postgres/postgres.js";+import { experiments, featureFlags, goals, type ExperimentStatus } from "../../db/postgres/schema.js";+import type { ExperimentBody } from "./schemas.js";+import type { ExperimentRecord, ExperimentResultRow, ExperimentWithRelations, FeatureFlagRecord } from "./types.js";++export function parseSiteId(siteIdParam: string, reply: FastifyReply): number | null {+ const siteId = parseInt(siteIdParam, 10);+ if (isNaN(siteId) || siteId <= 0) {+ reply.status(400).send({ error: "Invalid site ID" });+ return null;+ }+ return siteId;+}++export function parseExperimentId(experimentIdParam: string, reply: FastifyReply): number | null {+ const experimentId = parseInt(experimentIdParam, 10);+ if (isNaN(experimentId) || experimentId <= 0) {+ reply.status(400).send({ error: "Invalid experiment ID" });+ return null;+ }+ return experimentId;+}++export function getDuplicateExperimentMessage(error: unknown) {+ if (typeof error === "object" && error !== null && "code" in error && error.code === "23505") {+ return "An experiment already exists for this feature flag";+ }+ return null;+}++export async function validateExperimentReferences(+ siteId: number,+ body: Pick<ExperimentBody, "featureFlagId" | "primaryGoalId">+) {+ const [flag, goal] = await Promise.all([+ db.query.featureFlags.findFirst({+ where: and(eq(featureFlags.siteId, siteId), eq(featureFlags.flagId, body.featureFlagId)),+ }),+ body.primaryGoalId+ ? db.query.goals.findFirst({+ where: and(eq(goals.siteId, siteId), eq(goals.goalId, body.primaryGoalId)),+ })+ : Promise.resolve(undefined),+ ]);++ if (!flag) {+ return { error: "Feature flag not found" as const };+ }++ if (flag.flagType !== "multivariate") {+ return { error: "Experiments require a multivariate feature flag" as const };+ }++ if (body.primaryGoalId && !goal) {+ return { error: "Goal not found" as const };+ }++ return { flag, goal };+}++export function timestampsForStatus(status: ExperimentStatus, existing?: ExperimentRecord) {+ const now = new Date().toISOString();+ return {+ startedAt: status === "running" && !existing?.startedAt ? now : undefined,+ endedAt: status === "completed" && !existing?.endedAt ? now : undefined,+ };+}++export async function getExperimentWithRelations(+ siteId: number,+ experimentId: number+): Promise<ExperimentWithRelations | undefined> {+ const [record] = await db+ .select({+ experiment: experiments,+ featureFlag: featureFlags,+ primaryGoal: goals,+ })+ .from(experiments)+ .innerJoin(featureFlags, eq(experiments.featureFlagId, featureFlags.flagId))+ .leftJoin(goals, eq(experiments.primaryGoalId, goals.goalId))+ .where(and(eq(experiments.siteId, siteId), eq(experiments.experimentId, experimentId)));++ return record;+}++export function serializeExperiment(record: ExperimentWithRelations) {+ return {+ ...record.experiment,+ featureFlag: record.featureFlag,+ primaryGoal: record.primaryGoal,+ };+}++export function getExperimentVariantKeys(flag: FeatureFlagRecord) {+ const variantKeys: string[] = [];++ for (const conditionSet of flag.conditionSets || []) {+ for (const variant of conditionSet.variants || []) {+ if (!variantKeys.includes(variant.key)) {+ variantKeys.push(variant.key);+ }+ }+ }++ for (const variant of flag.variants || []) {+ if (!variantKeys.includes(variant.key)) {+ variantKeys.push(variant.key);+ }+ }++ return variantKeys;+}++function getControlVariant(variants: string[], rows: ExperimentResultRow[]) {+ return variants.find(variant => variant === "control") || variants[0] || rows[0]?.variant || null;+}++export function buildExperimentResults(variants: string[], rows: ExperimentResultRow[]) {+ const resultMap = new Map(rows.map(row => [row.variant, row]));+ const allVariants = [...variants];++ for (const row of rows) {+ if (!allVariants.includes(row.variant)) {+ allVariants.push(row.variant);+ }+ }++ const controlVariant = getControlVariant(allVariants, rows);+ const controlRow = controlVariant ? resultMap.get(controlVariant) : undefined;+ const controlRate = controlRow && controlRow.sessions > 0 ? controlRow.conversions / controlRow.sessions : null;++ return allVariants.map(variant => {+ const row = resultMap.get(variant);+ const sessions = row?.sessions ?? 0;+ const exposures = row?.exposures ?? 0;+ const conversions = row?.conversions ?? 0;+ const conversionRate = sessions > 0 ? conversions / sessions : 0;+ const lift = controlRate && controlRate > 0 ? (conversionRate - controlRate) / controlRate : null;++ return {+ variant,+ sessions,+ exposures,+ conversions,+ conversionRate,+ lift,+ isControl: variant === controlVariant,+ };+ });+}diff --git a/server/src/api/featureFlags/index.ts b/server/src/api/featureFlags/index.tsnew file mode 100644index 000000000..a53f576da--- /dev/null+++ b/server/src/api/featureFlags/index.ts@@ -0,0 +1,343 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { and, eq } from "drizzle-orm";+import SqlString from "sqlstring";+import { UAParser as userAgentParser } from "ua-parser-js";+import { z } from "zod";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { getLocation } from "../../db/geolocation/geolocation.js";+import { db } from "../../db/postgres/postgres.js";+import { featureFlags, userProfiles } from "../../db/postgres/schema.js";+import { siteConfig } from "../../lib/siteConfig.js";+import { getRequestUserAgent } from "../../services/tracker/requestIdentity.js";+import { processResults } from "../analytics/utils/utils.js";+import { getDeviceType, getIpAddress } from "../../utils.js";+import { evaluateFeatureFlagsForSite } from "../../services/featureFlags/evaluator.js";+import {+ evaluateFeatureFlagsSchema,+ featureFlagBodySchema,+ featureFlagUpdateSchema,+ type EvaluateFeatureFlagsBody,+ type FeatureFlagBody,+ type FeatureFlagUpdateBody,+} from "./schemas.js";++type FeatureFlagStatsRow = {+ flag_key: string;+ flag_value: string;+ sessions: number;+ events: number;+ exposures: number;+};++function parseSiteId(siteIdParam: string, reply: FastifyReply): number | null {+ const siteId = parseInt(siteIdParam, 10);+ if (isNaN(siteId) || siteId <= 0) {+ reply.status(400).send({ error: "Invalid site ID" });+ return null;+ }+ return siteId;+}++function getDuplicateKeyMessage(error: unknown) {+ if (typeof error === "object" && error !== null && "code" in error && error.code === "23505") {+ return "A feature flag with this key already exists";+ }+ return null;+}++async function getFeatureFlagStats(siteId: number, keys: string[]) {+ if (keys.length === 0) return {};++ const escapedKeys = keys.map(key => SqlString.escape(key)).join(", ");++ try {+ const result = await clickhouse.query({+ query: `+ SELECT+ flag_key,+ flag_value,+ uniq(session_id) AS sessions,+ count() AS events,+ countIf(type = 'custom_event' AND event_name = 'feature_flag_exposure') AS exposures+ FROM (+ SELECT+ session_id,+ type,+ event_name,+ arrayJoin(mapKeys(feature_flags)) AS flag_key,+ feature_flags[flag_key] AS flag_value+ FROM events+ WHERE site_id = ${SqlString.escape(siteId)}+ AND length(mapKeys(feature_flags)) > 0+ )+ WHERE flag_key IN (${escapedKeys})+ GROUP BY flag_key, flag_value+ ORDER BY flag_key ASC, sessions DESC+ `,+ format: "JSONEachRow",+ });++ const rows = await processResults<FeatureFlagStatsRow>(result);+ const stats: Record<string, FeatureFlagStatsRow[]> = {};++ for (const row of rows) {+ stats[row.flag_key] ??= [];+ stats[row.flag_key].push(row);+ }++ return stats;+ } catch {+ return {};+ }+}++export async function getFeatureFlags(+ request: FastifyRequest<{+ Params: { siteId: string };+ }>,+ reply: FastifyReply+) {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const rows = await db.query.featureFlags.findMany({+ where: eq(featureFlags.siteId, siteId),+ orderBy: (table, { asc }) => [asc(table.key)],+ });++ const stats = await getFeatureFlagStats(+ siteId,+ rows.map(flag => flag.key)+ );++ return reply.send({+ data: rows.map(flag => ({+ ...flag,+ stats: stats[flag.key] ?? [],+ })),+ });+}++export async function createFeatureFlag(+ request: FastifyRequest<{+ Params: { siteId: string };+ Body: FeatureFlagBody;+ }>,+ reply: FastifyReply+) {+ try {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const body = featureFlagBodySchema.parse(request.body);++ const [created] = await db+ .insert(featureFlags)+ .values({+ siteId,+ key: body.key,+ description: body.description || null,+ enabled: body.enabled,+ runtime: body.runtime,+ flagType: body.flagType,+ payload: body.payload,+ variants: body.variants,+ rolloutPercentage: body.rolloutPercentage,+ rules: body.rules,+ conditionSets: body.conditionSets,+ })+ .returning();++ return reply.status(201).send({ success: true, data: created });+ } catch (error) {+ const duplicateMessage = getDuplicateKeyMessage(error);+ if (duplicateMessage) {+ return reply.status(409).send({ error: duplicateMessage });+ }+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to create feature flag" });+ }+}++export async function updateFeatureFlag(+ request: FastifyRequest<{+ Params: { siteId: string; flagId: string };+ Body: FeatureFlagUpdateBody;+ }>,+ reply: FastifyReply+) {+ try {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const flagId = parseInt(request.params.flagId, 10);+ if (isNaN(flagId) || flagId <= 0) {+ return reply.status(400).send({ error: "Invalid feature flag ID" });+ }++ const body = featureFlagUpdateSchema.parse(request.body);+ const updateData: Partial<typeof featureFlags.$inferInsert> = {+ ...body,+ description: body.description === undefined ? undefined : body.description || null,+ updatedAt: new Date().toISOString(),+ };++ if (body.key === undefined) delete updateData.key;+ if (body.enabled === undefined) delete updateData.enabled;+ if (body.runtime === undefined) delete updateData.runtime;+ if (body.flagType === undefined) delete updateData.flagType;+ if (body.payload === undefined) delete updateData.payload;+ if (body.variants === undefined) delete updateData.variants;+ if (body.rolloutPercentage === undefined) delete updateData.rolloutPercentage;+ if (body.rules === undefined) delete updateData.rules;+ if (body.conditionSets === undefined) delete updateData.conditionSets;++ updateData.version = (+ await db.query.featureFlags.findFirst({+ columns: { version: true },+ where: and(eq(featureFlags.siteId, siteId), eq(featureFlags.flagId, flagId)),+ })+ )?.version;++ if (updateData.version === undefined) {+ return reply.status(404).send({ error: "Feature flag not found" });+ }+ updateData.version += 1;++ const [updated] = await db+ .update(featureFlags)+ .set(updateData)+ .where(and(eq(featureFlags.siteId, siteId), eq(featureFlags.flagId, flagId)))+ .returning();++ if (!updated) {+ return reply.status(404).send({ error: "Feature flag not found" });+ }++ return reply.send({ success: true, data: updated });+ } catch (error) {+ const duplicateMessage = getDuplicateKeyMessage(error);+ if (duplicateMessage) {+ return reply.status(409).send({ error: duplicateMessage });+ }+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to update feature flag" });+ }+}++export async function deleteFeatureFlag(+ request: FastifyRequest<{+ Params: { siteId: string; flagId: string };+ }>,+ reply: FastifyReply+) {+ const siteId = parseSiteId(request.params.siteId, reply);+ if (!siteId) return;++ const flagId = parseInt(request.params.flagId, 10);+ if (isNaN(flagId) || flagId <= 0) {+ return reply.status(400).send({ error: "Invalid feature flag ID" });+ }++ const [deleted] = await db+ .delete(featureFlags)+ .where(and(eq(featureFlags.siteId, siteId), eq(featureFlags.flagId, flagId)))+ .returning({ flagId: featureFlags.flagId });++ if (!deleted) {+ return reply.status(404).send({ error: "Feature flag not found" });+ }++ return reply.send({ success: true });+}++function parseQuery(querystring?: string) {+ if (!querystring) return {};+ const params = new URLSearchParams(querystring.startsWith("?") ? querystring.slice(1) : querystring);+ return Object.fromEntries(params.entries());+}++export async function evaluateFeatureFlags(+ request: FastifyRequest<{+ Params: { siteId: string };+ Body: EvaluateFeatureFlagsBody;+ }>,+ reply: FastifyReply+) {+ return evaluateFeatureFlagsForRuntime(request, reply, "client");+}++export async function evaluateServerFeatureFlags(+ request: FastifyRequest<{+ Params: { siteId: string };+ Body: EvaluateFeatureFlagsBody;+ }>,+ reply: FastifyReply+) {+ return evaluateFeatureFlagsForRuntime(request, reply, "server");+}++async function evaluateFeatureFlagsForRuntime(+ request: FastifyRequest<{+ Params: { siteId: string };+ Body: EvaluateFeatureFlagsBody;+ }>,+ reply: FastifyReply,+ runtime: "client" | "server"+) {+ try {+ const body = evaluateFeatureFlagsSchema.parse(request.body);+ const site = await siteConfig.getConfig(request.params.siteId);++ if (!site) {+ return reply.status(404).send({ error: "Site not found" });+ }++ const ipAddress = getIpAddress(request);+ const [locationByIp, profile] = await Promise.all([+ getLocation([ipAddress]).catch(() => ({}) as Awaited<ReturnType<typeof getLocation>>),+ body.identifiedUserId+ ? db.query.userProfiles.findFirst({+ where: and(eq(userProfiles.siteId, site.siteId), eq(userProfiles.userId, body.identifiedUserId)),+ })+ : Promise.resolve(undefined),+ ]);++ const location = locationByIp[ipAddress];+ const ua = userAgentParser(getRequestUserAgent(request));+ const deviceType = getDeviceType(body.screenWidth || 0, body.screenHeight || 0, ua);++ const assignments = await evaluateFeatureFlagsForSite(+ site.siteId,+ {+ anonymousId: body.anonymousId,+ identifiedUserId: body.identifiedUserId,+ hostname: body.hostname,+ pathname: body.pathname,+ query: body.query ?? parseQuery(body.querystring),+ referrer: body.referrer,+ language: body.language,+ country: location?.countryIso,+ region: location?.region ? `${location.countryIso}-${location.region}` : undefined,+ city: location?.city,+ deviceType,+ traits: profile?.traits ?? {},+ },+ { runtime }+ );++ return reply.send({+ flags: assignments,+ generatedAt: new Date().toISOString(),+ });+ } catch (error) {+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ return reply.status(500).send({ error: "Failed to evaluate feature flags" });+ }+}diff --git a/server/src/api/featureFlags/schemas.test.ts b/server/src/api/featureFlags/schemas.test.tsnew file mode 100644index 000000000..b75763457--- /dev/null+++ b/server/src/api/featureFlags/schemas.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { featureFlagBodySchema } from "./schemas.js";++const baseFlag = {+ key: "new_checkout",+ enabled: true,+ runtime: "client",+ flagType: "boolean",+ rolloutPercentage: 100,+};++describe("feature flag schemas", () => {+ it("accepts safe regex targeting rules", () => {+ const result = featureFlagBodySchema.safeParse({+ ...baseFlag,+ rules: [{ field: "pathname", operator: "regex", value: "^/pricing(/|$)" }],+ });++ expect(result.success).toBe(true);+ });++ it("rejects unsafe regex targeting rules", () => {+ const result = featureFlagBodySchema.safeParse({+ ...baseFlag,+ rules: [{ field: "pathname", operator: "regex", value: "(a+)+$" }],+ });++ expect(result.success).toBe(false);+ });+});diff --git a/server/src/api/featureFlags/schemas.ts b/server/src/api/featureFlags/schemas.tsnew file mode 100644index 000000000..650ec0a56--- /dev/null+++ b/server/src/api/featureFlags/schemas.ts@@ -0,0 +1,278 @@+import { z } from "zod";+import type { FeatureFlagPayloadValue } from "../../db/postgres/schema.js";+import { precompileFeatureFlagRegexPattern, validateFeatureFlagRegexPattern } from "../../services/featureFlags/regex.js";++const payloadValueSchema: z.ZodType<FeatureFlagPayloadValue> = z.lazy(() =>+ z.union([+ z.string().max(4096),+ z.number(),+ z.boolean(),+ z.null(),+ z.array(payloadValueSchema).max(100),+ z.record(payloadValueSchema),+ ])+);++const ruleValueSchema = z.union([+ z.string().max(512),+ z.number(),+ z.boolean(),+ z.array(z.union([z.string().max(512), z.number(), z.boolean()])).max(50),+]);++const featureFlagKeySchema = z+ .string()+ .trim()+ .min(1)+ .max(100)+ .regex(/^[A-Za-z][A-Za-z0-9_.:-]*$/, "Key must start with a letter and contain only letters, numbers, _, ., :, or -");++const featureFlagTypeSchema = z.enum(["boolean", "multivariate", "remote_config"]);+const featureFlagRuntimeSchema = z.enum(["client", "server", "both"]);++export const featureFlagRuleSchema = z+ .object({+ field: z.enum([+ "hostname",+ "pathname",+ "query",+ "referrer",+ "language",+ "country",+ "region",+ "city",+ "device_type",+ "user_id",+ "trait",+ ]),+ key: z.string().trim().min(1).max(128).optional(),+ operator: z.enum(["equals", "not_equals", "contains", "starts_with", "ends_with", "regex"]),+ value: ruleValueSchema,+ })+ .superRefine((rule, ctx) => {+ if (rule.operator !== "regex") return;++ const values = Array.isArray(rule.value) ? rule.value : [rule.value];+ values.forEach((value, index) => {+ const path = Array.isArray(rule.value) ? ["value", index] : ["value"];++ if (typeof value !== "string") {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Regex rule values must be strings",+ path,+ });+ return;+ }++ const error = validateFeatureFlagRegexPattern(value);+ if (error) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: error,+ path,+ });+ return;+ }++ precompileFeatureFlagRegexPattern(value);+ });+ })+ .refine(+ rule => {+ if (rule.field === "query" || rule.field === "trait") {+ return !!rule.key;+ }+ return true;+ },+ {+ message: "key is required for query and trait rules",+ path: ["key"],+ }+ );++const featureFlagVariantSchema = z.object({+ key: z+ .string()+ .trim()+ .min(1)+ .max(100)+ .regex(+ /^[A-Za-z][A-Za-z0-9_.:-]*$/,+ "Variant key must start with a letter and contain only letters, numbers, _, ., :, or -"+ ),+ name: z.string().trim().max(120).optional(),+ rolloutPercentage: z.number().int().min(0).max(100),+ payload: payloadValueSchema.optional(),+});++const featureFlagConditionSetSchema = z.object({+ name: z.string().trim().max(120).optional(),+ rules: z.array(featureFlagRuleSchema).max(25).default([]),+ rolloutPercentage: z.number().int().min(0).max(100).optional(),+ variants: z.array(featureFlagVariantSchema).max(20).optional(),+ payload: payloadValueSchema.optional().nullable(),+});++const featureFlagBaseSchema = z.object({+ key: featureFlagKeySchema,+ description: z.string().trim().max(1000).optional().nullable(),+ enabled: z.boolean().default(false),+ runtime: featureFlagRuntimeSchema.default("client"),+ flagType: featureFlagTypeSchema.default("boolean"),+ payload: payloadValueSchema.optional().nullable(),+ variants: z.array(featureFlagVariantSchema).max(20).default([]),+ rolloutPercentage: z.number().int().min(0).max(100).default(100),+ rules: z.array(featureFlagRuleSchema).max(25).default([]),+ conditionSets: z.array(featureFlagConditionSetSchema).max(20).default([]),+});++const featureFlagUpdateBaseSchema = z.object({+ key: featureFlagKeySchema.optional(),+ description: z.string().trim().max(1000).optional().nullable(),+ enabled: z.boolean().optional(),+ runtime: featureFlagRuntimeSchema.optional(),+ flagType: featureFlagTypeSchema.optional(),+ payload: payloadValueSchema.optional().nullable(),+ variants: z.array(featureFlagVariantSchema).max(20).optional(),+ rolloutPercentage: z.number().int().min(0).max(100).optional(),+ rules: z.array(featureFlagRuleSchema).max(25).optional(),+ conditionSets: z.array(featureFlagConditionSetSchema).max(20).optional(),+});++export const featureFlagBodySchema = featureFlagBaseSchema.superRefine(validateFeatureFlagShape);++export const featureFlagUpdateSchema = featureFlagUpdateBaseSchema+ .refine(data => Object.keys(data).length > 0, {+ message: "At least one field must be provided",+ })+ .superRefine(validateFeatureFlagShape);++export const evaluateFeatureFlagsSchema = z.object({+ anonymousId: z.string().trim().min(1).max(128),+ identifiedUserId: z.string().trim().max(255).optional(),+ hostname: z.string().max(253).optional(),+ pathname: z.string().max(2048).optional(),+ querystring: z.string().max(2048).optional(),+ query: z.record(z.string().max(2048)).optional(),+ referrer: z.string().max(2048).optional(),+ language: z.string().max(35).optional(),+ screenWidth: z.number().int().nonnegative().optional(),+ screenHeight: z.number().int().nonnegative().optional(),+});++export type FeatureFlagBody = z.infer<typeof featureFlagBodySchema>;+export type FeatureFlagUpdateBody = z.infer<typeof featureFlagUpdateSchema>;+export type EvaluateFeatureFlagsBody = z.infer<typeof evaluateFeatureFlagsSchema>;++function validateFeatureFlagShape(+ data: z.infer<typeof featureFlagBaseSchema> | z.infer<typeof featureFlagUpdateBaseSchema>,+ ctx: z.RefinementCtx+) {+ const variants = data.variants ?? [];+ const conditionSets = data.conditionSets ?? [];+ const flagType = data.flagType;++ if (flagType === "remote_config" && variants.length > 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Remote config flags cannot have variants",+ path: ["variants"],+ });+ }++ if (flagType === "boolean" && variants.length > 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Boolean flags cannot have variants",+ path: ["variants"],+ });+ }++ if (flagType === "multivariate") {+ const hasConditionSetVariants = conditionSets.some(conditionSet => (conditionSet.variants?.length ?? 0) > 0);++ if (!hasConditionSetVariants && variants.length < 2) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Multivariate flags require at least two variants",+ path: ["variants"],+ });+ }++ const uniqueKeys = new Set(variants.map(variant => variant.key));+ if (uniqueKeys.size !== variants.length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Variant keys must be unique",+ path: ["variants"],+ });+ }++ const totalRollout = variants.reduce((sum, variant) => sum + variant.rolloutPercentage, 0);+ if (totalRollout > 100) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Variant rollout percentages cannot exceed 100",+ path: ["variants"],+ });+ }+ }++ conditionSets.forEach((conditionSet, index) => {+ const setVariants = conditionSet.variants ?? [];+ const path = ["conditionSets", index];++ if (flagType === "boolean" && setVariants.length > 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Boolean condition sets cannot have variants",+ path: [...path, "variants"],+ });+ }++ if (flagType === "remote_config" && setVariants.length > 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Remote config condition sets cannot have variants",+ path: [...path, "variants"],+ });+ }++ if (flagType === "multivariate" && setVariants.length > 0) {+ if (setVariants.length < 2) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Multivariate condition sets require at least two variants",+ path: [...path, "variants"],+ });+ }++ const uniqueSetKeys = new Set(setVariants.map(variant => variant.key));+ if (uniqueSetKeys.size !== setVariants.length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Variant keys must be unique",+ path: [...path, "variants"],+ });+ }++ const setTotalRollout = setVariants.reduce((sum, variant) => sum + variant.rolloutPercentage, 0);+ if (setTotalRollout > 100) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Variant rollout percentages cannot exceed 100",+ path: [...path, "variants"],+ });+ }+ }++ if (conditionSet.rolloutPercentage !== undefined && flagType === "multivariate" && setVariants.length > 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Multivariate condition sets use variant rollout percentages",+ path: [...path, "rolloutPercentage"],+ });+ }+ });+}diff --git a/server/src/db/clickhouse/clickhouse.ts b/server/src/db/clickhouse/clickhouse.tsindex 106d7cf1d..b703da206 100644--- a/server/src/db/clickhouse/clickhouse.ts+++ b/server/src/db/clickhouse/clickhouse.ts@@ -81,6 +81,14 @@ export const initializeClickhouse = async () => {`);+ await execClickhouseInitStep(+ "add feature flag assignments to events table",+ `+ ALTER TABLE events+ ADD COLUMN IF NOT EXISTS feature_flags Map(String, String) DEFAULT map()+ `+ );+await execClickhouseInitStep("create bot events table",`diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 674e7518e..3f99457f7 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -324,6 +324,114 @@ export const goals = pgTable(]);+export type FeatureFlagType = "boolean" | "multivariate" | "remote_config";+export type FeatureFlagRuntime = "client" | "server" | "both";+export type ExperimentStatus = "draft" | "running" | "paused" | "completed";++export type FeatureFlagPayloadValue =+ | string+ | number+ | boolean+ | null+ | FeatureFlagPayloadValue[]+ | { [key: string]: FeatureFlagPayloadValue };++export type FeatureFlagRule = {+ field:+ | "hostname"+ | "pathname"+ | "query"+ | "referrer"+ | "language"+ | "country"+ | "region"+ | "city"+ | "device_type"+ | "user_id"+ | "trait";+ key?: string;+ operator: "equals" | "not_equals" | "contains" | "starts_with" | "ends_with" | "regex";+ value: string | number | boolean | Array<string | number | boolean>;+};++export type FeatureFlagVariant = {+ key: string;+ name?: string;+ rolloutPercentage: number;+ payload?: FeatureFlagPayloadValue;+};++export type FeatureFlagConditionSet = {+ name?: string;+ rules: FeatureFlagRule[];+ rolloutPercentage?: number;+ variants?: FeatureFlagVariant[];+ payload?: FeatureFlagPayloadValue;+};++export const featureFlags = pgTable(+ "feature_flags",+ {+ flagId: serial("flag_id").primaryKey().notNull(),+ siteId: integer("site_id")+ .notNull()+ .references(() => sites.siteId, { onDelete: "cascade" }),+ key: text("key").notNull(),+ description: text("description"),+ enabled: boolean("enabled").default(false).notNull(),+ runtime: text("runtime").default("client").notNull().$type<FeatureFlagRuntime>(),+ flagType: text("flag_type").default("boolean").notNull().$type<FeatureFlagType>(),+ payload: jsonb("payload").$type<FeatureFlagPayloadValue>(),+ variants: jsonb("variants").default([]).notNull().$type<FeatureFlagVariant[]>(),+ rolloutPercentage: integer("rollout_percentage").default(100).notNull(),+ rules: jsonb("rules").default([]).notNull().$type<FeatureFlagRule[]>(),+ conditionSets: jsonb("condition_sets").default([]).notNull().$type<FeatureFlagConditionSet[]>(),+ salt: text("salt")+ .default(sql`md5(random()::text || clock_timestamp()::text)`)+ .notNull(),+ version: integer("version").default(1).notNull(),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow().notNull(),+ },+ table => [+ unique("feature_flags_site_key_unique").on(table.siteId, table.key),+ index("feature_flags_site_idx").on(table.siteId),+ check("feature_flags_rollout_check", sql`rollout_percentage >= 0 AND rollout_percentage <= 100`),+ check("feature_flags_runtime_check", sql`runtime IN ('client', 'server', 'both')`),+ check("feature_flags_type_check", sql`flag_type IN ('boolean', 'multivariate', 'remote_config')`),+ ]+);++export const experiments = pgTable(+ "experiments",+ {+ experimentId: serial("experiment_id").primaryKey().notNull(),+ siteId: integer("site_id")+ .notNull()+ .references(() => sites.siteId, { onDelete: "cascade" }),+ featureFlagId: integer("feature_flag_id")+ .notNull()+ .references(() => featureFlags.flagId, { onDelete: "cascade" }),+ primaryGoalId: integer("primary_goal_id").references(() => goals.goalId, { onDelete: "set null" }),+ name: text("name").notNull(),+ description: text("description"),+ hypothesis: text("hypothesis"),+ status: text("status").default("draft").notNull().$type<ExperimentStatus>(),+ winningVariant: text("winning_variant"),+ startedAt: timestamp("started_at", { mode: "string" }),+ endedAt: timestamp("ended_at", { mode: "string" }),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow().notNull(),+ },+ table => [+ unique("experiments_site_flag_unique").on(table.siteId, table.featureFlagId),+ index("experiments_site_idx").on(table.siteId),+ index("experiments_feature_flag_idx").on(table.featureFlagId),+ index("experiments_primary_goal_idx").on(table.primaryGoalId),+ check("experiments_status_check", sql`status IN ('draft', 'running', 'paused', 'completed')`),+ ]+);+// Telemetry table for tracking self-hosted instancesexport const telemetry = pgTable("telemetry", {id: serial("id").primaryKey().notNull(),diff --git a/server/src/index.ts b/server/src/index.tsindex 062072bbf..37095a89c 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -60,6 +60,21 @@ import {updateGoal,} from "./api/analytics/index.js";import { getConfig, getVersion } from "./api/getConfig.js";+import {+ createExperiment,+ deleteExperiment,+ getExperimentResults,+ getExperiments,+ updateExperiment,+} from "./api/experiments/index.js";+import {+ createFeatureFlag,+ deleteFeatureFlag,+ evaluateFeatureFlags,+ evaluateServerFeatureFlags,+ getFeatureFlags,+ updateFeatureFlag,+} from "./api/featureFlags/index.js";import {connectGSC,disconnectGSC,@@ -276,6 +291,17 @@ async function analyticsRoutes(fastify: FastifyInstance) {fastify.post("/sites/:siteId/goals", authSite, createGoal);fastify.delete("/sites/:siteId/goals/:goalId", authSite, deleteGoal);fastify.put("/sites/:siteId/goals/:goalId", authSite, updateGoal);+ fastify.get("/sites/:siteId/feature-flags", authSite, getFeatureFlags);+ fastify.post("/sites/:siteId/feature-flags", adminSite, createFeatureFlag);+ fastify.put("/sites/:siteId/feature-flags/:flagId", adminSite, updateFeatureFlag);+ fastify.delete("/sites/:siteId/feature-flags/:flagId", adminSite, deleteFeatureFlag);+ fastify.post("/sites/:siteId/feature-flags/evaluate", authSite, evaluateServerFeatureFlags);+ fastify.post("/site/:siteId/feature-flags/evaluate", evaluateFeatureFlags);+ fastify.get("/sites/:siteId/experiments", authSite, getExperiments);+ fastify.post("/sites/:siteId/experiments", adminSite, createExperiment);+ fastify.put("/sites/:siteId/experiments/:experimentId", adminSite, updateExperiment);+ fastify.delete("/sites/:siteId/experiments/:experimentId", adminSite, deleteExperiment);+ fastify.get("/sites/:siteId/experiments/:experimentId/results", authSite, getExperimentResults);fastify.get("/sites/:siteId/events/names", publicSite, getEventNames);fastify.get("/sites/:siteId/events/properties", publicSite, getEventProperties);fastify.get("/sites/:siteId/events/outbound", publicSite, getOutboundLinks);diff --git a/server/src/services/featureFlags/evaluator.test.ts b/server/src/services/featureFlags/evaluator.test.tsnew file mode 100644index 000000000..4ab78bbb6--- /dev/null+++ b/server/src/services/featureFlags/evaluator.test.ts@@ -0,0 +1,212 @@+import { describe, expect, it } from "vitest";+import { bucketPercentage, evaluateFeatureFlag, matchesFeatureFlagRule } from "./evaluator.js";+import { precompileFeatureFlagRegexPattern } from "./regex.js";++const baseFlag = {+ flagId: 1,+ siteId: 10,+ key: "new_checkout",+ description: null,+ enabled: true,+ runtime: "client",+ flagType: "boolean",+ payload: null,+ variants: [],+ rolloutPercentage: 100,+ rules: [],+ conditionSets: [],+ salt: "salt",+ version: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+} as any;++describe("feature flag evaluator", () => {+ it("matches targeting rules against request context", () => {+ expect(+ matchesFeatureFlagRule(+ { field: "pathname", operator: "starts_with", value: "/pricing" },+ { anonymousId: "visitor-1", pathname: "/pricing/pro" }+ )+ ).toBe(true);++ expect(+ matchesFeatureFlagRule(+ { field: "query", key: "plan", operator: "equals", value: ["pro", "team"] },+ { anonymousId: "visitor-1", query: { plan: "team" } }+ )+ ).toBe(true);+ });++ it("matches regex rules using precompiled patterns", () => {+ const pattern = "^/pricing(/|$)";+ precompileFeatureFlagRegexPattern(pattern);++ expect(+ matchesFeatureFlagRule(+ { field: "pathname", operator: "regex", value: pattern },+ { anonymousId: "visitor-1", pathname: "/pricing/pro" }+ )+ ).toBe(true);+ });++ it("returns off value when disabled or targeting fails", () => {+ expect(evaluateFeatureFlag({ ...baseFlag, enabled: false }, { anonymousId: "visitor-1" })).toMatchObject({+ value: false,+ reason: "disabled",+ matched: false,+ });++ expect(+ evaluateFeatureFlag(+ { ...baseFlag, rules: [{ field: "country", operator: "equals", value: "US" }] },+ { anonymousId: "visitor-1", country: "GB" }+ )+ ).toMatchObject({+ value: false,+ reason: "target_mismatch",+ matched: false,+ });+ });++ it("applies rollout after targeting matches", () => {+ expect(evaluateFeatureFlag({ ...baseFlag, rolloutPercentage: 100 }, { anonymousId: "visitor-1" })).toMatchObject({+ value: true,+ payload: null,+ reason: "rollout",+ matched: true,+ });++ expect(evaluateFeatureFlag({ ...baseFlag, rolloutPercentage: 0 }, { anonymousId: "visitor-1" })).toMatchObject({+ value: false,+ reason: "fallthrough",+ matched: false,+ });+ });++ it("uses the first matching condition set", () => {+ expect(+ evaluateFeatureFlag(+ {+ ...baseFlag,+ conditionSets: [+ {+ name: "us beta",+ rules: [{ field: "country", operator: "equals", value: "US" }],+ rolloutPercentage: 0,+ },+ {+ name: "all traffic",+ rules: [],+ rolloutPercentage: 100,+ payload: { copy: "fallback" },+ },+ ],+ },+ { anonymousId: "visitor-1", country: "GB" }+ )+ ).toMatchObject({+ value: true,+ payload: { copy: "fallback" },+ conditionSet: "all traffic",+ reason: "rollout",+ matched: true,+ });+ });++ it("assigns multivariate variants by rollout percentage", () => {+ expect(+ evaluateFeatureFlag(+ {+ ...baseFlag,+ flagType: "multivariate",+ variants: [+ { key: "control", rolloutPercentage: 100, payload: { color: "blue" } },+ { key: "test", rolloutPercentage: 0, payload: { color: "green" } },+ ],+ },+ { anonymousId: "visitor-1" }+ )+ ).toMatchObject({+ value: "control",+ variant: "control",+ payload: { color: "blue" },+ reason: "variant",+ matched: true,+ });+ });++ it("assigns multivariate variants from the first matching condition set", () => {+ expect(+ evaluateFeatureFlag(+ {+ ...baseFlag,+ flagType: "multivariate",+ variants: [],+ conditionSets: [+ {+ name: "wrong country",+ rules: [{ field: "country", operator: "equals", value: "GB" }],+ variants: [+ { key: "gb_control", rolloutPercentage: 100 },+ { key: "gb_test", rolloutPercentage: 0 },+ ],+ },+ {+ name: "us traffic",+ rules: [{ field: "country", operator: "equals", value: "US" }],+ variants: [+ { key: "us_control", rolloutPercentage: 100, payload: { color: "blue" } },+ { key: "us_test", rolloutPercentage: 0, payload: { color: "green" } },+ ],+ },+ ],+ },+ { anonymousId: "visitor-1", country: "US" }+ )+ ).toMatchObject({+ value: "us_control",+ variant: "us_control",+ payload: { color: "blue" },+ conditionSet: "us traffic",+ reason: "variant",+ matched: true,+ });+ });++ it("returns remote config payload from the first matching condition set", () => {+ expect(+ evaluateFeatureFlag(+ {+ ...baseFlag,+ flagType: "remote_config",+ conditionSets: [+ {+ name: "wrong country",+ rules: [{ field: "country", operator: "equals", value: "US" }],+ payload: { checkoutColor: "blue" },+ },+ {+ name: "fallback",+ rules: [],+ payload: { checkoutColor: "green" },+ },+ ],+ },+ { anonymousId: "visitor-1", country: "GB" }+ )+ ).toMatchObject({+ value: true,+ payload: { checkoutColor: "green" },+ conditionSet: "fallback",+ reason: "remote_config",+ matched: true,+ });+ });++ it("uses stable hash buckets", () => {+ expect(bucketPercentage("site:flag:visitor:salt")).toBe(bucketPercentage("site:flag:visitor:salt"));+ expect(bucketPercentage("site:flag:visitor:salt")).toBeGreaterThanOrEqual(0);+ expect(bucketPercentage("site:flag:visitor:salt")).toBeLessThanOrEqual(100);+ });+});diff --git a/server/src/services/featureFlags/evaluator.ts b/server/src/services/featureFlags/evaluator.tsnew file mode 100644index 000000000..b74b4104c--- /dev/null+++ b/server/src/services/featureFlags/evaluator.ts@@ -0,0 +1,298 @@+import { createHash } from "node:crypto";+import { asc, eq } from "drizzle-orm";+import { db } from "../../db/postgres/postgres.js";+import {+ featureFlags,+ type FeatureFlagConditionSet,+ type FeatureFlagRule,+ type FeatureFlagRuntime,+ type FeatureFlagType,+ type FeatureFlagVariant,+} from "../../db/postgres/schema.js";+import {+ getCompiledFeatureFlagRegex,+ precompileFeatureFlagConditionSetRegexes,+ precompileFeatureFlagRuleRegexes,+} from "./regex.js";++export type FeatureFlagContext = {+ anonymousId: string;+ identifiedUserId?: string;+ hostname?: string;+ pathname?: string;+ query?: Record<string, string>;+ referrer?: string;+ language?: string;+ country?: string;+ region?: string;+ city?: string;+ deviceType?: string;+ traits?: Record<string, unknown>;+};++export type FeatureFlagAssignment = {+ key: string;+ value: unknown;+ flagType: FeatureFlagType;+ payload?: unknown;+ variant?: string;+ conditionSet?: string;+ version: number;+ reason: "disabled" | "target_mismatch" | "rollout" | "variant" | "remote_config" | "fallthrough";+ matched: boolean;+ rolloutPercentage: number;+};++type FeatureFlagRow = typeof featureFlags.$inferSelect;++function normalizeComparableValue(value: unknown): string {+ if (value === null || value === undefined) return "";+ return String(value);+}++function getContextValue(rule: FeatureFlagRule, context: FeatureFlagContext): unknown {+ switch (rule.field) {+ case "hostname":+ return context.hostname;+ case "pathname":+ return context.pathname;+ case "query":+ return rule.key ? context.query?.[rule.key] : undefined;+ case "referrer":+ return context.referrer;+ case "language":+ return context.language;+ case "country":+ return context.country;+ case "region":+ return context.region;+ case "city":+ return context.city;+ case "device_type":+ return context.deviceType;+ case "user_id":+ return context.identifiedUserId || context.anonymousId;+ case "trait":+ return rule.key ? context.traits?.[rule.key] : undefined;+ }+}++export function bucketPercentage(seed: string): number {+ const hash = createHash("sha256").update(seed).digest("hex");+ const bucket = parseInt(hash.slice(0, 8), 16) / 0xffffffff;+ return bucket * 100;+}++export function matchesFeatureFlagRule(rule: FeatureFlagRule, context: FeatureFlagContext): boolean {+ const actual = normalizeComparableValue(getContextValue(rule, context));+ const expectedValues = Array.isArray(rule.value) ? rule.value : [rule.value];+ const expected = expectedValues.map(normalizeComparableValue);++ switch (rule.operator) {+ case "equals":+ return expected.some(value => actual === value);+ case "not_equals":+ return expected.every(value => actual !== value);+ case "contains":+ return expected.some(value => actual.includes(value));+ case "starts_with":+ return expected.some(value => actual.startsWith(value));+ case "ends_with":+ return expected.some(value => actual.endsWith(value));+ case "regex":+ return expectedValues.some(value => {+ if (typeof value !== "string") return false;+ return getCompiledFeatureFlagRegex(value)?.test(actual) ?? false;+ });+ }+}++function clampPercentage(value: number | undefined, fallback = 100): number {+ return Math.min(100, Math.max(0, value ?? fallback));+}++function getConditionSets(flag: FeatureFlagRow): FeatureFlagConditionSet[] {+ if (Array.isArray(flag.conditionSets) && flag.conditionSets.length > 0) {+ return flag.conditionSets;+ }++ return [+ {+ rules: Array.isArray(flag.rules) ? flag.rules : [],+ rolloutPercentage: flag.rolloutPercentage,+ variants: Array.isArray(flag.variants) ? flag.variants : [],+ payload: flag.payload,+ },+ ];+}++function getConditionSetName(conditionSet: FeatureFlagConditionSet, index: number) {+ return conditionSet.name || `condition_${index + 1}`;+}++function matchesConditionSet(conditionSet: FeatureFlagConditionSet, context: FeatureFlagContext): boolean {+ const rules = Array.isArray(conditionSet.rules) ? conditionSet.rules : [];+ return rules.every(rule => matchesFeatureFlagRule(rule, context));+}++function selectVariant(variants: FeatureFlagVariant[], bucket: number) {+ let cumulativeRollout = 0;++ for (const variant of variants) {+ cumulativeRollout += clampPercentage(variant.rolloutPercentage, 0);+ if (bucket < cumulativeRollout) {+ return {+ variant,+ totalRollout: Math.min(100, cumulativeRollout),+ };+ }+ }++ return {+ variant: undefined,+ totalRollout: Math.min(+ 100,+ variants.reduce((sum, variant) => sum + clampPercentage(variant.rolloutPercentage, 0), 0)+ ),+ };+}++function runtimeMatches(flagRuntime: FeatureFlagRuntime, runtime?: FeatureFlagRuntime) {+ if (!runtime) return true;+ if (flagRuntime === "both") return true;+ return flagRuntime === runtime;+}++function getPayload(conditionSet: FeatureFlagConditionSet, flag: FeatureFlagRow) {+ return conditionSet.payload !== undefined ? conditionSet.payload : flag.payload;+}++export function evaluateFeatureFlag(flag: FeatureFlagRow, context: FeatureFlagContext): FeatureFlagAssignment {+ const rolloutPercentage = clampPercentage(flag.rolloutPercentage);+ precompileFeatureFlagRuleRegexes(flag.rules);+ precompileFeatureFlagConditionSetRegexes(flag.conditionSets);++ if (!flag.enabled) {+ return {+ key: flag.key,+ value: false,+ flagType: flag.flagType,+ version: flag.version,+ reason: "disabled",+ matched: false,+ rolloutPercentage,+ };+ }++ const bucket = bucketPercentage(`${flag.siteId}:${flag.key}:${context.anonymousId}:${flag.salt}`);+ const conditionSets = getConditionSets(flag);++ for (let index = 0; index < conditionSets.length; index++) {+ const conditionSet = conditionSets[index];+ if (!matchesConditionSet(conditionSet, context)) {+ continue;+ }++ const conditionSetName = getConditionSetName(conditionSet, index);++ if (flag.flagType === "remote_config") {+ return {+ key: flag.key,+ value: true,+ flagType: flag.flagType,+ payload: getPayload(conditionSet, flag),+ conditionSet: conditionSetName,+ version: flag.version,+ reason: "remote_config",+ matched: true,+ rolloutPercentage: 100,+ };+ }++ if (flag.flagType === "multivariate") {+ const variants =+ Array.isArray(conditionSet.variants) && conditionSet.variants.length > 0+ ? conditionSet.variants+ : Array.isArray(flag.variants)+ ? flag.variants+ : [];+ const selected = selectVariant(variants, bucket);++ if (selected.variant) {+ return {+ key: flag.key,+ value: selected.variant.key,+ flagType: flag.flagType,+ variant: selected.variant.key,+ payload: selected.variant.payload,+ conditionSet: conditionSetName,+ version: flag.version,+ reason: "variant",+ matched: true,+ rolloutPercentage: selected.variant.rolloutPercentage,+ };+ }++ return {+ key: flag.key,+ value: false,+ flagType: flag.flagType,+ conditionSet: conditionSetName,+ version: flag.version,+ reason: "fallthrough",+ matched: false,+ rolloutPercentage: selected.totalRollout,+ };+ }++ const conditionRolloutPercentage = clampPercentage(conditionSet.rolloutPercentage, rolloutPercentage);+ const inRollout =+ conditionRolloutPercentage >= 100 || (conditionRolloutPercentage > 0 && bucket < conditionRolloutPercentage);++ return {+ key: flag.key,+ value: inRollout,+ flagType: flag.flagType,+ payload: inRollout ? getPayload(conditionSet, flag) : undefined,+ conditionSet: conditionSetName,+ version: flag.version,+ reason: inRollout ? "rollout" : "fallthrough",+ matched: inRollout,+ rolloutPercentage: conditionRolloutPercentage,+ };+ }++ return {+ key: flag.key,+ value: false,+ flagType: flag.flagType,+ version: flag.version,+ reason: "target_mismatch",+ matched: false,+ rolloutPercentage,+ };+}++export async function evaluateFeatureFlagsForSite(+ siteId: number,+ context: FeatureFlagContext,+ options: { runtime?: FeatureFlagRuntime } = {}+): Promise<Record<string, FeatureFlagAssignment>> {+ const rows = await db+ .select()+ .from(featureFlags)+ .where(eq(featureFlags.siteId, siteId))+ .orderBy(asc(featureFlags.key));++ const assignments: Record<string, FeatureFlagAssignment> = {};++ for (const flag of rows) {+ if (!runtimeMatches(flag.runtime, options.runtime)) {+ continue;+ }++ assignments[flag.key] = evaluateFeatureFlag(flag, context);+ }++ return assignments;+}diff --git a/server/src/services/featureFlags/regex.ts b/server/src/services/featureFlags/regex.tsnew file mode 100644index 000000000..596d96caf--- /dev/null+++ b/server/src/services/featureFlags/regex.ts@@ -0,0 +1,87 @@+import safeRegex from "safe-regex2";+import type { FeatureFlagConditionSet, FeatureFlagRule } from "../../db/postgres/schema.js";++const MAX_REGEX_PATTERN_LENGTH = 256;+const MAX_REGEX_REPETITIONS = 25;+const MAX_REGEX_CACHE_SIZE = 1000;++const compiledRegexCache = new Map<string, RegExp>();+const invalidRegexCache = new Set<string>();++export function validateFeatureFlagRegexPattern(pattern: string): string | null {+ if (!pattern) {+ return "Regex pattern cannot be empty";+ }++ if (pattern.length > MAX_REGEX_PATTERN_LENGTH) {+ return `Regex pattern cannot exceed ${MAX_REGEX_PATTERN_LENGTH} characters`;+ }++ try {+ new RegExp(pattern);+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ return `Invalid regex pattern: ${message}`;+ }++ if (!safeRegex(pattern, { limit: MAX_REGEX_REPETITIONS })) {+ return "Regex pattern is too complex";+ }++ return null;+}++export function precompileFeatureFlagRegexPattern(pattern: string): RegExp | undefined {+ const cached = compiledRegexCache.get(pattern);+ if (cached) {+ return cached;+ }++ if (invalidRegexCache.has(pattern)) {+ return undefined;+ }++ if (validateFeatureFlagRegexPattern(pattern)) {+ invalidRegexCache.add(pattern);+ return undefined;+ }++ const compiled = new RegExp(pattern);++ if (compiledRegexCache.size >= MAX_REGEX_CACHE_SIZE) {+ const firstKey = compiledRegexCache.keys().next().value;+ if (firstKey) {+ compiledRegexCache.delete(firstKey);+ }+ }++ compiledRegexCache.set(pattern, compiled);+ return compiled;+}++export function getCompiledFeatureFlagRegex(pattern: string): RegExp | undefined {+ return compiledRegexCache.get(pattern);+}++export function precompileFeatureFlagRuleRegexes(rules: FeatureFlagRule[] | undefined): void {+ if (!Array.isArray(rules)) return;++ for (const rule of rules) {+ if (rule.operator !== "regex") continue;++ const values = Array.isArray(rule.value) ? rule.value : [rule.value];+ for (const value of values) {+ if (typeof value === "string") {+ precompileFeatureFlagRegexPattern(value);+ }+ }+ }+}++export function precompileFeatureFlagConditionSetRegexes(conditionSets: FeatureFlagConditionSet[] | undefined): void {+ if (!Array.isArray(conditionSets)) return;++ for (const conditionSet of conditionSets) {+ precompileFeatureFlagRuleRegexes(conditionSet.rules);+ }+}diff --git a/server/src/services/tracker/pageviewQueue.ts b/server/src/services/tracker/pageviewQueue.tsindex 1498d9f1a..5444f4b5b 100644--- a/server/src/services/tracker/pageviewQueue.ts+++ b/server/src/services/tracker/pageviewQueue.ts@@ -105,6 +105,7 @@ class PageviewQueue {ip: pv.storeIp ? pv.ipAddress : null,timezone: timezone,tag: pv.tag || "",+ feature_flags: pv.feature_flags || {},import_id: null,};});diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex 14113c0ba..100fe688f 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -25,6 +25,7 @@ const baseEventFields = {referrer: z.string().max(2048).optional(),user_id: z.string().max(255).optional(),tag: z.string().max(256).optional(),+ feature_flags: z.record(z.string().max(100), z.string().max(2048)).optional(),ip_address: z.string().ip().optional(),user_agent: z.string().max(512).optional(),_bs: z.number().int().min(0).max(10).optional(),diff --git a/server/src/services/tracker/types.ts b/server/src/services/tracker/types.tsindex 6e8f70cf3..64ee5d6b3 100644--- a/server/src/services/tracker/types.ts+++ b/server/src/services/tracker/types.ts@@ -10,4 +10,5 @@ export interface TrackingPayload {page_title: string;referrer: string;tag?: string;+ feature_flags?: Record<string, string>;}diff --git a/server/src/services/tracker/utils.ts b/server/src/services/tracker/utils.tsindex b480fbdfd..caf5ccda3 100644--- a/server/src/services/tracker/utils.ts+++ b/server/src/services/tracker/utils.ts@@ -25,6 +25,7 @@ export type TotalTrackingPayload = TrackingPayload & {fcp?: number;ttfb?: number;tag?: string;+ feature_flags?: Record<string, string>;};// Infer type from Zod schemadiff --git a/shared/src/filters.ts b/shared/src/filters.tsindex 680a8e7ee..ad606e7c9 100644--- a/shared/src/filters.ts+++ b/shared/src/filters.ts@@ -43,7 +43,8 @@ export type FilterParameter =| "lat"| "lon"| "timezone"- | "tag";+ | "tag"+ | `feature_flag:${string}`;export interface Filter {parameter: FilterParameter;