feat(analytics): add first-party analytics collector, SDK, rollups, and admin dashboard
Phase 1 of replacing Microsoft Clarity with first-party usage analytics: - Plain Postgres tables via shared DDL module (src/lib/analytics/schema.ts) executed by both the add_analytics_tables migration and the test bootstrap; test-db.ts drops them around drizzle push (composite-PK introspector bug) - /api/collect beacon collector with IP/UA enrichment, retroactive login attribution, bot blocklist, per-IP rate limiting, strict validation - Client SDK (src/lib/client-analytics): SPA pageviews, clicks, scroll depth, focus, data-track visibility, heartbeats; NEXT_PUBLIC_ANALYTICS_DEV=1 dev gate with console mirror; mounted beside Clarity in the two frontend layouts - Hourly rollup + daily retention bins (payload analytics-rollup/-purge) - Chronicle read progress/completion, wiki new-clicked/created, minigame route mapping custom events - admin:analytics:manage permission (+ roles enum migration) and the /admin/analytics Payload view with six recharts-backed report panels
This commit is contained in:
parent
35a88ccd8f
commit
268d4bb117
40 changed files with 85357 additions and 16 deletions
61
bun.lock
61
bun.lock
|
|
@ -66,6 +66,7 @@
|
||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
"react-leaflet": "^5.0.0",
|
"react-leaflet": "^5.0.0",
|
||||||
"react-markdown": "10.1.0",
|
"react-markdown": "10.1.0",
|
||||||
|
"recharts": "3.8.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
"rehype-highlight": "^7.0.2",
|
||||||
"remark-directive": "4.0.0",
|
"remark-directive": "4.0.0",
|
||||||
"remark-gfm": "4.0.1",
|
"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=="],
|
"@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=="],
|
"@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=="],
|
"@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/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=="],
|
"@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=="],
|
"@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/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-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-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-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-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-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=="],
|
"@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/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/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=="],
|
"@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=="],
|
"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-color": ["d3-color@3.1.0", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
|
||||||
|
|
||||||
"d3-dispatch": ["d3-dispatch@3.0.1", "", {}, "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg=="],
|
"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-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-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-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-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=="],
|
"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": ["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=="],
|
"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=="],
|
"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-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": ["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=="],
|
"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=="],
|
"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=="],
|
"events": ["events@3.3.0", "", {}, "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="],
|
||||||
|
|
||||||
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="],
|
||||||
|
|
||||||
"ip-address": ["ip-address@10.5.0", "", {}, "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g=="],
|
"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-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-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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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": ["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=="],
|
"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=="],
|
"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=="],
|
"tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
|
||||||
|
|
||||||
"tinyexec": ["tinyexec@1.0.2", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],
|
"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=="],
|
"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": ["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=="],
|
"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=="],
|
"@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/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=="],
|
"@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=="],
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,7 @@
|
||||||
"react-dom": "19.2.3",
|
"react-dom": "19.2.3",
|
||||||
"react-leaflet": "^5.0.0",
|
"react-leaflet": "^5.0.0",
|
||||||
"react-markdown": "10.1.0",
|
"react-markdown": "10.1.0",
|
||||||
|
"recharts": "3.8.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
"rehype-highlight": "^7.0.2",
|
||||||
"remark-directive": "4.0.0",
|
"remark-directive": "4.0.0",
|
||||||
"remark-gfm": "4.0.1",
|
"remark-gfm": "4.0.1",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import type { Journal, Mission, User } from "@/payload-types";
|
||||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ChronicleArticle } from "@/lib/client-analytics/chronicle";
|
||||||
import { BEAT_BODY_CLASSES } from "@/lib/story/richtextClasses";
|
import { BEAT_BODY_CLASSES } from "@/lib/story/richtextClasses";
|
||||||
import { formatJournalDate } from "@/lib/journals/dates";
|
import { formatJournalDate } from "@/lib/journals/dates";
|
||||||
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||||
|
|
@ -135,9 +136,11 @@ export default async function JournalDetailPage({
|
||||||
/>
|
/>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
|
<ChronicleArticle kind="journal" articleId={String(journal.id)}>
|
||||||
<RichText data={journal.body} />
|
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
|
||||||
</article>
|
<RichText data={journal.body} />
|
||||||
|
</article>
|
||||||
|
</ChronicleArticle>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ import type { AnnouncementEntry } from "@/lib/announcements/evaluate";
|
||||||
import { TourHost } from "@/components/frontend/tours/TourHost";
|
import { TourHost } from "@/components/frontend/tours/TourHost";
|
||||||
import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
|
import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
|
||||||
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
|
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
|
||||||
|
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
|
||||||
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
|
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
|
||||||
import type { RegistryGame } from "@/lib/minigames/registry";
|
import type { RegistryGame } from "@/lib/minigames/registry";
|
||||||
|
|
||||||
|
|
@ -250,6 +251,7 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
|
||||||
<Toaster />
|
<Toaster />
|
||||||
<ShimLoader shims={shimEntries} userId={user?.id ?? null} userRoles={user?.roles ?? []} />
|
<ShimLoader shims={shimEntries} userId={user?.id ?? null} userRoles={user?.roles ?? []} />
|
||||||
<ClarityAnalytics />
|
<ClarityAnalytics />
|
||||||
|
<AnalyticsTracker />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { LockdownBanner } from "@/components/frontend/wiki/LockdownBanner";
|
import { LockdownBanner } from "@/components/frontend/wiki/LockdownBanner";
|
||||||
|
import { WikiPageViewMeta } from "@/components/frontend/wiki/WikiPageViewMeta";
|
||||||
import { WikiContent } from "@/components/frontend/wiki/WikiContent";
|
import { WikiContent } from "@/components/frontend/wiki/WikiContent";
|
||||||
import { WikiToolbar } from "@/components/frontend/wiki/WikiToolbar";
|
import { WikiToolbar } from "@/components/frontend/wiki/WikiToolbar";
|
||||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||||
|
|
@ -238,6 +239,8 @@ export default async function WikiDetailPage({
|
||||||
|
|
||||||
{lockdown && <LockdownBanner />}
|
{lockdown && <LockdownBanner />}
|
||||||
|
|
||||||
|
<WikiPageViewMeta slug={page.slug} />
|
||||||
|
|
||||||
<article>
|
<article>
|
||||||
<WikiContent
|
<WikiContent
|
||||||
prepared={prepared}
|
prepared={prepared}
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,7 @@ import { default as default_05548cb43495e62d80b80ec4d9f0f7e9 } from '@/component
|
||||||
import { default as default_459d6b6f5ead73c736013da63a5ace3f } from '@/components/static/GoToFrontendLink'
|
import { default as default_459d6b6f5ead73c736013da63a5ace3f } from '@/components/static/GoToFrontendLink'
|
||||||
import { InstructionsProvider as InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
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_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 { default as default_f3a799acf91e60a0d7a8ec121a8f5690 } from '@/components/admin/dashboard/CollectionCards'
|
||||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||||
|
|
||||||
|
|
@ -105,6 +106,7 @@ export const importMap = {
|
||||||
"@/components/static/GoToFrontendLink#default": default_459d6b6f5ead73c736013da63a5ace3f,
|
"@/components/static/GoToFrontendLink#default": default_459d6b6f5ead73c736013da63a5ace3f,
|
||||||
"@ai-stack/payloadcms/client#InstructionsProvider": InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73,
|
"@ai-stack/payloadcms/client#InstructionsProvider": InstructionsProvider_4490b89d4413c1ffaecdacfe72efaf73,
|
||||||
"@/components/admin/tech-tree/TechTreeView#default": default_2b34d0df0cf91f4442ca2cd62ae7cd94,
|
"@/components/admin/tech-tree/TechTreeView#default": default_2b34d0df0cf91f4442ca2cd62ae7cd94,
|
||||||
|
"@/components/admin/analytics/AnalyticsView#default": default_56514cbb96bba531e9cd351ac4f78023,
|
||||||
"@/components/admin/dashboard/CollectionCards#default": default_f3a799acf91e60a0d7a8ec121a8f5690,
|
"@/components/admin/dashboard/CollectionCards#default": default_f3a799acf91e60a0d7a8ec121a8f5690,
|
||||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||||
}
|
}
|
||||||
|
|
|
||||||
102
src/app/api/collect/route.ts
Normal file
102
src/app/api/collect/route.ts
Normal 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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import "@/app/(frontend)/styles.css";
|
import "@/app/(frontend)/styles.css";
|
||||||
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
|
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
|
||||||
|
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
|
||||||
|
|
||||||
export default function LoginLayout(props: { children: React.ReactNode }) {
|
export default function LoginLayout(props: { children: React.ReactNode }) {
|
||||||
return (
|
return (
|
||||||
|
|
@ -7,6 +8,7 @@ export default function LoginLayout(props: { children: React.ReactNode }) {
|
||||||
<body className="h-full font-sans m-0 text-white">
|
<body className="h-full font-sans m-0 text-white">
|
||||||
{props.children}
|
{props.children}
|
||||||
<ClarityAnalytics />
|
<ClarityAnalytics />
|
||||||
|
<AnalyticsTracker />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
138
src/components/admin/analytics/AnalyticsCharts.tsx
Normal file
138
src/components/admin/analytics/AnalyticsCharts.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
531
src/components/admin/analytics/AnalyticsView.tsx
Normal file
531
src/components/admin/analytics/AnalyticsView.tsx
Normal 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
|
||||||
|
"Manage Usage Analytics" 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;
|
||||||
39
src/components/admin/analytics/format.ts
Normal file
39
src/components/admin/analytics/format.ts
Normal 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)}%`;
|
||||||
|
}
|
||||||
|
|
@ -7,6 +7,7 @@ import type { PayloadRequest, SanitizedPermissions, ServerProps } from "payload"
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
import { TechTreeNavClient, type TechTreeNavGroup, type TechTreeNavEntity } from "./TechTreeNavClient";
|
import { TechTreeNavClient, type TechTreeNavGroup, type TechTreeNavEntity } from "./TechTreeNavClient";
|
||||||
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||||
|
|
||||||
const baseClass = "nav";
|
const baseClass = "nav";
|
||||||
|
|
||||||
|
|
@ -74,6 +75,35 @@ export const TechTreeNav = async ({
|
||||||
return { ...group, entities };
|
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;
|
let navPreferences: { groups?: { [key: string]: { open: boolean } } } | null = null;
|
||||||
if (req?.user?.collection) {
|
if (req?.user?.collection) {
|
||||||
const prefs = await req.payload.find({
|
const prefs = await req.payload.find({
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
|
||||||
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
|
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
|
||||||
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||||
import type { StoryViewerBeat } from "@/components/frontend/story/StoryViewer";
|
import type { StoryViewerBeat } from "@/components/frontend/story/StoryViewer";
|
||||||
|
import { ChronicleTrackedRegion } from "@/lib/client-analytics/chronicle";
|
||||||
import {
|
import {
|
||||||
BOOK_COLUMN_GAP,
|
BOOK_COLUMN_GAP,
|
||||||
BOOK_MAX_WIDTH,
|
BOOK_MAX_WIDTH,
|
||||||
|
|
@ -231,11 +232,12 @@ export function BookView({ beats }: { readonly beats: readonly StoryViewerBeat[]
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<ChronicleTrackedRegion kind="beat">
|
||||||
ref={pagesRef}
|
<div
|
||||||
className="mx-auto h-[100dvh] w-full overflow-hidden"
|
ref={pagesRef}
|
||||||
style={{ maxWidth: BOOK_MAX_WIDTH, touchAction: "pan-y" }}
|
className="mx-auto h-[100dvh] w-full overflow-hidden"
|
||||||
>
|
style={{ maxWidth: BOOK_MAX_WIDTH, touchAction: "pan-y" }}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
ref={contentRef}
|
ref={contentRef}
|
||||||
className="h-full w-full px-8 py-14 motion-reduce:transition-none sm:py-16"
|
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>
|
||||||
</div>
|
</div>
|
||||||
|
</ChronicleTrackedRegion>
|
||||||
|
|
||||||
<div className="fixed inset-x-0 bottom-0 z-10 flex items-center justify-center gap-4 p-4">
|
<div className="fixed inset-x-0 bottom-0 z-10 flex items-center justify-center gap-4 p-4">
|
||||||
<Button
|
<Button
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||||
import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
|
import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
|
||||||
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
|
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
|
||||||
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||||
|
import { ChronicleTrackedRegion } from "@/lib/client-analytics/chronicle";
|
||||||
import type { StoryBeat } from "@/payload-types";
|
import type { StoryBeat } from "@/payload-types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { READER_BODY_CLASSES } from "@/lib/story/richtextClasses";
|
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">
|
<h1 id="story-reader-title" className="sr-only">
|
||||||
The Unit Chronicle
|
The Unit Chronicle
|
||||||
</h1>
|
</h1>
|
||||||
<ol className="flex flex-col gap-24">
|
<ChronicleTrackedRegion kind="beat">
|
||||||
{beats.map((beat) => (
|
<ol className="flex flex-col gap-24">
|
||||||
<li key={beat.id} className="scroll-mt-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">
|
<div className="flex items-center justify-between gap-4">
|
||||||
<p className="text-xs uppercase tracking-[0.3em] text-neutral-500">
|
<p className="text-xs uppercase tracking-[0.3em] text-neutral-500">
|
||||||
Chapter {beat.chapter}
|
Chapter {beat.chapter}
|
||||||
|
|
@ -124,8 +126,9 @@ export function StoryViewer({ beats }: { readonly beats: readonly StoryViewerBea
|
||||||
<RichText data={beat.body} className={cn(READER_BODY_CLASSES)} />
|
<RichText data={beat.body} className={cn(READER_BODY_CLASSES)} />
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
|
</ChronicleTrackedRegion>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ import {
|
||||||
import { createWikiPage, updateWikiPage } from "@/app/(frontend)/wiki/actions";
|
import { createWikiPage, updateWikiPage } from "@/app/(frontend)/wiki/actions";
|
||||||
import { WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
|
import { WIKI_CATEGORIES, type WikiCategory } from "@/lib/wiki/categories";
|
||||||
import { prepareMarkdown } from "@/lib/wiki/prepare";
|
import { prepareMarkdown } from "@/lib/wiki/prepare";
|
||||||
|
import { track } from "@/lib/client-analytics";
|
||||||
import { buildTemplateStyles } from "@/lib/wiki/templateCss";
|
import { buildTemplateStyles } from "@/lib/wiki/templateCss";
|
||||||
import { MarkdownGuide } from "@/components/frontend/wiki/MarkdownGuide";
|
import { MarkdownGuide } from "@/components/frontend/wiki/MarkdownGuide";
|
||||||
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
|
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
|
||||||
|
|
@ -148,6 +149,9 @@ export function WikiEditor({
|
||||||
}
|
}
|
||||||
|
|
||||||
const awardedXp = result.data.awardedXp ?? 0;
|
const awardedXp = result.data.awardedXp ?? 0;
|
||||||
|
if (mode === "create") {
|
||||||
|
track("wiki.article_created", { slug: result.data.slug });
|
||||||
|
}
|
||||||
toast.success(
|
toast.success(
|
||||||
`${mode === "create" ? "Wiki page created" : "Wiki page updated"}${
|
`${mode === "create" ? "Wiki page created" : "Wiki page updated"}${
|
||||||
awardedXp > 0 ? ` \u00b7 +${awardedXp} XP` : ""
|
awardedXp > 0 ? ` \u00b7 +${awardedXp} XP` : ""
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ import {
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { WIKI_CATEGORIES } from "@/lib/wiki/categories";
|
import { WIKI_CATEGORIES } from "@/lib/wiki/categories";
|
||||||
|
import { track } from "@/lib/client-analytics";
|
||||||
import { WikiRow } from "./WikiRow";
|
import { WikiRow } from "./WikiRow";
|
||||||
import {
|
import {
|
||||||
collectTagCounts,
|
collectTagCounts,
|
||||||
|
|
@ -214,7 +215,7 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
|
||||||
{isModerator && <Badge variant="outline">Intel editor</Badge>}
|
{isModerator && <Badge variant="outline">Intel editor</Badge>}
|
||||||
|
|
||||||
<Button asChild className="ml-auto" size="sm">
|
<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" />
|
<PlusIcon data-icon="inline-start" />
|
||||||
New page
|
New page
|
||||||
</Link>
|
</Link>
|
||||||
|
|
@ -238,7 +239,9 @@ export function WikiIndex({ pages, isModerator }: WikiIndexProps) {
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Button asChild size="sm">
|
<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>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
|
||||||
18
src/components/frontend/wiki/WikiPageViewMeta.tsx
Normal file
18
src/components/frontend/wiki/WikiPageViewMeta.tsx
Normal 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
373
src/components/ui/chart.tsx
Normal 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,
|
||||||
|
}
|
||||||
177
src/lib/analytics/events.ts
Normal file
177
src/lib/analytics/events.ts
Normal 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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
28
src/lib/analytics/games.ts
Normal file
28
src/lib/analytics/games.ts
Normal 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
315
src/lib/analytics/ingest.ts
Normal 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
423
src/lib/analytics/queries.ts
Normal file
423
src/lib/analytics/queries.ts
Normal 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
307
src/lib/analytics/rollup.ts
Normal 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
143
src/lib/analytics/schema.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
79
src/lib/client-analytics/AnalyticsTracker.tsx
Normal file
79
src/lib/client-analytics/AnalyticsTracker.tsx
Normal 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;
|
||||||
|
}
|
||||||
356
src/lib/client-analytics/capture.ts
Normal file
356
src/lib/client-analytics/capture.ts
Normal 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,
|
||||||
|
};
|
||||||
|
}
|
||||||
245
src/lib/client-analytics/chronicle.tsx
Normal file
245
src/lib/client-analytics/chronicle.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
288
src/lib/client-analytics/core.ts
Normal file
288
src/lib/client-analytics/core.ts
Normal 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;
|
||||||
|
}
|
||||||
9
src/lib/client-analytics/index.ts
Normal file
9
src/lib/client-analytics/index.ts
Normal 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";
|
||||||
40724
src/migrations/20261014_134620_add_analytics_tables.json
Normal file
40724
src/migrations/20261014_134620_add_analytics_tables.json
Normal file
File diff suppressed because it is too large
Load diff
33
src/migrations/20261014_134620_add_analytics_tables.ts
Normal file
33
src/migrations/20261014_134620_add_analytics_tables.ts
Normal 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}"`));
|
||||||
|
}
|
||||||
|
}
|
||||||
40726
src/migrations/20261014_135614_add_analytics_permission_enum_value.json
Normal file
40726
src/migrations/20261014_135614_add_analytics_permission_enum_value.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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.
|
||||||
|
}
|
||||||
|
|
@ -134,6 +134,8 @@ 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_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_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_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';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -814,6 +816,16 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261013_184745_add_garage_fields.up,
|
up: migration_20261013_184745_add_garage_fields.up,
|
||||||
down: migration_20261013_184745_add_garage_fields.down,
|
down: migration_20261013_184745_add_garage_fields.down,
|
||||||
name: '20261013_184745_add_garage_fields'
|
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'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -997,6 +997,7 @@ export interface Role {
|
||||||
| 'achievements:update'
|
| 'achievements:update'
|
||||||
| 'achievements:delete'
|
| 'achievements:delete'
|
||||||
| 'admin:achievements:manage'
|
| 'admin:achievements:manage'
|
||||||
|
| 'admin:analytics:manage'
|
||||||
)[]
|
)[]
|
||||||
| null;
|
| null;
|
||||||
/**
|
/**
|
||||||
|
|
@ -3143,6 +3144,7 @@ export interface GameEventLog {
|
||||||
| 'achievements:update'
|
| 'achievements:update'
|
||||||
| 'achievements:delete'
|
| 'achievements:delete'
|
||||||
| 'admin:achievements:manage'
|
| 'admin:achievements:manage'
|
||||||
|
| 'admin:analytics:manage'
|
||||||
)[]
|
)[]
|
||||||
| null;
|
| null;
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
|
|
|
||||||
|
|
@ -475,6 +475,10 @@ export default buildConfig({
|
||||||
path: "/tech-tree",
|
path: "/tech-tree",
|
||||||
Component: "@/components/admin/tech-tree/TechTreeView",
|
Component: "@/components/admin/tech-tree/TechTreeView",
|
||||||
},
|
},
|
||||||
|
analytics: {
|
||||||
|
path: "/analytics",
|
||||||
|
Component: "@/components/admin/analytics/AnalyticsView",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -537,6 +541,14 @@ export default buildConfig({
|
||||||
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
|
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
|
||||||
key: "generate-mission",
|
key: "generate-mission",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
scriptPath: path.resolve(dirname, "scripts/analyticsRollup.ts"),
|
||||||
|
key: "analytics-rollup",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
scriptPath: path.resolve(dirname, "scripts/analyticsPurge.ts"),
|
||||||
|
key: "analytics-purge",
|
||||||
|
},
|
||||||
],
|
],
|
||||||
plugins: [
|
plugins: [
|
||||||
formBuilderPlugin(surveyFormBuilderConfig()),
|
formBuilderPlugin(surveyFormBuilderConfig()),
|
||||||
|
|
|
||||||
|
|
@ -823,6 +823,17 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
||||||
{ value: "admin:achievements:manage", label: ["Achievements", "Manage Admin Page"] },
|
{ 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:update",
|
||||||
"achievements:delete",
|
"achievements:delete",
|
||||||
"admin:achievements:manage",
|
"admin:achievements:manage",
|
||||||
|
"admin:analytics:manage",
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
30
src/scripts/analyticsPurge.ts
Normal file
30
src/scripts/analyticsPurge.ts
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
45
src/scripts/analyticsRollup.ts
Normal file
45
src/scripts/analyticsRollup.ts
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { execSync } from "node:child_process";
|
import { execSync } from "node:child_process";
|
||||||
import { Client } from "pg";
|
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
|
// Global setup/teardown processes never load .env (only setupFiles do); load
|
||||||
// it here so every entry point sees the same variables. dotenv does not
|
// 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
|
* Truncate every table in the public schema except migration journals and
|
||||||
* PostGIS internals. Idempotent by construction: the result is the same empty
|
* PostGIS internals. Idempotent by construction: the result is the same empty
|
||||||
|
|
@ -186,7 +223,9 @@ export async function bootstrapTestDatabase(): Promise<string> {
|
||||||
const hardReset = hardResetRequested();
|
const hardReset = hardResetRequested();
|
||||||
|
|
||||||
await ensureTestDatabase(testUri, hardReset);
|
await ensureTestDatabase(testUri, hardReset);
|
||||||
|
await dropAnalyticsTables(testUri);
|
||||||
pushSchema(testUri);
|
pushSchema(testUri);
|
||||||
|
await ensureAnalyticsTables(testUri);
|
||||||
await truncateAllData(testUri);
|
await truncateAllData(testUri);
|
||||||
runSeedScripts(testUri);
|
runSeedScripts(testUri);
|
||||||
await repairSequences(testUri);
|
await repairSequences(testUri);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue