also looking at this
chore: wip stx improvements
#1649
241 files
+19022
-1323
| @@ -0,0 +1,81 @@ | ||
| 1 | import type { AnalyticsConfig, AnalyticsEvent, PageView } from './types' | |
| 2 | import { getAnalyticsEngine } from './analytics' | |
| 3 | ||
| 4 | export async function trackPageView( | |
| 5 | request: Request | { path: string, referrer?: string, userAgent?: string, sessionId?: string }, | |
| 6 | ): Promise<PageView> { | |
| 7 | const engine = getAnalyticsEngine() | |
| 8 | return engine.trackPageView(request) | |
| 9 | } | |
| 10 | ||
| 11 | export async function trackEvent( | |
| 12 | name: string, | |
| 13 | data?: Record<string, unknown>, | |
| 14 | request?: Request | { path?: string, sessionId?: string }, | |
| 15 | ): Promise<AnalyticsEvent> { | |
| 16 | const engine = getAnalyticsEngine() | |
| 17 | ||
| 18 | let path: string | undefined | |
| 19 | let sessionId: string | undefined | |
| 20 | ||
| 21 | if (request) { | |
| 22 | if (request instanceof Request) { | |
| 23 | const url = new URL(request.url) | |
| 24 | path = url.pathname | |
| 25 | } | |
| 26 | else { | |
| 27 | path = request.path | |
| 28 | sessionId = request.sessionId | |
| 29 | } | |
| 30 | } | |
| 31 | ||
| 32 | const event: AnalyticsEvent = { | |
| 33 | id: generateId(), | |
| 34 | name, | |
| 35 | data, | |
| 36 | path, | |
| 37 | timestamp: Date.now(), | |
| 38 | sessionId, | |
| 39 | } | |
| 40 | ||
| 41 | await engine.storage.saveEvent(event) | |
| 42 | return event | |
| 43 | } | |
| 44 | ||
| 45 | export function shouldTrack(path: string, config: AnalyticsConfig): boolean { | |
| 46 | if (!config.ignorePaths || config.ignorePaths.length === 0) { | |
| 47 | return true | |
| 48 | } | |
| 49 | ||
| 50 | for (const pattern of config.ignorePaths) { | |
| 51 | if (matchGlob(path, pattern)) { | |
| 52 | return false | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | return true | |
| 57 | } | |
| 58 | ||
| 59 | function matchGlob(path: string, pattern: string): boolean { | |
| 60 | // Exact match | |
| 61 | if (pattern === path) { | |
| 62 | return true | |
| 63 | } | |
| 64 | ||
| 65 | // Convert glob pattern to regex | |
| 66 | const regexStr = pattern | |
| 67 | .replace(/[.+^${}()|[\]\\]/g, '\\$&') | |
| 68 | .replace(/\*/g, '.*') | |
| 69 | ||
| 70 | const regex = new RegExp(`^${regexStr}$`) | |
| 71 | return regex.test(path) | |
| 72 | } | |
| 73 | ||
| 74 | function generateId(): string { | |
| 75 | if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { | |
| 76 | return crypto.randomUUID() | |
| 77 | } | |
| 78 | return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}` | |
| 79 | } | |
| 80 | ||
| 81 | export { generateId } | |