also looking at this
chore: wip stx improvements
#1649
241 files
+19022
-1323
| @@ -0,0 +1,46 @@ | ||
| 1 | export function processAnalyticsDirective(content: string): string { | |
| 2 | return content.replace(/@analytics\b/g, generateTrackingScript()) | |
| 3 | } | |
| 4 | ||
| 5 | export function generateTrackingScript(config?: { endpoint?: string, sessionTimeout?: number }): string { | |
| 6 | const endpoint = config?.endpoint || '/_stx/analytics/pageview' | |
| 7 | const sessionTimeout = config?.sessionTimeout || 1800000 | |
| 8 | ||
| 9 | return `<script> | |
| 10 | (function() { | |
| 11 | var endpoint = ${JSON.stringify(endpoint)}; | |
| 12 | var sessionTimeout = ${sessionTimeout}; | |
| 13 | var sessionKey = '_stx_sid'; | |
| 14 | ||
| 15 | function getSessionId() { | |
| 16 | var stored = sessionStorage.getItem(sessionKey); | |
| 17 | if (stored) { | |
| 18 | try { | |
| 19 | var parsed = JSON.parse(stored); | |
| 20 | if (Date.now() - parsed.ts < sessionTimeout) { | |
| 21 | parsed.ts = Date.now(); | |
| 22 | sessionStorage.setItem(sessionKey, JSON.stringify(parsed)); | |
| 23 | return parsed.id; | |
| 24 | } | |
| 25 | } catch(e) {} | |
| 26 | } | |
| 27 | var id = Math.random().toString(36).slice(2) + Date.now().toString(36); | |
| 28 | sessionStorage.setItem(sessionKey, JSON.stringify({ id: id, ts: Date.now() })); | |
| 29 | return id; | |
| 30 | } | |
| 31 | ||
| 32 | var sessionId = getSessionId(); | |
| 33 | ||
| 34 | fetch(endpoint, { | |
| 35 | method: 'POST', | |
| 36 | headers: { 'Content-Type': 'application/json' }, | |
| 37 | body: JSON.stringify({ | |
| 38 | path: location.pathname, | |
| 39 | referrer: document.referrer || undefined, | |
| 40 | sessionId: sessionId | |
| 41 | }), | |
| 42 | keepalive: true | |
| 43 | }).catch(function() {}); | |
| 44 | })(); | |
| 45 | </script>` | |
| 46 | } | |