🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor Rybbit Analytics Script for improved readability and performance by minifying code and consolidating functions. Maintain existing functionality for tracking page views and outbound links.
Bill Yangec42ec133180
diff --git a/.prettierignore b/.prettierignorenew file mode 100644index 000000000..75e397a62--- /dev/null+++ b/.prettierignore@@ -0,0 +1,2 @@+# So minified script is not formatted+**/script.js\ No newline at end of filediff --git a/server/public/script-full.js b/server/public/script-full.jsnew file mode 100644index 000000000..d39014b73--- /dev/null+++ b/server/public/script-full.js@@ -0,0 +1,211 @@+// Rybbit Analytics Script+(function () {+ const scriptTag = document.currentScript;+ const ANALYTICS_HOST = scriptTag.getAttribute("src").split("/script.js")[0];++ if (!ANALYTICS_HOST) {+ console.error("Please provide a valid analytics host");+ return;+ }++ const SITE_ID =+ scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");++ if (!SITE_ID || isNaN(Number(SITE_ID))) {+ console.error(+ "Please provide a valid site ID using the data-site-id attribute"+ );+ return;+ }++ const debounceDuration = scriptTag.getAttribute("data-debounce")+ ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")))+ : 500;++ const autoTrackSpa = scriptTag.getAttribute("data-track-spa") !== "false";+ const trackQuerystring =+ scriptTag.getAttribute("data-track-query") !== "false";+ const trackOutbound =+ scriptTag.getAttribute("data-track-outbound") !== "false";++ let skipPatterns = [];+ try {+ const skipAttr = scriptTag.getAttribute("data-skip-patterns");+ if (skipAttr) {+ skipPatterns = JSON.parse(skipAttr);+ if (!Array.isArray(skipPatterns)) skipPatterns = [];+ }+ } catch (e) {+ console.error("Error parsing data-skip-patterns:", e);+ }++ let maskPatterns = [];+ try {+ const maskAttr = scriptTag.getAttribute("data-mask-patterns");+ if (maskAttr) {+ maskPatterns = JSON.parse(maskAttr);+ if (!Array.isArray(maskPatterns)) maskPatterns = [];+ }+ } catch (e) {+ console.error("Error parsing data-mask-patterns:", e);+ }++ // Helper function to convert wildcard pattern to regex+ function patternToRegex(pattern) {+ // Use a safer approach by replacing wildcards with unique tokens first+ const DOUBLE_WILDCARD_TOKEN = "__DOUBLE_ASTERISK_TOKEN__";+ const SINGLE_WILDCARD_TOKEN = "__SINGLE_ASTERISK_TOKEN__";++ // Replace wildcards with tokens+ let tokenized = pattern+ .replace(/\*\*/g, DOUBLE_WILDCARD_TOKEN)+ .replace(/\*/g, SINGLE_WILDCARD_TOKEN);++ // Escape special regex characters+ let escaped = tokenized.replace(/[.+?^${}()|[\]\\]/g, "\\$&");++ // Escape forward slashes+ escaped = escaped.replace(/\//g, "\\/");++ // Replace tokens with appropriate regex patterns+ let regexPattern = escaped+ .replace(new RegExp(DOUBLE_WILDCARD_TOKEN, "g"), ".*")+ .replace(new RegExp(SINGLE_WILDCARD_TOKEN, "g"), "[^/]+");++ return new RegExp("^" + regexPattern + "$");+ }++ function findMatchingPattern(path, patterns) {+ for (const pattern of patterns) {+ try {+ const regex = patternToRegex(pattern);+ if (regex.test(path)) {+ return pattern; // Return the pattern string itself+ }+ } catch (e) {+ console.error(`Invalid pattern: ${pattern}`, e);+ }+ }+ return null;+ }++ function debounce(func, wait) {+ let timeout;+ return (...args) => {+ clearTimeout(timeout);+ timeout = setTimeout(() => func.apply(this, args), wait);+ };+ }++ // Check if a URL is an outbound link+ function isOutboundLink(url) {+ try {+ const currentHost = window.location.hostname;+ const linkHost = new URL(url).hostname;+ return linkHost !== currentHost && linkHost !== "";+ } catch (e) {+ return false;+ }+ }++ const track = (eventType = "pageview", eventName = "", properties = {}) => {+ if (+ eventType === "custom_event" &&+ (!eventName || typeof eventName !== "string")+ ) {+ console.error(+ "Event name is required and must be a string for custom events"+ );+ return;+ }++ const url = new URL(window.location.href);+ let pathname = url.pathname;++ if (findMatchingPattern(pathname, skipPatterns)) {+ return;+ }++ const maskMatch = findMatchingPattern(pathname, maskPatterns);+ if (maskMatch) {+ pathname = maskMatch;+ }++ const payload = {+ site_id: SITE_ID,+ hostname: url.hostname,+ pathname: pathname,+ querystring: trackQuerystring ? url.search : "",+ screenWidth: window.innerWidth,+ screenHeight: window.innerHeight,+ language: navigator.language,+ page_title: document.title,+ referrer: document.referrer,+ type: eventType,+ event_name: eventName,+ properties:+ eventType === "custom_event" || eventType === "outbound"+ ? JSON.stringify(properties)+ : undefined,+ };++ fetch(`${ANALYTICS_HOST}/track`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(payload),+ mode: "cors",+ keepalive: true,+ }).catch(console.error);+ };++ const trackPageview = () => track("pageview");++ const debouncedTrackPageview =+ debounceDuration > 0+ ? debounce(trackPageview, debounceDuration)+ : trackPageview;++ // Track outbound link clicks+ if (trackOutbound) {+ document.addEventListener("click", function (e) {+ const link = e.target.closest("a");+ if (!link || !link.href) return;++ if (isOutboundLink(link.href)) {+ track("outbound", "", {+ url: link.href,+ text: link.innerText || link.textContent || "",+ target: link.target || "_self",+ });+ }+ });+ }++ if (autoTrackSpa) {+ const originalPushState = history.pushState;+ const originalReplaceState = history.replaceState;++ history.pushState = function (...args) {+ originalPushState.apply(this, args);+ debouncedTrackPageview();+ };++ history.replaceState = function (...args) {+ originalReplaceState.apply(this, args);+ debouncedTrackPageview();+ };++ window.addEventListener("popstate", debouncedTrackPageview);+ }++ window.rybbit = {+ pageview: trackPageview,+ event: (name, properties = {}) => track("custom_event", name, properties),+ trackOutbound: (url, text = "", target = "_self") =>+ track("outbound", "", { url, text, target }),+ };++ trackPageview();+})();diff --git a/server/public/script.js b/server/public/script.jsindex d39014b73..7c2b73179 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1,211 +1 @@-// Rybbit Analytics Script-(function () {- const scriptTag = document.currentScript;- const ANALYTICS_HOST = scriptTag.getAttribute("src").split("/script.js")[0];-- if (!ANALYTICS_HOST) {- console.error("Please provide a valid analytics host");- return;- }-- const SITE_ID =- scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");-- if (!SITE_ID || isNaN(Number(SITE_ID))) {- console.error(- "Please provide a valid site ID using the data-site-id attribute"- );- return;- }-- const debounceDuration = scriptTag.getAttribute("data-debounce")- ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")))- : 500;-- const autoTrackSpa = scriptTag.getAttribute("data-track-spa") !== "false";- const trackQuerystring =- scriptTag.getAttribute("data-track-query") !== "false";- const trackOutbound =- scriptTag.getAttribute("data-track-outbound") !== "false";-- let skipPatterns = [];- try {- const skipAttr = scriptTag.getAttribute("data-skip-patterns");- if (skipAttr) {- skipPatterns = JSON.parse(skipAttr);- if (!Array.isArray(skipPatterns)) skipPatterns = [];- }- } catch (e) {- console.error("Error parsing data-skip-patterns:", e);- }-- let maskPatterns = [];- try {- const maskAttr = scriptTag.getAttribute("data-mask-patterns");- if (maskAttr) {- maskPatterns = JSON.parse(maskAttr);- if (!Array.isArray(maskPatterns)) maskPatterns = [];- }- } catch (e) {- console.error("Error parsing data-mask-patterns:", e);- }-- // Helper function to convert wildcard pattern to regex- function patternToRegex(pattern) {- // Use a safer approach by replacing wildcards with unique tokens first- const DOUBLE_WILDCARD_TOKEN = "__DOUBLE_ASTERISK_TOKEN__";- const SINGLE_WILDCARD_TOKEN = "__SINGLE_ASTERISK_TOKEN__";-- // Replace wildcards with tokens- let tokenized = pattern- .replace(/\*\*/g, DOUBLE_WILDCARD_TOKEN)- .replace(/\*/g, SINGLE_WILDCARD_TOKEN);-- // Escape special regex characters- let escaped = tokenized.replace(/[.+?^${}()|[\]\\]/g, "\\$&");-- // Escape forward slashes- escaped = escaped.replace(/\//g, "\\/");-- // Replace tokens with appropriate regex patterns- let regexPattern = escaped- .replace(new RegExp(DOUBLE_WILDCARD_TOKEN, "g"), ".*")- .replace(new RegExp(SINGLE_WILDCARD_TOKEN, "g"), "[^/]+");-- return new RegExp("^" + regexPattern + "$");- }-- function findMatchingPattern(path, patterns) {- for (const pattern of patterns) {- try {- const regex = patternToRegex(pattern);- if (regex.test(path)) {- return pattern; // Return the pattern string itself- }- } catch (e) {- console.error(`Invalid pattern: ${pattern}`, e);- }- }- return null;- }-- function debounce(func, wait) {- let timeout;- return (...args) => {- clearTimeout(timeout);- timeout = setTimeout(() => func.apply(this, args), wait);- };- }-- // Check if a URL is an outbound link- function isOutboundLink(url) {- try {- const currentHost = window.location.hostname;- const linkHost = new URL(url).hostname;- return linkHost !== currentHost && linkHost !== "";- } catch (e) {- return false;- }- }-- const track = (eventType = "pageview", eventName = "", properties = {}) => {- if (- eventType === "custom_event" &&- (!eventName || typeof eventName !== "string")- ) {- console.error(- "Event name is required and must be a string for custom events"- );- return;- }-- const url = new URL(window.location.href);- let pathname = url.pathname;-- if (findMatchingPattern(pathname, skipPatterns)) {- return;- }-- const maskMatch = findMatchingPattern(pathname, maskPatterns);- if (maskMatch) {- pathname = maskMatch;- }-- const payload = {- site_id: SITE_ID,- hostname: url.hostname,- pathname: pathname,- querystring: trackQuerystring ? url.search : "",- screenWidth: window.innerWidth,- screenHeight: window.innerHeight,- language: navigator.language,- page_title: document.title,- referrer: document.referrer,- type: eventType,- event_name: eventName,- properties:- eventType === "custom_event" || eventType === "outbound"- ? JSON.stringify(properties)- : undefined,- };-- fetch(`${ANALYTICS_HOST}/track`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(payload),- mode: "cors",- keepalive: true,- }).catch(console.error);- };-- const trackPageview = () => track("pageview");-- const debouncedTrackPageview =- debounceDuration > 0- ? debounce(trackPageview, debounceDuration)- : trackPageview;-- // Track outbound link clicks- if (trackOutbound) {- document.addEventListener("click", function (e) {- const link = e.target.closest("a");- if (!link || !link.href) return;-- if (isOutboundLink(link.href)) {- track("outbound", "", {- url: link.href,- text: link.innerText || link.textContent || "",- target: link.target || "_self",- });- }- });- }-- if (autoTrackSpa) {- const originalPushState = history.pushState;- const originalReplaceState = history.replaceState;-- history.pushState = function (...args) {- originalPushState.apply(this, args);- debouncedTrackPageview();- };-- history.replaceState = function (...args) {- originalReplaceState.apply(this, args);- debouncedTrackPageview();- };-- window.addEventListener("popstate", debouncedTrackPageview);- }-- window.rybbit = {- pageview: trackPageview,- event: (name, properties = {}) => track("custom_event", name, properties),- trackOutbound: (url, text = "", target = "_self") =>- track("outbound", "", { url, text, target }),- };-- trackPageview();-})();+!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(!e){console.error("Please provide a valid analytics host");return}let r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r))){console.error("Please provide a valid site ID using the data-site-id attribute");return}let a=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,n="false"!==t.getAttribute("data-track-spa"),i="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound"),o=[];try{let u=t.getAttribute("data-skip-patterns");u&&(o=JSON.parse(u),Array.isArray(o)||(o=[]))}catch(l){console.error("Error parsing data-skip-patterns:",l)}let c=[];try{let p=t.getAttribute("data-mask-patterns");p&&(c=JSON.parse(p),Array.isArray(c)||(c=[]))}catch(d){console.error("Error parsing data-mask-patterns:",d)}function g(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+n+"$")}function f(t,e){for(let r of e)try{let a=g(r);if(a.test(t))return r}catch(n){console.error(`Invalid pattern: ${r}`,n)}return null}let h=(t="pageview",a="",n={})=>{if("custom_event"===t&&(!a||"string"!=typeof a)){console.error("Event name is required and must be a string for custom events");return}let s=new URL(window.location.href),u=s.pathname;if(f(u,o))return;let l=f(u,c);l&&(u=l);let p={site_id:r,hostname:s.hostname,pathname:u,querystring:i?s.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer,type:t,event_name:a,properties:"custom_event"===t||"outbound"===t?JSON.stringify(n):void 0};fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),mode:"cors",keepalive:!0}).catch(console.error)},b=()=>h("pageview"),v=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(b,a):b;if(s&&document.addEventListener("click",function(t){let e=t.target.closest("a");e&&e.href&&function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(n){return!1}}(e.href)&&h("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}),n){let y=history.pushState,m=history.replaceState;history.pushState=function(...t){y.apply(this,t),v()},history.replaceState=function(...t){m.apply(this,t),v()},window.addEventListener("popstate",v)}window.rybbit={pageview:b,event:(t,e={})=>h("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>h("outbound","",{url:t,text:e,target:r})},b()}();\ No newline at end of file