1
0
Fork 0

Merge branch 'feat/first-party-analytics'

# Conflicts:
#	src/migrations/index.ts
This commit is contained in:
Jason Fraley 2026-10-15 00:17:58 -04:00
commit 1d6db3b92b
66 changed files with 86487 additions and 20 deletions

View file

@ -66,6 +66,7 @@
"react-dom": "19.2.3",
"react-leaflet": "^5.0.0",
"react-markdown": "10.1.0",
"recharts": "3.8.0",
"rehype-highlight": "^7.0.2",
"remark-directive": "4.0.0",
"remark-gfm": "4.0.1",
@ -765,6 +766,8 @@
"@redis/time-series": ["@redis/time-series@1.1.0", "", { "peerDependencies": { "@redis/client": "^1.0.0" } }, "sha512-c1Q99M5ljsIuc4YdaCwfUEXsofakb9c8+Zse2qxTadu8TalLXuAESzLvFAvNVbkmSlvlzIQOLpBCmWI9wTOt+g=="],
"@reduxjs/toolkit": ["@reduxjs/toolkit@2.13.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-f6jwVRfwW30+tnllz4YcsHHpPYYOE7abcHkyUCovD+P7DyhdAI5prz2Fh/8TLhakjpN+7aIEion1s5L/tvlYlA=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.53", "", {}, "sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.52.4", "", { "os": "android", "cpu": "arm" }, "sha512-BTm2qKNnWIQ5auf4deoetINJm2JzvihvGb9R6K/ETwKLql/Bb3Eg2H1FBp1gUb4YGbydMA3jcmQTR73q7J+GAA=="],
@ -923,6 +926,8 @@
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
"@swc/helpers": ["@swc/helpers@0.5.15", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g=="],
"@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],
@ -981,14 +986,28 @@
"@types/chai": ["@types/chai@5.2.2", "", { "dependencies": { "@types/deep-eql": "4.0.2" } }, "sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg=="],
"@types/d3-array": ["@types/d3-array@3.2.2", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
"@types/d3-color": ["@types/d3-color@3.1.3", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
"@types/d3-drag": ["@types/d3-drag@3.0.7", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ=="],
"@types/d3-ease": ["@types/d3-ease@3.0.2", "", {}, "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="],
"@types/d3-interpolate": ["@types/d3-interpolate@3.0.4", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="],
"@types/d3-path": ["@types/d3-path@3.1.1", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
"@types/d3-scale": ["@types/d3-scale@4.0.9", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],
"@types/d3-selection": ["@types/d3-selection@3.0.11", "", {}, "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w=="],
"@types/d3-shape": ["@types/d3-shape@3.2.0", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw=="],
"@types/d3-time": ["@types/d3-time@3.0.4", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
"@types/d3-timer": ["@types/d3-timer@3.0.2", "", {}, "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="],
"@types/d3-transition": ["@types/d3-transition@3.0.9", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg=="],
"@types/d3-zoom": ["@types/d3-zoom@3.0.8", "", { "dependencies": { "@types/d3-interpolate": "*", "@types/d3-selection": "*" } }, "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw=="],
@ -1035,6 +1054,8 @@
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
"@types/use-sync-external-store": ["@types/use-sync-external-store@0.0.6", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
@ -1321,6 +1342,8 @@
"cycle": ["cycle@1.0.3", "", {}, "sha512-TVF6svNzeQCOpjCqsy0/CSy8VgObG3wXusJ73xW2GbG5rGx7lC8zxDSURicsXI2UsGdi2L0QNRCi745/wUDvsA=="],
"d3-array": ["d3-array@3.2.4", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
"d3-color": ["d3-color@3.1.0", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
"d3-dispatch": ["d3-dispatch@3.0.1", "", {}, "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg=="],
@ -1329,10 +1352,22 @@
"d3-ease": ["d3-ease@3.0.1", "", {}, "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w=="],
"d3-format": ["d3-format@3.1.2", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="],
"d3-interpolate": ["d3-interpolate@3.0.1", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
"d3-path": ["d3-path@3.1.0", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
"d3-scale": ["d3-scale@4.0.2", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
"d3-selection": ["d3-selection@3.0.0", "", {}, "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ=="],
"d3-shape": ["d3-shape@3.2.0", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
"d3-time": ["d3-time@3.1.0", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
"d3-time-format": ["d3-time-format@4.1.0", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
"d3-timer": ["d3-timer@3.0.1", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
"d3-transition": ["d3-transition@3.0.1", "", { "dependencies": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", "d3-ease": "1 - 3", "d3-interpolate": "1 - 3", "d3-timer": "1 - 3" }, "peerDependencies": { "d3-selection": "2 - 3" } }, "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w=="],
@ -1361,6 +1396,8 @@
"decimal.js": ["decimal.js@10.6.0", "", {}, "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg=="],
"decimal.js-light": ["decimal.js-light@2.5.1", "", {}, "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg=="],
"decode-named-character-reference": ["decode-named-character-reference@1.2.0", "", { "dependencies": { "character-entities": "2.0.2" } }, "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q=="],
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
@ -1441,6 +1478,8 @@
"es-to-primitive": ["es-to-primitive@1.3.0", "", { "dependencies": { "is-callable": "1.2.7", "is-date-object": "1.1.0", "is-symbol": "1.1.1" } }, "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g=="],
"es-toolkit": ["es-toolkit@1.52.0", "", {}, "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA=="],
"esbuild": ["esbuild@0.25.11", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.11", "@esbuild/android-arm": "0.25.11", "@esbuild/android-arm64": "0.25.11", "@esbuild/android-x64": "0.25.11", "@esbuild/darwin-arm64": "0.25.11", "@esbuild/darwin-x64": "0.25.11", "@esbuild/freebsd-arm64": "0.25.11", "@esbuild/freebsd-x64": "0.25.11", "@esbuild/linux-arm": "0.25.11", "@esbuild/linux-arm64": "0.25.11", "@esbuild/linux-ia32": "0.25.11", "@esbuild/linux-loong64": "0.25.11", "@esbuild/linux-mips64el": "0.25.11", "@esbuild/linux-ppc64": "0.25.11", "@esbuild/linux-riscv64": "0.25.11", "@esbuild/linux-s390x": "0.25.11", "@esbuild/linux-x64": "0.25.11", "@esbuild/netbsd-arm64": "0.25.11", "@esbuild/netbsd-x64": "0.25.11", "@esbuild/openbsd-arm64": "0.25.11", "@esbuild/openbsd-x64": "0.25.11", "@esbuild/openharmony-arm64": "0.25.11", "@esbuild/sunos-x64": "0.25.11", "@esbuild/win32-arm64": "0.25.11", "@esbuild/win32-ia32": "0.25.11", "@esbuild/win32-x64": "0.25.11" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q=="],
"esbuild-register": ["esbuild-register@3.6.0", "", { "dependencies": { "debug": "4.4.3" }, "peerDependencies": { "esbuild": "0.25.11" } }, "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg=="],
@ -1491,6 +1530,8 @@
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="],
"events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
@ -1683,6 +1724,8 @@
"image-dimensions": ["image-dimensions@2.5.1", "", { "bin": { "image-dimensions": "cli.js" } }, "sha512-It7CkTNp7IYA8jhvGgz8K18OAbHF3/Juk8RNEyTyMFfolJOIU1Y2wGDnzDQPbGCjyxVF/++pwIZE0BKJUEOb1g=="],
"immer": ["immer@10.2.0", "", {}, "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw=="],
"immutable": ["immutable@4.3.7", "", {}, "sha512-1hqclzwYwjRDFLjcFxOM5AYkkG0rpFPpr1RLPMEuGczoS7YA8gLhy8SWXYRAA/XwfEHpfo3cw5JGioS32fnMRw=="],
"import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "1.0.1", "resolve-from": "4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
@ -1695,6 +1738,8 @@
"internal-slot": ["internal-slot@1.1.0", "", { "dependencies": { "es-errors": "1.3.0", "hasown": "2.0.2", "side-channel": "1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
"invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="],
"ip-address": ["ip-address@10.5.0", "", {}, "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g=="],
@ -2239,6 +2284,8 @@
"react-mentions": ["react-mentions@4.4.10", "", { "dependencies": { "@babel/runtime": "7.4.5", "invariant": "^2.2.4", "prop-types": "^15.5.8", "substyle": "^9.1.0" }, "peerDependencies": { "react": ">=16.8.3", "react-dom": ">=16.8.3" } }, "sha512-JHiQlgF1oSZR7VYPjq32wy97z1w1oE4x10EuhKjPr4WUKhVzG1uFQhQjKqjQkbVqJrmahf+ldgBTv36NrkpKpA=="],
"react-redux": ["react-redux@9.3.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-KQopgqFo/p/fgmAs5qz6p5RWaNAzq40WAu7fJIXnQpYxFPbJYtsJPWvGeF2rOBaY/kEuV77AVsX8TsQzKm+A/g=="],
"react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "2.3.8", "react-style-singleton": "2.2.3", "tslib": "2.8.1", "use-callback-ref": "1.3.3", "use-sidecar": "1.1.3" }, "optionalDependencies": { "@types/react": "19.2.7" }, "peerDependencies": { "react": "19.2.3" } }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
@ -2259,8 +2306,14 @@
"real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="],
"recharts": ["recharts@3.8.0", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^10.1.1", "react-redux": "8.x.x || 9.x.x", "reselect": "5.1.1", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Z/m38DX3L73ExO4Tpc9/iZWHmHnlzWG4njQbxsF5aSjwqmHNDDIm0rdEBArkwsBvR8U6EirlEHiQNYWCVh9sGQ=="],
"redis": ["redis@4.7.1", "", { "dependencies": { "@redis/bloom": "1.2.0", "@redis/client": "1.6.1", "@redis/graph": "1.1.1", "@redis/json": "1.0.7", "@redis/search": "1.2.0", "@redis/time-series": "1.1.0" } }, "sha512-S1bJDnqLftzHXHP8JsT5II/CtHWQrASX5K96REjWjlmWKrviSOLWmM7QnRLstAWsu1VBBV1ffV6DzCvxNP0UJQ=="],
"redux": ["redux@5.0.1", "", {}, "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w=="],
"redux-thunk": ["redux-thunk@3.1.0", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
"reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "1.0.8", "define-properties": "1.2.1", "es-abstract": "1.24.0", "es-errors": "1.3.0", "es-object-atoms": "1.1.1", "get-intrinsic": "1.3.0", "get-proto": "1.0.1", "which-builtin-type": "1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
"regenerator-runtime": ["regenerator-runtime@0.13.11", "", {}, "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="],
@ -2281,6 +2334,8 @@
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"reselect": ["reselect@5.1.1", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
"resolve": ["resolve@1.22.10", "", { "dependencies": { "is-core-module": "2.16.1", "path-parse": "1.0.7", "supports-preserve-symlinks-flag": "1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w=="],
"resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
@ -2451,6 +2506,8 @@
"throttleit": ["throttleit@2.1.0", "", {}, "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw=="],
"tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
"tinyexec": ["tinyexec@1.0.2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],
@ -2577,6 +2634,8 @@
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "3.0.3", "unist-util-stringify-position": "4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
"victory-vendor": ["victory-vendor@37.3.6", "", { "dependencies": { "@types/d3-array": "^3.0.3", "@types/d3-ease": "^3.0.0", "@types/d3-interpolate": "^3.0.1", "@types/d3-scale": "^4.0.2", "@types/d3-shape": "^3.1.0", "@types/d3-time": "^3.0.0", "@types/d3-timer": "^3.0.0", "d3-array": "^3.1.6", "d3-ease": "^3.0.1", "d3-interpolate": "^3.0.1", "d3-scale": "^4.0.2", "d3-shape": "^3.1.0", "d3-time": "^3.0.0", "d3-timer": "^3.0.1" } }, "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ=="],
"vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "0.25.11", "fdir": "6.5.0", "picomatch": "4.0.3", "postcss": "8.5.6", "rollup": "4.52.4", "tinyglobby": "0.2.15" }, "optionalDependencies": { "@types/node": "25.0.3", "fsevents": "2.3.3", "jiti": "2.6.1", "lightningcss": "1.30.2", "sass": "1.77.4", "tsx": "4.20.6" }, "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="],
"vite-tsconfig-paths": ["vite-tsconfig-paths@6.0.1", "", { "dependencies": { "debug": "4.4.3", "globrex": "0.1.2", "tsconfck": "3.1.6" }, "optionalDependencies": { "vite": "7.1.10" } }, "sha512-OQuYkfCQhc2T+n//0N7/oogTosgiSyZQ7dydrpUlH5SbnFTtplpekdY4GMi6jDwEpiwWlqeUJMyPfC2ePM1+2A=="],
@ -2727,6 +2786,8 @@
"@redis/client/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
"@reduxjs/toolkit/immer": ["immer@11.1.21", "", {}, "sha512-bZSadeCPGdaY5/qRLgr6mDSH1ra21rD3rqpiWk7+QTr4ayYPTE9qZYdLh/NdPhMe0wSrTvHD/Lk8q5EwhUs0aw=="],
"@tailwindcss/node/jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
"@tailwindcss/node/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],

View file

@ -94,6 +94,7 @@
"react-dom": "19.2.3",
"react-leaflet": "^5.0.0",
"react-markdown": "10.1.0",
"recharts": "3.8.0",
"rehype-highlight": "^7.0.2",
"remark-directive": "4.0.0",
"remark-gfm": "4.0.1",

View file

@ -81,6 +81,9 @@ export default defineConfig({
env: {
...process.env,
DATABASE_URI: testDatabaseUri,
// Enable the first-party analytics tracker in the dev server so the
// analytics e2e smoke can assert rows land.
NEXT_PUBLIC_ANALYTICS_DEV: "1",
},
},
globalSetup: "./tests/e2e/global-setup.ts",

View file

@ -9,6 +9,7 @@ import type { Journal, Mission, User } from "@/payload-types";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { cn } from "@/lib/utils";
import { ChronicleArticle } from "@/lib/client-analytics/chronicle";
import { BEAT_BODY_CLASSES } from "@/lib/story/richtextClasses";
import { formatJournalDate } from "@/lib/journals/dates";
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
@ -135,9 +136,11 @@ export default async function JournalDetailPage({
/>
</header>
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
<RichText data={journal.body} />
</article>
<ChronicleArticle kind="journal" articleId={String(journal.id)}>
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
<RichText data={journal.body} />
</article>
</ChronicleArticle>
</div>
);
}

View file

@ -36,6 +36,7 @@ import type { AnnouncementEntry } from "@/lib/announcements/evaluate";
import { TourHost } from "@/components/frontend/tours/TourHost";
import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
import type { RegistryGame } from "@/lib/minigames/registry";
@ -250,6 +251,7 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
<Toaster />
<ShimLoader shims={shimEntries} userId={user?.id ?? null} userRoles={user?.roles ?? []} />
<ClarityAnalytics />
<AnalyticsTracker />
</body>
</html>
);

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Club } from "lucide-react";
import { BlackjackArena } from "@/components/frontend/minigames/blackjack/BlackjackArena";
@ -66,6 +67,9 @@ export default async function BlackjackPage({ searchParams }: BlackjackPageProps
return (
<div className="flex flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Club className="size-5 text-muted-foreground" />

View file

@ -5,6 +5,7 @@ import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { Swords } from "lucide-react";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { CallForFireVersusArena } from "@/components/frontend/minigames/call-for-fire-versus/CallForFireVersusArena";
@ -62,6 +63,9 @@ export default async function CallForFireVersusPage({ searchParams }: VersusPage
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Swords className="size-5 text-muted-foreground" />

View file

@ -6,6 +6,8 @@ import { redirect } from "next/navigation";
import { Target } from "lucide-react";
import { CallForFireArena } from "@/components/frontend/minigames/call-for-fire/CallForFireArena";
import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
export const metadata: Metadata = {
title: "Call for Fire (Polaris Task Force)",
@ -22,6 +24,8 @@ export default async function CallForFirePage() {
redirect(`/login?returnTo=${encodeURIComponent("/minigames/call-for-fire")}`);
}
const release = await getMinigameReleaseState(payload, "callForFire");
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
@ -50,6 +54,9 @@ export default async function CallForFirePage() {
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Target className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Bomb } from "lucide-react";
import { EodArena } from "@/components/frontend/minigames/eod/EodArena";
@ -57,6 +58,9 @@ export default async function EodPage() {
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Bomb className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Bird } from "lucide-react";
import { FlappyArena } from "@/components/frontend/minigames/flappy/FlappyArena";
@ -54,6 +55,9 @@ export default async function FlappyPage() {
return (
<div className="p-5 flex flex-col gap-6">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Bird className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { ScrollText } from "lucide-react";
import { OpordArena } from "@/components/frontend/minigames/opord/OpordArena";
@ -58,6 +59,9 @@ export default async function OpordPage() {
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<ScrollText className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Spade } from "lucide-react";
import { PokerArena } from "@/components/frontend/minigames/poker/PokerArena";
@ -66,6 +67,9 @@ export default async function PokerPage({ searchParams }: PokerPageProps) {
return (
<div className="flex flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Spade className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Crosshair } from "lucide-react";
@ -62,6 +63,9 @@ export default async function QualificationPage() {
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Crosshair className="size-5 text-muted-foreground" />

View file

@ -4,6 +4,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { redirect } from "next/navigation";
import { MinigameComingSoon } from "@/components/frontend/minigames/MinigameComingSoon";
import { PhasingOutBanner } from "@/components/frontend/minigames/PhasingOutBanner";
import { getMinigameReleaseState } from "@/lib/minigames/loadRegistry";
import { Radio } from "lucide-react";
import { RadioArena } from "@/components/frontend/minigames/radio/RadioArena";
@ -66,6 +67,9 @@ export default async function RadioPage() {
return (
<div className="flex min-w-0 flex-col gap-6 p-5">
{release.game?.status === "phasingOut" && (
<PhasingOutBanner estimatedRemovalDate={release.game.estimatedRemovalDate} />
)}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<Radio className="size-5 text-muted-foreground" />

View file

@ -8,6 +8,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { LockdownBanner } from "@/components/frontend/wiki/LockdownBanner";
import { WikiPageViewMeta } from "@/components/frontend/wiki/WikiPageViewMeta";
import { WikiContent } from "@/components/frontend/wiki/WikiContent";
import { WikiToolbar } from "@/components/frontend/wiki/WikiToolbar";
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
@ -238,6 +239,8 @@ export default async function WikiDetailPage({
{lockdown && <LockdownBanner />}
<WikiPageViewMeta slug={page.slug} />
<article>
<WikiContent
prepared={prepared}

View file

@ -49,6 +49,7 @@ import { default as default_05548cb43495e62d80b80ec4d9f0f7e9 } from '@/component
import { default as default_459d6b6f5ead73c736013da63a5ace3f } from '@/components/static/GoToFrontendLink'
import { InstructionsProvider as InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_2b34d0df0cf91f4442ca2cd62ae7cd94 } from '@/components/admin/tech-tree/TechTreeView'
import { default as default_56514cbb96bba531e9cd351ac4f78023 } from '@/components/admin/analytics/AnalyticsView'
import { default as default_f3a799acf91e60a0d7a8ec121a8f5690 } from '@/components/admin/dashboard/CollectionCards'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
@ -105,6 +106,7 @@ export const importMap = {
"@/components/static/GoToFrontendLink#default": default_459d6b6f5ead73c736013da63a5ace3f,
"@ai-stack/payloadcms/client#InstructionsProvider": InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/tech-tree/TechTreeView#default": default_2b34d0df0cf91f4442ca2cd62ae7cd94,
"@/components/admin/analytics/AnalyticsView#default": default_56514cbb96bba531e9cd351ac4f78023,
"@/components/admin/dashboard/CollectionCards#default": default_f3a799acf91e60a0d7a8ec121a8f5690,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}

View file

@ -0,0 +1,102 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import { parseCollectEnvelope, resolveAnalyticsEnv } from "@/lib/analytics/events";
import { checkCollectRateLimit, ingestBatch } from "@/lib/analytics/ingest";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Analytics collector (Phase 1).
*
* First-party replacement for Microsoft Clarity: accepts batched beacon
* envelopes `{ sid, aid, events }` from `<AnalyticsTracker />`, enriches them
* server-side (full IP, UA, referrer, user attribution via the same-origin
* payload-token cookie) and writes the plain analytics tables directly. Not
* a Payload operation by design; see `src/lib/analytics/ingest.ts`.
*
* Always answers 204 on success so beacons stay cheap. Bots are dropped
* silently; per-IP rate limiting blunts abuse (429).
*/
/** First-party cookie carrying the collector-issued session id. */
export const ANALYTICS_SID_COOKIE = "ptf_analytics_sid";
const SID_COOKIE_MAX_AGE = 7 * 24 * 60 * 60;
function clientIp(req: NextRequest): string | null {
// Single-instance deployment behind nginx: the first XFF hop is the client.
const forwarded = req.headers.get("x-forwarded-for");
if (forwarded) {
const first = forwarded.split(",")[0]?.trim();
if (first) return first;
}
return req.headers.get("x-real-ip") ?? req.headers.get("cf-connecting-ip") ?? null;
}
async function readBeaconBody(req: NextRequest): Promise<unknown> {
// sendBeacon may deliver application/json or text/plain depending on how
// the Blob was constructed, and fetch keepalive sends what it is told;
// parse defensively from raw text.
const text = await req.text();
if (!text) return null;
try {
return JSON.parse(text);
} catch {
return null;
}
}
export async function POST(req: NextRequest) {
const ip = clientIp(req);
if (!checkCollectRateLimit(ip)) {
return NextResponse.json({ error: "Too many analytics requests" }, { status: 429 });
}
const body = await readBeaconBody(req);
const parsed = parseCollectEnvelope(body);
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 });
}
const payload = await getPayload({ config: await config });
// Attribution against the same-origin payload-token cookie. Anonymous
// guests simply have no user; ingest links sessions on first authed flush.
let userId: number | null = null;
try {
const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false });
userId = user?.id ?? null;
} catch {
userId = null;
}
try {
const result = await ingestBatch(payload, parsed.envelope, {
ip,
ua: req.headers.get("user-agent"),
referrer: req.headers.get("referer"),
userId,
env: resolveAnalyticsEnv(process.env.NODE_ENV),
});
const response = new NextResponse(null, { status: 204 });
if (!result.isBot && result.sessionId) {
// (Re)issue the first-party session cookie so the client SDK can echo
// the id back on every flush without trusting its own storage.
response.cookies.set(ANALYTICS_SID_COOKIE, result.sessionId, {
path: "/",
maxAge: SID_COOKIE_MAX_AGE,
httpOnly: false,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
});
}
return response;
} catch (error) {
payload.logger.error(`[analytics] collect failed: ${String(error)}`);
return NextResponse.json({ error: "Analytics ingest failed" }, { status: 500 });
}
}

View file

@ -1,5 +1,6 @@
import "@/app/(frontend)/styles.css";
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
export default function LoginLayout(props: { children: React.ReactNode }) {
return (
@ -7,6 +8,7 @@ export default function LoginLayout(props: { children: React.ReactNode }) {
<body className="h-full font-sans m-0 text-white">
{props.children}
<ClarityAnalytics />
<AnalyticsTracker />
</body>
</html>
);

View file

@ -72,6 +72,7 @@ export const Minigames: CollectionConfig = {
{ label: "Active", value: "active" },
{ label: "Upcoming", value: "upcoming" },
{ label: "Retired", value: "retired" },
{ label: "Phasing out", value: "phasingOut" },
],
},
{
@ -83,6 +84,15 @@ export const Minigames: CollectionConfig = {
"Optional target for an upcoming game. Shown as a countdown in the sidebar and on the game page. Display only: the game goes live when status changes to Active.",
},
},
{
name: "estimatedRemovalDate",
type: "date",
admin: {
date: { pickerAppearance: "dayAndTime" },
description:
"Optional target for a phasing-out game. Shown as a countdown in the sidebar and on the game page so operators know when it leaves. Display only: the game stays playable until status changes to Retired.",
},
},
{ name: "order", type: "number", required: true, defaultValue: 0 },
{
name: "countsForPeriods",

View file

@ -0,0 +1,138 @@
"use client";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { DailyPoint, GameReportRow, ScrollBucket } from "@/lib/analytics/queries";
/**
* Recharts panels for the analytics admin view. Kept as tiny client islands:
* the surrounding view (tabs, tables, filters) renders server-side. Colors
* are explicit hex values because the Payload admin panel does not define the
* frontend chart CSS variables.
*/
const AXIS_STYLE = { fill: "#a3a3a3", fontSize: 11 } as const;
interface TooltipEntry {
name?: string | number;
value?: string | number;
color?: string;
}
function AdminTooltip({
active,
payload,
label,
labelFormatter,
}: {
active?: boolean;
payload?: TooltipEntry[];
label?: string | number;
labelFormatter?: (label: string | number) => string;
}) {
if (!active || !payload || payload.length === 0) return null;
return (
<div className="rounded border border-white/15 bg-neutral-900 px-2.5 py-1.5 text-xs text-neutral-200 shadow-lg">
<p className="mb-1 font-medium text-neutral-400">
{labelFormatter && label !== undefined ? labelFormatter(label) : label}
</p>
{payload.map((entry, index) => (
<p key={index} className="flex items-center gap-1.5">
<span
className="inline-block size-2 rounded-sm"
style={{ backgroundColor: entry.color ?? "#a3a3a3" }}
/>
<span>{entry.name}</span>
<span className="ml-auto tabular-nums">{entry.value}</span>
</p>
))}
</div>
);
}
export function OverviewTrendChart({ series }: { series: DailyPoint[] }) {
return (
<div className="h-64 w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={series} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>
<defs>
<linearGradient id="pv" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#a78bfa" stopOpacity={0.35} />
<stop offset="100%" stopColor="#a78bfa" stopOpacity={0} />
</linearGradient>
<linearGradient id="ss" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#22d3ee" stopOpacity={0.35} />
<stop offset="100%" stopColor="#22d3ee" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid stroke="rgba(255,255,255,0.06)" vertical={false} />
<XAxis dataKey="day" tick={AXIS_STYLE} tickLine={false} axisLine={false} />
<YAxis tick={AXIS_STYLE} tickLine={false} axisLine={false} width={48} allowDecimals={false} />
<Tooltip content={<AdminTooltip />} cursor={{ stroke: "rgba(255,255,255,0.2)" }} />
<Area
type="monotone"
dataKey="pageviews"
name="Pageviews"
stroke="#a78bfa"
strokeWidth={1.5}
fill="url(#pv)"
/>
<Area
type="monotone"
dataKey="sessions"
name="Sessions"
stroke="#22d3ee"
strokeWidth={1.5}
fill="url(#ss)"
/>
</AreaChart>
</ResponsiveContainer>
</div>
);
}
export function ScrollDistributionChart({ buckets }: { buckets: ScrollBucket[] }) {
return (
<div className="h-56 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={buckets} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>
<CartesianGrid stroke="rgba(255,255,255,0.06)" vertical={false} />
<XAxis dataKey="bucket" tick={AXIS_STYLE} tickLine={false} axisLine={false} />
<YAxis tick={AXIS_STYLE} tickLine={false} axisLine={false} width={48} allowDecimals={false} />
<Tooltip
content={<AdminTooltip labelFormatter={(label) => `Scrolled ${label}` as string} />}
cursor={{ fill: "rgba(255,255,255,0.04)" }}
/>
<Bar dataKey="pages" name="Page views" fill="#34d399" radius={[2, 2, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
);
}
export function GamesBarChart({ rows }: { rows: GameReportRow[] }) {
const data = rows.map((row) => ({ name: row.gameKey, sessions: row.sessions }));
return (
<div className="h-56 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -16 }}>
<CartesianGrid stroke="rgba(255,255,255,0.06)" vertical={false} />
<XAxis dataKey="name" tick={AXIS_STYLE} tickLine={false} axisLine={false} />
<YAxis tick={AXIS_STYLE} tickLine={false} axisLine={false} width={48} allowDecimals={false} />
<Tooltip content={<AdminTooltip />} cursor={{ fill: "rgba(255,255,255,0.04)" }} />
<Bar dataKey="sessions" name="Play sessions" fill="#fbbf24" radius={[2, 2, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
);
}

View file

@ -0,0 +1,531 @@
import { DefaultTemplate } from "@payloadcms/next/templates";
import type { AdminViewServerProps } from "payload";
import { hasPermission } from "@/utils/access-control/hasPermission";
import {
getChronicleReport,
getDailySeries,
getGamesReport,
getLongestSessions,
getOverview,
getPagesReport,
getScrollDistribution,
getSessionsExplorer,
getTopPages,
getUserLeaderboard,
} from "@/lib/analytics/queries";
import { formatDateTime, formatDuration, formatNumber, formatPercent } from "./format";
import { GamesBarChart, OverviewTrendChart, ScrollDistributionChart } from "./AnalyticsCharts";
/**
* Custom Payload admin view at /admin/analytics (Phase 1).
*
* Registered in payload.config.ts under admin.components.views.analytics,
* following the techTree precedent. Gated by the admin:analytics:manage
* permission (the nav entry is injected with the same gate). Reports read the
* plain analytics tables through `src/lib/analytics/queries.ts`.
*
* Tabs and range filters ride on query params so navigation stays plain
* server-rendered links; only the recharts islands are client components. The
* Payload admin panel does not load the frontend shadcn theme variables, so
* everything here uses explicit Tailwind palette classes (tech-tree style).
*/
const TABS = [
{ key: "overview", label: "Overview" },
{ key: "pages", label: "Pages" },
{ key: "users", label: "Users" },
{ key: "games", label: "Minigames" },
{ key: "chronicle", label: "Chronicle" },
{ key: "sessions", label: "Sessions" },
] as const;
type TabKey = (typeof TABS)[number]["key"];
const RANGES = [7, 30, 90] as const;
const cardCls = "rounded-lg border border-white/10 bg-white/[0.03] p-4";
const thCls = "px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-neutral-500";
const tdCls = "border-t border-white/5 px-3 py-2 text-sm text-neutral-300";
function StatCard({ label, value }: { label: string; value: string }) {
return (
<div className={cardCls}>
<p className="text-[11px] font-medium uppercase tracking-wider text-neutral-500">{label}</p>
<p className="mt-1 text-2xl font-semibold tabular-nums text-white">{value}</p>
</div>
);
}
function EmptyNote({ label }: { label: string }) {
return (
<p className="py-8 text-center text-sm text-neutral-500">
{label} Tracking events will appear here once real traffic lands.
</p>
);
}
export async function AnalyticsView({
initPageResult,
params,
searchParams,
}: AdminViewServerProps) {
const {
req: { payload, user },
} = initPageResult;
const sp = (await Promise.resolve(searchParams ?? {})) as Record<string, string | string[]>;
const rangeValue = Number(Array.isArray(sp.range) ? sp.range[0] : sp.range);
const range: number = (RANGES as readonly number[]).includes(rangeValue) ? rangeValue : 30;
const tabParam = String(Array.isArray(sp.tab) ? sp.tab[0] : sp.tab ?? "overview");
const tab: TabKey = (TABS as readonly { key: string }[]).some((t) => t.key === tabParam)
? (tabParam as TabKey)
: "overview";
const q = typeof sp.q === "string" ? sp.q.trim() : "";
const offset = Math.max(Number(sp.offset) || 0, 0);
const shell = (children: React.ReactNode) => (
<DefaultTemplate
i18n={initPageResult.req.i18n}
locale={initPageResult.locale}
params={params}
payload={payload}
permissions={initPageResult.permissions}
searchParams={searchParams}
user={user ?? undefined}
visibleEntities={initPageResult.visibleEntities}
>
{children}
</DefaultTemplate>
);
if (!user) {
return shell(
<div className="p-8">
<p className="text-sm text-white/70">You must be logged in to view analytics.</p>
</div>,
);
}
const allowed = await hasPermission(payload, user, "admin:analytics:manage");
if (!allowed) {
return shell(
<div className="p-8">
<p className="text-sm text-white/70">
You do not have permission to view usage analytics. Ask for the
&quot;Manage Usage Analytics&quot; permission.
</p>
</div>,
);
}
// Fetch only what the active tab renders.
const [
overview,
series,
topPages,
pagesRows,
scrollBuckets,
leaderboard,
longestSessions,
gamesRows,
chronicleRows,
sessionsResult,
] = await Promise.all([
tab === "overview" ? getOverview(payload, range) : Promise.resolve(null),
tab === "overview" ? getDailySeries(payload, range) : Promise.resolve([]),
tab === "overview" ? getTopPages(payload, range) : Promise.resolve([]),
tab === "pages" ? getPagesReport(payload, range, q || undefined) : Promise.resolve([]),
tab === "pages" ? getScrollDistribution(payload, range) : Promise.resolve([]),
tab === "users" ? getUserLeaderboard(payload, range) : Promise.resolve([]),
tab === "users" ? getLongestSessions(payload, range) : Promise.resolve([]),
tab === "games" ? getGamesReport(payload, range) : Promise.resolve([]),
tab === "chronicle" ? getChronicleReport(payload, range) : Promise.resolve([]),
tab === "sessions"
? getSessionsExplorer(payload, { q: q || undefined, limit: 50, offset })
: Promise.resolve({ rows: [], total: 0 }),
]);
const tabHref = (key: string) => `?tab=${key}&range=${range}`;
const rangeHref = (value: number) => `?tab=${tab}&range=${value}${q ? `&q=${encodeURIComponent(q)}` : ""}`;
return shell(
<div className="p-6">
<header className="mb-6 flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="text-xl font-semibold text-white">Usage Analytics</h1>
<p className="mt-1 text-sm text-neutral-500">
First-party product analytics. Raw events are kept for 90 days; daily
aggregates are permanent.
</p>
</div>
<div className="flex items-center gap-1 rounded-md border border-white/10 bg-white/[0.03] p-1">
{RANGES.map((value) => (
<a
key={value}
href={rangeHref(value)}
className={`rounded px-2.5 py-1 text-xs font-medium transition-colors ${
range === value
? "bg-white/10 text-white"
: "text-neutral-400 hover:text-neutral-200"
}`}
>
{value}d
</a>
))}
</div>
</header>
<nav className="mb-6 flex flex-wrap gap-1 border-b border-white/10 pb-px">
{TABS.map((item) => (
<a
key={item.key}
href={tabHref(item.key)}
className={`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${
tab === item.key
? "border-cyan-400 text-white"
: "border-transparent text-neutral-500 hover:text-neutral-300"
}`}
>
{item.label}
</a>
))}
</nav>
{tab === "overview" && overview && (
<div className="flex flex-col gap-6">
<div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
<StatCard label={`Sessions (${range}d)`} value={formatNumber(overview.sessions)} />
<StatCard label={`Visitors (${range}d)`} value={formatNumber(overview.visitors)} />
<StatCard label={`Pageviews (${range}d)`} value={formatNumber(overview.pageviews)} />
<StatCard label="Active users" value={formatNumber(overview.activeUsers)} />
</div>
<div className={cardCls}>
<p className="mb-3 text-sm font-medium text-neutral-300">Daily trend</p>
<OverviewTrendChart series={series} />
</div>
<div className={cardCls}>
<p className="mb-2 text-sm font-medium text-neutral-300">Top pages</p>
{topPages.length === 0 ? (
<EmptyNote label="No pageviews in this window." />
) : (
<table className="w-full">
<tbody>
{topPages.map((page) => (
<tr key={page.path}>
<td className={tdCls}>
<code className="text-xs text-neutral-400">{page.path}</code>
</td>
<td className={`${tdCls} w-24 text-right tabular-nums`}>
{formatNumber(page.views)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
)}
{tab === "pages" && (
<div className="flex flex-col gap-6">
<div className={cardCls}>
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<p className="text-sm font-medium text-neutral-300">Per-route report</p>
<form method="GET" className="flex items-center gap-2">
<input type="hidden" name="tab" value="pages" />
<input type="hidden" name="range" value={range} />
<input
name="q"
defaultValue={q}
placeholder="Filter by path, e.g. /wiki"
className="w-56 rounded border border-white/15 bg-black/40 px-2 py-1 text-xs text-neutral-200 placeholder:text-neutral-600"
/>
<button
type="submit"
className="rounded border border-white/15 px-2 py-1 text-xs text-neutral-300 hover:bg-white/5"
>
Filter
</button>
</form>
</div>
{scrollBuckets.length > 0 && (
<div className="mb-6">
<p className="mb-2 text-xs uppercase tracking-wider text-neutral-500">
Scroll depth distribution
</p>
<ScrollDistributionChart buckets={scrollBuckets} />
</div>
)}
{pagesRows.length === 0 ? (
<EmptyNote label="No page traffic in this window." />
) : (
<table className="w-full">
<thead>
<tr>
<th className={thCls}>Path</th>
<th className={`${thCls} text-right`}>Views</th>
<th className={`${thCls} text-right`}>Visitors</th>
<th className={`${thCls} text-right`}>Avg dwell</th>
<th className={`${thCls} text-right`}>Avg max scroll</th>
</tr>
</thead>
<tbody>
{pagesRows.map((row) => (
<tr key={row.path}>
<td className={tdCls}>
<code className="text-xs text-neutral-400">{row.path}</code>
</td>
<td className={`${tdCls} text-right tabular-nums`}>{formatNumber(row.views)}</td>
<td className={`${tdCls} text-right tabular-nums`}>{formatNumber(row.visitors)}</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatDuration(row.avgDwellMs)}
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatPercent(row.avgMaxScroll)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
)}
{tab === "users" && (
<div className="flex flex-col gap-6">
<div className={cardCls}>
<p className="mb-2 text-sm font-medium text-neutral-300">Active-time leaderboard</p>
{leaderboard.length === 0 ? (
<EmptyNote label="No member sessions in this window." />
) : (
<table className="w-full">
<thead>
<tr>
<th className={thCls}>Member</th>
<th className={`${thCls} text-right`}>Active time</th>
<th className={`${thCls} text-right`}>Sessions</th>
<th className={`${thCls} text-right`}>Pageviews</th>
</tr>
</thead>
<tbody>
{leaderboard.map((row) => (
<tr key={row.userId ?? "anon"}>
<td className={tdCls}>
{row.displayName || row.username || `#${row.userId}`}
{row.displayName && row.username ? (
<span className="ml-1.5 text-xs text-neutral-600">{row.username}</span>
) : null}
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatDuration(row.activeMs)}
</td>
<td className={`${tdCls} text-right tabular-nums`}>{row.sessions}</td>
<td className={`${tdCls} text-right tabular-nums`}>{row.pageviews}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className={cardCls}>
<p className="mb-2 text-sm font-medium text-neutral-300">Longest sessions</p>
{longestSessions.length === 0 ? (
<EmptyNote label="No sessions in this window." />
) : (
<table className="w-full">
<thead>
<tr>
<th className={thCls}>Started</th>
<th className={thCls}>Member</th>
<th className={thCls}>Entry path</th>
<th className={`${thCls} text-right`}>Duration</th>
<th className={thCls}>Env</th>
</tr>
</thead>
<tbody>
{longestSessions.map((row) => (
<tr key={row.id}>
<td className={tdCls}>{formatDateTime(row.startedAt)}</td>
<td className={tdCls}>{row.username ?? "guest"}</td>
<td className={tdCls}>
<code className="text-xs text-neutral-400">{row.entryPath ?? "-"}</code>
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatDuration(row.durationMs)}
</td>
<td className={tdCls}>{row.env}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
)}
{tab === "games" && (
<div className="flex flex-col gap-6">
<div className={cardCls}>
<p className="mb-2 text-sm font-medium text-neutral-300">Play sessions by game</p>
{gamesRows.length === 0 ? (
<EmptyNote label="No minigame traffic in this window." />
) : (
<>
<GamesBarChart rows={gamesRows} />
<table className="mt-4 w-full">
<thead>
<tr>
<th className={thCls}>Game</th>
<th className={`${thCls} text-right`}>Players</th>
<th className={`${thCls} text-right`}>Sessions</th>
<th className={`${thCls} text-right`}>Avg play session</th>
</tr>
</thead>
<tbody>
{gamesRows.map((row) => (
<tr key={row.gameKey}>
<td className={tdCls}>{row.gameKey}</td>
<td className={`${tdCls} text-right tabular-nums`}>{formatNumber(row.players)}</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatNumber(row.sessions)}
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatDuration(row.avgSessionMs)}
</td>
</tr>
))}
</tbody>
</table>
</>
)}
</div>
</div>
)}
{tab === "chronicle" && (
<div className={cardCls}>
<p className="mb-2 text-sm font-medium text-neutral-300">
Chronicle completion (beats and journals)
</p>
{chronicleRows.length === 0 ? (
<EmptyNote label="No chronicle reads in this window." />
) : (
<table className="w-full">
<thead>
<tr>
<th className={thCls}>Article</th>
<th className={thCls}>Kind</th>
<th className={`${thCls} text-right`}>Opens</th>
<th className={`${thCls} text-right`}>Completions</th>
<th className={`${thCls} text-right`}>Completion rate</th>
<th className={`${thCls} text-right`}>Median time</th>
</tr>
</thead>
<tbody>
{chronicleRows.map((row) => (
<tr key={`${row.kind}:${row.ref}`}>
<td className={tdCls}>{row.title ?? `#${row.ref}`}</td>
<td className={tdCls}>{row.kind}</td>
<td className={`${tdCls} text-right tabular-nums`}>{formatNumber(row.opens)}</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatNumber(row.completions)}
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{row.opens > 0 ? formatPercent((row.completions / row.opens) * 100) : "-"}
</td>
<td className={`${tdCls} text-right tabular-nums`}>
{row.medianTimeMs == null ? "-" : formatDuration(row.medianTimeMs)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
)}
{tab === "sessions" && (
<div className={cardCls}>
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<p className="text-sm font-medium text-neutral-300">
Sessions ({formatNumber(sessionsResult.total)})
</p>
<form method="GET" className="flex items-center gap-2">
<input type="hidden" name="tab" value="sessions" />
<input type="hidden" name="range" value={range} />
<input
name="q"
defaultValue={q}
placeholder="Path, username, or user id"
className="w-64 rounded border border-white/15 bg-black/40 px-2 py-1 text-xs text-neutral-200 placeholder:text-neutral-600"
/>
<button
type="submit"
className="rounded border border-white/15 px-2 py-1 text-xs text-neutral-300 hover:bg-white/5"
>
Search
</button>
</form>
</div>
{sessionsResult.rows.length === 0 ? (
<EmptyNote label="No sessions found." />
) : (
<table className="w-full">
<thead>
<tr>
<th className={thCls}>Started</th>
<th className={thCls}>User</th>
<th className={thCls}>Entry path</th>
<th className={`${thCls} text-right`}>Views</th>
<th className={`${thCls} text-right`}>Active</th>
<th className={thCls}>Env</th>
</tr>
</thead>
<tbody>
{sessionsResult.rows.map((row) => (
<tr key={row.id}>
<td className={tdCls}>{formatDateTime(row.startedAt)}</td>
<td className={tdCls}>
{row.displayName || row.username || (row.userId ? `#${row.userId}` : "guest")}
{row.isBot ? <span className="ml-1.5 text-xs text-rose-400">bot</span> : null}
</td>
<td className={tdCls}>
<code className="text-xs text-neutral-400">{row.entryPath ?? "-"}</code>
</td>
<td className={`${tdCls} text-right tabular-nums`}>{row.pageviewCount}</td>
<td className={`${tdCls} text-right tabular-nums`}>
{formatDuration(row.activeMs)}
</td>
<td className={tdCls}>{row.env}</td>
</tr>
))}
</tbody>
</table>
)}
<div className="mt-3 flex items-center gap-3 text-xs">
{offset > 0 && (
<a
href={`?tab=sessions&range=${range}${q ? `&q=${encodeURIComponent(q)}` : ""}&offset=${Math.max(0, offset - 50)}`}
className="rounded border border-white/15 px-2 py-1 text-neutral-300 hover:bg-white/5"
>
Previous
</a>
)}
{offset + sessionsResult.rows.length < sessionsResult.total && (
<a
href={`?tab=sessions&range=${range}${q ? `&q=${encodeURIComponent(q)}` : ""}&offset=${offset + 50}`}
className="rounded border border-white/15 px-2 py-1 text-neutral-300 hover:bg-white/5"
>
Next
</a>
)}
</div>
</div>
)}
</div>,
);
}
export default AnalyticsView;

View file

@ -0,0 +1,39 @@
/**
* Formatting helpers for the analytics admin dashboard. The Payload admin
* panel does not load the frontend's shadcn theme variables, so the panels
* use explicit Tailwind palette classes and these plain formatters instead of
* semantic styling.
*/
export function formatNumber(value: number): string {
return new Intl.NumberFormat("en-US").format(value);
}
/** Compact duration: "4h 03m", "12m 40s", "45s". */
export function formatDuration(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return "0s";
const totalSeconds = Math.round(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
return `${seconds}s`;
}
/** Short timestamp for tables: "Oct 14, 12:33". */
export function formatDateTime(iso: string | null): string {
if (!iso) return "-";
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return iso;
return new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date);
}
export function formatPercent(value: number): string {
return `${Math.round(value)}%`;
}

View file

@ -7,6 +7,7 @@ import type { PayloadRequest, SanitizedPermissions, ServerProps } from "payload"
import React from "react";
import { TechTreeNavClient, type TechTreeNavGroup, type TechTreeNavEntity } from "./TechTreeNavClient";
import { hasPermission } from "@/utils/access-control/hasPermission";
const baseClass = "nav";
@ -74,6 +75,35 @@ export const TechTreeNav = async ({
return { ...group, entities };
});
// Analytics custom view entry, gated by its own permission (the Tech Tree
// entry above rides with technologies visibility; this one follows the
// admin:analytics:manage convention instead). Injected after the Tech Tree
// entry when that group exists, otherwise at the top of the first group.
const canViewAnalytics = await hasPermission(
payload,
user as unknown as { id: number | string } | null,
"admin:analytics:manage",
);
if (canViewAnalytics && groups.length > 0) {
const techGroupIndex = groups.findIndex((group) =>
group.entities.some(
(entity) => entity.type === EntityType.collection && entity.slug === "technologies",
),
);
const targetIndex = techGroupIndex === -1 ? 0 : techGroupIndex;
const entities: TechTreeNavEntity[] = [...groups[targetIndex].entities];
const techTreeIndex = entities.findIndex(
(entity) => (entity as { slug?: string }).slug === "tech-tree",
);
entities.splice(techTreeIndex === -1 ? 0 : techTreeIndex + 1, 0, {
slug: "analytics",
label: "Analytics",
type: "custom",
href: "/analytics",
});
groups[targetIndex] = { ...groups[targetIndex], entities };
}
let navPreferences: { groups?: { [key: string]: { open: boolean } } } | null = null;
if (req?.user?.collection) {
const prefs = await req.payload.find({

View file

@ -5,6 +5,7 @@ import Link from "next/link";
import { minigameIcon } from "@/components/frontend/minigames/minigameIcon";
import { UpcomingCountdown } from "@/components/frontend/minigames/UpcomingCountdown";
import { phasingOutTooltip } from "@/lib/minigames/countdown";
import type { RegistryGame } from "@/lib/minigames/registry";
import {
DropdownMenu,
@ -31,6 +32,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
* links: they render as a plain hoverable row rather than a disabled
* `DropdownMenuItem`, because that item sets `pointer-events: none` when
* disabled, which would suppress the hover that reveals the tooltip.
* `phasingOut` games stay clickable but carry an amber "Phasing out" badge and a
* tooltip showing the optional `estimatedRemovalDate`.
*/
export function NavMinigames({ games }: { games: RegistryGame[] }) {
const { isMobile } = useSidebar();
@ -65,6 +68,27 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) {
);
}
if (game.status === "phasingOut") {
return (
<Tooltip key={game.key}>
<TooltipTrigger asChild>
<DropdownMenuItem asChild>
<Link href={game.route}>
<Icon />
<span className="truncate">{game.label}</span>
<span className="ml-auto shrink-0 text-[10px] font-normal uppercase tracking-wide text-amber-400">
Phasing out
</span>
</Link>
</DropdownMenuItem>
</TooltipTrigger>
<TooltipContent side={isMobile ? "bottom" : "right"}>
<span>{phasingOutTooltip(game.estimatedRemovalDate)}</span>
</TooltipContent>
</Tooltip>
);
}
return (
<DropdownMenuItem key={game.key} asChild>
<Link href={game.route}>

View file

@ -0,0 +1,46 @@
"use client";
import { AlarmClockIcon } from "lucide-react";
import { useNow } from "@/hooks/useNow";
import { formatCountdown, formatReleaseInstant } from "@/lib/minigames/countdown";
import { cn } from "@/lib/utils";
interface PhasingOutBannerProps {
readonly estimatedRemovalDate?: string | null;
}
/**
* In-game notice for a minigame whose registry status is "phasingOut". The game
* stays fully playable and keeps scoring periods until it is removed; this just
* tells operators when it is leaving. Display only.
*/
export function PhasingOutBanner({ estimatedRemovalDate }: PhasingOutBannerProps) {
const now = useNow();
const instant = formatReleaseInstant(estimatedRemovalDate ?? null);
const countdown = formatCountdown(estimatedRemovalDate ?? null, new Date(now));
return (
<div
role="note"
aria-label="This minigame is being phased out"
className={cn(
"flex items-center gap-3 rounded-lg border px-4 py-3 text-sm",
"border-amber-500/30 bg-amber-500/10 text-amber-100",
)}
>
<AlarmClockIcon className="size-5 shrink-0 text-amber-400" />
<p className="min-w-0">
<span className="font-semibold">This game is being phased out.</span>{" "}
{instant ? (
<>
Leaving <span className="font-medium">{instant}</span>
{countdown ? ` (in ${countdown})` : "."}
</>
) : (
"No removal date has been set yet."
)}
</p>
</div>
);
}

View file

@ -8,6 +8,7 @@ import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
import type { StoryViewerBeat } from "@/components/frontend/story/StoryViewer";
import { ChronicleTrackedRegion } from "@/lib/client-analytics/chronicle";
import {
BOOK_COLUMN_GAP,
BOOK_MAX_WIDTH,
@ -231,11 +232,12 @@ export function BookView({ beats }: { readonly beats: readonly StoryViewerBeat[]
</Button>
</div>
<div
ref={pagesRef}
className="mx-auto h-[100dvh] w-full overflow-hidden"
style={{ maxWidth: BOOK_MAX_WIDTH, touchAction: "pan-y" }}
>
<ChronicleTrackedRegion kind="beat">
<div
ref={pagesRef}
className="mx-auto h-[100dvh] w-full overflow-hidden"
style={{ maxWidth: BOOK_MAX_WIDTH, touchAction: "pan-y" }}
>
<div
ref={contentRef}
className="h-full w-full px-8 py-14 motion-reduce:transition-none sm:py-16"
@ -289,6 +291,7 @@ export function BookView({ beats }: { readonly beats: readonly StoryViewerBeat[]
))}
</div>
</div>
</ChronicleTrackedRegion>
<div className="fixed inset-x-0 bottom-0 z-10 flex items-center justify-center gap-4 p-4">
<Button

View file

@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
import { ChronicleTrackedRegion } from "@/lib/client-analytics/chronicle";
import type { StoryBeat } from "@/payload-types";
import { cn } from "@/lib/utils";
import { READER_BODY_CLASSES } from "@/lib/story/richtextClasses";
@ -90,9 +91,10 @@ export function StoryViewer({ beats }: { readonly beats: readonly StoryViewerBea
<h1 id="story-reader-title" className="sr-only">
The Unit Chronicle
</h1>
<ol className="flex flex-col gap-24">
{beats.map((beat) => (
<li key={beat.id} className="scroll-mt-24">
<ChronicleTrackedRegion kind="beat">
<ol className="flex flex-col gap-24">
{beats.map((beat) => (
<li key={beat.id} data-beat-id={beat.id} className="scroll-mt-24">
<div className="flex items-center justify-between gap-4">
<p className="text-xs uppercase tracking-[0.3em] text-neutral-500">
Chapter {beat.chapter}
@ -124,8 +126,9 @@ export function StoryViewer({ beats }: { readonly beats: readonly StoryViewerBea
<RichText data={beat.body} className={cn(READER_BODY_CLASSES)} />
</div>
</li>
))}
</ol>
))}
</ol>
</ChronicleTrackedRegion>
</div>
</div>
</div>

View file

@ -19,6 +19,7 @@ import {
import { createWikiPage, updateWikiPage } from "@/app/(frontend)/wiki/actions";
import { WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
import { prepareMarkdown } from "@/lib/wiki/prepare";
import { track } from "@/lib/client-analytics";
import { buildTemplateStyles } from "@/lib/wiki/templateCss";
import { MarkdownGuide } from "@/components/frontend/wiki/MarkdownGuide";
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
@ -148,6 +149,9 @@ export function WikiEditor({
}
const awardedXp = result.data.awardedXp ?? 0;
if (mode === "create") {
track("wiki.article_created", { slug: result.data.slug });
}
toast.success(
`${mode === "create" ? "Wiki page created" : "Wiki page updated"}${
awardedXp > 0 ? ` \u00b7 +${awardedXp} XP` : ""

View file

@ -17,6 +17,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { WIKI_CATEGORIES } from "@/lib/wiki/categories";
import { track } from "@/lib/client-analytics";
import { WikiRow } from "./WikiRow";
import {
collectTagCounts,
@ -214,7 +215,7 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
{isModerator && <Badge variant="outline">Intel editor</Badge>}
<Button asChild className="ml-auto" size="sm">
<Link href="/wiki/new">
<Link href="/wiki/new" onClick={() => track("wiki.new_clicked", { source: "toolbar" })}>
<PlusIcon data-icon="inline-start" />
New page
</Link>
@ -238,7 +239,9 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
</Button>
)}
<Button asChild size="sm">
<Link href="/wiki/new">New page</Link>
<Link href="/wiki/new" onClick={() => track("wiki.new_clicked", { source: "empty" })}>
New page
</Link>
</Button>
</div>
</CardContent>

View file

@ -0,0 +1,18 @@
"use client";
import { useEffect } from "react";
import { annotatePageview } from "@/lib/client-analytics";
/**
* Tags the current analytics pageview with the wiki article's slug so the
* dashboard can group article reads per slug (Phase 1 domain instrumentation).
* Rendered by the `/wiki/[slug]` server page; annotations recorded before the
* layout tracker enqueues the pageview are parked and merged on record.
*/
export function WikiPageViewMeta({ slug }: { slug: string }) {
useEffect(() => {
annotatePageview({ wikiSlug: slug });
}, [slug]);
return null;
}

373
src/components/ui/chart.tsx Normal file
View file

@ -0,0 +1,373 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import * as RechartsPrimitive from "recharts"
import type { TooltipValueType } from "recharts"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
>
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
id,
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer
initialDimension={initialDimension}
>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme ?? config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
TooltipValueType,
TooltipNameType
>,
"accessibilityLayer"
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? (config[label]?.label ?? label)
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={index}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === "number"
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={index}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}

View file

@ -0,0 +1,77 @@
# AGENTS.md - First-Party Analytics (server side)
> **Parent**: `../../AGENTS.md` (commands, auth flow, Next.js 16 rules, deployment).
## Overview
Phase 1 of the first-party analytics feature (usage data only, replacing
Microsoft Clarity). Plain Postgres tables outside Payload, a beacon collector,
hourly rollups, 90-day raw retention, and a custom admin view at
`/admin/analytics`. The client SDK lives in `src/lib/client-analytics/` (its
README holds the event taxonomy).
## Structure
```
src/lib/analytics/
schema.ts shared DDL for all six tables (migration + test bootstrap run it)
events.ts pure taxonomy + envelope validation (client-safe, no Payload)
ingest.ts sessionization, attribution, bot filter, rate limit (raw SQL)
rollup.ts daily aggregate recomputation + retention deletes
games.ts /minigames/<slug> -> registry key mapping
queries.ts read-side service for the admin dashboard
src/app/api/collect/route.ts beacon collector (not a Payload operation)
src/scripts/analyticsRollup.ts hourly bin (`payload analytics-rollup`)
src/scripts/analyticsPurge.ts daily bin (`payload analytics-purge`)
src/components/admin/analytics/ the /admin/analytics view (+ recharts islands)
```
## Never-miss rules
- **The tables are plain SQL, not collections.** Write via
`payload.db.drizzle.execute(sql\`...\`)`; never `payload.create`. The single
DDL source is `schema.ts`: the migration `add_analytics_tables` and
`tests/test-db.ts` both execute it. Schema changes mean editing that module
AND creating a new named migration that applies the delta.
- **drizzle push must never see these tables.** The test bootstrap pushes only
the Payload schema; drizzle-kit 0.31.11's introspector breaks on composite
primary keys, so `tests/test-db.ts` drops the analytics tables BEFORE
`pushSchema` and recreates them after. Do not reorder those calls.
- **The collector bypasses Payload on purpose.** No hooks, no access control;
validation is `parseCollectEnvelope` (strict: type whitelist, size caps,
timestamp sanity), bot filtering and per-IP rate limiting are in `ingest.ts`.
It answers 204 and sets the `ptf_analytics_sid` first-party cookie.
- **Sessionization lives server-side**: 30 minutes of inactivity (`SESSION_IDLE_MS`)
closes a session even if the client keeps posting its id; expired sessions get
`ended_at`. Guest sessions link to a user retroactively on first authed flush.
- **Retention**: raw events/sessions older than 90 days are deleted by the
purge bin; the four `analytics_daily_*` aggregate tables are permanent and
must never be purged. Rollups are delete-then-insert per UTC day, so re-runs
(and the hourly cron recomputing today + yesterday) are idempotent.
- **Dashboard gating**: view registered as `admin.components.views.analytics`
in `payload.config.ts`, gated by `admin:analytics:manage` (the Nav entry in
`TechTreeNav.tsx` checks the same permission). The Payload admin panel does
NOT load the frontend shadcn CSS variables: style dashboard panels with
explicit Tailwind palette classes, never `bg-background`/`text-foreground`.
## Cron (external, single instance)
```
0 * * * * payload analytics-rollup # hourly aggregates
30 4 * * * payload analytics-purge # daily retention sweep
```
`ANALYTICS_ROLLUP_DAY=YYYY-MM-DD` backfills one specific day.
## Testing
Integration tests: `tests/int/analytics.int.spec.ts` (envelope validation,
sessionization, attribution, rollup idempotency, retention). E2E smoke:
`tests/e2e/analytics.e2e.spec.ts` (dev-flag pageview lands, collector accepts
beacons, dashboard renders), enabled by `NEXT_PUBLIC_ANALYTICS_DEV=1` in
playwright.config.ts.
## Phase 2 (not built yet)
Heatmaps/rage/dead clicks, scroll maps, JS error + Web Vitals capture, session
timeline reconstruction ("recording" from events), Clarity removal.

177
src/lib/analytics/events.ts Normal file
View file

@ -0,0 +1,177 @@
/**
* Shared analytics event taxonomy and envelope validation (Phase 1).
*
* Pure module: no Payload, no DOM. Imported by the client SDK
* (`src/lib/client-analytics/`), the collector route, the ingest service and
* the rollup bins, so the event vocabulary has exactly one source of truth.
* The Postgres `analytics_events.type` column mirrors this union; adding a
* type here is a taxonomy change that belongs in the SDK README.
*/
export const ANALYTICS_EVENT_TYPES = [
"pageview",
"click",
"scroll",
"focus",
"visible",
"custom",
"heartbeat",
] as const;
export type AnalyticsEventType = (typeof ANALYTICS_EVENT_TYPES)[number];
export function isAnalyticsEventType(value: unknown): value is AnalyticsEventType {
return typeof value === "string" && (ANALYTICS_EVENT_TYPES as readonly string[]).includes(value);
}
/** Environment tag carried on every row ("dev" vs "production"). */
export const ANALYTICS_ENVS = ["dev", "production"] as const;
export type AnalyticsEnv = (typeof ANALYTICS_ENVS)[number];
/** Resolve the env tag from the server process (clients never set it). */
export function resolveAnalyticsEnv(nodeEnv: string | undefined): AnalyticsEnv {
return nodeEnv === "production" ? "production" : "dev";
}
// ---------------------------------------------------------------------------
// Ingest limits (strict validation at the collector boundary)
// ---------------------------------------------------------------------------
/** Maximum events accepted per batched envelope. */
export const MAX_EVENTS_PER_BATCH = 50;
/** Maximum characters kept for a path. */
export const MAX_PATH_LENGTH = 2048;
/** Maximum serialized JSON size for one `element` or `data` payload. */
export const MAX_JSON_BYTES = 4_096;
/** Maximum characters for the session / anonymous identifiers. */
export const MAX_ID_LENGTH = 64;
/** A batch may not carry timestamps further ahead than this. */
export const MAX_FUTURE_SKEW_MS = 5 * 60 * 1000;
/** A batch may not carry timestamps older than this (stale beacon replays). */
export const MAX_PAST_AGE_MS = 24 * 60 * 60 * 1000;
// ---------------------------------------------------------------------------
// Envelope shape
// ---------------------------------------------------------------------------
/** One client event before validation. The SDK sends epoch-ms `ts`. */
export interface RawClientEvent {
ts?: number;
type: string;
path?: string;
element?: unknown;
data?: unknown;
}
/** POST body of `/api/collect`: `{ sid, aid, events }`. */
export interface CollectEnvelope {
sid: string | null;
aid: string | null;
events: RawClientEvent[];
}
/** A validated event ready for insertion. */
export interface ValidatedEvent {
ts: Date;
type: AnalyticsEventType;
path: string | null;
element: Record<string, unknown> | null;
data: Record<string, unknown> | null;
}
export interface ParsedEnvelope {
sid: string | null;
aid: string | null;
events: ValidatedEvent[];
/** Events dropped by per-event validation (bad type, oversized json, ...). */
dropped: number;
}
function clampId(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed) return null;
return trimmed.slice(0, MAX_ID_LENGTH);
}
function clampPath(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
if (!trimmed || !trimmed.startsWith("/")) return null;
return trimmed.slice(0, MAX_PATH_LENGTH);
}
function clampJsonObject(value: unknown): Record<string, unknown> | null {
if (value === null || value === undefined) return null;
if (typeof value !== "object" || Array.isArray(value)) return null;
let serialized: string;
try {
serialized = JSON.stringify(value);
} catch {
return null;
}
if (serialized.length > MAX_JSON_BYTES) return null;
return value as Record<string, unknown>;
}
/**
* Validate a parsed JSON body into a `ParsedEnvelope`. Structural problems
* (non-object body, missing/empty events array, oversized batch) reject the
* whole request; individual bad events are dropped and counted so one broken
* event never costs the rest of the batch.
*/
export function parseCollectEnvelope(body: unknown):
| { ok: true; envelope: ParsedEnvelope }
| { ok: false; error: string } {
if (body === null || typeof body !== "object" || Array.isArray(body)) {
return { ok: false, error: "Body must be a JSON object" };
}
const raw = body as Record<string, unknown>;
if (!Array.isArray(raw.events) || raw.events.length === 0) {
return { ok: false, error: "events must be a non-empty array" };
}
if (raw.events.length > MAX_EVENTS_PER_BATCH) {
return { ok: false, error: `events exceeds ${MAX_EVENTS_PER_BATCH}` };
}
const now = Date.now();
const events: ValidatedEvent[] = [];
let dropped = 0;
for (const candidate of raw.events as unknown[]) {
if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) {
dropped += 1;
continue;
}
const event = candidate as Record<string, unknown>;
if (!isAnalyticsEventType(event.type)) {
dropped += 1;
continue;
}
let tsMs = now;
if (typeof event.ts === "number" && Number.isFinite(event.ts)) {
if (event.ts > now + MAX_FUTURE_SKEW_MS || event.ts < now - MAX_PAST_AGE_MS) {
dropped += 1;
continue;
}
tsMs = event.ts;
}
events.push({
ts: new Date(tsMs),
type: event.type,
path: clampPath(event.path),
element: clampJsonObject(event.element),
data: clampJsonObject(event.data),
});
}
return {
ok: true,
envelope: {
sid: clampId(raw.sid),
aid: clampId(raw.aid),
events,
dropped,
},
};
}

View file

@ -0,0 +1,28 @@
/**
* Minigame route -> registry key mapping shared by the analytics rollup and
* the admin dashboard. Route pattern `/minigames/<slug>` maps to registry
* keys via the registry's own `route` field (flappy, eod, radio,
* qualification, opord, callForFire, poker, blackjack, custom games), so no
* per-game code is needed and newly registered games aggregate automatically.
*/
import type { BuiltinMinigame } from "@/lib/minigames/registry";
/** The `/minigames/<slug>` slug of a path, or null when it is not one. */
export function minigameSlugFromPath(path: string | null | undefined): string | null {
if (!path) return null;
const match = /^\/minigames\/([^/?#]+)/.exec(path);
return match ? match[1] : null;
}
/** slug -> registry key, derived from each game's canonical route. */
export function buildGameKeyMap(
games: Pick<BuiltinMinigame, "route" | "key">[],
): Map<string, string> {
const map = new Map<string, string>();
for (const game of games) {
const slug = minigameSlugFromPath(game.route);
if (slug) map.set(slug, game.key);
}
return map;
}

315
src/lib/analytics/ingest.ts Normal file
View file

@ -0,0 +1,315 @@
import { sql } from "@payloadcms/db-postgres";
import type { Payload } from "payload";
import type { ParsedEnvelope, ValidatedEvent } from "./events";
/**
* Collector ingest service (Phase 1).
*
* Writes the analytics sessions/events tables with raw SQL through
* `payload.db.drizzle` (the established pattern for plain tables, see
* `src/lib/tech-tree/positions.ts`). This is intentionally NOT a Payload
* operation: no hooks, no access control, no document overhead on a
* high-volume fire-and-forget endpoint. The route handler owns HTTP concerns
* (body parsing, cookies, status codes); this module owns attribution,
* sessionization, bot filtering and rate limiting so integration tests can
* drive it directly.
*/
// ---------------------------------------------------------------------------
// Session boundary
// ---------------------------------------------------------------------------
/** 30 minutes of inactivity ends a session (locked decision). */
export const SESSION_IDLE_MS = 30 * 60 * 1000;
// ---------------------------------------------------------------------------
// Bot filtering (UA blocklist at ingest)
// ---------------------------------------------------------------------------
const BOT_UA_PATTERN =
/(\bbot\b|crawler|crawl|spider|slurp|headless|phantom|lighthouse|pagespeed|screenshot|discordbot|slackbot|telegrambot|whatsapp|facebookexternalhit|twitterbot|linkedinbot|embedly|quora link preview|outbrain|pinterest|amazonbot|applebot|duckduckbot|baiduspider|yandex|semrush|ahrefs|mj12bot|dotbot|petalbot|bytespider|compatible;.*bot|curl|wget|python-requests|go-http-client|java\/|okhttp|httpclient|feedfetcher|w3\.validator|newrelicpvm|datadogagent|pingdom|uptimerobot|statuspage|selenium|playwright|puppeteer|cypress|nightmare|electron)/i;
export function isBotUserAgent(userAgent: string | null | undefined): boolean {
if (!userAgent) return false;
return BOT_UA_PATTERN.test(userAgent);
}
// ---------------------------------------------------------------------------
// Per-IP rate limiting (in-process sliding window)
// ---------------------------------------------------------------------------
/** Requests accepted per IP per window. Generous: a busy tab flushes ~6/min. */
export const RATE_LIMIT_WINDOW_MS = 60_000;
export const RATE_LIMIT_MAX_REQUESTS = 120;
interface RateBucket {
count: number;
windowStart: number;
}
const rateBuckets = new Map<string, RateBucket>();
/**
* Consume one request for `ip`. Single-instance in-memory limiter, which
* matches the deployment (one container); it exists to blunt abuse, not to
* be a CDN-grade WAF. Returns `false` once the window budget is exhausted.
*/
export function checkCollectRateLimit(ip: string | null, now = Date.now()): boolean {
const key = ip ?? "unknown";
const bucket = rateBuckets.get(key);
if (!bucket || now - bucket.windowStart >= RATE_LIMIT_WINDOW_MS) {
// Keep the map bounded even under IP churn.
if (rateBuckets.size > 10_000) rateBuckets.clear();
rateBuckets.set(key, { count: 1, windowStart: now });
return true;
}
bucket.count += 1;
return bucket.count <= RATE_LIMIT_MAX_REQUESTS;
}
/** Test helper: forget all rate-limit state. */
export function resetCollectRateLimit(): void {
rateBuckets.clear();
}
// ---------------------------------------------------------------------------
// Ingest context + result
// ---------------------------------------------------------------------------
export interface IngestContext {
/** Full client IP (first X-Forwarded-For hop), stored as-is. */
ip: string | null;
/** Full User-Agent header, stored as-is. */
ua: string | null;
/** Referer header. */
referrer: string | null;
/** Resolved from payload.auth() when the caller carries a valid session. */
userId: number | null;
/** "dev" | "production", derived server-side. */
env: "dev" | "production";
}
export interface IngestResult {
/** Session the batch landed in (new id when `newSession`). */
sessionId: string;
newSession: boolean;
isBot: boolean;
stored: number;
dropped: number;
}
interface SessionRow {
id: string;
user_id: number | null;
last_activity_at: Date | string;
}
function rowActivityTime(row: SessionRow): number {
const value = row.last_activity_at;
if (value instanceof Date) return value.getTime();
const parsed = Date.parse(String(value));
return Number.isNaN(parsed) ? 0 : parsed;
}
/** Heartbeats carry their visible dwell slice; clamp to sane per-event bounds. */
function heartbeatMs(event: ValidatedEvent): number {
const raw = event.data?.ms;
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return 0;
return Math.min(Math.round(raw), 60_000);
}
function firstPathOf(events: ValidatedEvent[]): string | null {
for (const event of events) {
if (event.type === "pageview" && event.path) return event.path;
}
for (const event of events) {
if (event.path) return event.path;
}
return null;
}
function lastPathOf(events: ValidatedEvent[]): string | null {
for (let i = events.length - 1; i >= 0; i -= 1) {
const path = events[i].path;
if (path) return path;
}
return null;
}
// ---------------------------------------------------------------------------
// Batch ingest
// ---------------------------------------------------------------------------
/**
* Persist one validated batch. Session resolution order:
*
* 1. known `sid` active within the idle window -> reuse the row;
* 2. known `sid` past the idle window -> close it (`ended_at`) and start over;
* 3. unknown/missing `sid` -> new session.
*
* Attribution: a guest session that shows up again with a logged-in user is
* linked retroactively (session + already-stored events). Bots are dropped
* before any write.
*/
/**
* Resolve the drizzle executor for the plain analytics tables. Defensively
* re-initializes the db adapter when a cold-start race left `drizzle`
* unattached (Payload itself re-runs `db.init()` argument-free on hot reload).
*/
export async function analyticsExecutor(payload: Payload): Promise<{
execute: (query: ReturnType<typeof sql>) => Promise<unknown>;
}> {
const db = payload.db as typeof payload.db & {
drizzle?: { execute: (query: ReturnType<typeof sql>) => Promise<unknown> };
init?: () => Promise<void>;
};
if (!db.drizzle && typeof db.init === "function") {
await db.init();
}
if (!db.drizzle) {
throw new Error("[analytics] database driver unavailable");
}
return db.drizzle;
}
export async function ingestBatch(
payload: Payload,
envelope: ParsedEnvelope,
ctx: IngestContext,
): Promise<IngestResult> {
const droppedInvalid = envelope.dropped;
if (envelope.events.length === 0) {
return { sessionId: "", newSession: false, isBot: false, stored: 0, dropped: droppedInvalid };
}
if (isBotUserAgent(ctx.ua)) {
return {
sessionId: "",
newSession: false,
isBot: true,
stored: 0,
dropped: droppedInvalid + envelope.events.length,
};
}
const now = new Date();
const db = await analyticsExecutor(payload);
let session: SessionRow | null = null;
if (envelope.sid) {
// drizzle's node-postgres driver resolves execute() to `{ rows, rowCount }`.
const found = (await db.execute(sql`
SELECT id, user_id, last_activity_at
FROM analytics_sessions
WHERE id = ${envelope.sid}
`)) as unknown as { rows: SessionRow[] };
session = found.rows?.[0] ?? null;
}
let newSession = false;
let sessionId: string;
let sessionUserId: number | null;
if (session && now.getTime() - rowActivityTime(session) <= SESSION_IDLE_MS) {
sessionId = session.id;
sessionUserId = session.user_id;
} else {
if (session) {
// Expired: close it out so session durations stay honest.
await db.execute(sql`
UPDATE analytics_sessions
SET ended_at = last_activity_at
WHERE id = ${session.id} AND ended_at IS NULL
`);
}
newSession = true;
sessionId = crypto.randomUUID();
sessionUserId = ctx.userId;
const entryPath = firstPathOf(envelope.events);
await db.execute(sql`
INSERT INTO analytics_sessions (
id, user_id, anonymous_id, started_at, last_activity_at,
entry_path, pageview_count, active_ms, is_bot, env, ip, ua, referrer
) VALUES (
${sessionId},
${ctx.userId},
${envelope.aid},
${now.toISOString()}::timestamptz,
${now.toISOString()}::timestamptz,
${entryPath},
0,
0,
false,
${ctx.env},
${ctx.ip},
${ctx.ua},
${ctx.referrer}
)
`);
}
// Guest session upgrading to a login: link the session and its stored
// events retroactively (locked decision #4).
const effectiveUserId = ctx.userId ?? sessionUserId;
if (session && session.user_id == null && ctx.userId != null) {
await db.execute(sql`
UPDATE analytics_events SET user_id = ${ctx.userId}
WHERE session_id = ${sessionId} AND user_id IS NULL
`);
sessionUserId = ctx.userId;
}
const pageviews = envelope.events.filter((e) => e.type === "pageview").length;
const activeMs = envelope.events.reduce((sum, e) => sum + heartbeatMs(e), 0);
const exitPath = lastPathOf(envelope.events);
const values = sql.join(
envelope.events.map((event) => sql`(
${sessionId},
${effectiveUserId},
${event.ts.toISOString()}::timestamptz,
${event.type},
${event.path},
${event.element == null ? null : JSON.stringify(event.element)}::jsonb,
${event.data == null ? null : JSON.stringify(event.data)}::jsonb,
${ctx.env}
)`),
sql`, `,
);
await db.execute(sql`
INSERT INTO analytics_events (session_id, user_id, ts, type, path, element, data, env)
VALUES ${values}
`);
if (newSession) {
await db.execute(sql`
UPDATE analytics_sessions
SET
pageview_count = ${pageviews},
active_ms = ${activeMs},
exit_path = COALESCE(${exitPath}, exit_path),
user_id = COALESCE(user_id, ${effectiveUserId})
WHERE id = ${sessionId}
`);
} else {
await db.execute(sql`
UPDATE analytics_sessions
SET
last_activity_at = ${now.toISOString()}::timestamptz,
pageview_count = pageview_count + ${pageviews},
active_ms = active_ms + ${activeMs},
exit_path = COALESCE(${exitPath}, exit_path),
user_id = COALESCE(user_id, ${effectiveUserId})
WHERE id = ${sessionId}
`);
}
return {
sessionId,
newSession,
isBot: false,
stored: envelope.events.length,
dropped: droppedInvalid,
};
}

View file

@ -0,0 +1,423 @@
import { sql } from "@payloadcms/db-postgres";
import type { Payload } from "payload";
import { analyticsExecutor } from "./ingest";
/**
* Read-side service for the analytics admin dashboard (Phase 1).
*
* All report queries run as raw SQL against the plain analytics tables via
* `payload.db.drizzle` (same pattern as `src/lib/tech-tree/positions.ts`).
* The admin view component owns presentation and permission gating; this
* module only returns plain data.
*/
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface OverviewStats {
sessions: number;
visitors: number;
pageviews: number;
activeUsers: number;
}
export interface DailyPoint {
day: string;
sessions: number;
visitors: number;
pageviews: number;
}
export interface TopPage {
path: string;
views: number;
}
export interface PageReportRow {
path: string;
views: number;
visitors: number;
avgDwellMs: number;
avgMaxScroll: number;
}
export interface ScrollBucket {
bucket: string;
pages: number;
}
export interface UserLeaderboardRow {
userId: number | null;
displayName: string | null;
username: string | null;
activeMs: number;
sessions: number;
pageviews: number;
}
export interface LongSessionRow {
id: string;
userId: number | null;
username: string | null;
startedAt: string;
durationMs: number;
entryPath: string | null;
env: string;
}
export interface GameReportRow {
gameKey: string;
players: number;
sessions: number;
avgSessionMs: number;
}
export interface ChronicleReportRow {
kind: string;
ref: string;
title: string | null;
opens: number;
completions: number;
medianTimeMs: number | null;
}
export interface SessionExplorerRow {
id: string;
userId: number | null;
username: string | null;
displayName: string | null;
startedAt: string;
lastActivityAt: string;
endedAt: string | null;
entryPath: string | null;
exitPath: string | null;
pageviewCount: number;
activeMs: number;
isBot: boolean;
env: string;
}
async function query<T>(payload: Payload, fragment: ReturnType<typeof sql>): Promise<T[]> {
const result = (await analyticsExecutor(payload).then((db) =>
db.execute(fragment),
)) as unknown as { rows: T[] };
return result.rows ?? [];
}
/** Inclusive UTC day window: the last `days` calendar days including today. */
function windowStart(days: number): string {
const start = new Date();
start.setUTCHours(0, 0, 0, 0);
start.setUTCDate(start.getUTCDate() - (days - 1));
return start.toISOString();
}
// ---------------------------------------------------------------------------
// Overview
// ---------------------------------------------------------------------------
export async function getOverview(payload: Payload, days: number): Promise<OverviewStats> {
const rows = await query<OverviewStats>(
payload,
sql`
SELECT
(SELECT COUNT(*) FROM analytics_sessions WHERE started_at >= ${windowStart(days)}::timestamptz AND NOT is_bot)::integer AS sessions,
(SELECT COUNT(DISTINCT COALESCE(user_id::text, anonymous_id, id)) FROM analytics_sessions WHERE started_at >= ${windowStart(days)}::timestamptz AND NOT is_bot)::integer AS visitors,
(SELECT COUNT(*) FROM analytics_events WHERE type = 'pageview' AND ts >= ${windowStart(days)}::timestamptz)::integer AS pageviews,
(SELECT COUNT(DISTINCT user_id) FROM analytics_sessions WHERE started_at >= ${windowStart(days)}::timestamptz AND user_id IS NOT NULL)::integer AS "activeUsers"
`,
);
return rows[0] ?? { sessions: 0, visitors: 0, pageviews: 0, activeUsers: 0 };
}
export async function getDailySeries(payload: Payload, days: number): Promise<DailyPoint[]> {
const rows = await query<{ day: string | Date; sessions: number; visitors: number; pageviews: number }>(
payload,
sql`
SELECT
s.day::text AS day,
s.sessions,
v.visitors,
p.pageviews
FROM (
SELECT (started_at AT TIME ZONE 'UTC')::date AS day, COUNT(*) AS sessions
FROM analytics_sessions
WHERE started_at >= ${windowStart(days)}::timestamptz AND NOT is_bot
GROUP BY 1
) s
FULL OUTER JOIN (
SELECT (ts AT TIME ZONE 'UTC')::date AS day,
COUNT(DISTINCT session_id) AS visitors,
COUNT(*) FILTER (WHERE type = 'pageview') AS pageviews
FROM analytics_events
WHERE ts >= ${windowStart(days)}::timestamptz
GROUP BY 1
) v ON v.day = s.day
FULL OUTER JOIN (
SELECT day, SUM(pageviews)::integer AS pageviews
FROM analytics_daily_users
WHERE day >= (${windowStart(days)}::timestamptz AT TIME ZONE 'UTC')::date
GROUP BY day
) p ON p.day = COALESCE(s.day, v.day)
ORDER BY COALESCE(s.day, v.day)
`,
);
return rows.map((row) => ({
day: typeof row.day === "string" ? row.day.slice(0, 10) : String(row.day).slice(0, 10),
sessions: Number(row.sessions ?? 0),
visitors: Number(row.visitors ?? 0),
pageviews: Number(row.pageviews ?? 0),
}));
}
export async function getTopPages(payload: Payload, days: number, limit = 10): Promise<TopPage[]> {
const rows = await query<TopPage>(
payload,
sql`
SELECT path, COUNT(*)::integer AS views
FROM analytics_events
WHERE type = 'pageview' AND path IS NOT NULL AND ts >= ${windowStart(days)}::timestamptz
GROUP BY path
ORDER BY views DESC
LIMIT ${limit}
`,
);
return rows;
}
// ---------------------------------------------------------------------------
// Pages report
// ---------------------------------------------------------------------------
export async function getPagesReport(
payload: Payload,
days: number,
pathFilter?: string,
): Promise<PageReportRow[]> {
const where = pathFilter
? sql`AND e.path LIKE ${`%${pathFilter}%`}::text`
: sql``;
const rows = await query<PageReportRow>(
payload,
sql`
SELECT
e.path,
COUNT(*) FILTER (WHERE e.type = 'pageview')::integer AS views,
COUNT(DISTINCT e.session_id)::integer AS visitors,
COALESCE(AVG(NULLIF(sc.dwell_ms, ''))::numeric, 0)::bigint AS "avgDwellMs",
COALESCE(AVG(NULLIF(sc.scroll_pct, ''))::numeric, 0)::numeric AS "avgMaxScroll"
FROM analytics_events e
LEFT JOIN LATERAL (
SELECT data->>'dwellMs' AS dwell_ms, data->>'maxScrollPct' AS scroll_pct
FROM analytics_events s
WHERE s.type = 'scroll' AND s.path = e.path AND s.ts >= ${windowStart(days)}::timestamptz
) sc ON TRUE
WHERE e.type IN ('pageview', 'scroll')
AND e.path IS NOT NULL
AND e.ts >= ${windowStart(days)}::timestamptz
${where}
GROUP BY e.path
ORDER BY views DESC
LIMIT 100
`,
);
return rows.map((row) => ({
...row,
avgDwellMs: Number(row.avgDwellMs),
avgMaxScroll: Number(row.avgMaxScroll),
}));
}
export async function getScrollDistribution(payload: Payload, days: number): Promise<ScrollBucket[]> {
const rows = await query<ScrollBucket>(
payload,
sql`
WITH pct AS (
SELECT NULLIF(data->>'maxScrollPct', '')::numeric AS p
FROM analytics_events
WHERE type = 'scroll' AND ts >= ${windowStart(days)}::timestamptz
)
SELECT bucket, COUNT(*)::integer AS pages
FROM (
SELECT CASE
WHEN p <= 25 THEN '0-25%'
WHEN p <= 50 THEN '26-50%'
WHEN p <= 75 THEN '51-75%'
WHEN p < 100 THEN '76-99%'
ELSE '100%'
END AS bucket,
CASE
WHEN p <= 25 THEN 1
WHEN p <= 50 THEN 2
WHEN p <= 75 THEN 3
WHEN p < 100 THEN 4
ELSE 5
END AS ord
FROM pct WHERE p IS NOT NULL
) b
GROUP BY bucket, ord
ORDER BY ord
`,
);
return rows;
}
// ---------------------------------------------------------------------------
// Users report
// ---------------------------------------------------------------------------
export async function getUserLeaderboard(payload: Payload, days: number): Promise<UserLeaderboardRow[]> {
const rows = await query<UserLeaderboardRow>(
payload,
sql`
SELECT
s.user_id AS "userId",
u.display_name AS "displayName",
u.username,
COALESCE(SUM(s.active_ms), 0)::bigint AS "activeMs",
COUNT(*)::integer AS sessions,
COALESCE(SUM(s.pageview_count), 0)::integer AS pageviews
FROM analytics_sessions s
LEFT JOIN users u ON u.id = s.user_id
WHERE s.user_id IS NOT NULL
AND s.started_at >= ${windowStart(days)}::timestamptz
AND NOT s.is_bot
GROUP BY s.user_id, u.display_name, u.username
ORDER BY "activeMs" DESC
LIMIT 25
`,
);
return rows.map((row) => ({ ...row, activeMs: Number(row.activeMs) }));
}
export async function getLongestSessions(payload: Payload, days: number): Promise<LongSessionRow[]> {
const rows = await query<LongSessionRow>(
payload,
sql`
SELECT
s.id,
s.user_id AS "userId",
u.username,
s.started_at::text AS "startedAt",
(EXTRACT(EPOCH FROM (s.last_activity_at - s.started_at)) * 1000)::bigint AS "durationMs",
s.entry_path AS "entryPath",
s.env
FROM analytics_sessions s
LEFT JOIN users u ON u.id = s.user_id
WHERE s.started_at >= ${windowStart(days)}::timestamptz AND NOT s.is_bot
ORDER BY "durationMs" DESC
LIMIT 20
`,
);
return rows.map((row) => ({ ...row, durationMs: Number(row.durationMs) }));
}
// ---------------------------------------------------------------------------
// Minigames report (permanent aggregates)
// ---------------------------------------------------------------------------
export async function getGamesReport(payload: Payload, days: number): Promise<GameReportRow[]> {
const rows = await query<GameReportRow>(
payload,
sql`
SELECT
game_key AS "gameKey",
SUM(players)::integer AS players,
SUM(sessions)::integer AS sessions,
COALESCE(AVG(avg_session_ms), 0)::bigint AS "avgSessionMs"
FROM analytics_daily_games
WHERE day >= (${windowStart(days)}::timestamptz AT TIME ZONE 'UTC')::date
GROUP BY game_key
ORDER BY sessions DESC
`,
);
return rows.map((row) => ({ ...row, avgSessionMs: Number(row.avgSessionMs) }));
}
// ---------------------------------------------------------------------------
// Chronicle report (permanent aggregates + titles)
// ---------------------------------------------------------------------------
export async function getChronicleReport(payload: Payload, days: number): Promise<ChronicleReportRow[]> {
const rows = await query<ChronicleReportRow>(
payload,
sql`
SELECT
c.kind,
c.ref,
CASE WHEN c.kind = 'beat' THEN sb.title ELSE jl.title END AS title,
SUM(c.opens)::integer AS opens,
SUM(c.completions)::integer AS completions,
(percentile_cont(0.5) WITHIN GROUP (ORDER BY c.median_time_ms))::bigint AS "medianTimeMs"
FROM analytics_daily_chronicle c
LEFT JOIN story_beats sb ON c.kind = 'beat' AND sb.id::text = c.ref
LEFT JOIN journals jl ON c.kind = 'journal' AND jl.id::text = c.ref
WHERE c.day >= (${windowStart(days)}::timestamptz AT TIME ZONE 'UTC')::date
GROUP BY c.kind, c.ref, title
ORDER BY opens DESC
LIMIT 100
`,
);
return rows.map((row) => ({
...row,
medianTimeMs: row.medianTimeMs == null ? null : Number(row.medianTimeMs),
}));
}
// ---------------------------------------------------------------------------
// Sessions explorer
// ---------------------------------------------------------------------------
export interface SessionExplorerResult {
rows: SessionExplorerRow[];
total: number;
}
export async function getSessionsExplorer(
payload: Payload,
options: { q?: string; limit?: number; offset?: number } = {},
): Promise<SessionExplorerResult> {
const limit = Math.min(Math.max(options.limit ?? 50, 1), 200);
const offset = Math.max(options.offset ?? 0, 0);
const q = options.q?.trim();
const where = q
? sql`WHERE (s.entry_path ILIKE ${`%${q}%`} OR s.exit_path ILIKE ${`%${q}%`}
OR u.username ILIKE ${`%${q}%`}
OR CAST(s.user_id AS TEXT) = ${/^\d+$/.test(q) ? q : "-1"})`
: sql``;
const countRows = await query<{ total: number }>(
payload,
sql`SELECT COUNT(*)::integer AS total FROM analytics_sessions s LEFT JOIN users u ON u.id = s.user_id ${where}`,
);
const rows = await query<SessionExplorerRow>(
payload,
sql`
SELECT
s.id,
s.user_id AS "userId",
u.username,
u.display_name AS "displayName",
s.started_at::text AS "startedAt",
s.last_activity_at::text AS "lastActivityAt",
s.ended_at::text AS "endedAt",
s.entry_path AS "entryPath",
s.exit_path AS "exitPath",
s.pageview_count AS "pageviewCount",
s.active_ms AS "activeMs",
s.is_bot AS "isBot",
s.env
FROM analytics_sessions s
LEFT JOIN users u ON u.id = s.user_id
${where}
ORDER BY s.started_at DESC
LIMIT ${limit} OFFSET ${offset}
`,
);
return {
rows: rows.map((row) => ({ ...row, activeMs: Number(row.activeMs) })),
total: countRows[0]?.total ?? 0,
};
}

307
src/lib/analytics/rollup.ts Normal file
View file

@ -0,0 +1,307 @@
import { sql } from "@payloadcms/db-postgres";
import type { Payload } from "payload";
/**
* Analytics rollup + retention (Phase 1).
*
* The hourly `analytics-rollup` bin recomputes the permanent daily aggregate
* tables from the raw `analytics_events` rows; the daily `analytics-purge` bin
* deletes raw events older than the retention window. Aggregates are never
* purged.
*
* Every aggregate is computed per UTC calendar day and written delete-then-
* insert, so re-running a day is idempotent (a retried cron hour produces the
* exact same rows). Raw SQL runs through `payload.db.drizzle`; these are plain
* tables, not Payload collections.
*/
/** Raw events older than this are purged; aggregates live forever. */
export const RETENTION_DAYS = 90;
/** A UTC calendar date as `YYYY-MM-DD`. */
export type AnalyticsDay = string;
export function isoDay(date: Date): AnalyticsDay {
return date.toISOString().slice(0, 10);
}
/** The most recent N UTC days, oldest first (today last). */
export function recentDays(count: number, now = new Date()): AnalyticsDay[] {
const days: AnalyticsDay[] = [];
for (let offset = count - 1; offset >= 0; offset -= 1) {
days.push(isoDay(new Date(now.getTime() - offset * 86_400_000)));
}
return days;
}
// ---------------------------------------------------------------------------
// Per-page daily aggregate
// ---------------------------------------------------------------------------
export async function rollupDailyPages(payload: Payload, day: AnalyticsDay): Promise<number> {
await payload.db.drizzle.execute(sql`
DELETE FROM analytics_daily_pages WHERE day = ${day}::date
`);
const result = (await payload.db.drizzle.execute(sql`
INSERT INTO analytics_daily_pages (day, path, views, visitors, avg_dwell_ms, avg_max_scroll)
SELECT
${day}::date,
pv.path,
pv.views,
pv.visitors,
COALESCE(sc.avg_dwell_ms, 0)::bigint,
COALESCE(sc.avg_max_scroll, 0)
FROM (
SELECT path,
COUNT(*) AS views,
COUNT(DISTINCT session_id) AS visitors
FROM analytics_events
WHERE type = 'pageview'
AND path IS NOT NULL
AND (ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY path
) pv
LEFT JOIN (
SELECT path,
AVG(NULLIF(data->>'dwellMs', '')::numeric) AS avg_dwell_ms,
AVG(NULLIF(data->>'maxScrollPct', '')::numeric) AS avg_max_scroll
FROM analytics_events
WHERE type = 'scroll'
AND path IS NOT NULL
AND (ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY path
) sc ON sc.path = pv.path
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}
// ---------------------------------------------------------------------------
// Per-user daily aggregate (user_id = 0 is the anonymous rollup row)
// ---------------------------------------------------------------------------
export async function rollupDailyUsers(payload: Payload, day: AnalyticsDay): Promise<number> {
await payload.db.drizzle.execute(sql`
DELETE FROM analytics_daily_users WHERE day = ${day}::date
`);
const result = (await payload.db.drizzle.execute(sql`
WITH active AS (
SELECT COALESCE(user_id, 0) AS uid,
SUM(NULLIF(data->>'ms', '')::bigint) AS active_ms
FROM analytics_events
WHERE type = 'heartbeat' AND (ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY COALESCE(user_id, 0)
),
sess AS (
SELECT COALESCE(user_id, 0) AS uid,
COUNT(DISTINCT session_id) AS sessions,
SUM(pageviews) AS pageviews
FROM (
SELECT user_id, session_id,
COUNT(*) FILTER (WHERE type = 'pageview') AS pageviews
FROM analytics_events
WHERE (ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY user_id, session_id
) per_session
GROUP BY COALESCE(user_id, 0)
),
top AS (
SELECT uid, jsonb_agg(jsonb_build_object('path', path, 'views', views)) AS top_paths
FROM (
SELECT COALESCE(user_id, 0) AS uid, path, COUNT(*) AS views
FROM analytics_events
WHERE type = 'pageview' AND path IS NOT NULL
AND (ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY COALESCE(user_id, 0), path
ORDER BY views DESC
LIMIT 30
) ranked
GROUP BY uid
),
uids AS (
SELECT uid FROM active UNION SELECT uid FROM sess
)
INSERT INTO analytics_daily_users (day, user_id, active_ms, sessions, pageviews, top_paths)
SELECT
${day}::date,
u.uid,
COALESCE(a.active_ms, 0),
COALESCE(s.sessions, 0),
COALESCE(s.pageviews, 0),
COALESCE(t.top_paths, '[]'::jsonb)
FROM uids u
LEFT JOIN active a ON a.uid = u.uid
LEFT JOIN sess s ON s.uid = u.uid
LEFT JOIN top t ON t.uid = u.uid
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}
// ---------------------------------------------------------------------------
// Per-minigame daily aggregate
// ---------------------------------------------------------------------------
/**
* Play-session length is the visible dwell (heartbeat ms) on `/minigames/*`
* routes, bucketed per game via the registry slug->key map. A session that
* played two games contributes to both rows separately.
*/
export async function rollupDailyGames(
payload: Payload,
day: AnalyticsDay,
slugToKey: Record<string, string>,
): Promise<number> {
await payload.db.drizzle.execute(sql`
DELETE FROM analytics_daily_games WHERE day = ${day}::date
`);
const entries = Object.entries(slugToKey);
if (entries.length === 0) return 0;
const mapping = sql.join(
entries.map(([slug, key]) => sql`(${slug}, ${key})`),
sql`, `,
);
const result = (await payload.db.drizzle.execute(sql`
WITH game_map(slug, game_key) AS (VALUES ${mapping}),
hb AS (
SELECT
m.game_key,
e.session_id,
MAX(e.user_id) AS user_id,
SUM(NULLIF(e.data->>'ms', '')::bigint) AS dwell_ms
FROM analytics_events e
JOIN game_map m ON split_part(e.path, '/', 3) = m.slug
WHERE e.type = 'heartbeat'
AND e.path LIKE '/minigames/%'
AND (e.ts AT TIME ZONE 'UTC')::date = ${day}::date
GROUP BY m.game_key, e.session_id
)
INSERT INTO analytics_daily_games (day, game_key, players, sessions, avg_session_ms)
SELECT
${day}::date,
game_key,
COUNT(DISTINCT COALESCE(user_id::text, session_id)) AS players,
COUNT(DISTINCT session_id) AS sessions,
COALESCE(AVG(dwell_ms), 0)::bigint AS avg_session_ms
FROM hb
GROUP BY game_key
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}
// ---------------------------------------------------------------------------
// Per-chronicle daily aggregate
// ---------------------------------------------------------------------------
/**
* Chronicle events arrive as `custom` events named chronicle.read_progress /
* chronicle.read_completed carrying `{ kind, ref, timeMs }`. opens counts
* distinct sessions that opened an article; completions counts read_completed
* events; median_time_ms is the median time-to-complete across completions.
*/
export async function rollupDailyChronicle(payload: Payload, day: AnalyticsDay): Promise<number> {
await payload.db.drizzle.execute(sql`
DELETE FROM analytics_daily_chronicle WHERE day = ${day}::date
`);
const result = (await payload.db.drizzle.execute(sql`
WITH base AS (
SELECT
data->>'kind' AS kind,
data->>'ref' AS ref,
data->>'name' AS name,
session_id,
NULLIF(data->>'timeMs', '')::bigint AS time_ms
FROM analytics_events
WHERE type = 'custom'
AND data->>'name' IN ('chronicle.read_progress', 'chronicle.read_completed')
AND (ts AT TIME ZONE 'UTC')::date = ${day}::date
),
opens AS (
SELECT kind, ref, COUNT(DISTINCT session_id) AS opens
FROM base WHERE name = 'chronicle.read_progress' GROUP BY kind, ref
),
done AS (
SELECT kind, ref,
COUNT(*) AS completions,
percentile_cont(0.5) WITHIN GROUP (ORDER BY time_ms)::bigint AS median_ms
FROM base WHERE name = 'chronicle.read_completed' GROUP BY kind, ref
),
keys AS (SELECT kind, ref FROM opens UNION SELECT kind, ref FROM done)
INSERT INTO analytics_daily_chronicle (day, kind, ref, opens, completions, median_time_ms)
SELECT
${day}::date,
k.kind,
k.ref,
COALESCE(o.opens, 0),
COALESCE(d.completions, 0),
d.median_ms
FROM keys k
LEFT JOIN opens o ON o.kind = k.kind AND o.ref = k.ref
LEFT JOIN done d ON d.kind = k.kind AND d.ref = k.ref
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}
// ---------------------------------------------------------------------------
// Orchestration
// ---------------------------------------------------------------------------
export interface RollupResult {
day: AnalyticsDay;
pages: number;
users: number;
games: number;
chronicle: number;
}
/** Recompute every daily aggregate for one UTC day. Idempotent per day. */
export async function rollupDay(
payload: Payload,
day: AnalyticsDay,
slugToKey: Record<string, string>,
): Promise<RollupResult> {
const [pages, users, games, chronicle] = await Promise.all([
rollupDailyPages(payload, day),
rollupDailyUsers(payload, day),
rollupDailyGames(payload, day, slugToKey),
rollupDailyChronicle(payload, day),
]);
return { day, pages, users, games, chronicle };
}
/** Delete raw events older than the retention window. Aggregates untouched. */
export async function purgeOldEvents(
payload: Payload,
retentionDays = RETENTION_DAYS,
): Promise<number> {
const cutoff = new Date(Date.now() - retentionDays * 86_400_000).toISOString();
const result = (await payload.db.drizzle.execute(sql`
DELETE FROM analytics_events WHERE ts < ${cutoff}::timestamptz
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}
/**
* Delete session rows whose last activity predates the retention window,
* along with their events. Every daily aggregate is already permanent, so a
* stale session row carries no remaining value; removing both keeps the
* sessions explorer and the tables from growing without bound. (The FK
* cascade would cover the events too; deleting explicitly first keeps the
* statement order obvious and index-friendly.)
*/
export async function purgeOldSessions(
payload: Payload,
retentionDays = RETENTION_DAYS,
): Promise<number> {
const cutoff = new Date(Date.now() - retentionDays * 86_400_000).toISOString();
await payload.db.drizzle.execute(sql`
DELETE FROM analytics_events
WHERE session_id IN (
SELECT id FROM analytics_sessions WHERE last_activity_at < ${cutoff}::timestamptz
)
`);
const result = (await payload.db.drizzle.execute(sql`
DELETE FROM analytics_sessions WHERE last_activity_at < ${cutoff}::timestamptz
`)) as unknown as { rowCount?: number | null };
return result.rowCount ?? 0;
}

143
src/lib/analytics/schema.ts Normal file
View file

@ -0,0 +1,143 @@
/**
* Plain-SQL schema for the first-party analytics feature (Phase 1).
*
* These tables deliberately live OUTSIDE the Payload schema: they are written
* by the collector route and the rollup/purge bins through raw SQL, never
* through Payload collections. Because drizzle push (DB_PUSH=1, used by the
* test-database bootstrap) only knows about Payload-managed tables, the DDL
* lives here as a shared module executed by BOTH:
*
* - the migration `add_analytics_tables` (production/dev/staging databases),
* - `tests/test-db.ts` (vitest + Playwright test databases).
*
* Every statement is idempotent (`IF NOT EXISTS`), so both paths can re-run
* against an already-primed database without failing.
*
* This module must stay dependency-free (no Payload, no pg import): it is
* loaded from migrations, route handlers, bins and the test bootstrap alike.
*/
/** Every table this module owns; used by tests and ops tooling. */
export const ANALYTICS_TABLE_NAMES = [
"analytics_sessions",
"analytics_events",
"analytics_daily_pages",
"analytics_daily_users",
"analytics_daily_games",
"analytics_daily_chronicle",
] as const;
/**
* The full DDL, one self-contained statement per array entry. Keep each
* entry executable on its own (both `db.execute` in the migration and the
* pg client in the test bootstrap run them sequentially).
*/
export const ANALYTICS_DDL_STATEMENTS: string[] = [
// ------------------------------------------------------------------
// Raw sessions. One row per browsing session (30-minute inactivity
// boundary enforced at ingest). user_id stays NULL until a guest session
// upgrades to a login; there is intentionally no FK to users() so events
// survive account deletion.
// ------------------------------------------------------------------
`CREATE TABLE IF NOT EXISTS "analytics_sessions" (
"id" text PRIMARY KEY,
"user_id" integer,
"anonymous_id" text,
"started_at" timestamptz NOT NULL DEFAULT now(),
"last_activity_at" timestamptz NOT NULL DEFAULT now(),
"ended_at" timestamptz,
"entry_path" text,
"exit_path" text,
"pageview_count" integer NOT NULL DEFAULT 0,
"active_ms" bigint NOT NULL DEFAULT 0,
"is_bot" boolean NOT NULL DEFAULT false,
"env" text NOT NULL DEFAULT 'production',
"ip" text,
"ua" text,
"referrer" text
)`,
`CREATE INDEX IF NOT EXISTS "analytics_sessions_started_idx" ON "analytics_sessions" ("started_at")`,
`CREATE INDEX IF NOT EXISTS "analytics_sessions_user_started_idx" ON "analytics_sessions" ("user_id", "started_at")`,
// ------------------------------------------------------------------
// Raw events. Purged after 90 days by the analytics-purge bin; the daily
// aggregate tables below are the permanent record.
//
// NOTE FOR THE TEST BOOTSTRAP: drizzle push (DB_PUSH=1) treats these plain
// tables as drift, and its introspector has a broken composite-primary-key
// query path (drizzle-kit 0.31.11), so `tests/test-db.ts` drops these
// tables BEFORE pushing and recreates them afterwards via applyAnalyticsDdl.
// Never make the push see them.
// ------------------------------------------------------------------
`CREATE TABLE IF NOT EXISTS "analytics_events" (
"id" bigserial PRIMARY KEY,
"session_id" text NOT NULL REFERENCES "analytics_sessions"("id") ON DELETE CASCADE,
"user_id" integer,
"ts" timestamptz NOT NULL,
"type" text NOT NULL,
"path" text,
"element" jsonb,
"data" jsonb,
"env" text NOT NULL DEFAULT 'production'
)`,
`CREATE INDEX IF NOT EXISTS "analytics_events_session_idx" ON "analytics_events" ("session_id")`,
`CREATE INDEX IF NOT EXISTS "analytics_events_path_ts_idx" ON "analytics_events" ("path", "ts")`,
`CREATE INDEX IF NOT EXISTS "analytics_events_user_ts_idx" ON "analytics_events" ("user_id", "ts")`,
`CREATE INDEX IF NOT EXISTS "analytics_events_ts_idx" ON "analytics_events" ("ts")`,
// ------------------------------------------------------------------
// Permanent daily aggregates (written by the analytics-rollup bin).
// ------------------------------------------------------------------
`CREATE TABLE IF NOT EXISTS "analytics_daily_pages" (
"day" date NOT NULL,
"path" text NOT NULL,
"views" integer NOT NULL DEFAULT 0,
"visitors" integer NOT NULL DEFAULT 0,
"avg_dwell_ms" bigint NOT NULL DEFAULT 0,
"avg_max_scroll" numeric NOT NULL DEFAULT 0,
CONSTRAINT "analytics_daily_pages_pkey" PRIMARY KEY ("day", "path")
)`,
// user_id = 0 is the rollup row aggregating all anonymous traffic.
`CREATE TABLE IF NOT EXISTS "analytics_daily_users" (
"day" date NOT NULL,
"user_id" integer NOT NULL DEFAULT 0,
"active_ms" bigint NOT NULL DEFAULT 0,
"sessions" integer NOT NULL DEFAULT 0,
"pageviews" integer NOT NULL DEFAULT 0,
"top_paths" jsonb NOT NULL DEFAULT '[]'::jsonb,
CONSTRAINT "analytics_daily_users_pkey" PRIMARY KEY ("day", "user_id")
)`,
`CREATE TABLE IF NOT EXISTS "analytics_daily_games" (
"day" date NOT NULL,
"game_key" text NOT NULL,
"players" integer NOT NULL DEFAULT 0,
"sessions" integer NOT NULL DEFAULT 0,
"avg_session_ms" bigint NOT NULL DEFAULT 0,
CONSTRAINT "analytics_daily_games_pkey" PRIMARY KEY ("day", "game_key")
)`,
// kind: 'beat' | 'journal'; ref: the StoryBeat or Journal id as a string.
`CREATE TABLE IF NOT EXISTS "analytics_daily_chronicle" (
"day" date NOT NULL,
"kind" text NOT NULL,
"ref" text NOT NULL,
"opens" integer NOT NULL DEFAULT 0,
"completions" integer NOT NULL DEFAULT 0,
"median_time_ms" bigint,
CONSTRAINT "analytics_daily_chronicle_pkey" PRIMARY KEY ("day", "kind", "ref")
)`,
];
/** Minimal structural type so callers can pass a pg Client or similar. */
interface SqlExecutor {
query: (sql: string) => Promise<unknown>;
}
/** Run every DDL statement against the given connection (idempotent). */
export async function applyAnalyticsDdl(client: SqlExecutor): Promise<void> {
for (const statement of ANALYTICS_DDL_STATEMENTS) {
await client.query(statement);
}
}

View file

@ -0,0 +1,79 @@
"use client";
import { useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { disposeTracker, flush, initTracker } from "./core";
import { startCaptures, type Captures } from "./capture";
/**
* First-party analytics tracker (Phase 1), the replacement for Microsoft
* Clarity (which stays mounted during the transition).
*
* Renders nothing. Mount once per top-level frontend layout
* (`src/app/(frontend)/layout.tsx` and `src/app/login/layout.tsx`) next to
* `<ClarityAnalytics />`; one mount covers every route below it. The Payload
* admin panel is intentionally NOT tracked.
*
* Enablement lives in `core.isAnalyticsEnabled()`: production builds always
* track; development tracks only with NEXT_PUBLIC_ANALYTICS_DEV=1 (and then
* mirrors every event to console.debug("[analytics]", ...)). All failures are
* swallowed: analytics must never break the app.
*
* SPA navigation is captured twice over: a `usePathname()` effect covers App
* Router navigations, and patched `history.pushState`/`replaceState` cover
* any pushState that does not re-render the tree (duplicate calls for the
* same path are deduped inside the capture layer).
*/
export function AnalyticsTracker() {
const pathname = usePathname();
const capturesRef = useRef<Captures | null>(null);
useEffect(() => {
initTracker();
const captures = startCaptures();
capturesRef.current = captures;
// History patching: fire a synthetic event whenever app code (or a
// library) pushes state without a React navigation.
const originalPush = history.pushState.bind(history);
const originalReplace = history.replaceState.bind(history);
const emit =
(fn: typeof history.pushState) =>
(...args: Parameters<typeof history.pushState>) => {
fn(...args);
window.dispatchEvent(new Event("ptf:analytics-route"));
};
history.pushState = emit(originalPush);
history.replaceState = emit(originalReplace);
const onRouteEvent = () => {
try {
captures.handleRouteChange(window.location.pathname);
flush(false);
} catch {
// Swallowed by contract.
}
};
window.addEventListener("ptf:analytics-route", onRouteEvent);
return () => {
window.removeEventListener("ptf:analytics-route", onRouteEvent);
history.pushState = originalPush;
history.replaceState = originalReplace;
capturesRef.current = null;
captures.stop();
disposeTracker();
};
}, []);
useEffect(() => {
try {
capturesRef.current?.handleRouteChange(pathname);
} catch {
// Swallowed by contract.
}
}, [pathname]);
return null;
}

View file

@ -0,0 +1,106 @@
# Client Analytics SDK (Phase 1)
First-party, blocker-resistant usage analytics for Polaris Task Force, replacing
Microsoft Clarity (which stays mounted during the transition; removal is a later
release). Usage data only: no rrweb, no recording, no advertising tech.
- Collector endpoint: `src/app/api/collect/route.ts`
- Server-side ingest + taxonomy validation: `src/lib/analytics/ingest.ts`,
`src/lib/analytics/events.ts`
- Tables and rollups: `src/lib/analytics/` (see its AGENTS.md)
- Admin dashboard: `/admin/analytics` (`src/components/admin/analytics/`)
## Enablement
The tracker mounts in exactly two layouts (all user-facing surfaces; the Payload
admin panel is deliberately NOT tracked):
- `src/app/(frontend)/layout.tsx` (covers guests on the landing page too)
- `src/app/login/layout.tsx`
It tracks in production builds always, and in development only when
`NEXT_PUBLIC_ANALYTICS_DEV=1` was set at build time. In dev mode every event is
also mirrored to `console.debug("[analytics]", ...)` and rows carry `env='dev'`.
Exercise it locally:
```bash
NEXT_PUBLIC_ANALYTICS_DEV=1 bun run dev
# open http://localhost:3000, watch console for [analytics] lines,
# then check rows: SELECT * FROM analytics_events ORDER BY id DESC LIMIT 20;
```
Fire-and-forget contract: every SDK entry point swallows errors with a
`console.warn("[analytics] ...")`. Analytics must never break the app.
## Identity and sessions
- Session id: issued by the collector as the first-party cookie
`ptf_analytics_sid` (7 days). The client echoes it on every batch; the server
also enforces the boundary itself (30 minutes of inactivity starts a new
session row).
- Anonymous id: random UUID in localStorage (`ptf_analytics_aid`) until login;
the collector attributes batches via the same-origin `payload-token` cookie
and links guest sessions to the user retroactively.
- No consent banner (locked decision: usage data only, unit-internal tool).
doNotTrack/GPC are ignored. No sampling. Full IP + UA stored per session.
## Flush lifecycle
Batched `fetch keepalive` POSTs every 10s, on route change, and via
`navigator.sendBeacon` on `pagehide` / tab hidden. Queue is capped at 50 events
(the server's per-batch limit); overflow drops oldest.
SPA navigation is captured by a `usePathname()` effect plus patched
`history.pushState/replaceState`; duplicate notifications for the same path are
deduped.
## Event taxonomy
All rows land in `analytics_events` with `type` one of the seven values below
(the single source of truth is `ANALYTICS_EVENT_TYPES` in
`src/lib/analytics/events.ts`). `path` is the raw pathname as visited; the
dashboard groups by prefix.
| type | when | `data` | `element` |
| ---------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------- |
| `pageview` | mount + every SPA route change | `referrerPath` / `externalReferrer`; extra keys from `annotatePageview()` (e.g. `wikiSlug`) | - |
| `click` | delegated click on interactive elements | `xPct`, `yPct` (viewport-relative percentages) | selector, visible text, w/h, trackLabel |
| `scroll` | emitted when leaving a page | `maxScrollPct` (0-100), `dwellMs` | - |
| `focus` | focusin/focusout on inputs, selects, buttons, links, editables | `action: "focus" \| "blur"` | element descriptor |
| `visible` | opt-in `data-track="label"` elements, on route change/unload | `trackLabel`, `visibleMs`, `maxRatioPct` | - |
| `heartbeat`| every 15s while `document.visibilityState === "visible"` | `ms` (elapsed visible slice, capped 60s) | - |
| `custom` | `track(name, props)` calls | `name` + flattened props; domain events below | - |
### Domain custom events (Phase 1)
| name | fired by | payload |
| --------------------------- | ------------------------------------------ | -------------------------------------------------- |
| `chronicle.read_progress` | first visibility of a beat/journal article | `kind: "beat"\|"journal"`, `ref`, `progressPct` |
| `chronicle.read_completed` | >=90% scrolled AND >=10s visible dwell | `kind`, `ref`, `timeMs` (visible dwell to complete) |
| `wiki.new_clicked` | WikiIndex "New page" links | `source: "toolbar" \| "empty"` |
| `wiki.article_created` | WikiEditor create success | `slug` |
Minigames need no per-game events: `/minigames/<slug>` routes are mapped to
registry keys at rollup time (`src/lib/analytics/games.ts`), and play-session
length is the heartbeat dwell on those routes.
## Public API
```ts
import { track, annotatePageview } from "@/lib/client-analytics";
track("market.listing_viewed", { listingId: 42 }); // custom event
annotatePageview({ wikiSlug: "radio-procedures" }); // merge into current pageview
```
Both are safe to call anywhere in client components; they no-op when tracking
is disabled and never throw.
## Adding a new event type or domain event
1. Extend `ANALYTICS_EVENT_TYPES` in `src/lib/analytics/events.ts` (only for a
new structural type, not for custom events).
2. Update this README's taxonomy table.
3. If it should appear in aggregates, extend the rollup SQL in
`src/lib/analytics/rollup.ts`.

View file

@ -0,0 +1,356 @@
/**
* SDK capture layers (Phase 1): clicks, per-page scroll depth + dwell,
* focus/blur on interactive elements, `data-track` element viewability, and
* 15s dwell heartbeats while the tab is visible.
*
* Every capture is delegated at the document level and mounted once by
* `<AnalyticsTracker />`. All handlers are try/catch fire-and-forget.
*/
import { currentPath, flush, record, takePendingPageviewProps } from "./core";
export type CaptureCleanup = () => void;
const MAX_TEXT_LENGTH = 80;
const MIN_VISIBLE_MS = 250; // ignore blink-of-an-eye data-track hits
const HEARTBEAT_INTERVAL_MS = 15_000;
function safe(fn: () => void): void {
try {
fn();
} catch {
// Capture must never break interaction handlers.
}
}
// ---------------------------------------------------------------------------
// Element descriptors (shared by click + focus capture)
// ---------------------------------------------------------------------------
function cssSegment(el: Element): string {
const tag = el.tagName.toLowerCase();
if (el.id) return `${tag}#${el.id}`;
const classes = Array.from(el.classList)
.filter((c) => c.length <= 24 && !/[\s:./[%\]]/.test(c))
.slice(0, 2);
return classes.length > 0 ? `${tag}.${classes.join(".")}` : tag;
}
/** Short structural selector: up to three ancestors, outermost first. */
function describeSelector(el: Element): string {
const parts: string[] = [];
let node: Element | null = el;
while (node && parts.length < 3) {
parts.unshift(cssSegment(node));
node = node.parentElement;
}
return parts.join(" > ");
}
function visibleText(el: Element): string | undefined {
const raw =
(el as HTMLElement).innerText ?? el.getAttribute("aria-label") ?? el.getAttribute("title") ?? "";
const text = String(raw).replace(/\s+/g, " ").trim();
return text ? text.slice(0, MAX_TEXT_LENGTH) : undefined;
}
function describeElement(el: Element): Record<string, unknown> {
const descriptor: Record<string, unknown> = {
selector: describeSelector(el),
};
const text = visibleText(el);
if (text) descriptor.text = text;
if (el instanceof HTMLElement) {
descriptor.w = Math.round(el.offsetWidth);
descriptor.h = Math.round(el.offsetHeight);
}
const tracked = el.closest("[data-track]");
if (tracked) {
const label = tracked.getAttribute("data-track");
if (label) descriptor.trackLabel = label.slice(0, 120);
}
return descriptor;
}
// ---------------------------------------------------------------------------
// Click capture (delegated)
// ---------------------------------------------------------------------------
export function startClickCapture(): CaptureCleanup {
const onClick = (event: MouseEvent) =>
safe(() => {
const target = event.target;
if (!(target instanceof Element)) return;
const interactive = target.closest(
"a,button,[role='button'],input,select,textarea,label,summary,[data-track]",
);
if (!interactive) return;
const data: Record<string, unknown> = {};
if (typeof window !== "undefined" && window.innerWidth > 0) {
// Viewport-relative percentages (locked decision: viewport-relative).
data.xPct = Math.round((event.clientX / window.innerWidth) * 100);
data.yPct = Math.round((event.clientY / window.innerHeight) * 100);
}
record("click", {
path: currentPath() ?? undefined,
element: describeElement(interactive),
data,
});
});
document.addEventListener("click", onClick, true);
return () => document.removeEventListener("click", onClick, true);
}
// ---------------------------------------------------------------------------
// Focus / blur capture on interactive elements
// ---------------------------------------------------------------------------
const INTERACTIVE_SELECTOR =
"input:not([type='hidden']),select,textarea,button,a[href],[contenteditable='true']";
export function startFocusCapture(): CaptureCleanup {
const handler = (event: FocusEvent) =>
safe(() => {
const target = event.target;
if (!(target instanceof Element)) return;
const el = target.closest(INTERACTIVE_SELECTOR);
if (!el) return;
record("focus", {
path: currentPath() ?? undefined,
element: describeElement(el),
data: { action: event.type === "focusin" ? "focus" : "blur" },
});
});
document.addEventListener("focusin", handler, true);
document.addEventListener("focusout", handler, true);
return () => {
document.removeEventListener("focusin", handler, true);
document.removeEventListener("focusout", handler, true);
};
}
// ---------------------------------------------------------------------------
// Scroll depth + dwell for the current page
// ---------------------------------------------------------------------------
interface PageState {
path: string | null;
startedAt: number;
maxScrollPct: number;
}
let page: PageState | null = null;
function documentScrollPct(): number {
const doc = document.documentElement;
const scrollHeight = Math.max(doc.scrollHeight, 1);
const viewed = window.scrollY + window.innerHeight;
return Math.min(100, Math.round((viewed / scrollHeight) * 100));
}
function onScroll(): void {
safe(() => {
if (!page) return;
const pct = documentScrollPct();
if (pct > page.maxScrollPct) page.maxScrollPct = pct;
});
}
/** Emit the leaving-page summary (max scroll depth + dwell). */
function finishPage(): void {
if (!page) return;
const dwellMs = Math.max(0, Date.now() - page.startedAt);
record("scroll", {
path: page.path ?? undefined,
data: { maxScrollPct: page.maxScrollPct, dwellMs },
});
page = null;
}
// ---------------------------------------------------------------------------
// data-track viewability (IntersectionObserver + MutationObserver)
// ---------------------------------------------------------------------------
interface TrackRecord {
label: string;
enteredAt: number | null;
visibleMs: number;
maxRatio: number;
}
let trackRecords = new Map<Element, TrackRecord>();
let trackObserver: IntersectionObserver | null = null;
let trackMutator: MutationObserver | null = null;
function observeTrackable(el: Element): void {
if (!trackObserver || trackRecords.has(el)) return;
const label = el.getAttribute("data-track") || "unnamed";
trackRecords.set(el, { label, enteredAt: null, visibleMs: 0, maxRatio: 0 });
trackObserver.observe(el);
}
function scanTrackables(root: ParentNode): void {
root.querySelectorAll("[data-track]").forEach(observeTrackable);
}
/** Emit pending viewability records (route change / unload). */
function flushTrackRecords(): void {
if (trackRecords.size === 0) return;
const now = Date.now();
const records = [...trackRecords.values()];
trackRecords = new Map();
trackObserver?.disconnect();
// Re-create the observer so elements still on the page are re-observed.
trackObserver = null;
startTrackObserver();
for (const rec of records) {
if (rec.enteredAt != null) {
rec.visibleMs += now - rec.enteredAt;
}
if (rec.visibleMs >= MIN_VISIBLE_MS || rec.maxRatio > 0) {
record("visible", {
path: currentPath() ?? undefined,
data: {
trackLabel: rec.label.slice(0, 120),
visibleMs: Math.round(rec.visibleMs),
maxRatioPct: Math.round(rec.maxRatio * 100),
},
});
}
}
}
function startTrackObserver(): void {
if (trackObserver) return;
trackObserver = new IntersectionObserver(
(entries) =>
safe(() => {
const now = Date.now();
for (const entry of entries) {
const rec = trackRecords.get(entry.target);
if (!rec) continue;
rec.maxRatio = Math.max(rec.maxRatio, entry.intersectionRatio);
const visible = entry.isIntersecting && entry.intersectionRatio >= 0.5;
if (visible && rec.enteredAt == null) {
rec.enteredAt = now;
} else if (!visible && rec.enteredAt != null) {
rec.visibleMs += now - rec.enteredAt;
rec.enteredAt = null;
}
}
}),
{ threshold: [0, 0.25, 0.5, 0.75, 1] },
);
scanTrackables(document);
if (!trackMutator) {
trackMutator = new MutationObserver((mutations) =>
safe(() => {
for (const mutation of mutations) {
mutation.addedNodes.forEach((node) => {
if (!(node instanceof Element)) return;
if (node.hasAttribute("data-track")) observeTrackable(node);
scanTrackables(node);
});
}
}),
);
trackMutator.observe(document.body, { childList: true, subtree: true });
}
}
function stopTrackObserver(): void {
trackObserver?.disconnect();
trackObserver = null;
trackMutator?.disconnect();
trackMutator = null;
trackRecords = new Map();
}
// ---------------------------------------------------------------------------
// Heartbeats (dwell while visible)
// ---------------------------------------------------------------------------
export function startHeartbeat(): CaptureCleanup {
let lastTick = Date.now();
const timer = setInterval(() => {
safe(() => {
const now = Date.now();
const elapsed = now - lastTick;
lastTick = now;
if (document.visibilityState !== "visible") return;
record("heartbeat", {
path: currentPath() ?? undefined,
data: { ms: Math.min(Math.round(elapsed), 60_000) },
});
});
}, HEARTBEAT_INTERVAL_MS);
return () => clearInterval(timer);
}
// ---------------------------------------------------------------------------
// Orchestration
// ---------------------------------------------------------------------------
export interface Captures {
stop: CaptureCleanup;
/** Called on mount and on every SPA navigation with the new pathname. */
handleRouteChange: (path: string) => void;
}
export function startCaptures(): Captures {
safe(() => startTrackObserver());
const cleanups: CaptureCleanup[] = [startClickCapture(), startFocusCapture(), startHeartbeat()];
window.addEventListener("scroll", onScroll, { passive: true });
const onPagehide = () =>
safe(() => {
finishPage();
flushTrackRecords();
});
window.addEventListener("pagehide", onPagehide);
let firstView = true;
const handleRouteChange = (path: string) =>
safe(() => {
if (!firstView && page && page.path === path) return;
firstView = false;
finishPage();
flushTrackRecords();
page = { path, startedAt: Date.now(), maxScrollPct: documentScrollPct() };
const data: Record<string, unknown> = {};
if (typeof document !== "undefined" && document.referrer) {
try {
const ref = new URL(document.referrer);
if (ref.origin === window.location.origin) data.referrerPath = ref.pathname;
else data.externalReferrer = ref.hostname;
} catch {
// Malformed referrer: omit it.
}
}
// Merge annotations parked by child effects (e.g. wiki slug tagging).
const pending = takePendingPageviewProps();
if (pending) Object.assign(data, pending);
record("pageview", { path, data });
// Route changes flush so batches align with pages (and so annotate
// calls that run during render land before the batch ships).
flush(false);
});
return {
stop: () => {
cleanups.forEach((fn) => fn());
window.removeEventListener("scroll", onScroll);
window.removeEventListener("pagehide", onPagehide);
stopTrackObserver();
finishPage();
},
handleRouteChange,
};
}

View file

@ -0,0 +1,245 @@
"use client";
import { useEffect, useRef } from "react";
import { track } from "./core";
/**
* Chronicle read tracking (Phase 1 domain instrumentation).
*
* Article-level read progress from scroll + dwell inside the article
* container. Emits custom events that complement (never replace) the
* StoryBeatStates read markers:
*
* - `chronicle.read_progress` once when an article first becomes visible
* (this is what the rollup counts as an "open"), carrying `progressPct`;
* - `chronicle.read_completed` once per mount when the reader has scrolled
* at least CHRONICLE_COMPLETION_PROGRESS of the article AND dwelled at
* least CHRONICLE_MIN_DWELL_MS while it was on screen, carrying `timeMs`
* (accumulated visible dwell up to completion).
*
* Both events carry `{ kind: "beat" | "journal", ref: <id> }`.
*/
export const CHRONICLE_COMPLETION_PROGRESS = 0.9;
export const CHRONICLE_MIN_DWELL_MS = 10_000;
const COMPLETION_CHECK_INTERVAL_MS = 2_000;
export type ChronicleKind = "beat" | "journal";
function clamp01(value: number): number {
return Math.max(0, Math.min(1, value));
}
/**
* Fraction of the article the reader has consumed: for articles taller than
* the viewport this is the classic read-progress ratio (0 when the top hits
* the fold, 1 when the bottom clears it); for shorter articles it is the
* visible fraction.
*/
function readProgress(el: HTMLElement): number {
const rect = el.getBoundingClientRect();
if (rect.height <= 0) return 0;
const vh = window.innerHeight || 1;
if (rect.height <= vh) {
const visible = Math.min(rect.bottom, vh) - Math.max(rect.top, 0);
return clamp01(visible / rect.height);
}
return clamp01(-rect.top / (rect.height - vh));
}
/** Start a read session for one article element. Returns a dispose fn. */
function startReadSession(kind: ChronicleKind, ref: string, el: HTMLElement): () => void {
let disposed = false;
let dwellMs = 0;
let visibleSince: number | null = null;
let maxProgress = 0;
let opened = false;
let completed = false;
const currentDwell = (): number => {
if (visibleSince != null && document.visibilityState === "visible") {
return dwellMs + (Date.now() - visibleSince);
}
return dwellMs;
};
const complete = (): void => {
if (completed) return;
completed = true;
track("chronicle.read_completed", { kind, ref, timeMs: Math.round(currentDwell()) });
};
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (disposed) continue;
if (entry.isIntersecting) {
if (visibleSince == null) visibleSince = Date.now();
if (!opened) {
opened = true;
maxProgress = Math.max(maxProgress, readProgress(el));
track("chronicle.read_progress", {
kind,
ref,
progressPct: Math.round(maxProgress * 100),
});
}
} else if (visibleSince != null) {
dwellMs += Date.now() - visibleSince;
visibleSince = null;
}
}
},
{ threshold: 0.35 },
);
let rafPending = false;
const onScroll = () => {
if (disposed || rafPending) return;
rafPending = true;
requestAnimationFrame(() => {
rafPending = false;
if (disposed) return;
try {
maxProgress = Math.max(maxProgress, readProgress(el));
} catch {
// Swallowed by contract.
}
});
};
const onVisibility = () => {
if (disposed) return;
if (document.visibilityState === "hidden" && visibleSince != null) {
dwellMs += Date.now() - visibleSince;
visibleSince = null;
} else if (document.visibilityState === "visible" && visibleSince == null) {
// Re-observe below; only count while the element is actually on screen.
const rect = el.getBoundingClientRect();
const vh = window.innerHeight || 1;
if (rect.bottom > 0 && rect.top < vh) visibleSince = Date.now();
}
};
observer.observe(el);
window.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", onScroll);
document.addEventListener("visibilitychange", onVisibility);
const timer = setInterval(() => {
if (disposed || completed || !opened) return;
try {
maxProgress = Math.max(maxProgress, readProgress(el));
if (maxProgress >= CHRONICLE_COMPLETION_PROGRESS && currentDwell() >= CHRONICLE_MIN_DWELL_MS) {
complete();
}
} catch {
// Swallowed by contract.
}
}, COMPLETION_CHECK_INTERVAL_MS);
return () => {
disposed = true;
observer.disconnect();
clearInterval(timer);
window.removeEventListener("scroll", onScroll);
window.removeEventListener("resize", onScroll);
document.removeEventListener("visibilitychange", onVisibility);
};
}
/**
* Wraps a single article (used for the journal reader). The wrapper div is
* layout-transparent apart from being a block box.
*/
export function ChronicleArticle({
kind,
articleId,
className,
children,
}: {
kind: ChronicleKind;
articleId: string;
className?: string;
children: React.ReactNode;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
return startReadSession(kind, articleId, el);
}, [kind, articleId]);
return (
<div ref={ref} className={className}>
{children}
</div>
);
}
/**
* Tracks every descendant carrying `idAttr` (default `data-beat-id`) as a
* separate beat article. Used by the two Chronicle readers, which render many
* beats inside one scroll/paging surface and add the attribute per beat.
*/
export function ChronicleTrackedRegion({
kind = "beat",
idAttr = "data-beat-id",
className,
children,
}: {
kind?: ChronicleKind;
idAttr?: string;
className?: string;
children: React.ReactNode;
}) {
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const sessions = new Map<Element, () => void>();
const attach = (el: Element) => {
const id = el.getAttribute(idAttr);
if (!id || sessions.has(el)) return;
sessions.set(el, startReadSession(kind, id, el as HTMLElement));
};
const detach = (el: Element) => {
const dispose = sessions.get(el);
if (dispose) {
dispose();
sessions.delete(el);
}
};
root.querySelectorAll(`[${idAttr}]`).forEach(attach);
const mutator = new MutationObserver((mutations) => {
for (const mutation of mutations) {
mutation.removedNodes.forEach((node) => {
if (node instanceof Element) detach(node);
});
mutation.addedNodes.forEach((node) => {
if (!(node instanceof Element)) return;
if (node.hasAttribute(idAttr)) attach(node);
node.querySelectorAll?.(`[${idAttr}]`).forEach(attach);
});
}
});
mutator.observe(root, { childList: true, subtree: true });
return () => {
mutator.disconnect();
sessions.forEach((dispose) => dispose());
sessions.clear();
};
}, [kind, idAttr]);
return (
<div ref={rootRef} className={className}>
{children}
</div>
);
}

View file

@ -0,0 +1,288 @@
/**
* Client-side analytics core (Phase 1).
*
* Framework-free tracker singleton mounted by `<AnalyticsTracker />`. Owns:
*
* - enablement (production builds, or dev with NEXT_PUBLIC_ANALYTICS_DEV=1),
* - identity: collector-issued session id (first-party cookie) + anonymous id
* (localStorage until login upgrades attribution server-side),
* - a bounded event queue flushed via fetch keepalive / sendBeacon,
* - the public `track()` API used by domain instrumentation.
*
* Fire-and-forget contract: every entry point swallows its own errors with a
* console warning. Analytics must never break the app (same rule Clarity
* follows in this codebase).
*/
import type { AnalyticsEventType } from "@/lib/analytics/events";
export const ANALYTICS_ENDPOINT = "/api/collect";
export const ANALYTICS_SID_COOKIE = "ptf_analytics_sid";
const ANONYMOUS_ID_KEY = "ptf_analytics_aid";
const FLUSH_INTERVAL_MS = 10_000;
const MAX_QUEUE_SIZE = 50; // matches MAX_EVENTS_PER_BATCH on the server
const LOG_PREFIX = "[analytics]";
/** One queued event, shaped for the collector envelope. */
export interface QueuedEvent {
ts: number;
type: AnalyticsEventType;
path?: string;
element?: Record<string, unknown>;
data?: Record<string, unknown>;
}
interface TrackerState {
enabled: boolean;
started: boolean;
queue: QueuedEvent[];
flushTimer: ReturnType<typeof setInterval> | null;
lastFlushAttempt: number;
}
// Anchored on globalThis so Next dev HMR cannot fork the queue or double the
// flush interval (the same pattern the realtime bus uses).
const globalScope = globalThis as typeof globalThis & { __ptfAnalytics?: TrackerState };
function getState(): TrackerState {
if (!globalScope.__ptfAnalytics) {
globalScope.__ptfAnalytics = {
enabled: false,
started: false,
queue: [],
flushTimer: null,
lastFlushAttempt: 0,
};
}
return globalScope.__ptfAnalytics;
}
/**
* Tracking is production-only unless NEXT_PUBLIC_ANALYTICS_DEV=1 was set at
* build time (mirrors how ClarityAnalytics gates on its env var). In dev mode
* every event is also mirrored to console.debug for local verification.
*/
export function isAnalyticsEnabled(): boolean {
return process.env.NODE_ENV === "production" || process.env.NEXT_PUBLIC_ANALYTICS_DEV === "1";
}
export function isAnalyticsDevMode(): boolean {
return process.env.NODE_ENV !== "production";
}
function debugMirror(event: QueuedEvent): void {
if (isAnalyticsDevMode() && isAnalyticsEnabled()) {
// eslint-disable-next-line no-console
console.debug(LOG_PREFIX, event);
}
}
// ---------------------------------------------------------------------------
// Identity
// ---------------------------------------------------------------------------
function getAnonymousId(): string | null {
try {
let aid = window.localStorage.getItem(ANONYMOUS_ID_KEY);
if (!aid) {
aid = crypto.randomUUID();
window.localStorage.setItem(ANONYMOUS_ID_KEY, aid);
}
return aid;
} catch {
return null; // private mode / storage disabled: stay anonymous
}
}
/** Read the collector-issued session id from the first-party cookie. */
export function getSessionId(): string | null {
if (typeof document === "undefined") return null;
for (const part of document.cookie.split(";")) {
const [name, ...rest] = part.trim().split("=");
if (name === ANALYTICS_SID_COOKIE) {
return decodeURIComponent(rest.join("=")) || null;
}
}
return null;
}
// ---------------------------------------------------------------------------
// Queue + flush
// ---------------------------------------------------------------------------
/** Enqueue an event; drops the oldest events when the queue overflows. */
export function enqueue(event: QueuedEvent): void {
if (typeof window === "undefined") return;
const state = getState();
if (!state.enabled) return;
try {
debugMirror(event);
state.queue.push(event);
if (state.queue.length > MAX_QUEUE_SIZE) {
state.queue.splice(0, state.queue.length - MAX_QUEUE_SIZE);
}
} catch (error) {
warn(error);
}
}
function warn(error: unknown): void {
try {
console.warn(`${LOG_PREFIX} ignored error:`, error);
} catch {
// console itself unavailable; nothing left to do.
}
}
/**
* Send the queued batch. `useBeacon` switches to navigator.sendBeacon for
* pagehide/visibilitychange, where fetch may not survive the unload.
*/
export function flush(useBeacon = false): void {
if (typeof window === "undefined") return;
const state = getState();
if (!state.enabled || state.queue.length === 0) return;
try {
const batch = state.queue.splice(0, MAX_QUEUE_SIZE);
const body = JSON.stringify({
sid: getSessionId(),
aid: getAnonymousId(),
events: batch,
});
state.lastFlushAttempt = Date.now();
if (useBeacon && typeof navigator.sendBeacon === "function") {
const ok = navigator.sendBeacon(ANALYTICS_ENDPOINT, new Blob([body], { type: "application/json" }));
if (ok) return;
// Beacon rejected (queue full / offline): fall through to fetch.
}
void fetch(ANALYTICS_ENDPOINT, {
method: "POST",
headers: { "content-type": "application/json" },
body,
keepalive: true,
credentials: "same-origin",
}).catch(() => {
// Swallowed by contract; the next flush retries what is still queued.
});
} catch (error) {
warn(error);
}
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
/** Start the tracker: enable it, start the interval, hook unload flushes. */
export function initTracker(): void {
if (typeof window === "undefined") return;
const state = getState();
state.enabled = isAnalyticsEnabled();
if (!state.enabled || state.started) return;
state.started = true;
try {
state.flushTimer = setInterval(() => flush(false), FLUSH_INTERVAL_MS);
const flushWithBeacon = () => flush(true);
window.addEventListener("pagehide", flushWithBeacon);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") flushWithBeacon();
});
} catch (error) {
warn(error);
}
}
/** Tear down timers/listeners (layout unmount, HMR). Queued data is flushed. */
export function disposeTracker(): void {
const state = getState();
if (state.flushTimer) {
clearInterval(state.flushTimer);
state.flushTimer = null;
}
state.started = false;
flush(true);
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/** Record a structured event of any taxonomy type. */
export function record(
type: AnalyticsEventType,
options: { path?: string; element?: Record<string, unknown>; data?: Record<string, unknown> } = {},
): void {
enqueue({ ts: Date.now(), type, ...options });
}
/**
* Public custom-event API for domain instrumentation:
* `track("chronicle.read_completed", { beatId: 12 })` becomes a `custom`
* event whose data carries `{ name, ...props }`.
*/
export function track(name: string, props?: Record<string, unknown>): void {
try {
if (typeof name !== "string" || !name) return;
const data: Record<string, unknown> = { name };
if (props && typeof props === "object") {
for (const [key, value] of Object.entries(props)) {
if (value === undefined) continue;
if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
data[key] = value;
} else {
data[key] = String(value);
}
}
}
record("custom", { path: currentPath() ?? undefined, data });
} catch (error) {
warn(error);
}
}
let lastKnownPath: string | null = null;
export function currentPath(): string | null {
if (lastKnownPath) return lastKnownPath;
if (typeof window !== "undefined") return window.location.pathname;
return null;
}
/**
* Merge extra metadata into the most recent queued pageview (used to tag
* `/wiki/<slug>` views with the slug before the batch leaves the queue).
* Child component effects run BEFORE the layout's tracker effect, so when no
* pageview is queued yet the props are parked and merged into the next
* pageview that gets recorded.
*/
let pendingPageviewProps: Record<string, unknown> | null = null;
export function annotatePageview(props: Record<string, unknown>): void {
const state = getState();
if (!state.enabled) return;
try {
for (let i = state.queue.length - 1; i >= 0; i -= 1) {
const event = state.queue[i];
if (event.type === "pageview") {
event.data = { ...event.data, ...props };
debugMirror(event);
return;
}
}
pendingPageviewProps = { ...(pendingPageviewProps ?? {}), ...props };
} catch (error) {
warn(error);
}
}
/** Consume any annotation parked before the pageview was recorded. */
export function takePendingPageviewProps(): Record<string, unknown> | null {
const pending = pendingPageviewProps;
pendingPageviewProps = null;
return pending;
}

View file

@ -0,0 +1,9 @@
/**
* Public surface of the first-party analytics SDK (Phase 1).
*
* Domain instrumentation should import `track` / `annotatePageview` from here
* (client components only). Layouts mount `<AnalyticsTracker />`.
*/
export { AnalyticsTracker } from "./AnalyticsTracker";
export { track, annotatePageview } from "./core";
export type { AnalyticsEventType } from "@/lib/analytics/events";

View file

@ -58,3 +58,4 @@ code; the invariants are:
leaderboards, and their page renders `MinigameComingSoon` instead of the arena. The date is
display only: the game goes live when an admin flips `status` to active. Countdown formatting:
`src/lib/minigames/countdown.ts`; page gate: `getMinigameReleaseState` plus a per-page check.
- **Phasing-out games**: a registry row with `status: "phasingOut"` stays fully playable and keeps scoring periods until it is removed. It shows an amber "Phasing out" badge in the sidebar (tooltip over the optional `estimatedRemovalDate`, via `phasingOutTooltip`) and a banner (`PhasingOutBanner`) on its game page, both rendering the countdown to removal. Unlike `retired` games, phasing-out games stay visible in the nav (`visibleRegistryGames` does not filter them) and on the leaderboards (`buildLeaderboardPayload` only excludes `upcoming`). The date is display only: the game keeps playing until an admin flips `status` to `retired`.

View file

@ -68,3 +68,20 @@ export function upcomingTooltip(
const countdown = formatCountdown(estimatedReleaseDate, now);
return countdown ? `Upcoming · releases ${instant} (${countdown})` : `Upcoming · releases ${instant}`;
}
/**
* Full tooltip line for a phasing-out game, e.g.
* "Phasing out · leaves Dec 3, 2026 18:00 UTC (in 12d 3h)". Reduces to just
* "Phasing out" when no estimate is set.
*/
export function phasingOutTooltip(
estimatedRemovalDate: string | null | undefined,
now: Date = new Date(),
): string {
const instant = formatReleaseInstant(estimatedRemovalDate);
if (!instant) return "Phasing out";
const countdown = formatCountdown(estimatedRemovalDate, now);
return countdown
? `Phasing out · leaves ${instant} (${countdown})`
: `Phasing out · leaves ${instant}`;
}

View file

@ -39,6 +39,7 @@ export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMin
countsForPeriods: Boolean(doc.countsForPeriods),
scoreLabel: doc.scoreLabel || "Score",
estimatedReleaseDate: doc.estimatedReleaseDate ?? null,
estimatedRemovalDate: doc.estimatedRemovalDate ?? null,
}),
);
if (rows.length > 0) return rows;

View file

@ -12,7 +12,7 @@
*/
export type MinigameCategory = "core" | "cardtable" | "multiplayer";
export type MinigameStatus = "active" | "retired" | "upcoming";
export type MinigameStatus = "active" | "retired" | "upcoming" | "phasingOut";
/** The six period-scoring games. Poker and Blackjack stay out of periods. */
export const CORE_MINIGAME_KEYS = [
@ -50,6 +50,12 @@ export interface BuiltinMinigame {
* changes `status` to "active", so a slipped estimate never exposes it.
*/
estimatedReleaseDate?: string | null;
/**
* Optional target removal instant (ISO 8601, UTC) shown as a countdown while
* `status` is "phasingOut". Display only: the game stays fully playable and
* keeps scoring periods until an admin sets `status` to "retired".
*/
estimatedRemovalDate?: string | null;
}
/** The seven built-in games, seeded into the `minigames` registry collection. */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,33 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres";
import { ANALYTICS_DDL_STATEMENTS } from "@/lib/analytics/schema";
/**
* Creates the plain-SQL analytics tables (sessions, events, daily aggregates).
*
* These tables are NOT Payload collections: they are written by the
* `/api/collect` route handler and the analytics-rollup / analytics-purge
* bins. The DDL lives in `src/lib/analytics/schema.ts` so the test-database
* bootstrap (which only pushes the Payload schema) creates them too. Every
* statement is idempotent.
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
for (const statement of ANALYTICS_DDL_STATEMENTS) {
await db.execute(sql.raw(statement));
}
}
export async function down({ db }: MigrateDownArgs): Promise<void> {
// Drop events before sessions (the session_id foreign key), aggregates in
// any order; IF EXISTS keeps partial rollbacks safe.
const dropOrder = [
"analytics_daily_chronicle",
"analytics_daily_games",
"analytics_daily_users",
"analytics_daily_pages",
"analytics_events",
"analytics_sessions",
];
for (const table of dropOrder) {
await db.execute(sql.raw(`DROP TABLE IF EXISTS "${table}"`));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,18 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres";
/**
* Adds `admin:analytics:manage` to the roles.permissions enum so a role can
* be granted the first-party analytics admin view. Follows the precedent of
* 20260923_200000_add_missing_role_permission_enum_values (idempotent via IF
* NOT EXISTS; safe to re-run in any environment).
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE IF NOT EXISTS 'admin:analytics:manage';
`);
}
// Postgres cannot remove values from an enum type; down is a best-effort no-op.
export async function down(): Promise<void> {
// No-op.
}

View file

@ -0,0 +1,23 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from "@payloadcms/db-postgres";
/**
* Adds `phasingOut` to the minigames status enum and the
* `estimated_removal_date` column so a game can be marked as leaving soon while
* staying playable. Follows the precedent of 20261011_221250 (column) and
* 20261014_135614 (enum value): idempotent via IF NOT EXISTS, safe to re-run.
*/
export async function up({ db }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_minigames_status" ADD VALUE IF NOT EXISTS 'phasingOut';
`);
await db.execute(sql`
ALTER TABLE "minigames" ADD COLUMN "estimated_removal_date" timestamp(3) with time zone;
`);
}
// Postgres cannot remove values from an enum type; down drops the column only.
export async function down({ db }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "minigames" DROP COLUMN "estimated_removal_date";
`);
}

View file

@ -134,6 +134,9 @@ import * as migration_20261012_182016_add_journals_event_target from './20261012
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
import * as migration_20261014_134620_add_analytics_tables from './20261014_134620_add_analytics_tables';
import * as migration_20261014_135614_add_analytics_permission_enum_value from './20261014_135614_add_analytics_permission_enum_value';
import * as migration_20261014_140500_add_minigame_phasing_out_status from './20261014_140500_add_minigame_phasing_out_status';
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields';
@ -818,6 +821,21 @@ export const migrations = [
down: migration_20261013_184745_add_garage_fields.down,
name: '20261013_184745_add_garage_fields',
},
{
up: migration_20261014_134620_add_analytics_tables.up,
down: migration_20261014_134620_add_analytics_tables.down,
name: '20261014_134620_add_analytics_tables',
},
{
up: migration_20261014_135614_add_analytics_permission_enum_value.up,
down: migration_20261014_135614_add_analytics_permission_enum_value.down,
name: '20261014_135614_add_analytics_permission_enum_value'
},
{
up: migration_20261014_140500_add_minigame_phasing_out_status.up,
down: migration_20261014_140500_add_minigame_phasing_out_status.down,
name: '20261014_140500_add_minigame_phasing_out_status'
},
{
up: migration_20261014_192950_add_npc_dialogue_states.up,
down: migration_20261014_192950_add_npc_dialogue_states.down,

View file

@ -130,6 +130,16 @@ export const enum_game_event_logs_required_permissions = pgEnum(
"awards:update",
"awards:delete",
"admin:awards:manage",
"journals:create",
"journals:read",
"journals:update",
"journals:delete",
"admin:journals:manage",
"award-rules:create",
"award-rules:read",
"award-rules:update",
"award-rules:delete",
"admin:award-rules:manage",
"qualifications:create",
"qualifications:read",
"qualifications:update",
@ -444,6 +454,8 @@ export const enum_game_event_logs_required_permissions = pgEnum(
"tickets:staff",
"discord:staff",
"discord:announce",
"discord:rp:read",
"discord:rp:update",
"custom-minefields:update",
"custom-minefields:delete",
"custom-minefield-scores:delete",
@ -471,6 +483,7 @@ export const enum_game_event_logs_required_permissions = pgEnum(
"achievements:update",
"achievements:delete",
"admin:achievements:manage",
"admin:analytics:manage",
],
);
export const enum_game_event_logs_visibility = pgEnum("enum_game_event_logs_visibility", [
@ -516,6 +529,8 @@ export const enum_game_event_logs_target_collection = pgEnum(
"voice-scripts",
"voice-submissions",
"story-beats",
"journals",
"awards",
"story-beat-states",
"custom-minefields",
"custom-minefield-scores",
@ -635,6 +650,16 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
"awards:update",
"awards:delete",
"admin:awards:manage",
"journals:create",
"journals:read",
"journals:update",
"journals:delete",
"admin:journals:manage",
"award-rules:create",
"award-rules:read",
"award-rules:update",
"award-rules:delete",
"admin:award-rules:manage",
"qualifications:create",
"qualifications:read",
"qualifications:update",
@ -949,6 +974,8 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
"tickets:staff",
"discord:staff",
"discord:announce",
"discord:rp:read",
"discord:rp:update",
"custom-minefields:update",
"custom-minefields:delete",
"custom-minefield-scores:delete",
@ -976,6 +1003,7 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
"achievements:update",
"achievements:delete",
"admin:achievements:manage",
"admin:analytics:manage",
]);
export const enum_awards_grant_config_allowed_grantor_assignment_types = pgEnum(
"enum_awards_grant_config_allowed_grantor_assignment_types",
@ -986,6 +1014,13 @@ export const enum_awards_grant_config_recipient_scope = pgEnum(
"enum_awards_grant_config_recipient_scope",
["same_command", "whitelist", "anyone"],
);
export const enum_award_rules_metric = pgEnum("enum_award_rules_metric", [
"yearsOfService",
"accountAge",
"missionsAttended",
"xpTotal",
]);
export const enum_award_rules_operator = pgEnum("enum_award_rules_operator", ["gte", "gt"]);
export const enum_assignments_type = pgEnum("enum_assignments_type", [
"division",
"squad",
@ -1017,6 +1052,7 @@ export const enum_contribution_entries_type = pgEnum("enum_contribution_entries_
"wiki-page-edit",
"mission-map-marker",
"survey-completion",
"journal-publish",
"manual",
]);
export const enum_contribution_entries_status = pgEnum("enum_contribution_entries_status", [
@ -1027,7 +1063,7 @@ export const enum_contribution_entries_status = pgEnum("enum_contribution_entrie
]);
export const enum_contribution_entries_source_collection = pgEnum(
"enum_contribution_entries_source_collection",
["wiki-pages", "mission-map-markers", "form-submissions", "manual"],
["wiki-pages", "mission-map-markers", "form-submissions", "journals", "manual"],
);
export const enum_evaluations_kind = pgEnum("enum_evaluations_kind", [
"leader-direct",
@ -1477,6 +1513,7 @@ export const enum_story_beat_states_reaction = pgEnum("enum_story_beat_states_re
"heart",
"salute",
]);
export const enum_journals_status = pgEnum("enum_journals_status", ["draft", "published"]);
export const enum_game_servers_status = pgEnum("enum_game_servers_status", ["online", "offline"]);
export const enum_arma_commands_status = pgEnum("enum_arma_commands_status", [
"queued",
@ -1534,6 +1571,7 @@ export const enum_minigames_status = pgEnum("enum_minigames_status", [
"active",
"upcoming",
"retired",
"phasingOut",
]);
export const enum_minigame_periods_status = pgEnum("enum_minigame_periods_status", [
"open",
@ -1589,6 +1627,14 @@ export const enum_shims_shims_paths_match_type = pgEnum("enum_shims_shims_paths_
"include",
"exclude",
]);
export const enum_discord_presence_activity_type = pgEnum("enum_discord_presence_activity_type", [
"playing",
"streaming",
"listening",
"watching",
"competing",
"custom",
]);
export const media = pgTable(
"media",
@ -2148,6 +2194,10 @@ export const game_vehicles = pgTable(
deployedAt: integer("deployed_at_id").references(() => game_structures.id, {
onDelete: "set null",
}),
garageGridX: numeric("garage_grid_x", { mode: "number" }),
garageGridY: numeric("garage_grid_y", { mode: "number" }),
garageRotated: boolean("garage_rotated").default(false),
bridgeUid: varchar("bridge_uid"),
faction: integer("faction_id").references(() => factions.id, {
onDelete: "set null",
}),
@ -2164,6 +2214,7 @@ export const game_vehicles = pgTable(
(columns) => [
index("game_vehicles_type_idx").on(columns.type),
index("game_vehicles_deployed_at_idx").on(columns.deployedAt),
uniqueIndex("game_vehicles_bridge_uid_idx").on(columns.bridgeUid),
index("game_vehicles_faction_idx").on(columns.faction),
index("game_vehicles_updated_at_idx").on(columns.updatedAt),
index("game_vehicles_created_at_idx").on(columns.createdAt),
@ -2329,6 +2380,38 @@ export const npc_dialogues = pgTable(
],
);
export const npc_dialogue_states = pgTable(
"npc_dialogue_states",
{
id: serial("id").primaryKey(),
user: integer("user_id")
.notNull()
.references(() => users.id, {
onDelete: "set null",
}),
dialogue: integer("dialogue_id")
.notNull()
.references(() => npc_dialogues.id, {
onDelete: "set null",
}),
nodeId: varchar("node_id").notNull(),
readAt: timestamp("read_at", { mode: "string", withTimezone: true, precision: 3 }),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("npc_dialogue_states_user_idx").on(columns.user),
index("npc_dialogue_states_dialogue_idx").on(columns.dialogue),
index("npc_dialogue_states_updated_at_idx").on(columns.updatedAt),
index("npc_dialogue_states_created_at_idx").on(columns.createdAt),
uniqueIndex("user_dialogue_nodeId_idx").on(columns.user, columns.dialogue, columns.nodeId),
],
);
export const player_flags = pgTable(
"player_flags",
{
@ -2468,6 +2551,13 @@ export const game_event_logs = pgTable(
targetCollection: enum_game_event_logs_target_collection("target_collection"),
targetId: numeric("target_id", { mode: "number" }),
data: jsonb("data"),
discordRequested: boolean("discord_requested").default(false),
discordAnnouncedAt: timestamp("discord_announced_at", {
mode: "string",
withTimezone: true,
precision: 3,
}),
discordMessageId: varchar("discord_message_id"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
@ -2480,6 +2570,7 @@ export const game_event_logs = pgTable(
index("game_event_logs_type_idx").on(columns.type),
index("game_event_logs_actor_idx").on(columns.actor),
index("game_event_logs_structure_idx").on(columns.structure),
index("game_event_logs_discord_requested_idx").on(columns.discordRequested),
index("game_event_logs_updated_at_idx").on(columns.updatedAt),
index("game_event_logs_created_at_idx").on(columns.createdAt),
],
@ -2591,6 +2682,7 @@ export const users = pgTable(
preferences_display_showBackgroundTexture: boolean(
"preferences_display_show_background_texture",
).default(true),
preferences_display_sidebarOrder: jsonb("preferences_display_sidebar_order"),
preferences_discord_enabled: boolean("preferences_discord_enabled").default(false),
preferences_dashboard_layout: jsonb("preferences_dashboard_layout"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
@ -3264,6 +3356,36 @@ export const awards_rels = pgTable(
],
);
export const award_rules = pgTable(
"award_rules",
{
id: serial("id").primaryKey(),
label: varchar("label").notNull(),
award: integer("award_id")
.notNull()
.references(() => awards.id, {
onDelete: "set null",
}),
metric: enum_award_rules_metric("metric").notNull(),
operator: enum_award_rules_operator("operator").notNull().default("gte"),
value: numeric("value", { mode: "number" }).notNull(),
autoRetireLowerTiers: boolean("auto_retire_lower_tiers").default(false),
oncePerSeries: boolean("once_per_series").default(false),
active: boolean("active").default(true),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("award_rules_award_idx").on(columns.award),
index("award_rules_updated_at_idx").on(columns.updatedAt),
index("award_rules_created_at_idx").on(columns.createdAt),
],
);
export const qualifications = pgTable(
"qualifications",
{
@ -4861,6 +4983,8 @@ export const vehicles = pgTable(
transportMode: enum_vehicles_transport_mode("transport_mode").notNull().default("ground"),
width: numeric("width", { mode: "number" }),
height: numeric("height", { mode: "number" }),
garageWidth: numeric("garage_width", { mode: "number" }),
garageHeight: numeric("garage_height", { mode: "number" }),
maxMass: numeric("max_mass", { mode: "number" }),
aceCargoSlots: numeric("ace_cargo_slots", { mode: "number" }),
maxHealth: numeric("max_health", { mode: "number" }),
@ -5291,6 +5415,8 @@ export const structures = pgTable(
restrictToAllowed: boolean("restrict_to_allowed").default(false),
xSize: numeric("x_size", { mode: "number" }),
ySize: numeric("y_size", { mode: "number" }),
vehicleBay_xSize: numeric("vehicle_bay_x_size", { mode: "number" }),
vehicleBay_ySize: numeric("vehicle_bay_y_size", { mode: "number" }),
maxHealth: numeric("max_health", { mode: "number" }).notNull(),
repairSpeed: numeric("repair_speed", { mode: "number" }),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
@ -6666,6 +6792,38 @@ export const story_voiceovers = pgTable(
],
);
export const journals = pgTable(
"journals",
{
id: serial("id").primaryKey(),
title: varchar("title").notNull(),
author: integer("author_id")
.notNull()
.references(() => users.id, {
onDelete: "set null",
}),
status: enum_journals_status("status").notNull().default("draft"),
occurredAt: timestamp("occurred_at", { mode: "string", withTimezone: true, precision: 3 }),
mission: integer("mission_id").references(() => missions.id, {
onDelete: "set null",
}),
body: jsonb("body").notNull(),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("journals_author_idx").on(columns.author),
index("journals_status_idx").on(columns.status),
index("journals_mission_idx").on(columns.mission),
index("journals_updated_at_idx").on(columns.updatedAt),
index("journals_created_at_idx").on(columns.createdAt),
],
);
export const mission_files = pgTable(
"mission_files",
{
@ -7333,6 +7491,11 @@ export const minigames = pgTable(
withTimezone: true,
precision: 3,
}),
estimatedRemovalDate: timestamp("estimated_removal_date", {
mode: "string",
withTimezone: true,
precision: 3,
}),
order: numeric("order", { mode: "number" }).notNull().default(0),
countsForPeriods: boolean("counts_for_periods").default(false),
scoreLabel: varchar("score_label").default("Score"),
@ -8025,6 +8188,10 @@ export const payload_mcp_api_keys = pgTable(
npcDialogues_create: boolean("npc_dialogues_create").default(false),
npcDialogues_update: boolean("npc_dialogues_update").default(false),
npcDialogues_delete: boolean("npc_dialogues_delete").default(false),
npcDialogueStates_find: boolean("npc_dialogue_states_find").default(false),
npcDialogueStates_create: boolean("npc_dialogue_states_create").default(false),
npcDialogueStates_update: boolean("npc_dialogue_states_update").default(false),
npcDialogueStates_delete: boolean("npc_dialogue_states_delete").default(false),
playerFlags_find: boolean("player_flags_find").default(false),
playerFlags_create: boolean("player_flags_create").default(false),
playerFlags_update: boolean("player_flags_update").default(false),
@ -8061,6 +8228,10 @@ export const payload_mcp_api_keys = pgTable(
awards_create: boolean("awards_create").default(false),
awards_update: boolean("awards_update").default(false),
awards_delete: boolean("awards_delete").default(false),
awardRules_find: boolean("award_rules_find").default(false),
awardRules_create: boolean("award_rules_create").default(false),
awardRules_update: boolean("award_rules_update").default(false),
awardRules_delete: boolean("award_rules_delete").default(false),
qualifications_find: boolean("qualifications_find").default(false),
qualifications_create: boolean("qualifications_create").default(false),
qualifications_update: boolean("qualifications_update").default(false),
@ -8261,6 +8432,10 @@ export const payload_mcp_api_keys = pgTable(
storyVoiceovers_create: boolean("story_voiceovers_create").default(false),
storyVoiceovers_update: boolean("story_voiceovers_update").default(false),
storyVoiceovers_delete: boolean("story_voiceovers_delete").default(false),
journals_find: boolean("journals_find").default(false),
journals_create: boolean("journals_create").default(false),
journals_update: boolean("journals_update").default(false),
journals_delete: boolean("journals_delete").default(false),
missionFiles_find: boolean("mission_files_find").default(false),
missionFiles_create: boolean("mission_files_create").default(false),
missionFiles_update: boolean("mission_files_update").default(false),
@ -8402,6 +8577,7 @@ export const payload_locked_documents_rels = pgTable(
"game-npcsID": integer("game_npcs_id"),
"npc-staffingID": integer("npc_staffing_id"),
"npc-dialoguesID": integer("npc_dialogues_id"),
"npc-dialogue-statesID": integer("npc_dialogue_states_id"),
"player-flagsID": integer("player_flags_id"),
"reinforcement-poolsID": integer("reinforcement_pools_id"),
"labor-classificationsID": integer("labor_classifications_id"),
@ -8411,6 +8587,7 @@ export const payload_locked_documents_rels = pgTable(
ranksID: integer("ranks_id"),
profilesID: integer("profiles_id"),
awardsID: integer("awards_id"),
"award-rulesID": integer("award_rules_id"),
qualificationsID: integer("qualifications_id"),
assignmentsID: integer("assignments_id"),
"assignment-transfersID": integer("assignment_transfers_id"),
@ -8461,6 +8638,7 @@ export const payload_locked_documents_rels = pgTable(
"story-beatsID": integer("story_beats_id"),
"story-beat-statesID": integer("story_beat_states_id"),
"story-voiceoversID": integer("story_voiceovers_id"),
journalsID: integer("journals_id"),
"mission-filesID": integer("mission_files_id"),
"mod-listsID": integer("mod_lists_id"),
"game-serversID": integer("game_servers_id"),
@ -8500,6 +8678,9 @@ export const payload_locked_documents_rels = pgTable(
index("payload_locked_documents_rels_game_npcs_id_idx").on(columns["game-npcsID"]),
index("payload_locked_documents_rels_npc_staffing_id_idx").on(columns["npc-staffingID"]),
index("payload_locked_documents_rels_npc_dialogues_id_idx").on(columns["npc-dialoguesID"]),
index("payload_locked_documents_rels_npc_dialogue_states_id_idx").on(
columns["npc-dialogue-statesID"],
),
index("payload_locked_documents_rels_player_flags_id_idx").on(columns["player-flagsID"]),
index("payload_locked_documents_rels_reinforcement_pools_id_idx").on(
columns["reinforcement-poolsID"],
@ -8513,6 +8694,7 @@ export const payload_locked_documents_rels = pgTable(
index("payload_locked_documents_rels_ranks_id_idx").on(columns.ranksID),
index("payload_locked_documents_rels_profiles_id_idx").on(columns.profilesID),
index("payload_locked_documents_rels_awards_id_idx").on(columns.awardsID),
index("payload_locked_documents_rels_award_rules_id_idx").on(columns["award-rulesID"]),
index("payload_locked_documents_rels_qualifications_id_idx").on(columns.qualificationsID),
index("payload_locked_documents_rels_assignments_id_idx").on(columns.assignmentsID),
index("payload_locked_documents_rels_assignment_transfers_id_idx").on(
@ -8593,6 +8775,7 @@ export const payload_locked_documents_rels = pgTable(
index("payload_locked_documents_rels_story_voiceovers_id_idx").on(
columns["story-voiceoversID"],
),
index("payload_locked_documents_rels_journals_id_idx").on(columns.journalsID),
index("payload_locked_documents_rels_mission_files_id_idx").on(columns["mission-filesID"]),
index("payload_locked_documents_rels_mod_lists_id_idx").on(columns["mod-listsID"]),
index("payload_locked_documents_rels_game_servers_id_idx").on(columns["game-serversID"]),
@ -8690,6 +8873,11 @@ export const payload_locked_documents_rels = pgTable(
foreignColumns: [npc_dialogues.id],
name: "payload_locked_documents_rels_npc_dialogues_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["npc-dialogue-statesID"]],
foreignColumns: [npc_dialogue_states.id],
name: "payload_locked_documents_rels_npc_dialogue_states_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["player-flagsID"]],
foreignColumns: [player_flags.id],
@ -8735,6 +8923,11 @@ export const payload_locked_documents_rels = pgTable(
foreignColumns: [awards.id],
name: "payload_locked_documents_rels_awards_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["award-rulesID"]],
foreignColumns: [award_rules.id],
name: "payload_locked_documents_rels_award_rules_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["qualificationsID"]],
foreignColumns: [qualifications.id],
@ -8985,6 +9178,11 @@ export const payload_locked_documents_rels = pgTable(
foreignColumns: [story_voiceovers.id],
name: "payload_locked_documents_rels_story_voiceovers_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["journalsID"]],
foreignColumns: [journals.id],
name: "payload_locked_documents_rels_journals_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["mission-filesID"]],
foreignColumns: [mission_files.id],
@ -9378,6 +9576,26 @@ export const minigame_rules = pgTable("minigame_rules", {
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 }),
});
export const discord_presence = pgTable("discord_presence", {
id: serial("id").primaryKey(),
enabled: boolean("enabled").default(false),
activityType: enum_discord_presence_activity_type("activity_type").notNull().default("playing"),
state: varchar("state"),
details: varchar("details"),
startTimestamp: numeric("start_timestamp", { mode: "number" }),
endTimestamp: numeric("end_timestamp", { mode: "number" }),
largeImageKey: varchar("large_image_key"),
largeImageText: varchar("large_image_text"),
smallImageKey: varchar("small_image_key"),
smallImageText: varchar("small_image_text"),
partyId: varchar("party_id"),
partySize: numeric("party_size", { mode: "number" }),
partyMax: numeric("party_max", { mode: "number" }),
joinSecret: varchar("join_secret"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 }),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 }),
});
export const relations_media = relations(media, () => ({}));
export const relations_announcements_buttons = relations(announcements_buttons, ({ one }) => ({
_parentID: one(announcements, {
@ -9743,6 +9961,18 @@ export const relations_npc_dialogues = relations(npc_dialogues, ({ one }) => ({
relationName: "npc",
}),
}));
export const relations_npc_dialogue_states = relations(npc_dialogue_states, ({ one }) => ({
user: one(users, {
fields: [npc_dialogue_states.user],
references: [users.id],
relationName: "user",
}),
dialogue: one(npc_dialogues, {
fields: [npc_dialogue_states.dialogue],
references: [npc_dialogues.id],
relationName: "dialogue",
}),
}));
export const relations_player_flags = relations(player_flags, ({ one }) => ({
user: one(users, {
fields: [player_flags.user],
@ -9996,6 +10226,13 @@ export const relations_awards = relations(awards, ({ one, many }) => ({
relationName: "_rels",
}),
}));
export const relations_award_rules = relations(award_rules, ({ one }) => ({
award: one(awards, {
fields: [award_rules.award],
references: [awards.id],
relationName: "award",
}),
}));
export const relations_qualifications = relations(qualifications, () => ({}));
export const relations_assignments_rels = relations(assignments_rels, ({ one }) => ({
parent: one(assignments, {
@ -11538,6 +11775,18 @@ export const relations_story_beat_states = relations(story_beat_states, ({ one }
}),
}));
export const relations_story_voiceovers = relations(story_voiceovers, () => ({}));
export const relations_journals = relations(journals, ({ one }) => ({
author: one(users, {
fields: [journals.author],
references: [users.id],
relationName: "author",
}),
mission: one(missions, {
fields: [journals.mission],
references: [missions.id],
relationName: "mission",
}),
}));
export const relations_mission_files = relations(mission_files, ({ one }) => ({
author: one(users, {
fields: [mission_files.author],
@ -12084,6 +12333,11 @@ export const relations_payload_locked_documents_rels = relations(
references: [npc_dialogues.id],
relationName: "npc-dialogues",
}),
"npc-dialogue-statesID": one(npc_dialogue_states, {
fields: [payload_locked_documents_rels["npc-dialogue-statesID"]],
references: [npc_dialogue_states.id],
relationName: "npc-dialogue-states",
}),
"player-flagsID": one(player_flags, {
fields: [payload_locked_documents_rels["player-flagsID"]],
references: [player_flags.id],
@ -12129,6 +12383,11 @@ export const relations_payload_locked_documents_rels = relations(
references: [awards.id],
relationName: "awards",
}),
"award-rulesID": one(award_rules, {
fields: [payload_locked_documents_rels["award-rulesID"]],
references: [award_rules.id],
relationName: "award-rules",
}),
qualificationsID: one(qualifications, {
fields: [payload_locked_documents_rels.qualificationsID],
references: [qualifications.id],
@ -12379,6 +12638,11 @@ export const relations_payload_locked_documents_rels = relations(
references: [story_voiceovers.id],
relationName: "story-voiceovers",
}),
journalsID: one(journals, {
fields: [payload_locked_documents_rels.journalsID],
references: [journals.id],
relationName: "journals",
}),
"mission-filesID": one(mission_files, {
fields: [payload_locked_documents_rels["mission-filesID"]],
references: [mission_files.id],
@ -12618,6 +12882,7 @@ export const relations_shims = relations(shims, ({ many }) => ({
}),
}));
export const relations_minigame_rules = relations(minigame_rules, () => ({}));
export const relations_discord_presence = relations(discord_presence, () => ({}));
type DatabaseSchema = {
enum_announcements_buttons_style: typeof enum_announcements_buttons_style;
@ -12644,6 +12909,8 @@ type DatabaseSchema = {
enum_awards_grant_config_allowed_grantor_assignment_types: typeof enum_awards_grant_config_allowed_grantor_assignment_types;
enum_awards_type: typeof enum_awards_type;
enum_awards_grant_config_recipient_scope: typeof enum_awards_grant_config_recipient_scope;
enum_award_rules_metric: typeof enum_award_rules_metric;
enum_award_rules_operator: typeof enum_award_rules_operator;
enum_assignments_type: typeof enum_assignments_type;
enum_assignment_transfers_status: typeof enum_assignment_transfers_status;
enum_assignment_transfers_escalation_reason: typeof enum_assignment_transfers_escalation_reason;
@ -12731,6 +12998,7 @@ type DatabaseSchema = {
enum_narrative_events_triggers_type: typeof enum_narrative_events_triggers_type;
enum_story_beats_status: typeof enum_story_beats_status;
enum_story_beat_states_reaction: typeof enum_story_beat_states_reaction;
enum_journals_status: typeof enum_journals_status;
enum_game_servers_status: typeof enum_game_servers_status;
enum_arma_commands_status: typeof enum_arma_commands_status;
enum_supply_boxes_status: typeof enum_supply_boxes_status;
@ -12755,6 +13023,7 @@ type DatabaseSchema = {
enum_shims_shims_type: typeof enum_shims_shims_type;
enum_shims_shims_targeting_audience: typeof enum_shims_shims_targeting_audience;
enum_shims_shims_paths_match_type: typeof enum_shims_shims_paths_match_type;
enum_discord_presence_activity_type: typeof enum_discord_presence_activity_type;
media: typeof media;
announcements_buttons: typeof announcements_buttons;
announcements: typeof announcements;
@ -12780,6 +13049,7 @@ type DatabaseSchema = {
game_npcs_rels: typeof game_npcs_rels;
npc_staffing: typeof npc_staffing;
npc_dialogues: typeof npc_dialogues;
npc_dialogue_states: typeof npc_dialogue_states;
player_flags: typeof player_flags;
reinforcement_pools: typeof reinforcement_pools;
reinforcement_pools_texts: typeof reinforcement_pools_texts;
@ -12802,6 +13072,7 @@ type DatabaseSchema = {
awards_grant_config_allowed_grantor_assignment_types: typeof awards_grant_config_allowed_grantor_assignment_types;
awards: typeof awards;
awards_rels: typeof awards_rels;
award_rules: typeof award_rules;
qualifications: typeof qualifications;
assignments: typeof assignments;
assignments_rels: typeof assignments_rels;
@ -12906,6 +13177,7 @@ type DatabaseSchema = {
story_beats: typeof story_beats;
story_beat_states: typeof story_beat_states;
story_voiceovers: typeof story_voiceovers;
journals: typeof journals;
mission_files: typeof mission_files;
mod_lists: typeof mod_lists;
game_servers: typeof game_servers;
@ -12964,6 +13236,7 @@ type DatabaseSchema = {
shims_texts: typeof shims_texts;
shims_rels: typeof shims_rels;
minigame_rules: typeof minigame_rules;
discord_presence: typeof discord_presence;
relations_media: typeof relations_media;
relations_announcements_buttons: typeof relations_announcements_buttons;
relations_announcements_texts: typeof relations_announcements_texts;
@ -12989,6 +13262,7 @@ type DatabaseSchema = {
relations_game_npcs: typeof relations_game_npcs;
relations_npc_staffing: typeof relations_npc_staffing;
relations_npc_dialogues: typeof relations_npc_dialogues;
relations_npc_dialogue_states: typeof relations_npc_dialogue_states;
relations_player_flags: typeof relations_player_flags;
relations_reinforcement_pools_texts: typeof relations_reinforcement_pools_texts;
relations_reinforcement_pools: typeof relations_reinforcement_pools;
@ -13011,6 +13285,7 @@ type DatabaseSchema = {
relations_awards_grant_config_allowed_grantor_assignment_types: typeof relations_awards_grant_config_allowed_grantor_assignment_types;
relations_awards_rels: typeof relations_awards_rels;
relations_awards: typeof relations_awards;
relations_award_rules: typeof relations_award_rules;
relations_qualifications: typeof relations_qualifications;
relations_assignments_rels: typeof relations_assignments_rels;
relations_assignments: typeof relations_assignments;
@ -13115,6 +13390,7 @@ type DatabaseSchema = {
relations_story_beats: typeof relations_story_beats;
relations_story_beat_states: typeof relations_story_beat_states;
relations_story_voiceovers: typeof relations_story_voiceovers;
relations_journals: typeof relations_journals;
relations_mission_files: typeof relations_mission_files;
relations_mod_lists: typeof relations_mod_lists;
relations_game_servers: typeof relations_game_servers;
@ -13173,6 +13449,7 @@ type DatabaseSchema = {
relations_shims_rels: typeof relations_shims_rels;
relations_shims: typeof relations_shims;
relations_minigame_rules: typeof relations_minigame_rules;
relations_discord_presence: typeof relations_discord_presence;
};
declare module "@payloadcms/db-postgres" {

View file

@ -999,6 +999,7 @@ export interface Role {
| 'achievements:update'
| 'achievements:delete'
| 'admin:achievements:manage'
| 'admin:analytics:manage'
)[]
| null;
/**
@ -3169,6 +3170,7 @@ export interface GameEventLog {
| 'achievements:update'
| 'achievements:delete'
| 'admin:achievements:manage'
| 'admin:analytics:manage'
)[]
| null;
timestamp: string;
@ -6207,11 +6209,15 @@ export interface Minigame {
*/
icon?: string | null;
category: 'core' | 'cardtable' | 'multiplayer';
status: 'active' | 'upcoming' | 'retired';
status: 'active' | 'upcoming' | 'retired' | 'phasingOut';
/**
* Optional target for an upcoming game. Shown as a countdown in the sidebar and on the game page. Display only: the game goes live when status changes to Active.
*/
estimatedReleaseDate?: string | null;
/**
* Optional target for a phasing-out game. Shown as a countdown in the sidebar and on the game page so operators know when it leaves. Display only: the game stays playable until status changes to Retired.
*/
estimatedRemovalDate?: string | null;
order: number;
/**
* When on, ledger entries for this game feed anchored period boards.
@ -11088,6 +11094,7 @@ export interface MinigamesSelect<T extends boolean = true> {
category?: T;
status?: T;
estimatedReleaseDate?: T;
estimatedRemovalDate?: T;
order?: T;
countsForPeriods?: T;
scoreLabel?: T;

View file

@ -477,6 +477,10 @@ export default buildConfig({
path: "/tech-tree",
Component: "@/components/admin/tech-tree/TechTreeView",
},
analytics: {
path: "/analytics",
Component: "@/components/admin/analytics/AnalyticsView",
},
},
},
},
@ -539,6 +543,14 @@ export default buildConfig({
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
key: "generate-mission",
},
{
scriptPath: path.resolve(dirname, "scripts/analyticsRollup.ts"),
key: "analytics-rollup",
},
{
scriptPath: path.resolve(dirname, "scripts/analyticsPurge.ts"),
key: "analytics-purge",
},
],
plugins: [
formBuilderPlugin(surveyFormBuilderConfig()),

View file

@ -823,6 +823,17 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:achievements:manage", label: ["Achievements", "Manage Admin Page"] },
],
},
// ---- Analytics -----------------------------------------------------------
{
group: "Analytics",
permissions: [
{
value: "admin:analytics:manage",
label: "Manage Usage Analytics (first-party dashboard at /admin/analytics)",
},
],
},
];
// ---------------------------------------------------------------------------
@ -1219,6 +1230,7 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"achievements:update",
"achievements:delete",
"admin:achievements:manage",
"admin:analytics:manage",
];
/**

View file

@ -0,0 +1,30 @@
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { purgeOldEvents, purgeOldSessions, RETENTION_DAYS } from "@/lib/analytics/rollup";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
/**
* `bun run payload analytics-purge` - daily raw-event retention sweep
* (external cron). Deletes raw analytics events older than 90 days; the
* permanent daily aggregate tables are never touched. Sessions whose last
* activity predates the window go too (their events are gone and every
* aggregate is already permanent).
*/
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("analytics-purge", payload.logger);
try {
log.info(`[Analytics Purge] Deleting raw events older than ${RETENTION_DAYS} days...`);
const deleted = await purgeOldEvents(payload);
const sessions = await purgeOldSessions(payload);
log.info(
`[Analytics Purge] Complete. Deleted ${deleted} event(s), ${sessions} session(s).`,
);
process.exit(0);
} catch (error) {
log.error(`[Analytics Purge] Fatal: ${errorMessage(error)}`);
process.exit(1);
}
};

View file

@ -0,0 +1,45 @@
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { buildGameKeyMap } from "@/lib/analytics/games";
import { recentDays, rollupDay, type AnalyticsDay } from "@/lib/analytics/rollup";
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
/**
* `bun run payload analytics-rollup` - hourly aggregate rollup (external
* cron). Recomputes the permanent daily aggregate tables from raw analytics
* events for today and yesterday UTC (yesterday rides along so late beacons
* still land in a complete row; every day is recomputed delete-then-insert,
* so re-runs are idempotent).
*
* Backfill override: `ANALYTICS_ROLLUP_DAY=YYYY-MM-DD` rolls up exactly that
* one day.
*/
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("analytics-rollup", payload.logger);
try {
log.info("[Analytics Rollup] Starting daily aggregate rollup...");
const override = process.env.ANALYTICS_ROLLUP_DAY as AnalyticsDay | undefined;
const days = override ? [override] : recentDays(2);
const registry = await loadMinigameRegistry(payload);
const slugToKey = Object.fromEntries(buildGameKeyMap(registry).entries());
for (const day of days) {
const result = await rollupDay(payload, day, slugToKey);
log.info(
`[Analytics Rollup] ${day}: pages=${result.pages} users=${result.users} games=${result.games} chronicle=${result.chronicle}`,
);
}
log.info(`[Analytics Rollup] Complete (${days.join(", ")}).`);
process.exit(0);
} catch (error) {
log.error(`[Analytics Rollup] Fatal: ${errorMessage(error)}`);
process.exit(1);
}
};

View file

@ -0,0 +1,73 @@
import { expect, test } from "@playwright/test";
import { Client } from "pg";
/**
* First-party analytics e2e smoke (Phase 1).
*
* Runs with NEXT_PUBLIC_ANALYTICS_DEV=1 (set in playwright.config.ts), which
* enables the tracker in the dev server. Verifies the three surfaces end to
* end: the client SDK lands a guest pageview row, the collector endpoint
* accepts beacon batches (and rejects garbage), and the admin dashboard
* renders for a superuser.
*/
async function countDevPageviews(path: string): Promise<number> {
// global-setup points DATABASE_URI at the test database before workers run,
// so read it directly (calling resolveTestDatabaseUri() again would append
// a second _test suffix).
const client = new Client({ connectionString: process.env.DATABASE_URI });
await client.connect();
try {
const result = await client.query(
"SELECT COUNT(*)::int AS c FROM analytics_events WHERE type = 'pageview' AND path = $1 AND env = 'dev'",
[path],
);
return result.rows[0].c as number;
} finally {
await client.end();
}
}
test.describe("First-party analytics", () => {
test("the tracker records a guest pageview end to end", async ({ page }) => {
await page.goto("/");
await expect(page.getByRole("heading", { level: 1 })).toContainText("Polaris Task Force");
// The SDK flushes on the first route change, so the row should land fast.
await expect
.poll(() => countDevPageviews("/"), { timeout: 20_000, intervals: [500] })
.toBeGreaterThan(0);
});
test("the collector accepts beacon batches and rejects malformed ones", async ({ request }) => {
const accepted = await request.post("/api/collect", {
data: {
sid: null,
aid: "e2e-smoke",
events: [{ type: "pageview", path: "/e2e-collector-smoke" }],
},
});
expect(accepted.status()).toBe(204);
const rejected = await request.post("/api/collect", { data: { events: [] } });
expect(rejected.status()).toBe(400);
});
test("the admin analytics dashboard renders for a superuser", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
await page.goto("/admin/analytics");
await expect(page.getByRole("heading", { name: "Usage Analytics" })).toBeVisible({
timeout: 60_000,
});
// The six report tabs render; hop to one to prove tab navigation works.
await expect(page.getByRole("link", { name: "Minigames" })).toBeVisible();
await page.getByRole("link", { name: "Sessions" }).click();
await expect(page.getByText(/^Sessions \(/)).toBeVisible();
});
});

View file

@ -0,0 +1,357 @@
import { sql } from "@payloadcms/db-postgres";
import { getPayload, type Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
checkCollectRateLimit,
ingestBatch,
isBotUserAgent,
resetCollectRateLimit,
SESSION_IDLE_MS,
type IngestContext,
} from "@/lib/analytics/ingest";
import { parseCollectEnvelope, MAX_EVENTS_PER_BATCH } from "@/lib/analytics/events";
import {
isoDay,
purgeOldEvents,
purgeOldSessions,
rollupDay,
} from "@/lib/analytics/rollup";
/**
* Collector + rollup + retention integration tests against the real test
* database (the analytics tables are created by the shared DDL module during
* the test bootstrap). Raw SQL helpers go through payload.db.drizzle because
* these are plain tables, not Payload collections.
*/
let payload: Payload;
async function execute(fragment: ReturnType<typeof sql>): Promise<void> {
await payload.db.drizzle.execute(fragment);
}
async function rows<T>(fragment: ReturnType<typeof sql>): Promise<T[]> {
const result = (await payload.db.drizzle.execute(fragment)) as unknown as { rows: T[] };
return result.rows ?? [];
}
function ctx(overrides: Partial<IngestContext> = {}): IngestContext {
return {
ip: "203.0.113.10",
ua: "Mozilla/5.0 (Test Browser)",
referrer: null,
userId: null,
env: "production",
...overrides,
};
}
function envelope(body: Record<string, unknown>) {
const parsed = parseCollectEnvelope(body);
if (!parsed.ok) throw new Error(`envelope rejected in test: ${parsed.error}`);
return parsed.envelope;
}
const createdSessionIds: string[] = [];
beforeAll(async () => {
payload = await getPayload({ config: await config });
});
afterAll(async () => {
// Leave the shared database tidy for other spec files.
if (createdSessionIds.length > 0) {
await execute(sql`DELETE FROM analytics_events WHERE session_id IN (${sql.join(
createdSessionIds.map((id) => sql`${id}`),
sql`, `,
)})`);
await execute(sql`DELETE FROM analytics_sessions WHERE id IN (${sql.join(
createdSessionIds.map((id) => sql`${id}`),
sql`, `,
)})`);
}
});
describe("envelope validation", () => {
it("accepts a well-formed batch and clamps fields", () => {
const result = parseCollectEnvelope({
sid: "sid-123",
aid: "aid-456",
events: [
{ type: "pageview", path: "/dashboard", ts: Date.now() },
{ type: "click", path: "/dashboard", element: { selector: "button" }, data: { xPct: 10 } },
],
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.envelope.sid).toBe("sid-123");
expect(result.envelope.events).toHaveLength(2);
expect(result.envelope.dropped).toBe(0);
});
it("rejects empty or oversized batches", () => {
expect(parseCollectEnvelope({ events: [] }).ok).toBe(false);
const big = Array.from({ length: MAX_EVENTS_PER_BATCH + 1 }, () => ({ type: "pageview" }));
expect(parseCollectEnvelope({ events: big }).ok).toBe(false);
expect(parseCollectEnvelope("nope").ok).toBe(false);
});
it("drops invalid events but keeps valid ones", () => {
const result = parseCollectEnvelope({
events: [
{ type: "pageview", path: "/ok" },
{ type: "not-a-real-type", path: "/bad" },
{ type: "click", path: "relative-not-absolute" },
{ type: "custom", data: { huge: "x".repeat(10_000) } },
{ type: "heartbeat", ts: Date.now() + 60 * 60 * 1000 },
],
});
expect(result.ok).toBe(true);
if (!result.ok) return;
// Bad type and future timestamp drop the event; the oversized payload is
// dropped but its event survives, and the relative path is nulled.
expect(result.envelope.events).toHaveLength(3);
expect(result.envelope.dropped).toBe(2);
const click = result.envelope.events.find((e) => e.type === "click");
expect(click?.path).toBeNull();
const custom = result.envelope.events.find((e) => e.type === "custom");
expect(custom?.data).toBeNull();
});
});
describe("bot filtering and rate limiting", () => {
it("flags known bots by UA", () => {
expect(isBotUserAgent("Mozilla/5.0 (compatible; AhrefsBot/7.0)")).toBe(true);
expect(isBotUserAgent("curl/8.5.0")).toBe(true);
expect(isBotUserAgent("HeadlessChrome/120")).toBe(true);
expect(isBotUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120")).toBe(false);
expect(isBotUserAgent(null)).toBe(false);
});
it("rate limits per IP within the window", () => {
resetCollectRateLimit();
const ip = "198.51.100.7";
for (let i = 0; i < 120; i += 1) {
expect(checkCollectRateLimit(ip, 1_000_000)).toBe(true);
}
expect(checkCollectRateLimit(ip, 1_000_001)).toBe(false);
// Next window resets the budget.
expect(checkCollectRateLimit(ip, 1_000_000 + 61_000)).toBe(true);
resetCollectRateLimit();
});
});
describe("ingestBatch sessionization", () => {
it("creates a session on first flush and reuses it while active", async () => {
const first = await ingestBatch(
payload,
envelope({
sid: null,
aid: "aid-new-session",
events: [
{ type: "pageview", path: "/dashboard", ts: Date.now() },
{ type: "heartbeat", path: "/dashboard", data: { ms: 15000 }, ts: Date.now() },
],
}),
ctx(),
);
expect(first.newSession).toBe(true);
expect(first.stored).toBe(2);
createdSessionIds.push(first.sessionId);
const second = await ingestBatch(
payload,
envelope({
sid: first.sessionId,
aid: "aid-new-session",
events: [{ type: "pageview", path: "/logistics", ts: Date.now() }],
}),
ctx(),
);
expect(second.newSession).toBe(false);
expect(second.sessionId).toBe(first.sessionId);
const sessions = await rows<{ pageview_count: number; active_ms: string; entry_path: string }>(
sql`SELECT pageview_count, active_ms, entry_path FROM analytics_sessions WHERE id = ${first.sessionId}`,
);
expect(sessions[0].pageview_count).toBe(2);
expect(Number(sessions[0].active_ms)).toBe(15000);
expect(sessions[0].entry_path).toBe("/dashboard");
});
it("closes an idle-expired session and starts a new one", async () => {
const fresh = await ingestBatch(
payload,
envelope({ sid: null, events: [{ type: "pageview", path: "/wiki" }] }),
ctx(),
);
createdSessionIds.push(fresh.sessionId);
// Age the session past the idle window.
await execute(sql`
UPDATE analytics_sessions
SET last_activity_at = now() - (${SESSION_IDLE_MS + 60_000}::double precision * interval '1 millisecond')
WHERE id = ${fresh.sessionId}
`);
const next = await ingestBatch(
payload,
envelope({ sid: fresh.sessionId, events: [{ type: "pageview", path: "/story" }] }),
ctx(),
);
expect(next.newSession).toBe(true);
expect(next.sessionId).not.toBe(fresh.sessionId);
createdSessionIds.push(next.sessionId);
const old = await rows<{ ended_at: string | null }>(
sql`SELECT ended_at FROM analytics_sessions WHERE id = ${fresh.sessionId}`,
);
expect(old[0]?.ended_at).not.toBeNull();
});
it("drops bot traffic without writing anything", async () => {
const result = await ingestBatch(
payload,
envelope({ sid: null, events: [{ type: "pageview", path: "/secret" }] }),
ctx({ ua: "Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)" }),
);
expect(result.isBot).toBe(true);
expect(result.stored).toBe(0);
});
it("links guest sessions to the user retroactively on login", async () => {
const guest = await ingestBatch(
payload,
envelope({ sid: null, aid: "aid-upgrade", events: [{ type: "pageview", path: "/login" }] }),
ctx(),
);
createdSessionIds.push(guest.sessionId);
const authed = await ingestBatch(
payload,
envelope({
sid: guest.sessionId,
aid: "aid-upgrade",
events: [{ type: "pageview", path: "/dashboard" }],
}),
ctx({ userId: 424242 }),
);
expect(authed.sessionId).toBe(guest.sessionId);
const session = await rows<{ user_id: number | null }>(
sql`SELECT user_id FROM analytics_sessions WHERE id = ${guest.sessionId}`,
);
expect(session[0]?.user_id).toBe(424242);
const events = await rows<{ path: string; user_id: number | null }>(
sql`SELECT path, user_id FROM analytics_events WHERE session_id = ${guest.sessionId} ORDER BY path`,
);
expect(events).toHaveLength(2);
expect(events.every((e) => e.user_id === 424242)).toBe(true);
});
});
describe("rollup and retention", () => {
const today = isoDay(new Date());
let rollupSessionId: string;
it("computes daily aggregates from raw events (idempotently)", async () => {
// Seed a dedicated session with a mix of event types for today.
const seeded = await ingestBatch(
payload,
envelope({
sid: null,
events: [
{ type: "pageview", path: "/minigames/flappy", ts: Date.now() },
{ type: "heartbeat", path: "/minigames/flappy", data: { ms: 15000 }, ts: Date.now() },
{ type: "scroll", path: "/minigames/flappy", data: { maxScrollPct: 100, dwellMs: 30000 }, ts: Date.now() },
{
type: "custom",
path: "/story",
data: { name: "chronicle.read_progress", kind: "beat", ref: "991", progressPct: 40 },
ts: Date.now(),
},
{
type: "custom",
path: "/story",
data: { name: "chronicle.read_completed", kind: "beat", ref: "991", timeMs: 61000 },
ts: Date.now(),
},
],
}),
ctx({ userId: 555001 }),
);
rollupSessionId = seeded.sessionId;
createdSessionIds.push(rollupSessionId);
const slugToKey = { flappy: "flappy" };
const first = await rollupDay(payload, today, slugToKey);
const second = await rollupDay(payload, today, slugToKey);
expect(first.pages).toBe(second.pages);
expect(first.users).toBe(second.users);
expect(first.games).toBe(second.games);
const pages = await rows<{ views: string }>(
sql`SELECT views FROM analytics_daily_pages WHERE day = ${today}::date AND path = '/minigames/flappy'`,
);
expect(Number(pages[0]?.views ?? 0)).toBeGreaterThanOrEqual(1);
const users = await rows<{ active_ms: string; sessions: string }>(
sql`SELECT active_ms, sessions FROM analytics_daily_users WHERE day = ${today}::date AND user_id = 555001`,
);
expect(Number(users[0]?.active_ms)).toBeGreaterThanOrEqual(15000);
expect(Number(users[0]?.sessions)).toBeGreaterThanOrEqual(1);
const games = await rows<{ sessions: string; avg_session_ms: string }>(
sql`SELECT sessions, avg_session_ms FROM analytics_daily_games WHERE day = ${today}::date AND game_key = 'flappy'`,
);
expect(Number(games[0]?.sessions)).toBeGreaterThanOrEqual(1);
expect(Number(games[0]?.avg_session_ms)).toBeGreaterThanOrEqual(15000);
const chronicle = await rows<{ opens: string; completions: string; median_time_ms: string }>(
sql`SELECT opens, completions, median_time_ms FROM analytics_daily_chronicle WHERE day = ${today}::date AND kind = 'beat' AND ref = '991'`,
);
expect(Number(chronicle[0]?.opens)).toBeGreaterThanOrEqual(1);
expect(Number(chronicle[0]?.completions)).toBeGreaterThanOrEqual(1);
expect(Number(chronicle[0]?.median_time_ms)).toBeGreaterThanOrEqual(61000);
});
it("purges raw events and sessions past the retention window only", async () => {
// Seed directly via SQL: the collector validation intentionally rejects
// stale client timestamps, so an old event can only arrive this way.
const oldSessionId = crypto.randomUUID();
createdSessionIds.push(oldSessionId);
await execute(sql`
INSERT INTO analytics_sessions (id, started_at, last_activity_at, env)
VALUES (${oldSessionId}, now() - interval '95 days', now() - interval '95 days', 'production')
`);
await execute(sql`
INSERT INTO analytics_events (session_id, ts, type, path, env)
VALUES
(${oldSessionId}, now() - interval '94 days', 'pageview', '/old', 'production'),
(${oldSessionId}, now() - interval '1 hour', 'pageview', '/recent', 'production')
`);
const deletedEvents = await purgeOldEvents(payload, 90);
expect(deletedEvents).toBeGreaterThanOrEqual(1);
const remaining = await rows<{ path: string }>(
sql`SELECT path FROM analytics_events WHERE session_id = ${oldSessionId}`,
);
expect(remaining.map((r) => r.path)).toEqual(["/recent"]);
const deletedSessions = await purgeOldSessions(payload, 90);
expect(deletedSessions).toBeGreaterThanOrEqual(1);
const gone = await rows<{ id: string }>(
sql`SELECT id FROM analytics_sessions WHERE id = ${oldSessionId}`,
);
expect(gone).toHaveLength(0);
// The explicit session cleanup removed the remaining event too.
const eventsGone = await rows<{ id: string }>(
sql`SELECT id FROM analytics_events WHERE session_id = ${oldSessionId}`,
);
expect(eventsGone).toHaveLength(0);
createdSessionIds.splice(createdSessionIds.indexOf(oldSessionId), 1);
});
});

View file

@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
formatCountdown,
formatReleaseInstant,
phasingOutTooltip,
upcomingTooltip,
} from "@/lib/minigames/countdown";
@ -37,4 +38,11 @@ describe("Minigame release countdown", () => {
);
expect(upcomingTooltip(null)).toBe("Upcoming");
});
it("builds the phasing-out tooltip line, with and without an estimate", () => {
expect(phasingOutTooltip(TARGET, new Date(targetMs - (12 * DAY + 3 * HOUR)))).toBe(
"Phasing out · leaves Dec 3, 2026 18:00 UTC (in 12d 3h)",
);
expect(phasingOutTooltip(null)).toBe("Phasing out");
});
});

View file

@ -122,13 +122,36 @@ describe("Minigame registry", () => {
expect(achievements.docs[0]?.value).toBe(10);
});
it("keeps a phasing-out game in the nav, scoring, and round-trips its removal date", async () => {
await clearMinigameData();
await createGame({
key: "leaving",
label: "Leaving Soon",
category: "core",
status: "phasingOut",
order: 1,
countsForPeriods: true,
estimatedRemovalDate: "2027-01-15T00:00:00.000Z",
});
const games = await loadMinigameRegistry(payload);
const leaving = games.find((game) => game.key === "leaving");
// Still visible in the nav (unlike retired) with its removal date attached.
expect(leaving?.status).toBe("phasingOut");
expect(leaving?.estimatedRemovalDate).toBe("2027-01-15T00:00:00.000Z");
expect(visibleRegistryGames(games).map((game) => game.key)).toContain("leaving");
// Still scores periods while it is playable.
expect(periodScoringGameKeys(games)).toContain("leaving");
});
async function createGame(data: {
key: string;
label: string;
category: "core" | "cardtable";
status: "active" | "retired" | "upcoming";
status: "active" | "retired" | "upcoming" | "phasingOut";
order: number;
countsForPeriods?: boolean;
estimatedRemovalDate?: string;
}) {
await payload.create({
collection: "minigames",

View file

@ -69,12 +69,36 @@ describe("Upcoming minigames", () => {
expect(keys).not.toContain("signals");
});
it("keeps a phasing-out game playable: round-trips the removal date and leaderboard row", async () => {
await clearMinigameData();
await createGame({
key: "retire-me",
label: "Retire Me",
status: "phasingOut",
order: 1,
estimatedRemovalDate: RELEASE,
});
const games = await loadMinigameRegistry(payload);
const leaving = games.find((game) => game.key === "retire-me");
expect(leaving?.estimatedRemovalDate).toBe(RELEASE);
// Not a coming-soon gate: it renders the arena rather than the coming-soon screen.
const gate = await getMinigameReleaseState(payload, "retire-me");
expect(gate.upcoming).toBe(false);
// Still scores periods while it is playable.
const data = await buildLeaderboardPayload(payload, { scope: "period" });
expect(data.boards.map((board) => board.key)).toContain("retire-me");
});
async function createGame(data: {
key: string;
label: string;
status: "active" | "upcoming" | "retired";
status: "active" | "upcoming" | "retired" | "phasingOut";
order: number;
estimatedReleaseDate?: string;
estimatedRemovalDate?: string;
}) {
await payload.create({
collection: "minigames",

View file

@ -1,5 +1,6 @@
import { execSync } from "node:child_process";
import { Client } from "pg";
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
// Global setup/teardown processes never load .env (only setupFiles do); load
// it here so every entry point sees the same variables. dotenv does not
@ -110,6 +111,42 @@ export function pushSchema(testUri: string): void {
});
}
/**
* Drop the plain-SQL analytics tables BEFORE drizzle push runs. Push treats
* tables outside the Payload schema as drift, and its introspector has a
* broken composite-primary-key query path (drizzle-kit 0.31.11), so it must
* never see these tables. They are recreated empty right after the push by
* `ensureAnalyticsTables`, so every run also starts from a clean slate here.
*/
export async function dropAnalyticsTables(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
for (const table of ANALYTICS_TABLE_NAMES) {
await client.query(`DROP TABLE IF EXISTS ${quotedIdentifier(table)} CASCADE`);
}
} finally {
await client.end();
}
}
/**
* Create the plain-SQL analytics tables. They live outside the Payload schema,
* so drizzle push never creates them; the shared DDL module (also executed by
* the add_analytics_tables migration) is applied here so tests exercise the
* same tables production has. Runs AFTER pushSchema because push drops tables
* it does not know about. Idempotent.
*/
export async function ensureAnalyticsTables(testUri: string): Promise<void> {
const client = new Client({ connectionString: testUri });
await client.connect();
try {
await applyAnalyticsDdl(client);
} finally {
await client.end();
}
}
/**
* Truncate every table in the public schema except migration journals and
* PostGIS internals. Idempotent by construction: the result is the same empty
@ -186,7 +223,9 @@ export async function bootstrapTestDatabase(): Promise<string> {
const hardReset = hardResetRequested();
await ensureTestDatabase(testUri, hardReset);
await dropAnalyticsTables(testUri);
pushSchema(testUri);
await ensureAnalyticsTables(testUri);
await truncateAllData(testUri);
runSeedScripts(testUri);
await repairSequences(testUri);