Skip to content

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

build script (#410)

Bill Yang34cb820a18d5
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index b505e2962..2b587f0c2 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -3,7 +3,16 @@
"allow": [
"Bash(mkdir:*)",
"Bash(grep:*)",
- "Bash(npm install)"
+ "Bash(npm install)",
+ "Bash(npm install:*)",
+ "Bash(npm run build:analytics:*)",
+ "Bash(ls:*)",
+ "Bash(npm test:*)",
+ "Bash(node:*)",
+ "Bash(rm:*)",
+ "Bash(tsc --noEmit)",
+ "Bash(npx tsc:*)",
+ "Bash(npm run build:*)"
]
},
"enableAllProjectMcpServers": false
diff --git a/server/package-lock.json b/server/package-lock.json
index 429324ac1..c35fbbed6 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -31,15 +31,19 @@
"stripe": "18.1.0",
"ua-parser-js": "2.0.3",
"undici": "7.9.0",
+ "web-vitals": "^5.0.3",
"zod": "3.24.4"
},
"devDependencies": {
+ "@types/jsdom": "^21.1.7",
"@types/luxon": "3.6.2",
"@types/node": "^20.14.8",
"@types/pg": "8.15.1",
"@types/psl": "^1.1.3",
"@types/sqlstring": "2.3.2",
"drizzle-kit": "0.31.1",
+ "esbuild": "^0.25.5",
+ "jsdom": "^26.1.0",
"knip": "^5.60.2",
"terser": "^5.40.0",
"typescript": "^5.8.3",
@@ -55,6 +59,25 @@
"typescript": "^5.3.3"
}
},
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
+ "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
+ "dev": true,
+ "dependencies": {
+ "@csstools/css-calc": "^2.1.3",
+ "@csstools/css-color-parser": "^3.0.9",
+ "@csstools/css-parser-algorithms": "^3.0.4",
+ "@csstools/css-tokenizer": "^3.0.3",
+ "lru-cache": "^10.4.3"
+ }
+ },
+ "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true
+ },
"node_modules/@better-auth/utils": {
"version": "0.2.4",
"resolved": "https://registry.npmjs.org/@better-auth/utils/-/utils-0.2.4.tgz",
@@ -88,6 +111,116 @@
"integrity": "sha512-bme0le2yhDSAh13d2fxhSW5ZrNoVqZ3LTyac8jK6hNH0qkksXnjYkLS6KQalPU6NMpffxHmpI4+/Gi2MnX0NCA==",
"license": "Apache-2.0"
},
+ "node_modules/@csstools/color-helpers": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.0.2.tgz",
+ "integrity": "sha512-JqWH1vsgdGcw2RR6VliXXdA0/59LttzlU8UlRT/iUUsEeWfYq8I+K0yhihEUTTHLRm1EXvpsCx3083EU15ecsA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
+ "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "3.0.10",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.0.10.tgz",
+ "integrity": "sha512-TiJ5Ajr6WRd1r8HSiwJvZBiJOqtH86aHpUjq5aEKWHiII2Qfjqd/HCWKPOW8EP4vcspXbHnXrwIDlu5savQipg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "dependencies": {
+ "@csstools/color-helpers": "^5.0.2",
+ "@csstools/css-calc": "^2.1.4"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^3.0.5",
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
+ "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^3.0.4"
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
+ "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@drizzle-team/brocli": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@drizzle-team/brocli/-/brocli-0.10.2.tgz",
@@ -563,14 +696,13 @@
}
},
"node_modules/@esbuild/aix-ppc64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.4.tgz",
- "integrity": "sha512-1VCICWypeQKhVbE9oW/sJaAmjLxhVqacdkvPLEjwlttjfwENRSClS8EjBz0KzRyFSCPDIkuXW34Je/vk7zdB7Q==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz",
+ "integrity": "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA==",
"cpu": [
"ppc64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"aix"
@@ -580,14 +712,13 @@
}
},
"node_modules/@esbuild/android-arm": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.4.tgz",
- "integrity": "sha512-QNdQEps7DfFwE3hXiU4BZeOV68HHzYwGd0Nthhd3uCkkEKK7/R6MTgM0P7H7FAs5pU/DIWsviMmEGxEoxIZ+ZQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.5.tgz",
+ "integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==",
"cpu": [
"arm"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"android"
@@ -597,14 +728,13 @@
}
},
"node_modules/@esbuild/android-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.4.tgz",
- "integrity": "sha512-bBy69pgfhMGtCnwpC/x5QhfxAz/cBgQ9enbtwjf6V9lnPI/hMyT9iWpR1arm0l3kttTr4L0KSLpKmLp/ilKS9A==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz",
+ "integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"android"
@@ -614,14 +744,13 @@
}
},
"node_modules/@esbuild/android-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.4.tgz",
- "integrity": "sha512-TVhdVtQIFuVpIIR282btcGC2oGQoSfZfmBdTip2anCaVYcqWlZXGcdcKIUklfX2wj0JklNYgz39OBqh2cqXvcQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.5.tgz",
+ "integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"android"
@@ -631,14 +760,13 @@
}
},
"node_modules/@esbuild/darwin-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.4.tgz",
- "integrity": "sha512-Y1giCfM4nlHDWEfSckMzeWNdQS31BQGs9/rouw6Ub91tkK79aIMTH3q9xHvzH8d0wDru5Ci0kWB8b3up/nl16g==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz",
+ "integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"darwin"
@@ -648,14 +776,13 @@
}
},
"node_modules/@esbuild/darwin-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.4.tgz",
- "integrity": "sha512-CJsry8ZGM5VFVeyUYB3cdKpd/H69PYez4eJh1W/t38vzutdjEjtP7hB6eLKBoOdxcAlCtEYHzQ/PJ/oU9I4u0A==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz",
+ "integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"darwin"
@@ -665,14 +792,13 @@
}
},
"node_modules/@esbuild/freebsd-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.4.tgz",
- "integrity": "sha512-yYq+39NlTRzU2XmoPW4l5Ifpl9fqSk0nAJYM/V/WUGPEFfek1epLHJIkTQM6bBs1swApjO5nWgvr843g6TjxuQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz",
+ "integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"freebsd"
@@ -682,14 +808,13 @@
}
},
"node_modules/@esbuild/freebsd-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.4.tgz",
- "integrity": "sha512-0FgvOJ6UUMflsHSPLzdfDnnBBVoCDtBTVyn/MrWloUNvq/5SFmh13l3dvgRPkDihRxb77Y17MbqbCAa2strMQQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz",
+ "integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"freebsd"
@@ -699,14 +824,13 @@
}
},
"node_modules/@esbuild/linux-arm": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.4.tgz",
- "integrity": "sha512-kro4c0P85GMfFYqW4TWOpvmF8rFShbWGnrLqlzp4X1TNWjRY3JMYUfDCtOxPKOIY8B0WC8HN51hGP4I4hz4AaQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz",
+ "integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==",
"cpu": [
"arm"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -716,14 +840,13 @@
}
},
"node_modules/@esbuild/linux-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.4.tgz",
- "integrity": "sha512-+89UsQTfXdmjIvZS6nUnOOLoXnkUTB9hR5QAeLrQdzOSWZvNSAXAtcRDHWtqAUtAmv7ZM1WPOOeSxDzzzMogiQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz",
+ "integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -733,14 +856,13 @@
}
},
"node_modules/@esbuild/linux-ia32": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.4.tgz",
- "integrity": "sha512-yTEjoapy8UP3rv8dB0ip3AfMpRbyhSN3+hY8mo/i4QXFeDxmiYbEKp3ZRjBKcOP862Ua4b1PDfwlvbuwY7hIGQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz",
+ "integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==",
"cpu": [
"ia32"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -750,14 +872,13 @@
}
},
"node_modules/@esbuild/linux-loong64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.4.tgz",
- "integrity": "sha512-NeqqYkrcGzFwi6CGRGNMOjWGGSYOpqwCjS9fvaUlX5s3zwOtn1qwg1s2iE2svBe4Q/YOG1q6875lcAoQK/F4VA==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz",
+ "integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==",
"cpu": [
"loong64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -767,14 +888,13 @@
}
},
"node_modules/@esbuild/linux-mips64el": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.4.tgz",
- "integrity": "sha512-IcvTlF9dtLrfL/M8WgNI/qJYBENP3ekgsHbYUIzEzq5XJzzVEV/fXY9WFPfEEXmu3ck2qJP8LG/p3Q8f7Zc2Xg==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz",
+ "integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==",
"cpu": [
"mips64el"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -784,14 +904,13 @@
}
},
"node_modules/@esbuild/linux-ppc64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.4.tgz",
- "integrity": "sha512-HOy0aLTJTVtoTeGZh4HSXaO6M95qu4k5lJcH4gxv56iaycfz1S8GO/5Jh6X4Y1YiI0h7cRyLi+HixMR+88swag==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz",
+ "integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==",
"cpu": [
"ppc64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -801,14 +920,13 @@
}
},
"node_modules/@esbuild/linux-riscv64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.4.tgz",
- "integrity": "sha512-i8JUDAufpz9jOzo4yIShCTcXzS07vEgWzyX3NH2G7LEFVgrLEhjwL3ajFE4fZI3I4ZgiM7JH3GQ7ReObROvSUA==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz",
+ "integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==",
"cpu": [
"riscv64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -818,14 +936,13 @@
}
},
"node_modules/@esbuild/linux-s390x": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.4.tgz",
- "integrity": "sha512-jFnu+6UbLlzIjPQpWCNh5QtrcNfMLjgIavnwPQAfoGx4q17ocOU9MsQ2QVvFxwQoWpZT8DvTLooTvmOQXkO51g==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz",
+ "integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==",
"cpu": [
"s390x"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -835,14 +952,13 @@
}
},
"node_modules/@esbuild/linux-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.4.tgz",
- "integrity": "sha512-6e0cvXwzOnVWJHq+mskP8DNSrKBr1bULBvnFLpc1KY+d+irZSgZ02TGse5FsafKS5jg2e4pbvK6TPXaF/A6+CA==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz",
+ "integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"linux"
@@ -852,14 +968,13 @@
}
},
"node_modules/@esbuild/netbsd-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.4.tgz",
- "integrity": "sha512-vUnkBYxZW4hL/ie91hSqaSNjulOnYXE1VSLusnvHg2u3jewJBz3YzB9+oCw8DABeVqZGg94t9tyZFoHma8gWZQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.5.tgz",
+ "integrity": "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"netbsd"
@@ -869,14 +984,13 @@
}
},
"node_modules/@esbuild/netbsd-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.4.tgz",
- "integrity": "sha512-XAg8pIQn5CzhOB8odIcAm42QsOfa98SBeKUdo4xa8OvX8LbMZqEtgeWE9P/Wxt7MlG2QqvjGths+nq48TrUiKw==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz",
+ "integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"netbsd"
@@ -886,14 +1000,13 @@
}
},
"node_modules/@esbuild/openbsd-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.4.tgz",
- "integrity": "sha512-Ct2WcFEANlFDtp1nVAXSNBPDxyU+j7+tId//iHXU2f/lN5AmO4zLyhDcpR5Cz1r08mVxzt3Jpyt4PmXQ1O6+7A==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.5.tgz",
+ "integrity": "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"openbsd"
@@ -903,14 +1016,13 @@
}
},
"node_modules/@esbuild/openbsd-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.4.tgz",
- "integrity": "sha512-xAGGhyOQ9Otm1Xu8NT1ifGLnA6M3sJxZ6ixylb+vIUVzvvd6GOALpwQrYrtlPouMqd/vSbgehz6HaVk4+7Afhw==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz",
+ "integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"openbsd"
@@ -920,14 +1032,13 @@
}
},
"node_modules/@esbuild/sunos-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.4.tgz",
- "integrity": "sha512-Mw+tzy4pp6wZEK0+Lwr76pWLjrtjmJyUB23tHKqEDP74R3q95luY/bXqXZeYl4NYlvwOqoRKlInQialgCKy67Q==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz",
+ "integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"sunos"
@@ -937,14 +1048,13 @@
}
},
"node_modules/@esbuild/win32-arm64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.4.tgz",
- "integrity": "sha512-AVUP428VQTSddguz9dO9ngb+E5aScyg7nOeJDrF1HPYu555gmza3bDGMPhmVXL8svDSoqPCsCPjb265yG/kLKQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz",
+ "integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==",
"cpu": [
"arm64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"win32"
@@ -954,14 +1064,13 @@
}
},
"node_modules/@esbuild/win32-ia32": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.4.tgz",
- "integrity": "sha512-i1sW+1i+oWvQzSgfRcxxG2k4I9n3O9NRqy8U+uugaT2Dy7kLO9Y7wI72haOahxceMX8hZAzgGou1FhndRldxRg==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz",
+ "integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==",
"cpu": [
"ia32"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"win32"
@@ -971,14 +1080,13 @@
}
},
"node_modules/@esbuild/win32-x64": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.4.tgz",
- "integrity": "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz",
+ "integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==",
"cpu": [
"x64"
],
"dev": true,
- "license": "MIT",
"optional": true,
"os": [
"win32"
@@ -1948,6 +2056,17 @@
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
"dev": true
},
+ "node_modules/@types/jsdom": {
+ "version": "21.1.7",
+ "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.7.tgz",
+ "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*",
+ "@types/tough-cookie": "*",
+ "parse5": "^7.0.0"
+ }
+ },
"node_modules/@types/luxon": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.6.2.tgz",
@@ -1998,6 +2117,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/tough-cookie": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz",
+ "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
+ "dev": true
+ },
"node_modules/@vitest/expect": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.2.tgz",
@@ -2124,6 +2249,15 @@
"node": ">=0.4.0"
}
},
+ "node_modules/agent-base": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz",
+ "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==",
+ "dev": true,
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/ajv": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
@@ -2448,6 +2582,66 @@
"node": ">= 8"
}
},
+ "node_modules/cssstyle": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.4.0.tgz",
+ "integrity": "sha512-W0Y2HOXlPkb2yaKrCVRjinYKciu/qSLEmK0K9mcfDei3zwlnHFEHAs/Du3cIRwPqY+J4JsiBzUjoHyc8RsJ03A==",
+ "dev": true,
+ "dependencies": {
+ "@asamuzakjp/css-color": "^3.2.0",
+ "rrweb-cssom": "^0.8.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/data-urls": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
+ "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
+ "dev": true,
+ "dependencies": {
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/data-urls/node_modules/tr46": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+ "dev": true,
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/data-urls/node_modules/webidl-conversions": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+ "dev": true,
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/data-urls/node_modules/whatwg-url": {
+ "version": "14.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+ "dev": true,
+ "dependencies": {
+ "tr46": "^5.1.0",
+ "webidl-conversions": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/dateformat": {
"version": "4.6.3",
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
@@ -2475,6 +2669,12 @@
}
}
},
+ "node_modules/decimal.js": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.5.0.tgz",
+ "integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==",
+ "dev": true
+ },
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
@@ -2843,12 +3043,11 @@
}
},
"node_modules/esbuild": {
- "version": "0.25.4",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.4.tgz",
- "integrity": "sha512-8pgjLUcUjcgDg+2Q4NYXnPbo/vncAY4UmyaCm0jZevERqCHZIaWwdJHkf8XQtu4AxSKCdvrUbT0XUr1IdZzI8Q==",
+ "version": "0.25.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.5.tgz",
+ "integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==",
"dev": true,
"hasInstallScript": true,
- "license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
@@ -2856,31 +3055,31 @@
"node": ">=18"
},
"optionalDependencies": {
- "@esbuild/aix-ppc64": "0.25.4",
- "@esbuild/android-arm": "0.25.4",
- "@esbuild/android-arm64": "0.25.4",
- "@esbuild/android-x64": "0.25.4",
- "@esbuild/darwin-arm64": "0.25.4",
- "@esbuild/darwin-x64": "0.25.4",
- "@esbuild/freebsd-arm64": "0.25.4",
- "@esbuild/freebsd-x64": "0.25.4",
- "@esbuild/linux-arm": "0.25.4",
- "@esbuild/linux-arm64": "0.25.4",
- "@esbuild/linux-ia32": "0.25.4",
- "@esbuild/linux-loong64": "0.25.4",
- "@esbuild/linux-mips64el": "0.25.4",
- "@esbuild/linux-ppc64": "0.25.4",
- "@esbuild/linux-riscv64": "0.25.4",
- "@esbuild/linux-s390x": "0.25.4",
- "@esbuild/linux-x64": "0.25.4",
- "@esbuild/netbsd-arm64": "0.25.4",
- "@esbuild/netbsd-x64": "0.25.4",
- "@esbuild/openbsd-arm64": "0.25.4",
- "@esbuild/openbsd-x64": "0.25.4",
- "@esbuild/sunos-x64": "0.25.4",
- "@esbuild/win32-arm64": "0.25.4",
- "@esbuild/win32-ia32": "0.25.4",
- "@esbuild/win32-x64": "0.25.4"
+ "@esbuild/aix-ppc64": "0.25.5",
+ "@esbuild/android-arm": "0.25.5",
+ "@esbuild/android-arm64": "0.25.5",
+ "@esbuild/android-x64": "0.25.5",
+ "@esbuild/darwin-arm64": "0.25.5",
+ "@esbuild/darwin-x64": "0.25.5",
+ "@esbuild/freebsd-arm64": "0.25.5",
+ "@esbuild/freebsd-x64": "0.25.5",
+ "@esbuild/linux-arm": "0.25.5",
+ "@esbuild/linux-arm64": "0.25.5",
+ "@esbuild/linux-ia32": "0.25.5",
+ "@esbuild/linux-loong64": "0.25.5",
+ "@esbuild/linux-mips64el": "0.25.5",
+ "@esbuild/linux-ppc64": "0.25.5",
+ "@esbuild/linux-riscv64": "0.25.5",
+ "@esbuild/linux-s390x": "0.25.5",
+ "@esbuild/linux-x64": "0.25.5",
+ "@esbuild/netbsd-arm64": "0.25.5",
+ "@esbuild/netbsd-x64": "0.25.5",
+ "@esbuild/openbsd-arm64": "0.25.5",
+ "@esbuild/openbsd-x64": "0.25.5",
+ "@esbuild/sunos-x64": "0.25.5",
+ "@esbuild/win32-arm64": "0.25.5",
+ "@esbuild/win32-ia32": "0.25.5",
+ "@esbuild/win32-x64": "0.25.5"
}
},
"node_modules/esbuild-register": {
@@ -3329,6 +3528,18 @@
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
"license": "MIT"
},
+ "node_modules/html-encoding-sniffer": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
+ "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
+ "dev": true,
+ "dependencies": {
+ "whatwg-encoding": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/html-to-text": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",
@@ -3378,6 +3589,44 @@
"node": ">= 0.8"
}
},
+ "node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "dev": true,
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "dev": true,
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dev": true,
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -3432,6 +3681,12 @@
"node": ">=0.12.0"
}
},
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true
+ },
"node_modules/is-standalone-pwa": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/is-standalone-pwa/-/is-standalone-pwa-0.1.1.tgz",
@@ -3520,6 +3775,79 @@
"js-yaml": "bin/js-yaml.js"
}
},
+ "node_modules/jsdom": {
+ "version": "26.1.0",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
+ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
+ "dev": true,
+ "dependencies": {
+ "cssstyle": "^4.2.1",
+ "data-urls": "^5.0.0",
+ "decimal.js": "^10.5.0",
+ "html-encoding-sniffer": "^4.0.0",
+ "http-proxy-agent": "^7.0.2",
+ "https-proxy-agent": "^7.0.6",
+ "is-potential-custom-element-name": "^1.0.1",
+ "nwsapi": "^2.2.16",
+ "parse5": "^7.2.1",
+ "rrweb-cssom": "^0.8.0",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^5.1.1",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^7.0.0",
+ "whatwg-encoding": "^3.1.1",
+ "whatwg-mimetype": "^4.0.0",
+ "whatwg-url": "^14.1.1",
+ "ws": "^8.18.0",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/jsdom/node_modules/tr46": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+ "dev": true,
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/jsdom/node_modules/webidl-conversions": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+ "dev": true,
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/jsdom/node_modules/whatwg-url": {
+ "version": "14.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+ "dev": true,
+ "dependencies": {
+ "tr46": "^5.1.0",
+ "webidl-conversions": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/json-schema-ref-resolver": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-2.0.1.tgz",
@@ -3902,6 +4230,12 @@
}
}
},
+ "node_modules/nwsapi": {
+ "version": "2.2.20",
+ "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
+ "integrity": "sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA==",
+ "dev": true
+ },
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -3969,6 +4303,30 @@
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0"
},
+ "node_modules/parse5": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
+ "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
+ "dev": true,
+ "dependencies": {
+ "entities": "^6.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5/node_modules/entities": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
+ "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/parseley": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",
@@ -4645,6 +5003,12 @@
"integrity": "sha512-OXMmJ3zRk2xeXFGfA3K+EOPHC5u7RDFG7lIOx0X1pdnhUkI8MdVrbV+sNsD80ElpUZ+MRHdyxPnFthq9VHs8uQ==",
"license": "MIT"
},
+ "node_modules/rrweb-cssom": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
+ "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
+ "dev": true
+ },
"node_modules/run-parallel": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
@@ -4716,6 +5080,24 @@
"node": ">=10"
}
},
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true
+ },
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
"node_modules/scheduler": {
"version": "0.26.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz",
@@ -5102,6 +5484,12 @@
}
}
},
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true
+ },
"node_modules/terser": {
"version": "5.40.0",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.40.0.tgz",
@@ -5208,6 +5596,24 @@
"node": ">=14.0.0"
}
},
+ "node_modules/tldts": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
+ "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
+ "dev": true,
+ "dependencies": {
+ "tldts-core": "^6.1.86"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "6.1.86",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
+ "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
+ "dev": true
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -5238,6 +5644,18 @@
"node": ">=0.6"
}
},
+ "node_modules/tough-cookie": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
+ "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
+ "dev": true,
+ "dependencies": {
+ "tldts": "^6.1.32"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
@@ -5540,6 +5958,18 @@
}
}
},
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/walk-up-path": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-4.0.0.tgz",
@@ -5549,12 +5979,38 @@
"node": "20 || >=22"
}
},
+ "node_modules/web-vitals": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.0.3.tgz",
+ "integrity": "sha512-4KmOFYxj7qT6RAdCH0SWwq8eKeXNhAFXR4PmgF6nrWFmrJ41n7lq3UCA6UK0GebQ4uu+XP8e8zGjaDO3wZlqTg=="
+ },
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
+ "node_modules/whatwg-encoding": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
+ "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
+ "dev": true,
+ "dependencies": {
+ "iconv-lite": "0.6.3"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
+ "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
+ "dev": true,
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -5693,6 +6149,42 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
+ "node_modules/ws": {
+ "version": "8.18.2",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
+ "integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true
+ },
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
diff --git a/server/package.json b/server/package.json
index 424d7b90c..1067d71be 100644
--- a/server/package.json
+++ b/server/package.json
@@ -5,9 +5,9 @@
"main": "dist/index.js",
"type": "module",
"scripts": {
- "pack-script": "sh -c 'if [ public/script-full.js -nt public/script.js ]; then terser --compress --mangle < public/script-full.js | tr -d \"\\n\" > public/script.js; else echo \"script.js up to date\"; fi'",
"dev": "tsc && node dist/index.js",
- "build": "tsc && npm run pack-script",
+ "build": "tsc && npm run build:analytics",
+ "build:analytics": "cd src/analytics-script && node build.js",
"start": "node dist/index.js",
"test": "vitest",
"test:run": "vitest run",
@@ -44,15 +44,19 @@
"stripe": "18.1.0",
"ua-parser-js": "2.0.3",
"undici": "7.9.0",
+ "web-vitals": "^5.0.3",
"zod": "3.24.4"
},
"devDependencies": {
+ "@types/jsdom": "^21.1.7",
"@types/luxon": "3.6.2",
"@types/node": "^20.14.8",
"@types/pg": "8.15.1",
"@types/psl": "^1.1.3",
"@types/sqlstring": "2.3.2",
"drizzle-kit": "0.31.1",
+ "esbuild": "^0.25.5",
+ "jsdom": "^26.1.0",
"knip": "^5.60.2",
"terser": "^5.40.0",
"typescript": "^5.8.3",
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 450216fac..54df072c0 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -1,450 +1,611 @@
-// Rybbit Analytics Script
-// NOTE: script.js is generated via `npm run pack-script` from the `server` directory
-(function () {
- const scriptTag = document.currentScript;
- const ANALYTICS_HOST = scriptTag.getAttribute("src").split("/script.js")[0];
+"use strict";
+(() => {
+ var __defProp = Object.defineProperty;
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
- // Check if the user has opted out of tracking
- if (
- !!window.__RYBBIT_OPTOUT__ ||
- localStorage.getItem("disable-rybbit") !== null
- ) {
- // Create a no-op implementation to ensure the API still works
- window.rybbit = {
- pageview: () => {},
- event: () => {},
- trackOutbound: () => {},
- identify: () => {},
- clearUserId: () => {},
- getUserId: () => null,
- };
- return;
- }
-
- 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 autoTrackPageview =
- scriptTag.getAttribute("data-auto-track-pageview") !== "false";
- const autoTrackSpa = scriptTag.getAttribute("data-track-spa") !== "false";
- const trackQuerystring =
- scriptTag.getAttribute("data-track-query") !== "false";
- const trackOutbound =
- scriptTag.getAttribute("data-track-outbound") !== "false";
- // only true temporarily to test web vitals
- const enableWebVitals = true;
- // const enableWebVitals = scriptTag.getAttribute("data-web-vitals") === "true";
-
- // Load Web Vitals library dynamically from CDN
- const loadWebVitals = () => {
- return new Promise((resolve, reject) => {
- const script = document.createElement("script");
- script.src = "https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js";
- script.onload = () => resolve();
- script.onerror = () =>
- reject(new Error("Failed to load web-vitals library"));
- document.head.appendChild(script);
- });
- };
-
- // Initialize web vitals loading only if enabled
- if (enableWebVitals) {
- loadWebVitals()
- .then(() => {
- initWebVitals();
- })
- .catch((e) => {
- console.warn("Failed to load web vitals library:", e);
- });
- }
-
- 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);
- }
-
- // Add user ID management
- let customUserId = null;
-
- // Load stored user ID from localStorage on script initialization
- try {
- const storedUserId = localStorage.getItem("rybbit-user-id");
- if (storedUserId) {
- customUserId = storedUserId;
- }
- } catch (e) {
- // localStorage not available, ignore
- }
-
- // Helper function to convert wildcard pattern to regex
+ // utils.ts
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 tokenized = pattern.replace(/\*\*/g, DOUBLE_WILDCARD_TOKEN).replace(/\*/g, SINGLE_WILDCARD_TOKEN);
let escaped = tokenized.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
-
- // Escape forward slashes
+ escaped = escaped.replace(new RegExp(`/${DOUBLE_WILDCARD_TOKEN}/`, "g"), "/(?:.+/)?");
+ escaped = escaped.replace(new RegExp(DOUBLE_WILDCARD_TOKEN, "g"), ".*");
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"), "[^/]+");
-
+ let regexPattern = escaped.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
+ return pattern;
}
- } catch (e) {
- console.error(`Invalid pattern: ${pattern}`, e);
+ } catch (e2) {
+ console.error(`Invalid pattern: ${pattern}`, e2);
}
}
return null;
}
-
function debounce(func, wait) {
- let timeout;
+ let timeout = null;
return (...args) => {
- clearTimeout(timeout);
- timeout = setTimeout(() => func.apply(this, args), wait);
+ if (timeout) {
+ clearTimeout(timeout);
+ }
+ timeout = setTimeout(() => func(...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) {
+ } catch (e2) {
return false;
}
}
-
- // Helper function to create base payload with pattern matching
- const createBasePayload = () => {
- const url = new URL(window.location.href);
- let pathname = url.pathname;
-
- // Always handle hash-based SPA routing
- if (url.hash && url.hash.startsWith("#/")) {
- // For #/path format, replace pathname with just /path
- pathname = url.hash.substring(1);
+ function parseJsonSafely(value, fallback) {
+ if (!value) return fallback;
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(fallback) && !Array.isArray(parsed) ? fallback : parsed;
+ } catch (e2) {
+ console.error("Error parsing JSON:", e2);
+ return fallback;
}
+ }
- // Check skip patterns
- if (findMatchingPattern(pathname, skipPatterns)) {
- return null; // Indicates tracking should be skipped
+ // config.ts
+ function parseScriptConfig(scriptTag) {
+ const src = scriptTag.getAttribute("src");
+ if (!src) {
+ console.error("Script src attribute is missing");
+ return null;
}
-
- // Apply mask patterns
- const maskMatch = findMatchingPattern(pathname, maskPatterns);
- if (maskMatch) {
- pathname = maskMatch;
+ const analyticsHost = src.split("/script.js")[0];
+ if (!analyticsHost) {
+ console.error("Please provide a valid analytics host");
+ return null;
}
-
- 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,
+ const siteId = scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");
+ if (!siteId || isNaN(Number(siteId))) {
+ console.error("Please provide a valid site ID using the data-site-id attribute");
+ return null;
+ }
+ const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;
+ const skipPatterns = parseJsonSafely(
+ scriptTag.getAttribute("data-skip-patterns"),
+ []
+ );
+ const maskPatterns = parseJsonSafely(
+ scriptTag.getAttribute("data-mask-patterns"),
+ []
+ );
+ return {
+ analyticsHost,
+ siteId,
+ debounceDuration,
+ autoTrackPageview: scriptTag.getAttribute("data-auto-track-pageview") !== "false",
+ autoTrackSpa: scriptTag.getAttribute("data-track-spa") !== "false",
+ trackQuerystring: scriptTag.getAttribute("data-track-query") !== "false",
+ trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",
+ enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",
+ skipPatterns,
+ maskPatterns
};
+ }
- // Add custom user ID only if it's set
- if (customUserId) {
- payload.user_id = customUserId;
+ // tracking.ts
+ var Tracker = class {
+ constructor(config) {
+ this.customUserId = null;
+ this.config = config;
+ this.loadUserId();
+ }
+ loadUserId() {
+ try {
+ const storedUserId = localStorage.getItem("rybbit-user-id");
+ if (storedUserId) {
+ this.customUserId = storedUserId;
+ }
+ } catch (e2) {
+ }
+ }
+ createBasePayload() {
+ const url = new URL(window.location.href);
+ let pathname = url.pathname;
+ if (url.hash && url.hash.startsWith("#/")) {
+ pathname = url.hash.substring(1);
+ }
+ if (findMatchingPattern(pathname, this.config.skipPatterns)) {
+ return null;
+ }
+ const maskMatch = findMatchingPattern(pathname, this.config.maskPatterns);
+ if (maskMatch) {
+ pathname = maskMatch;
+ }
+ const payload = {
+ site_id: this.config.siteId,
+ hostname: url.hostname,
+ pathname,
+ querystring: this.config.trackQuerystring ? url.search : "",
+ screenWidth: window.innerWidth,
+ screenHeight: window.innerHeight,
+ language: navigator.language,
+ page_title: document.title,
+ referrer: document.referrer
+ };
+ if (this.customUserId) {
+ payload.user_id = this.customUserId;
+ }
+ return payload;
+ }
+ async sendTrackingData(payload) {
+ try {
+ await fetch(`${this.config.analyticsHost}/track`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(payload),
+ mode: "cors",
+ keepalive: true
+ });
+ } catch (error) {
+ console.error("Failed to send tracking data:", error);
+ }
+ }
+ track(eventType, 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 basePayload = this.createBasePayload();
+ if (!basePayload) {
+ return;
+ }
+ const payload = {
+ ...basePayload,
+ type: eventType,
+ event_name: eventName,
+ properties: eventType === "custom_event" || eventType === "outbound" ? JSON.stringify(properties) : void 0
+ };
+ this.sendTrackingData(payload);
+ }
+ trackPageview() {
+ this.track("pageview");
+ }
+ trackEvent(name, properties = {}) {
+ this.track("custom_event", name, properties);
+ }
+ trackOutbound(url, text = "", target = "_self") {
+ this.track("outbound", "", { url, text, target });
+ }
+ trackWebVitals(vitals) {
+ const basePayload = this.createBasePayload();
+ if (!basePayload) {
+ return;
+ }
+ const payload = {
+ ...basePayload,
+ type: "performance",
+ event_name: "web-vitals",
+ ...vitals
+ };
+ this.sendTrackingData(payload);
+ }
+ identify(userId) {
+ if (typeof userId !== "string" || userId.trim() === "") {
+ console.error("User ID must be a non-empty string");
+ return;
+ }
+ this.customUserId = userId.trim();
+ try {
+ localStorage.setItem("rybbit-user-id", this.customUserId);
+ } catch (e2) {
+ console.warn("Could not persist user ID to localStorage");
+ }
+ }
+ clearUserId() {
+ this.customUserId = null;
+ try {
+ localStorage.removeItem("rybbit-user-id");
+ } catch (e2) {
+ }
+ }
+ getUserId() {
+ return this.customUserId;
}
-
- return payload;
};
- // Helper function to send tracking data
- const sendTrackingData = (payload) => {
- fetch(`${ANALYTICS_HOST}/track`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(payload),
- mode: "cors",
- keepalive: true,
- }).catch(console.error);
+ // ../../node_modules/web-vitals/dist/web-vitals.js
+ var e = -1;
+ var t = (t2) => {
+ addEventListener("pageshow", (n2) => {
+ n2.persisted && (e = n2.timeStamp, t2(n2));
+ }, true);
};
-
- 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;
+ var n = (e2, t2, n2, i2) => {
+ let o2, s2;
+ return (r2) => {
+ t2.value >= 0 && (r2 || i2) && (s2 = t2.value - (o2 ?? 0), (s2 || void 0 === o2) && (o2 = t2.value, t2.delta = s2, t2.rating = ((e3, t3) => e3 > t3[1] ? "poor" : e3 > t3[0] ? "needs-improvement" : "good")(t2.value, n2), e2(t2)));
+ };
+ };
+ var i = (e2) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => e2()));
+ };
+ var o = () => {
+ const e2 = performance.getEntriesByType("navigation")[0];
+ if (e2 && e2.responseStart > 0 && e2.responseStart < performance.now()) return e2;
+ };
+ var s = () => {
+ const e2 = o();
+ return e2?.activationStart ?? 0;
+ };
+ var r = (t2, n2 = -1) => {
+ const i2 = o();
+ let r2 = "navigate";
+ e >= 0 ? r2 = "back-forward-cache" : i2 && (document.prerendering || s() > 0 ? r2 = "prerender" : document.wasDiscarded ? r2 = "restore" : i2.type && (r2 = i2.type.replace(/_/g, "-")));
+ return { name: t2, value: n2, rating: "good", delta: 0, entries: [], id: `v5-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: r2 };
+ };
+ var c = /* @__PURE__ */ new WeakMap();
+ function a(e2, t2) {
+ return c.get(e2) || c.set(e2, new t2()), c.get(e2);
+ }
+ var d = class {
+ constructor() {
+ __publicField(this, "t");
+ __publicField(this, "i", 0);
+ __publicField(this, "o", []);
}
-
- const basePayload = createBasePayload();
- if (!basePayload) {
- return; // Skip tracking due to pattern match
+ h(e2) {
+ if (e2.hadRecentInput) return;
+ const t2 = this.o[0], n2 = this.o.at(-1);
+ this.i && t2 && n2 && e2.startTime - n2.startTime < 1e3 && e2.startTime - t2.startTime < 5e3 ? (this.i += e2.value, this.o.push(e2)) : (this.i = e2.value, this.o = [e2]), this.t?.(e2);
}
-
- const payload = {
- ...basePayload,
- type: eventType,
- event_name: eventName,
- properties:
- eventType === "custom_event" || eventType === "outbound"
- ? JSON.stringify(properties)
- : undefined,
+ };
+ var h = (e2, t2, n2 = {}) => {
+ try {
+ if (PerformanceObserver.supportedEntryTypes.includes(e2)) {
+ const i2 = new PerformanceObserver((e3) => {
+ Promise.resolve().then(() => {
+ t2(e3.getEntries());
+ });
+ });
+ return i2.observe({ type: e2, buffered: true, ...n2 }), i2;
+ }
+ } catch {
+ }
+ };
+ var f = (e2) => {
+ let t2 = false;
+ return () => {
+ t2 || (e2(), t2 = true);
};
-
- sendTrackingData(payload);
};
-
- // Web vitals collection state
- let webVitalsData = {
- lcp: null,
- cls: null,
- inp: null,
- fcp: null,
- ttfb: null,
+ var u = -1;
+ var l = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;
+ var m = (e2) => {
+ "hidden" === document.visibilityState && u > -1 && (u = "visibilitychange" === e2.type ? e2.timeStamp : 0, v());
};
- let webVitalsSent = false;
- let webVitalsTimeout = null;
-
- // Check if all metrics are collected and send if ready
- const checkAndSendWebVitals = () => {
- if (webVitalsSent) return;
-
- const allMetricsCollected = Object.values(webVitalsData).every(
- (value) => value !== null
- );
-
- if (allMetricsCollected) {
- sendWebVitals();
+ var g = () => {
+ addEventListener("visibilitychange", m, true), addEventListener("prerenderingchange", m, true);
+ };
+ var v = () => {
+ removeEventListener("visibilitychange", m, true), removeEventListener("prerenderingchange", m, true);
+ };
+ var p = () => {
+ if (u < 0) {
+ const e2 = s(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter((t2) => "hidden" === t2.name && t2.startTime > e2)[0]?.startTime;
+ u = n2 ?? l(), g(), t(() => {
+ setTimeout(() => {
+ u = l(), g();
+ });
+ });
}
+ return { get firstHiddenTime() {
+ return u;
+ } };
};
-
- // Send web vitals data in a single request
- const sendWebVitals = () => {
- if (webVitalsSent) return;
- webVitalsSent = true;
-
- // Clear timeout if it exists
- if (webVitalsTimeout) {
- clearTimeout(webVitalsTimeout);
- webVitalsTimeout = null;
+ var y = (e2) => {
+ document.prerendering ? addEventListener("prerenderingchange", () => e2(), true) : e2();
+ };
+ var b = [1800, 3e3];
+ var P = (e2, o2 = {}) => {
+ y(() => {
+ const c2 = p();
+ let a2, d2 = r("FCP");
+ const f2 = h("paint", (e3) => {
+ for (const t2 of e3) "first-contentful-paint" === t2.name && (f2.disconnect(), t2.startTime < c2.firstHiddenTime && (d2.value = Math.max(t2.startTime - s(), 0), d2.entries.push(t2), a2(true)));
+ });
+ f2 && (a2 = n(e2, d2, b, o2.reportAllChanges), t((t2) => {
+ d2 = r("FCP"), a2 = n(e2, d2, b, o2.reportAllChanges), i(() => {
+ d2.value = performance.now() - t2.timeStamp, a2(true);
+ });
+ }));
+ });
+ };
+ var T = [0.1, 0.25];
+ var E = (e2, o2 = {}) => {
+ P(f(() => {
+ let s2, c2 = r("CLS", 0);
+ const f2 = a(o2, d), u2 = (e3) => {
+ for (const t2 of e3) f2.h(t2);
+ f2.i > c2.value && (c2.value = f2.i, c2.entries = f2.o, s2());
+ }, l2 = h("layout-shift", u2);
+ l2 && (s2 = n(e2, c2, T, o2.reportAllChanges), document.addEventListener("visibilitychange", () => {
+ "hidden" === document.visibilityState && (u2(l2.takeRecords()), s2(true));
+ }), t(() => {
+ f2.i = 0, c2 = r("CLS", 0), s2 = n(e2, c2, T, o2.reportAllChanges), i(() => s2());
+ }), setTimeout(s2));
+ }));
+ };
+ var _ = 0;
+ var L = 1 / 0;
+ var M = 0;
+ var C = (e2) => {
+ for (const t2 of e2) t2.interactionId && (L = Math.min(L, t2.interactionId), M = Math.max(M, t2.interactionId), _ = M ? (M - L) / 7 + 1 : 0);
+ };
+ var I;
+ var w = () => I ? _ : performance.interactionCount ?? 0;
+ var F = () => {
+ "interactionCount" in performance || I || (I = h("event", C, { type: "event", buffered: true, durationThreshold: 0 }));
+ };
+ var k = 0;
+ var A = class {
+ constructor() {
+ __publicField(this, "u", []);
+ __publicField(this, "l", /* @__PURE__ */ new Map());
+ __publicField(this, "m");
+ __publicField(this, "v");
}
-
- const basePayload = createBasePayload();
- if (!basePayload) {
- return; // Skip web vitals tracking due to pattern match
+ p() {
+ k = w(), this.u.length = 0, this.l.clear();
+ }
+ P() {
+ const e2 = Math.min(this.u.length - 1, Math.floor((w() - k) / 50));
+ return this.u[e2];
+ }
+ h(e2) {
+ if (this.m?.(e2), !e2.interactionId && "first-input" !== e2.entryType) return;
+ const t2 = this.u.at(-1);
+ let n2 = this.l.get(e2.interactionId);
+ if (n2 || this.u.length < 10 || e2.duration > t2.T) {
+ if (n2 ? e2.duration > n2.T ? (n2.entries = [e2], n2.T = e2.duration) : e2.duration === n2.T && e2.startTime === n2.entries[0].startTime && n2.entries.push(e2) : (n2 = { id: e2.interactionId, entries: [e2], T: e2.duration }, this.l.set(n2.id, n2), this.u.push(n2)), this.u.sort((e3, t3) => t3.T - e3.T), this.u.length > 10) {
+ const e3 = this.u.splice(10);
+ for (const t3 of e3) this.l.delete(t3.id);
+ }
+ this.v?.(n2);
+ }
}
-
- const payload = {
- ...basePayload,
- type: "performance",
- event_name: "web-vitals",
- // Include all collected metrics
- lcp: webVitalsData.lcp,
- cls: webVitalsData.cls,
- inp: webVitalsData.inp,
- fcp: webVitalsData.fcp,
- ttfb: webVitalsData.ttfb,
- };
-
- sendTrackingData(payload);
};
-
- // Individual metric collectors
- const collectMetric = (metric) => {
- if (webVitalsSent) return;
-
- webVitalsData[metric.name.toLowerCase()] = metric.value;
- checkAndSendWebVitals();
+ var B = (e2) => {
+ const t2 = globalThis.requestIdleCallback || setTimeout;
+ "hidden" === document.visibilityState ? e2() : (e2 = f(e2), document.addEventListener("visibilitychange", e2, { once: true }), t2(() => {
+ e2(), document.removeEventListener("visibilitychange", e2);
+ }));
+ };
+ var N = [200, 500];
+ var S = (e2, i2 = {}) => {
+ globalThis.PerformanceEventTiming && "interactionId" in PerformanceEventTiming.prototype && y(() => {
+ F();
+ let o2, s2 = r("INP");
+ const c2 = a(i2, A), d2 = (e3) => {
+ B(() => {
+ for (const t3 of e3) c2.h(t3);
+ const t2 = c2.P();
+ t2 && t2.T !== s2.value && (s2.value = t2.T, s2.entries = t2.entries, o2());
+ });
+ }, f2 = h("event", d2, { durationThreshold: i2.durationThreshold ?? 40 });
+ o2 = n(e2, s2, N, i2.reportAllChanges), f2 && (f2.observe({ type: "first-input", buffered: true }), document.addEventListener("visibilitychange", () => {
+ "hidden" === document.visibilityState && (d2(f2.takeRecords()), o2(true));
+ }), t(() => {
+ c2.p(), s2 = r("INP"), o2 = n(e2, s2, N, i2.reportAllChanges);
+ }));
+ });
+ };
+ var q = class {
+ constructor() {
+ __publicField(this, "m");
+ }
+ h(e2) {
+ this.m?.(e2);
+ }
+ };
+ var x = [2500, 4e3];
+ var O = (e2, o2 = {}) => {
+ y(() => {
+ const c2 = p();
+ let d2, u2 = r("LCP");
+ const l2 = a(o2, q), m2 = (e3) => {
+ o2.reportAllChanges || (e3 = e3.slice(-1));
+ for (const t2 of e3) l2.h(t2), t2.startTime < c2.firstHiddenTime && (u2.value = Math.max(t2.startTime - s(), 0), u2.entries = [t2], d2());
+ }, g2 = h("largest-contentful-paint", m2);
+ if (g2) {
+ d2 = n(e2, u2, x, o2.reportAllChanges);
+ const s2 = f(() => {
+ m2(g2.takeRecords()), g2.disconnect(), d2(true);
+ });
+ for (const e3 of ["keydown", "click", "visibilitychange"]) addEventListener(e3, () => B(s2), { capture: true, once: true });
+ t((t2) => {
+ u2 = r("LCP"), d2 = n(e2, u2, x, o2.reportAllChanges), i(() => {
+ u2.value = performance.now() - t2.timeStamp, d2(true);
+ });
+ });
+ }
+ });
+ };
+ var $ = [800, 1800];
+ var D = (e2) => {
+ document.prerendering ? y(() => D(e2)) : "complete" !== document.readyState ? addEventListener("load", () => D(e2), true) : setTimeout(e2);
+ };
+ var H = (e2, i2 = {}) => {
+ let c2 = r("TTFB"), a2 = n(e2, c2, $, i2.reportAllChanges);
+ D(() => {
+ const d2 = o();
+ d2 && (c2.value = Math.max(d2.responseStart - s(), 0), c2.entries = [d2], a2(true), t(() => {
+ c2 = r("TTFB", 0), a2 = n(e2, c2, $, i2.reportAllChanges), a2(true);
+ }));
+ });
};
- // Initialize web vitals tracking if available and enabled
- const initWebVitals = () => {
- if (typeof webVitals !== "undefined" && enableWebVitals) {
+ // webVitals.ts
+ var WebVitalsCollector = class {
+ constructor(onReady) {
+ this.data = {
+ lcp: null,
+ cls: null,
+ inp: null,
+ fcp: null,
+ ttfb: null
+ };
+ this.sent = false;
+ this.timeout = null;
+ this.onReadyCallback = null;
+ this.onReadyCallback = onReady;
+ }
+ initialize() {
try {
- // Track Core Web Vitals
- webVitals.getLCP(collectMetric);
- webVitals.getCLS(collectMetric);
- webVitals.getINP(collectMetric);
-
- // Track additional metrics
- webVitals.getFCP(collectMetric);
- webVitals.getTTFB(collectMetric);
-
- // Set a timeout to send metrics even if not all are collected
- // This handles cases where some metrics might not fire (e.g., no user interactions for INP)
- webVitalsTimeout = setTimeout(() => {
- if (!webVitalsSent) {
- sendWebVitals();
+ O(this.collectMetric.bind(this));
+ E(this.collectMetric.bind(this));
+ S(this.collectMetric.bind(this));
+ P(this.collectMetric.bind(this));
+ H(this.collectMetric.bind(this));
+ this.timeout = setTimeout(() => {
+ if (!this.sent) {
+ this.sendData();
}
- }, 20000);
-
- // Also send on page unload to capture any remaining metrics
+ }, 2e4);
window.addEventListener("beforeunload", () => {
- if (!webVitalsSent) {
- sendWebVitals();
+ if (!this.sent) {
+ this.sendData();
}
});
- } catch (e) {
- console.warn("Error initializing web vitals tracking:", e);
+ } catch (e2) {
+ console.warn("Error initializing web vitals tracking:", e2);
}
}
+ collectMetric(metric) {
+ if (this.sent) return;
+ const metricName = metric.name.toLowerCase();
+ this.data[metricName] = metric.value;
+ const allCollected = Object.values(this.data).every((value) => value !== null);
+ if (allCollected) {
+ this.sendData();
+ }
+ }
+ sendData() {
+ if (this.sent) return;
+ this.sent = true;
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+ if (this.onReadyCallback) {
+ this.onReadyCallback(this.data);
+ }
+ }
+ getData() {
+ return { ...this.data };
+ }
};
- const trackPageview = () => track("pageview");
-
- const debouncedTrackPageview =
- debounceDuration > 0
- ? debounce(trackPageview, debounceDuration)
- : trackPageview;
-
- // Track outbound link clicks and custom data-attribute events
- document.addEventListener("click", function (e) {
- // First check for custom events via data attributes
- let target = e.target;
- while (target && target !== document) {
- if (target.hasAttribute("data-rybbit-event")) {
- const eventName = target.getAttribute("data-rybbit-event");
- if (eventName) {
- // Collect additional properties from data-rybbit-prop-* attributes
- const properties = {};
- for (const attr of target.attributes) {
- if (attr.name.startsWith("data-rybbit-prop-")) {
- const propName = attr.name.replace("data-rybbit-prop-", "");
- properties[propName] = attr.value;
+ // index.ts
+ (function() {
+ const scriptTag = document.currentScript;
+ if (!scriptTag) {
+ console.error("Could not find current script tag");
+ return;
+ }
+ if (window.__RYBBIT_OPTOUT__ || localStorage.getItem("disable-rybbit") !== null) {
+ window.rybbit = {
+ pageview: () => {
+ },
+ event: () => {
+ },
+ trackOutbound: () => {
+ },
+ identify: () => {
+ },
+ clearUserId: () => {
+ },
+ getUserId: () => null
+ };
+ return;
+ }
+ const config = parseScriptConfig(scriptTag);
+ if (!config) {
+ return;
+ }
+ const tracker = new Tracker(config);
+ if (config.enableWebVitals) {
+ const webVitalsCollector = new WebVitalsCollector((vitals) => {
+ tracker.trackWebVitals(vitals);
+ });
+ webVitalsCollector.initialize();
+ }
+ const trackPageview = () => tracker.trackPageview();
+ const debouncedTrackPageview = config.debounceDuration > 0 ? debounce(trackPageview, config.debounceDuration) : trackPageview;
+ function setupEventListeners() {
+ document.addEventListener("click", function(e2) {
+ let target = e2.target;
+ while (target && target !== document.documentElement) {
+ if (target.hasAttribute("data-rybbit-event")) {
+ const eventName = target.getAttribute("data-rybbit-event");
+ if (eventName) {
+ const properties = {};
+ for (const attr of target.attributes) {
+ if (attr.name.startsWith("data-rybbit-prop-")) {
+ const propName = attr.name.replace("data-rybbit-prop-", "");
+ properties[propName] = attr.value;
+ }
+ }
+ tracker.trackEvent(eventName, properties);
}
+ break;
}
- track("custom_event", eventName, properties);
+ target = target.parentElement;
}
- break;
- }
- target = target.parentElement;
- }
-
- // Then check for outbound links
- if (trackOutbound) {
- 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 (config.trackOutbound) {
+ const link = e2.target.closest("a");
+ if (link?.href && isOutboundLink(link.href)) {
+ tracker.trackOutbound(
+ link.href,
+ link.innerText || link.textContent || "",
+ link.target || "_self"
+ );
+ }
+ }
+ });
+ if (config.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.addEventListener("hashchange", debouncedTrackPageview);
}
}
- });
-
- 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.rybbit = {
+ pageview: () => tracker.trackPageview(),
+ event: (name, properties = {}) => tracker.trackEvent(name, properties),
+ trackOutbound: (url, text = "", target = "_self") => tracker.trackOutbound(url, text, target),
+ identify: (userId) => tracker.identify(userId),
+ clearUserId: () => tracker.clearUserId(),
+ getUserId: () => tracker.getUserId()
};
-
- window.addEventListener("popstate", debouncedTrackPageview);
- // Always listen for hashchange events for hash-based routing
- window.addEventListener("hashchange", debouncedTrackPageview);
- }
-
- window.rybbit = {
- pageview: trackPageview,
- event: (name, properties = {}) => track("custom_event", name, properties),
- trackOutbound: (url, text = "", target = "_self") =>
- track("outbound", "", { url, text, target }),
-
- // New methods for user identification
- identify: (userId) => {
- if (typeof userId !== "string" || userId.trim() === "") {
- console.error("User ID must be a non-empty string");
- return;
- }
- customUserId = userId.trim();
- try {
- localStorage.setItem("rybbit-user-id", customUserId);
- } catch (e) {
- // localStorage not available, user ID will only persist for session
- console.warn("Could not persist user ID to localStorage");
- }
- },
-
- clearUserId: () => {
- customUserId = null;
- try {
- localStorage.removeItem("rybbit-user-id");
- } catch (e) {
- // localStorage not available, ignore
- }
- },
-
- getUserId: () => customUserId,
- };
-
- if (autoTrackPageview) {
- trackPageview();
- }
+ setupEventListeners();
+ if (config.autoTrackPageview) {
+ tracker.trackPageview();
+ }
+ })();
})();
diff --git a/server/public/script.js b/server/public/script.js
index bc70ec08a..2acd76959 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(window.__RYBBIT_OPTOUT__||null!==localStorage.getItem("disable-rybbit")){window.rybbit={pageview(){},event(){},trackOutbound(){},identify(){},clearUserId(){},getUserId:()=>null};return}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,i="false"!==t.getAttribute("data-auto-track-pageview"),n="false"!==t.getAttribute("data-track-spa"),l="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound");new Promise((t,e)=>{let r=document.createElement("script");r.src="https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js",r.onload=()=>t(),r.onerror=()=>e(Error("Failed to load web-vitals library")),document.head.appendChild(r)}).then(()=>{L()}).catch(t=>{console.warn("Failed to load web vitals library:",t)});let u=[];try{let o=t.getAttribute("data-skip-patterns");o&&(u=JSON.parse(o),Array.isArray(u)||(u=[]))}catch(c){console.error("Error parsing data-skip-patterns:",c)}let p=[];try{let d=t.getAttribute("data-mask-patterns");d&&(p=JSON.parse(d),Array.isArray(p)||(p=[]))}catch(b){console.error("Error parsing data-mask-patterns:",b)}let f=null;try{let g=localStorage.getItem("rybbit-user-id");g&&(f=g)}catch(h){}function y(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),i=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+i+"$")}function v(t,e){for(let r of e)try{let a=y(r);if(a.test(t))return r}catch(i){console.error(`Invalid pattern: ${r}`,i)}return null}let m=()=>{let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),v(e,u))return null;let a=v(e,p);a&&(e=a);let i={site_id:r,hostname:t.hostname,pathname:e,querystring:l?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return f&&(i.user_id=f),i},w=t=>{fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0}).catch(console.error)},A=(t="pageview",e="",r={})=>{if("custom_event"===t&&(!e||"string"!=typeof e)){console.error("Event name is required and must be a string for custom events");return}let a=m();if(!a)return;let i={...a,type:t,event_name:e,properties:"custom_event"===t||"outbound"===t?JSON.stringify(r):void 0};w(i)},I={lcp:null,cls:null,inp:null,fcp:null,ttfb:null},k=!1,E=null,S=()=>{if(k)return;let t=Object.values(I).every(t=>null!==t);t&&T()},T=()=>{if(k)return;k=!0,E&&(clearTimeout(E),E=null);let t=m();if(!t)return;let e={...t,type:"performance",event_name:"web-vitals",lcp:I.lcp,cls:I.cls,inp:I.inp,fcp:I.fcp,ttfb:I.ttfb};w(e)},$=t=>{k||(I[t.name.toLowerCase()]=t.value,S())},L=()=>{if("undefined"!=typeof webVitals)try{webVitals.getLCP($),webVitals.getCLS($),webVitals.getINP($),webVitals.getFCP($),webVitals.getTTFB($),E=setTimeout(()=>{k||T()},2e4),window.addEventListener("beforeunload",()=>{k||T()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}},C=()=>A("pageview"),O=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(C,a):C;if(document.addEventListener("click",function(t){let e=t.target;for(;e&&e!==document;){if(e.hasAttribute("data-rybbit-event")){let r=e.getAttribute("data-rybbit-event");if(r){let a={};for(let i of e.attributes)if(i.name.startsWith("data-rybbit-prop-")){let n=i.name.replace("data-rybbit-prop-","");a[n]=i.value}A("custom_event",r,a)}break}e=e.parentElement}if(s){let l=t.target.closest("a");if(!l||!l.href)return;(function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(i){return!1}})(l.href)&&A("outbound","",{url:l.href,text:l.innerText||l.textContent||"",target:l.target||"_self"})}}),n){let P=history.pushState,U=history.replaceState;history.pushState=function(...t){P.apply(this,t),O()},history.replaceState=function(...t){U.apply(this,t),O()},window.addEventListener("popstate",O),window.addEventListener("hashchange",O)}window.rybbit={pageview:C,event:(t,e={})=>A("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>A("outbound","",{url:t,text:e,target:r}),identify(t){if("string"!=typeof t||""===t.trim()){console.error("User ID must be a non-empty string");return}f=t.trim();try{localStorage.setItem("rybbit-user-id",f)}catch(e){console.warn("Could not persist user ID to localStorage")}},clearUserId(){f=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>f},i&&C()}();
\ No newline at end of file
+"use strict";(()=>{var it=Object.defineProperty;var at=(r,t,e)=>t in r?it(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>at(r,typeof t!="symbol"?t+"":t,e);function st(r){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",i=r.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(t,"g"),".*"),i=i.replace(/\//g,"\\/");let c=i.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,t){for(let e of t)try{if(st(e).test(r))return e}catch(n){console.error(`Invalid pattern: ${e}`,n)}return null}function N(r,t){let e=null;return(...n)=>{e&&clearTimeout(e),e=setTimeout(()=>r(...n),t)}}function W(r){try{let t=window.location.hostname,e=new URL(r).hostname;return e!==t&&e!==""}catch{return!1}}function S(r,t){if(!r)return t;try{let e=JSON.parse(r);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}function B(r){let t=r.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n||isNaN(Number(n)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,c=S(r.getAttribute("data-skip-patterns"),[]),o=S(r.getAttribute("data-mask-patterns"),[]);return{analyticsHost:e,siteId:n,debounceDuration:i,autoTrackPageview:r.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:r.getAttribute("data-track-spa")!=="false",trackQuerystring:r.getAttribute("data-track-query")!=="false",trackOutbound:r.getAttribute("data-track-outbound")!=="false",enableWebVitals:r.getAttribute("data-web-vitals")==="true",skipPatterns:c,maskPatterns:o}}var b=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId()}loadUserId(){try{let t=localStorage.getItem("rybbit-user-id");t&&(this.customUserId=t)}catch{}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),P(e,this.config.skipPatterns))return null;let n=P(e,this.config.maskPatterns);n&&(e=n);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",n={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let c={...i,type:t,event_name:e,properties:t==="custom_event"||t==="outbound"?JSON.stringify(n):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",n="_self"){this.track("outbound","",{url:t,text:e,target:n})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let n={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(n)}identify(t){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}};var G=-1,p=r=>{addEventListener("pageshow",t=>{t.persisted&&(G=t.timeStamp,r(t))},!0)},d=(r,t,e,n)=>{let i,c;return o=>{t.value>=0&&(o||n)&&(c=t.value-(i??0),(c||i===void 0)&&(i=t.value,t.delta=c,t.rating=((a,s)=>a>s[1]?"poor":a>s[0]?"needs-improvement":"good")(t.value,e),r(t)))}},M=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},R=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>R()?.activationStart??0,u=(r,t=-1)=>{let e=R(),n="navigate";return G>=0?n="back-forward-cache":e&&(document.prerendering||m()>0?n="prerender":document.wasDiscarded?n="restore":e.type&&(n=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},E=new WeakMap;function O(r,t){return E.get(r)||E.set(r,new t),E.get(r)}var C=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],n=this.o.at(-1);this.i&&e&&n&&t.startTime-n.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},f=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver(i=>{Promise.resolve().then(()=>{t(i.getEntries())})});return n.observe({type:r,buffered:!0,...e}),n}}catch{}},x=r=>{let t=!1;return()=>{t||(r(),t=!0)}},g=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,y=r=>{document.visibilityState==="hidden"&&g>-1&&(g=r.type==="visibilitychange"?r.timeStamp:0,ot())},V=()=>{addEventListener("visibilitychange",y,!0),addEventListener("prerenderingchange",y,!0)},ot=()=>{removeEventListener("visibilitychange",y,!0),removeEventListener("prerenderingchange",y,!0)},Q=()=>{if(g<0){let r=m();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>e.name==="hidden"&&e.startTime>r)[0]?.startTime)??H(),V(),p(()=>{setTimeout(()=>{g=H(),V()})})}return{get firstHiddenTime(){return g}}},T=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},F=[1800,3e3],U=(r,t={})=>{T(()=>{let e=Q(),n,i=u("FCP"),c=f("paint",o=>{for(let a of o)a.name==="first-contentful-paint"&&(c.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-m(),0),i.entries.push(a),n(!0)))});c&&(n=d(r,i,F,t.reportAllChanges),p(o=>{i=u("FCP"),n=d(r,i,F,t.reportAllChanges),M(()=>{i.value=performance.now()-o.timeStamp,n(!0)})}))})},$=[.1,.25],Y=(r,t={})=>{U(x(()=>{let e,n=u("CLS",0),i=O(t,C),c=a=>{for(let s of a)i.h(s);i.i>n.value&&(n.value=i.i,n.entries=i.o,e())},o=f("layout-shift",c);o&&(e=d(r,n,$,t.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),p(()=>{i.i=0,n=u("CLS",0),e=d(r,n,$,t.reportAllChanges),M(()=>e())}),setTimeout(e))}))},X=0,I=1/0,v=0,ct=r=>{for(let t of r)t.interactionId&&(I=Math.min(I,t.interactionId),v=Math.max(v,t.interactionId),X=v?(v-I)/7+1:0)},L,J=()=>L?X:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||L||(L=f("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},K=0,_=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){K=J(),this.u.length=0,this.l.clear()}P(){let t=Math.min(this.u.length-1,Math.floor((J()-K)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),n=this.l.get(t.interactionId);if(n||this.u.length<10||t.duration>e.T){if(n?t.duration>n.T?(n.entries=[t],n.T=t.duration):t.duration===n.T&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],T:t.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort((i,c)=>c.T-i.T),this.u.length>10){let i=this.u.splice(10);for(let c of i)this.l.delete(c.id)}this.v?.(n)}}},Z=r=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),document.addEventListener("visibilitychange",r,{once:!0}),t(()=>{r(),document.removeEventListener("visibilitychange",r)}))},q=[200,500],tt=(r,t={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&T(()=>{lt();let e,n=u("INP"),i=O(t,_),c=a=>{Z(()=>{for(let l of a)i.h(l);let s=i.P();s&&s.T!==n.value&&(n.value=s.T,n.entries=s.entries,e())})},o=f("event",c,{durationThreshold:t.durationThreshold??40});e=d(r,n,q,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),p(()=>{i.p(),n=u("INP"),e=d(r,n,q,t.reportAllChanges)}))})},A=class{constructor(){h(this,"m")}h(t){this.m?.(t)}},z=[2500,4e3],et=(r,t={})=>{T(()=>{let e=Q(),n,i=u("LCP"),c=O(t,A),o=s=>{t.reportAllChanges||(s=s.slice(-1));for(let l of s)c.h(l),l.startTime<e.firstHiddenTime&&(i.value=Math.max(l.startTime-m(),0),i.entries=[l],n())},a=f("largest-contentful-paint",o);if(a){n=d(r,i,z,t.reportAllChanges);let s=x(()=>{o(a.takeRecords()),a.disconnect(),n(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>Z(s),{capture:!0,once:!0});p(l=>{i=u("LCP"),n=d(r,i,z,t.reportAllChanges),M(()=>{i.value=performance.now()-l.timeStamp,n(!0)})})}})},j=[800,1800],D=r=>{document.prerendering?T(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},rt=(r,t={})=>{let e=u("TTFB"),n=d(r,e,j,t.reportAllChanges);D(()=>{let i=R();i&&(e.value=Math.max(i.responseStart-m(),0),e.entries=[i],n(!0),p(()=>{e=u("TTFB",0),n=d(r,e,j,t.reportAllChanges),n(!0)}))})};var k=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{et(this.collectMetric.bind(this)),Y(this.collectMetric.bind(this)),tt(this.collectMetric.bind(this)),U(this.collectMetric.bind(this)),rt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};(function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null};return}let t=B(r);if(!t)return;let e=new b(t);t.enableWebVitals&&new k(a=>{e.trackWebVitals(a)}).initialize();let n=()=>e.trackPageview(),i=t.debounceDuration>0?N(n,t.debounceDuration):n;function c(){if(document.addEventListener("click",function(o){let a=o.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let s=a.getAttribute("data-rybbit-event");if(s){let l={};for(let w of a.attributes)if(w.name.startsWith("data-rybbit-prop-")){let nt=w.name.replace("data-rybbit-prop-","");l[nt]=w.value}e.trackEvent(s,l)}break}a=a.parentElement}if(t.trackOutbound){let s=o.target.closest("a");s?.href&&W(s.href)&&e.trackOutbound(s.href,s.innerText||s.textContent||"",s.target||"_self")}}),t.autoTrackSpa){let o=history.pushState,a=history.replaceState;history.pushState=function(...s){o.apply(this,s),i()},history.replaceState=function(...s){a.apply(this,s),i()},window.addEventListener("popstate",i),window.addEventListener("hashchange",i)}}window.rybbit={pageview:()=>e.trackPageview(),event:(o,a={})=>e.trackEvent(o,a),trackOutbound:(o,a="",s="_self")=>e.trackOutbound(o,a,s),identify:o=>e.identify(o),clearUserId:()=>e.clearUserId(),getUserId:()=>e.getUserId()},c(),t.autoTrackPageview&&e.trackPageview()})();})();
diff --git a/server/src/analytics-script/build.js b/server/src/analytics-script/build.js
new file mode 100644
index 000000000..65790ad2e
--- /dev/null
+++ b/server/src/analytics-script/build.js
@@ -0,0 +1,49 @@
+import { build } from 'esbuild';
+import { existsSync, mkdirSync } from 'fs';
+import { dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+// Ensure public directory exists
+const publicDir = '../../public';
+if (!existsSync(publicDir)) {
+ mkdirSync(publicDir, { recursive: true });
+}
+
+async function buildScript() {
+ try {
+ // Build the full version
+ await build({
+ entryPoints: ['./index.ts'],
+ bundle: true,
+ format: 'iife',
+ target: 'es2020',
+ outfile: '../../public/script-full.js',
+ minify: false,
+ sourcemap: false,
+ platform: 'browser',
+ });
+
+ console.log('✅ Built script-full.js');
+
+ // Build the minified version
+ await build({
+ entryPoints: ['./index.ts'],
+ bundle: true,
+ format: 'iife',
+ target: 'es2020',
+ outfile: '../../public/script.js',
+ minify: true,
+ sourcemap: false,
+ platform: 'browser',
+ });
+
+ console.log('✅ Built script.js (minified)');
+ } catch (error) {
+ console.error('Build failed:', error);
+ process.exit(1);
+ }
+}
+
+buildScript();
\ No newline at end of file
diff --git a/server/src/analytics-script/config.test.ts b/server/src/analytics-script/config.test.ts
new file mode 100644
index 000000000..2df3204a7
--- /dev/null
+++ b/server/src/analytics-script/config.test.ts
@@ -0,0 +1,183 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { parseScriptConfig } from "./config.js";
+
+describe("parseScriptConfig", () => {
+ let mockScriptTag: HTMLScriptElement;
+ let consoleSpy: any;
+
+ beforeEach(() => {
+ mockScriptTag = document.createElement("script");
+ consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ });
+
+ it("should parse valid configuration", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+
+ const config = parseScriptConfig(mockScriptTag);
+
+ expect(config).toEqual({
+ analyticsHost: "https://analytics.example.com",
+ siteId: "123",
+ debounceDuration: 500,
+ autoTrackPageview: true,
+ autoTrackSpa: true,
+ trackQuerystring: true,
+ trackOutbound: true,
+ enableWebVitals: false, // Default is false, only true when data-web-vitals="true"
+ skipPatterns: [],
+ maskPatterns: [],
+ });
+ });
+
+ it("should handle missing src attribute", () => {
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config).toBeNull();
+ expect(consoleSpy).toHaveBeenCalledWith("Script src attribute is missing");
+ });
+
+ it("should handle invalid analytics host", () => {
+ mockScriptTag.setAttribute("src", "/script.js"); // No host part
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config).toBeNull();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Please provide a valid analytics host"
+ );
+ });
+
+ it("should handle missing site ID", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config).toBeNull();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Please provide a valid site ID using the data-site-id attribute"
+ );
+ });
+
+ it("should handle invalid site ID", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "not-a-number");
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config).toBeNull();
+ });
+
+ it("should parse custom debounce duration", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute("data-debounce", "1000");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.debounceDuration).toBe(1000);
+ });
+
+ it("should handle negative debounce duration", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute("data-debounce", "-100");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.debounceDuration).toBe(0);
+ });
+
+ it("should parse boolean flags correctly", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute("data-auto-track-pageview", "false");
+ mockScriptTag.setAttribute("data-track-spa", "false");
+ mockScriptTag.setAttribute("data-track-query", "false");
+ mockScriptTag.setAttribute("data-track-outbound", "false");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.autoTrackPageview).toBe(false);
+ expect(config?.autoTrackSpa).toBe(false);
+ expect(config?.trackQuerystring).toBe(false);
+ expect(config?.trackOutbound).toBe(false);
+ });
+
+ it("should parse skip patterns", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute(
+ "data-skip-patterns",
+ '["/admin/**", "/api/**"]'
+ );
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.skipPatterns).toEqual(["/admin/**", "/api/**"]);
+ });
+
+ it("should parse mask patterns", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute(
+ "data-mask-patterns",
+ '["/user/*/profile", "/post/*"]'
+ );
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.maskPatterns).toEqual(["/user/*/profile", "/post/*"]);
+ });
+
+ it("should handle invalid JSON in patterns gracefully", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute("data-skip-patterns", "invalid-json");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.skipPatterns).toEqual([]);
+ });
+
+ it("should support legacy site-id attribute", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("site-id", "456");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.siteId).toBe("456");
+ });
+
+ it("should enable web vitals when data-web-vitals is true", () => {
+ mockScriptTag.setAttribute(
+ "src",
+ "https://analytics.example.com/script.js"
+ );
+ mockScriptTag.setAttribute("data-site-id", "123");
+ mockScriptTag.setAttribute("data-web-vitals", "true");
+
+ const config = parseScriptConfig(mockScriptTag);
+ expect(config?.enableWebVitals).toBe(true);
+ });
+});
diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.ts
new file mode 100644
index 000000000..03404f18e
--- /dev/null
+++ b/server/src/analytics-script/config.ts
@@ -0,0 +1,52 @@
+import { ScriptConfig } from './types.js';
+import { parseJsonSafely } from './utils.js';
+
+/**
+ * Parse script configuration from the script tag attributes
+ */
+export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig | null {
+ const src = scriptTag.getAttribute('src');
+ if (!src) {
+ console.error('Script src attribute is missing');
+ return null;
+ }
+
+ const analyticsHost = src.split('/script.js')[0];
+ if (!analyticsHost) {
+ console.error('Please provide a valid analytics host');
+ return null;
+ }
+
+ const siteId = scriptTag.getAttribute('data-site-id') || scriptTag.getAttribute('site-id');
+ if (!siteId || isNaN(Number(siteId))) {
+ console.error('Please provide a valid site ID using the data-site-id attribute');
+ return null;
+ }
+
+ const debounceDuration = scriptTag.getAttribute('data-debounce')
+ ? Math.max(0, parseInt(scriptTag.getAttribute('data-debounce')!))
+ : 500;
+
+ const skipPatterns = parseJsonSafely<string[]>(
+ scriptTag.getAttribute('data-skip-patterns'),
+ []
+ );
+
+ const maskPatterns = parseJsonSafely<string[]>(
+ scriptTag.getAttribute('data-mask-patterns'),
+ []
+ );
+
+ return {
+ analyticsHost,
+ siteId,
+ debounceDuration,
+ autoTrackPageview: scriptTag.getAttribute('data-auto-track-pageview') !== 'false',
+ autoTrackSpa: scriptTag.getAttribute('data-track-spa') !== 'false',
+ trackQuerystring: scriptTag.getAttribute('data-track-query') !== 'false',
+ trackOutbound: scriptTag.getAttribute('data-track-outbound') !== 'false',
+ enableWebVitals: scriptTag.getAttribute('data-web-vitals') === 'true',
+ skipPatterns,
+ maskPatterns,
+ };
+}
\ No newline at end of file
diff --git a/server/src/analytics-script/index.ts b/server/src/analytics-script/index.ts
new file mode 100644
index 000000000..dda9cb2ec
--- /dev/null
+++ b/server/src/analytics-script/index.ts
@@ -0,0 +1,135 @@
+import { parseScriptConfig } from './config.js';
+import { Tracker } from './tracking.js';
+import { WebVitalsCollector } from './webVitals.js';
+import { debounce, isOutboundLink } from './utils.js';
+import { RybbitAPI, WebVitalsData } from './types.js';
+
+declare global {
+ interface Window {
+ __RYBBIT_OPTOUT__?: boolean;
+ rybbit: RybbitAPI;
+ }
+}
+
+(function () {
+ const scriptTag = document.currentScript as HTMLScriptElement;
+ if (!scriptTag) {
+ console.error('Could not find current script tag');
+ return;
+ }
+
+ // Check if user has opted out
+ if (window.__RYBBIT_OPTOUT__ || localStorage.getItem('disable-rybbit') !== null) {
+ // Create no-op implementation
+ window.rybbit = {
+ pageview: () => {},
+ event: () => {},
+ trackOutbound: () => {},
+ identify: () => {},
+ clearUserId: () => {},
+ getUserId: () => null,
+ };
+ return;
+ }
+
+ // Parse configuration
+ const config = parseScriptConfig(scriptTag);
+ if (!config) {
+ return;
+ }
+
+ // Initialize tracker
+ const tracker = new Tracker(config);
+
+ // Initialize web vitals if enabled
+ if (config.enableWebVitals) {
+ const webVitalsCollector = new WebVitalsCollector((vitals: WebVitalsData) => {
+ tracker.trackWebVitals(vitals);
+ });
+ webVitalsCollector.initialize();
+ }
+
+ // Create debounced pageview tracker
+ const trackPageview = () => tracker.trackPageview();
+ const debouncedTrackPageview = config!.debounceDuration > 0
+ ? debounce(trackPageview, config!.debounceDuration)
+ : trackPageview;
+
+ // Setup event listeners
+ function setupEventListeners() {
+ // Track custom events and outbound links
+ document.addEventListener('click', function (e) {
+ let target = e.target as HTMLElement;
+
+ // Check for custom events via data attributes
+ while (target && target !== document.documentElement) {
+ if (target.hasAttribute('data-rybbit-event')) {
+ const eventName = target.getAttribute('data-rybbit-event');
+ if (eventName) {
+ const properties: Record<string, string> = {};
+ for (const attr of target.attributes) {
+ if (attr.name.startsWith('data-rybbit-prop-')) {
+ const propName = attr.name.replace('data-rybbit-prop-', '');
+ properties[propName] = attr.value;
+ }
+ }
+ tracker.trackEvent(eventName, properties);
+ }
+ break;
+ }
+ target = target.parentElement as HTMLElement;
+ }
+
+ // Check for outbound links
+ if (config!.trackOutbound) {
+ const link = (e.target as HTMLElement).closest('a') as HTMLAnchorElement;
+ if (link?.href && isOutboundLink(link.href)) {
+ tracker.trackOutbound(
+ link.href,
+ link.innerText || link.textContent || '',
+ link.target || '_self'
+ );
+ }
+ }
+ });
+
+ // Setup SPA tracking
+ if (config!.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.addEventListener('hashchange', debouncedTrackPageview);
+ }
+ }
+
+ // Setup public API
+ window.rybbit = {
+ pageview: () => tracker.trackPageview(),
+ event: (name: string, properties: Record<string, any> = {}) =>
+ tracker.trackEvent(name, properties),
+ trackOutbound: (url: string, text: string = '', target: string = '_self') =>
+ tracker.trackOutbound(url, text, target),
+ identify: (userId: string) => tracker.identify(userId),
+ clearUserId: () => tracker.clearUserId(),
+ getUserId: () => tracker.getUserId(),
+ };
+
+ // Initialize
+ setupEventListeners();
+
+ // Track initial pageview if enabled
+ 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.ts
new file mode 100644
index 000000000..0d9bd8367
--- /dev/null
+++ b/server/src/analytics-script/tracking.test.ts
@@ -0,0 +1,284 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Tracker } from './tracking.js';
+import { ScriptConfig } from './types.js';
+
+// Mock fetch globally
+global.fetch = vi.fn();
+
+describe('Tracker', () => {
+ let tracker: Tracker;
+ let config: ScriptConfig;
+ let mockLocation: any;
+
+ beforeEach(() => {
+ // Reset fetch mock
+ vi.mocked(global.fetch).mockReset();
+ vi.mocked(global.fetch).mockResolvedValue({} as Response);
+
+ // Mock localStorage
+ const localStorageMock = {
+ getItem: vi.fn(),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ };
+ Object.defineProperty(window, 'localStorage', {
+ value: localStorageMock,
+ writable: true,
+ });
+
+ // Mock window properties
+ mockLocation = {
+ href: 'https://example.com/page?query=test',
+ hostname: 'example.com',
+ pathname: '/page',
+ search: '?query=test',
+ hash: '',
+ };
+
+ Object.defineProperty(window, 'location', {
+ value: mockLocation,
+ configurable: true,
+ writable: true,
+ });
+
+ // Mock URL constructor to use our mockLocation
+ global.URL = vi.fn().mockImplementation(() => ({
+ hostname: mockLocation.hostname,
+ pathname: mockLocation.pathname,
+ search: mockLocation.search,
+ hash: mockLocation.hash,
+ })) as any;
+
+ Object.defineProperty(window, 'innerWidth', {
+ value: 1920,
+ writable: true,
+ });
+
+ Object.defineProperty(window, 'innerHeight', {
+ value: 1080,
+ writable: true,
+ });
+
+ Object.defineProperty(navigator, 'language', {
+ value: 'en-US',
+ writable: true,
+ });
+
+ Object.defineProperty(document, 'title', {
+ value: 'Test Page',
+ writable: true,
+ });
+
+ Object.defineProperty(document, 'referrer', {
+ value: 'https://google.com',
+ writable: true,
+ });
+
+ config = {
+ analyticsHost: 'https://analytics.example.com',
+ siteId: '123',
+ debounceDuration: 0,
+ autoTrackPageview: true,
+ autoTrackSpa: true,
+ trackQuerystring: true,
+ trackOutbound: true,
+ enableWebVitals: false,
+ skipPatterns: [],
+ maskPatterns: [],
+ };
+
+ tracker = new Tracker(config);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('createBasePayload', () => {
+ it('should create base payload with all required fields', () => {
+ const payload = tracker.createBasePayload();
+
+ expect(payload).toEqual({
+ site_id: '123',
+ hostname: 'example.com',
+ pathname: '/page',
+ querystring: '?query=test',
+ screenWidth: 1920,
+ screenHeight: 1080,
+ language: 'en-US',
+ page_title: 'Test Page',
+ referrer: 'https://google.com',
+ });
+ });
+
+ it('should handle hash-based routing', () => {
+ mockLocation.hash = '#/dashboard/users';
+ const payload = tracker.createBasePayload();
+ expect(payload?.pathname).toBe('/dashboard/users');
+ });
+
+ it('should skip tracking for matching skip patterns', () => {
+ config.skipPatterns = ['/admin/**', '/api/**'];
+ tracker = new Tracker(config);
+
+ mockLocation.pathname = '/admin/settings';
+ const payload = tracker.createBasePayload();
+ expect(payload).toBeNull();
+ });
+
+ it('should apply mask patterns', () => {
+ config.maskPatterns = ['/user/*/profile'];
+ tracker = new Tracker(config);
+
+ mockLocation.pathname = '/user/123/profile';
+ const payload = tracker.createBasePayload();
+ expect(payload?.pathname).toBe('/user/*/profile');
+ });
+
+ it('should exclude querystring when disabled', () => {
+ config.trackQuerystring = false;
+ tracker = new Tracker(config);
+
+ const payload = tracker.createBasePayload();
+ expect(payload?.querystring).toBe('');
+ });
+
+ it('should include user ID when set', () => {
+ vi.mocked(window.localStorage.getItem).mockReturnValue('user-123');
+ tracker = new Tracker(config);
+
+ const payload = tracker.createBasePayload();
+ expect(payload?.user_id).toBe('user-123');
+ });
+ });
+
+ describe('tracking methods', () => {
+ it('should track pageview', async () => {
+ tracker.trackPageview();
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://analytics.example.com/track',
+ expect.objectContaining({
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: expect.stringContaining('"type":"pageview"'),
+ mode: 'cors',
+ keepalive: true,
+ })
+ );
+ });
+
+ it('should track custom event', async () => {
+ tracker.trackEvent('button_click', { button: 'submit' });
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://analytics.example.com/track',
+ expect.objectContaining({
+ body: expect.stringContaining('"type":"custom_event"'),
+ })
+ );
+
+ const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);
+ expect(body.event_name).toBe('button_click');
+ expect(body.properties).toBe(JSON.stringify({ button: 'submit' }));
+ });
+
+ it('should validate custom event name', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ tracker.trackEvent('', {});
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ 'Event name is required and must be a string for custom events'
+ );
+
+ consoleSpy.mockRestore();
+ });
+
+ it('should track outbound link', async () => {
+ tracker.trackOutbound('https://external.com', 'External Link', '_blank');
+
+ const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);
+ expect(body.type).toBe('outbound');
+ expect(body.properties).toBe(JSON.stringify({
+ url: 'https://external.com',
+ text: 'External Link',
+ target: '_blank',
+ }));
+ });
+
+ it('should track web vitals', async () => {
+ const vitals = {
+ lcp: 2500,
+ cls: 0.1,
+ inp: 200,
+ fcp: 1800,
+ ttfb: 800,
+ };
+
+ tracker.trackWebVitals(vitals);
+
+ const body = JSON.parse(vi.mocked(global.fetch).mock.calls[0][1]!.body as string);
+ expect(body.type).toBe('performance');
+ expect(body.event_name).toBe('web-vitals');
+ expect(body.lcp).toBe(2500);
+ expect(body.cls).toBe(0.1);
+ });
+
+ it('should handle fetch errors gracefully', async () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(global.fetch).mockRejectedValue(new Error('Network error'));
+
+ tracker.trackPageview();
+
+ // Wait for async operation
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ 'Failed to send tracking data:',
+ expect.any(Error)
+ );
+
+ consoleSpy.mockRestore();
+ });
+ });
+
+ describe('user identification', () => {
+ it('should identify user', () => {
+ tracker.identify('user-456');
+
+ expect(window.localStorage.setItem).toHaveBeenCalledWith('rybbit-user-id', 'user-456');
+ expect(tracker.getUserId()).toBe('user-456');
+ });
+
+ it('should validate user ID', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ tracker.identify('');
+ expect(window.localStorage.setItem).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith('User ID must be a non-empty string');
+
+ consoleSpy.mockRestore();
+ });
+
+ it('should clear user ID', () => {
+ tracker.identify('user-789');
+ tracker.clearUserId();
+
+ expect(window.localStorage.removeItem).toHaveBeenCalledWith('rybbit-user-id');
+ expect(tracker.getUserId()).toBeNull();
+ });
+
+ it('should handle localStorage errors', () => {
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.mocked(window.localStorage.setItem).mockImplementation(() => {
+ throw new Error('Storage full');
+ });
+
+ tracker.identify('user-123');
+ expect(consoleSpy).toHaveBeenCalledWith('Could not persist user ID to localStorage');
+
+ consoleSpy.mockRestore();
+ });
+ });
+});
\ No newline at end of file
diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.ts
new file mode 100644
index 000000000..820e080c3
--- /dev/null
+++ b/server/src/analytics-script/tracking.ts
@@ -0,0 +1,160 @@
+import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData } from './types.js';
+import { findMatchingPattern } from './utils.js';
+
+export class Tracker {
+ private config: ScriptConfig;
+ private customUserId: string | null = null;
+
+ constructor(config: ScriptConfig) {
+ this.config = config;
+ this.loadUserId();
+ }
+
+ private loadUserId(): void {
+ try {
+ const storedUserId = localStorage.getItem('rybbit-user-id');
+ if (storedUserId) {
+ this.customUserId = storedUserId;
+ }
+ } catch (e) {
+ // localStorage not available
+ }
+ }
+
+ createBasePayload(): BasePayload | null {
+ const url = new URL(window.location.href);
+ let pathname = url.pathname;
+
+ // Handle hash-based SPA routing
+ if (url.hash && url.hash.startsWith('#/')) {
+ pathname = url.hash.substring(1);
+ }
+
+ // Check skip patterns
+ if (findMatchingPattern(pathname, this.config.skipPatterns)) {
+ return null;
+ }
+
+ // Apply mask patterns
+ const maskMatch = findMatchingPattern(pathname, this.config.maskPatterns);
+ if (maskMatch) {
+ pathname = maskMatch;
+ }
+
+ const payload: BasePayload = {
+ site_id: this.config.siteId,
+ hostname: url.hostname,
+ pathname: pathname,
+ querystring: this.config.trackQuerystring ? url.search : '',
+ screenWidth: window.innerWidth,
+ screenHeight: window.innerHeight,
+ language: navigator.language,
+ page_title: document.title,
+ referrer: document.referrer,
+ };
+
+ if (this.customUserId) {
+ payload.user_id = this.customUserId;
+ }
+
+ return payload;
+ }
+
+ async sendTrackingData(payload: TrackingPayload): Promise<void> {
+ try {
+ await fetch(`${this.config.analyticsHost}/track`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(payload),
+ mode: 'cors',
+ keepalive: true,
+ });
+ } catch (error) {
+ console.error('Failed to send tracking data:', error);
+ }
+ }
+
+ track(
+ eventType: TrackingPayload['type'],
+ eventName: string = '',
+ properties: Record<string, any> = {}
+ ): void {
+ if (eventType === 'custom_event' && (!eventName || typeof eventName !== 'string')) {
+ console.error('Event name is required and must be a string for custom events');
+ return;
+ }
+
+ const basePayload = this.createBasePayload();
+ if (!basePayload) {
+ return; // Skip tracking
+ }
+
+ const payload: TrackingPayload = {
+ ...basePayload,
+ type: eventType,
+ event_name: eventName,
+ properties: eventType === 'custom_event' || eventType === 'outbound'
+ ? JSON.stringify(properties)
+ : undefined,
+ };
+
+ this.sendTrackingData(payload);
+ }
+
+ trackPageview(): void {
+ this.track('pageview');
+ }
+
+ trackEvent(name: string, properties: Record<string, any> = {}): void {
+ this.track('custom_event', name, properties);
+ }
+
+ trackOutbound(url: string, text: string = '', target: string = '_self'): void {
+ this.track('outbound', '', { url, text, target });
+ }
+
+ trackWebVitals(vitals: WebVitalsData): void {
+ const basePayload = this.createBasePayload();
+ if (!basePayload) {
+ return;
+ }
+
+ const payload: TrackingPayload = {
+ ...basePayload,
+ type: 'performance',
+ event_name: 'web-vitals',
+ ...vitals,
+ };
+
+ this.sendTrackingData(payload);
+ }
+
+ identify(userId: string): void {
+ if (typeof userId !== 'string' || userId.trim() === '') {
+ console.error('User ID must be a non-empty string');
+ return;
+ }
+
+ this.customUserId = userId.trim();
+ try {
+ localStorage.setItem('rybbit-user-id', this.customUserId);
+ } catch (e) {
+ console.warn('Could not persist user ID to localStorage');
+ }
+ }
+
+ clearUserId(): void {
+ this.customUserId = null;
+ try {
+ localStorage.removeItem('rybbit-user-id');
+ } catch (e) {
+ // localStorage not available
+ }
+ }
+
+ getUserId(): string | null {
+ return this.customUserId;
+ }
+}
\ No newline at end of file
diff --git a/server/src/analytics-script/tsconfig.json b/server/src/analytics-script/tsconfig.json
new file mode 100644
index 000000000..a2d304c61
--- /dev/null
+++ b/server/src/analytics-script/tsconfig.json
@@ -0,0 +1,23 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "lib": ["ES2020", "DOM"],
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "moduleResolution": "node",
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "types": ["vitest/globals"]
+ },
+ "include": [
+ "*.ts"
+ ],
+ "exclude": [
+ "node_modules",
+ "*.test.ts",
+ "build.js"
+ ]
+}
\ No newline at end of file
diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.ts
new file mode 100644
index 000000000..f0778818d
--- /dev/null
+++ b/server/src/analytics-script/types.ts
@@ -0,0 +1,54 @@
+export interface ScriptConfig {
+ analyticsHost: string;
+ siteId: string;
+ debounceDuration: number;
+ autoTrackPageview: boolean;
+ autoTrackSpa: boolean;
+ trackQuerystring: boolean;
+ trackOutbound: boolean;
+ enableWebVitals: boolean;
+ skipPatterns: string[];
+ maskPatterns: string[];
+}
+
+export interface BasePayload {
+ site_id: string;
+ hostname: string;
+ pathname: string;
+ querystring: string;
+ screenWidth: number;
+ screenHeight: number;
+ language: string;
+ page_title: string;
+ referrer: string;
+ user_id?: string;
+}
+
+export interface TrackingPayload extends BasePayload {
+ type: 'pageview' | 'custom_event' | 'outbound' | 'performance';
+ event_name?: string;
+ properties?: string;
+ // Web vitals metrics
+ lcp?: number | null;
+ cls?: number | null;
+ inp?: number | null;
+ fcp?: number | null;
+ ttfb?: number | null;
+}
+
+export interface WebVitalsData {
+ lcp: number | null;
+ cls: number | null;
+ inp: number | null;
+ fcp: number | null;
+ ttfb: number | null;
+}
+
+export interface RybbitAPI {
+ pageview: () => void;
+ event: (name: string, properties?: Record<string, any>) => void;
+ trackOutbound: (url: string, text?: string, target?: string) => void;
+ identify: (userId: string) => void;
+ clearUserId: () => void;
+ getUserId: () => string | null;
+}
\ No newline at end of file
diff --git a/server/src/analytics-script/utils.test.ts b/server/src/analytics-script/utils.test.ts
new file mode 100644
index 000000000..4e3ff1352
--- /dev/null
+++ b/server/src/analytics-script/utils.test.ts
@@ -0,0 +1,149 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { patternToRegex, findMatchingPattern, debounce, isOutboundLink, parseJsonSafely } from './utils.js';
+
+describe('utils', () => {
+ describe('patternToRegex', () => {
+ it('should convert simple wildcards', () => {
+ const regex = patternToRegex('/api/*/users');
+ expect(regex.test('/api/v1/users')).toBe(true);
+ expect(regex.test('/api/v2/users')).toBe(true);
+ expect(regex.test('/api/v1/v2/users')).toBe(false);
+ });
+
+ it('should convert double wildcards', () => {
+ const regex = patternToRegex('/api/**/users');
+ expect(regex.test('/api/v1/users')).toBe(true);
+ expect(regex.test('/api/v1/v2/users')).toBe(true);
+ expect(regex.test('/api/users')).toBe(true); // ** can match empty path
+
+ // Test ** at beginning
+ const regex2 = patternToRegex('/**/users');
+ expect(regex2.test('/users')).toBe(true);
+ expect(regex2.test('/api/users')).toBe(true);
+ expect(regex2.test('/api/v1/users')).toBe(true);
+ });
+
+ it('should escape special regex characters', () => {
+ const regex = patternToRegex('/api/users.json');
+ expect(regex.test('/api/users.json')).toBe(true);
+ expect(regex.test('/api/usersXjson')).toBe(false);
+ });
+
+ it('should handle complex patterns', () => {
+ const regex = patternToRegex('/api/*/users/**/*.json');
+ expect(regex.test('/api/v1/users/123/profile.json')).toBe(true);
+ expect(regex.test('/api/v1/users/admin/settings/config.json')).toBe(true);
+ expect(regex.test('/api/v1/posts/123/data.json')).toBe(false);
+ });
+ });
+
+ describe('findMatchingPattern', () => {
+ const patterns = ['/api/*/users', '/admin/**', '*.json'];
+
+ it('should find matching pattern', () => {
+ expect(findMatchingPattern('/api/v1/users', patterns)).toBe('/api/*/users');
+ expect(findMatchingPattern('/admin/settings/general', patterns)).toBe('/admin/**');
+ });
+
+ it('should return null for no match', () => {
+ expect(findMatchingPattern('/public/images/logo.png', patterns)).toBe(null);
+ });
+
+ it('should handle invalid patterns gracefully', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const invalidPatterns = ['[invalid'];
+ expect(findMatchingPattern('/test', invalidPatterns)).toBe(null);
+ consoleSpy.mockRestore();
+ });
+ });
+
+ describe('debounce', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should debounce function calls', () => {
+ const fn = vi.fn();
+ const debouncedFn = debounce(fn, 100);
+
+ debouncedFn('a');
+ debouncedFn('b');
+ debouncedFn('c');
+
+ expect(fn).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(100);
+ expect(fn).toHaveBeenCalledOnce();
+ expect(fn).toHaveBeenCalledWith('c');
+ });
+
+ it('should reset timer on each call', () => {
+ const fn = vi.fn();
+ const debouncedFn = debounce(fn, 100);
+
+ debouncedFn();
+ vi.advanceTimersByTime(50);
+ debouncedFn();
+ vi.advanceTimersByTime(50);
+
+ expect(fn).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(50);
+ expect(fn).toHaveBeenCalledOnce();
+ });
+ });
+
+ describe('isOutboundLink', () => {
+ beforeEach(() => {
+ // Mock window.location
+ Object.defineProperty(window, 'location', {
+ value: {
+ hostname: 'example.com'
+ },
+ writable: true
+ });
+ });
+
+ it('should detect outbound links', () => {
+ expect(isOutboundLink('https://external.com/page')).toBe(true);
+ expect(isOutboundLink('http://another-site.org')).toBe(true);
+ });
+
+ it('should detect internal links', () => {
+ expect(isOutboundLink('https://example.com/page')).toBe(false);
+ expect(isOutboundLink('/relative/path')).toBe(false);
+ });
+
+ it('should handle invalid URLs', () => {
+ expect(isOutboundLink('not-a-url')).toBe(false);
+ expect(isOutboundLink('')).toBe(false);
+ });
+ });
+
+ describe('parseJsonSafely', () => {
+ it('should parse valid JSON', () => {
+ expect(parseJsonSafely('["a", "b"]', [])).toEqual(['a', 'b']);
+ expect(parseJsonSafely('{"key": "value"}', {})).toEqual({ key: 'value' });
+ });
+
+ it('should return fallback for invalid JSON', () => {
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(parseJsonSafely('invalid', [])).toEqual([]);
+ expect(parseJsonSafely('{invalid}', {})).toEqual({});
+ consoleSpy.mockRestore();
+ });
+
+ it('should return fallback for null/empty values', () => {
+ expect(parseJsonSafely(null, ['default'])).toEqual(['default']);
+ expect(parseJsonSafely('', { default: true })).toEqual({ default: true });
+ });
+
+ it('should enforce array type when fallback is array', () => {
+ expect(parseJsonSafely('{"not": "array"}', [])).toEqual([]);
+ });
+ });
+});
\ No newline at end of file
diff --git a/server/src/analytics-script/utils.ts b/server/src/analytics-script/utils.ts
new file mode 100644
index 000000000..fed76289a
--- /dev/null
+++ b/server/src/analytics-script/utils.ts
@@ -0,0 +1,91 @@
+/**
+ * Convert wildcard pattern to regex
+ */
+export function patternToRegex(pattern: string): RegExp {
+ 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 (except our tokens)
+ let escaped = tokenized.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
+
+ // Handle ** patterns specially before escaping slashes
+ // Replace /**/ with a pattern that matches / or /anything/
+ escaped = escaped.replace(new RegExp(`/${DOUBLE_WILDCARD_TOKEN}/`, 'g'), '/(?:.+/)?');
+
+ // Replace remaining ** (at start or end)
+ escaped = escaped.replace(new RegExp(DOUBLE_WILDCARD_TOKEN, 'g'), '.*');
+
+ // Now escape forward slashes
+ escaped = escaped.replace(/\//g, '\\/');
+
+ // Replace single wildcards
+ let regexPattern = escaped.replace(new RegExp(SINGLE_WILDCARD_TOKEN, 'g'), '[^/]+');
+
+ return new RegExp('^' + regexPattern + '$');
+}
+
+/**
+ * Find matching pattern from a list of patterns
+ */
+export function findMatchingPattern(path: string, patterns: string[]): string | null {
+ for (const pattern of patterns) {
+ try {
+ const regex = patternToRegex(pattern);
+ if (regex.test(path)) {
+ return pattern;
+ }
+ } catch (e) {
+ console.error(`Invalid pattern: ${pattern}`, e);
+ }
+ }
+ return null;
+}
+
+/**
+ * Debounce function implementation
+ */
+export function debounce<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): (...args: Parameters<T>) => void {
+ let timeout: NodeJS.Timeout | null = null;
+
+ return (...args: Parameters<T>) => {
+ if (timeout) {
+ clearTimeout(timeout);
+ }
+ timeout = setTimeout(() => func(...args), wait);
+ };
+}
+
+/**
+ * Check if a URL is an outbound link
+ */
+export function isOutboundLink(url: string): boolean {
+ try {
+ const currentHost = window.location.hostname;
+ const linkHost = new URL(url).hostname;
+ return linkHost !== currentHost && linkHost !== '';
+ } catch (e) {
+ return false;
+ }
+}
+
+/**
+ * Parse JSON safely with fallback
+ */
+export function parseJsonSafely<T>(value: string | null, fallback: T): T {
+ if (!value) return fallback;
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(fallback) && !Array.isArray(parsed) ? fallback : parsed;
+ } catch (e) {
+ console.error('Error parsing JSON:', e);
+ return fallback;
+ }
+}
\ No newline at end of file
diff --git a/server/src/analytics-script/webVitals.test.ts b/server/src/analytics-script/webVitals.test.ts
new file mode 100644
index 000000000..b4dfd72c4
--- /dev/null
+++ b/server/src/analytics-script/webVitals.test.ts
@@ -0,0 +1,163 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { WebVitalsCollector } from './webVitals.js';
+
+// Mock web-vitals module
+vi.mock('web-vitals', () => ({
+ onLCP: vi.fn(),
+ onCLS: vi.fn(),
+ onINP: vi.fn(),
+ onFCP: vi.fn(),
+ onTTFB: vi.fn(),
+}));
+
+import { onLCP, onCLS, onINP, onFCP, onTTFB } from 'web-vitals';
+
+describe('WebVitalsCollector', () => {
+ let collector: WebVitalsCollector;
+ let onReadyCallback: ReturnType<typeof vi.fn>;
+ let mockMetricCallbacks: Map<Function, Function>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ onReadyCallback = vi.fn();
+ mockMetricCallbacks = new Map();
+
+ // Setup mocks to capture callbacks
+ vi.mocked(onLCP).mockImplementation((callback) => {
+ mockMetricCallbacks.set(onLCP, callback);
+ });
+ vi.mocked(onCLS).mockImplementation((callback) => {
+ mockMetricCallbacks.set(onCLS, callback);
+ });
+ vi.mocked(onINP).mockImplementation((callback) => {
+ mockMetricCallbacks.set(onINP, callback);
+ });
+ vi.mocked(onFCP).mockImplementation((callback) => {
+ mockMetricCallbacks.set(onFCP, callback);
+ });
+ vi.mocked(onTTFB).mockImplementation((callback) => {
+ mockMetricCallbacks.set(onTTFB, callback);
+ });
+
+ collector = new WebVitalsCollector(onReadyCallback);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should initialize and register all metric callbacks', () => {
+ collector.initialize();
+
+ expect(onLCP).toHaveBeenCalled();
+ expect(onCLS).toHaveBeenCalled();
+ expect(onINP).toHaveBeenCalled();
+ expect(onFCP).toHaveBeenCalled();
+ expect(onTTFB).toHaveBeenCalled();
+ });
+
+ it('should collect individual metrics', () => {
+ collector.initialize();
+
+ // Simulate LCP metric
+ const lcpCallback = mockMetricCallbacks.get(onLCP)!;
+ lcpCallback({ name: 'LCP', value: 2500 });
+
+ const data = collector.getData();
+ expect(data.lcp).toBe(2500);
+ expect(data.cls).toBeNull();
+ });
+
+ it('should trigger callback when all metrics are collected', () => {
+ collector.initialize();
+
+ // Simulate all metrics
+ mockMetricCallbacks.get(onLCP)!({ name: 'LCP', value: 2500 });
+ mockMetricCallbacks.get(onCLS)!({ name: 'CLS', value: 0.1 });
+ mockMetricCallbacks.get(onINP)!({ name: 'INP', value: 200 });
+ mockMetricCallbacks.get(onFCP)!({ name: 'FCP', value: 1800 });
+ mockMetricCallbacks.get(onTTFB)!({ name: 'TTFB', value: 800 });
+
+ expect(onReadyCallback).toHaveBeenCalledWith({
+ lcp: 2500,
+ cls: 0.1,
+ inp: 200,
+ fcp: 1800,
+ ttfb: 800,
+ });
+ });
+
+ it('should only send data once', () => {
+ collector.initialize();
+
+ // Collect all metrics
+ mockMetricCallbacks.get(onLCP)!({ name: 'LCP', value: 2500 });
+ mockMetricCallbacks.get(onCLS)!({ name: 'CLS', value: 0.1 });
+ mockMetricCallbacks.get(onINP)!({ name: 'INP', value: 200 });
+ mockMetricCallbacks.get(onFCP)!({ name: 'FCP', value: 1800 });
+ mockMetricCallbacks.get(onTTFB)!({ name: 'TTFB', value: 800 });
+
+ // Try to send another metric
+ mockMetricCallbacks.get(onLCP)!({ name: 'LCP', value: 3000 });
+
+ expect(onReadyCallback).toHaveBeenCalledTimes(1);
+ expect(collector.getData().lcp).toBe(2500); // Original value
+ });
+
+ it('should send data after timeout even if not all metrics collected', () => {
+ collector.initialize();
+
+ // Only collect some metrics
+ mockMetricCallbacks.get(onLCP)!({ name: 'LCP', value: 2500 });
+ mockMetricCallbacks.get(onCLS)!({ name: 'CLS', value: 0.1 });
+
+ expect(onReadyCallback).not.toHaveBeenCalled();
+
+ // Advance timer past 20 seconds
+ vi.advanceTimersByTime(20000);
+
+ expect(onReadyCallback).toHaveBeenCalledWith({
+ lcp: 2500,
+ cls: 0.1,
+ inp: null,
+ fcp: null,
+ ttfb: null,
+ });
+ });
+
+ it('should send data on beforeunload event', () => {
+ collector.initialize();
+
+ // Collect some metrics
+ mockMetricCallbacks.get(onLCP)!({ name: 'LCP', value: 2500 });
+
+ // Trigger beforeunload
+ window.dispatchEvent(new Event('beforeunload'));
+
+ expect(onReadyCallback).toHaveBeenCalledWith({
+ lcp: 2500,
+ cls: null,
+ inp: null,
+ fcp: null,
+ ttfb: null,
+ });
+ });
+
+ it('should handle initialization errors gracefully', () => {
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // Make onLCP throw an error
+ vi.mocked(onLCP).mockImplementation(() => {
+ throw new Error('Test error');
+ });
+
+ collector.initialize();
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ 'Error initializing web vitals tracking:',
+ expect.any(Error)
+ );
+
+ consoleSpy.mockRestore();
+ });
+});
\ No newline at end of file
diff --git a/server/src/analytics-script/webVitals.ts b/server/src/analytics-script/webVitals.ts
new file mode 100644
index 000000000..6f47c3efa
--- /dev/null
+++ b/server/src/analytics-script/webVitals.ts
@@ -0,0 +1,80 @@
+import { onLCP, onCLS, onINP, onFCP, onTTFB, Metric } from 'web-vitals';
+import { WebVitalsData } from './types.js';
+
+export class WebVitalsCollector {
+ private data: WebVitalsData = {
+ lcp: null,
+ cls: null,
+ inp: null,
+ fcp: null,
+ ttfb: null,
+ };
+
+ private sent = false;
+ private timeout: NodeJS.Timeout | null = null;
+ private onReadyCallback: ((data: WebVitalsData) => void) | null = null;
+
+ constructor(onReady: (data: WebVitalsData) => void) {
+ this.onReadyCallback = onReady;
+ }
+
+ initialize(): void {
+ try {
+ // Track Core Web Vitals
+ onLCP(this.collectMetric.bind(this));
+ onCLS(this.collectMetric.bind(this));
+ onINP(this.collectMetric.bind(this));
+
+ // Track additional metrics
+ onFCP(this.collectMetric.bind(this));
+ onTTFB(this.collectMetric.bind(this));
+
+ // Set timeout to send metrics even if not all are collected
+ this.timeout = setTimeout(() => {
+ if (!this.sent) {
+ this.sendData();
+ }
+ }, 20000);
+
+ // Send on page unload
+ window.addEventListener('beforeunload', () => {
+ if (!this.sent) {
+ this.sendData();
+ }
+ });
+ } catch (e) {
+ console.warn('Error initializing web vitals tracking:', e);
+ }
+ }
+
+ private collectMetric(metric: Metric): void {
+ if (this.sent) return;
+
+ const metricName = metric.name.toLowerCase() as keyof WebVitalsData;
+ this.data[metricName] = metric.value;
+
+ // Check if all metrics are collected
+ const allCollected = Object.values(this.data).every(value => value !== null);
+ if (allCollected) {
+ this.sendData();
+ }
+ }
+
+ private sendData(): void {
+ if (this.sent) return;
+ this.sent = true;
+
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+
+ if (this.onReadyCallback) {
+ this.onReadyCallback(this.data);
+ }
+ }
+
+ getData(): WebVitalsData {
+ return { ...this.data };
+ }
+}
\ No newline at end of file
diff --git a/server/vitest.config.ts b/server/vitest.config.ts
index c7eb54768..154067cb5 100644
--- a/server/vitest.config.ts
+++ b/server/vitest.config.ts
@@ -6,6 +6,10 @@ export default defineConfig({
globals: true,
include: ["src/**/*.test.ts"],
exclude: ["node_modules", "dist"],
+ environmentMatchGlobs: [
+ // Use jsdom for analytics script tests
+ ["src/analytics-script/**", "jsdom"],
+ ],
},
resolve: {
alias: {