telemetry-utils.ts64 lines · main
| 1 | import { IS_PROD } from './constants' |
| 2 | import { isBrowser } from './helpers' |
| 3 | |
| 4 | export function getTelemetryCookieOptions() { |
| 5 | if (typeof window === 'undefined') return 'path=/; SameSite=Lax' |
| 6 | if (!IS_PROD) return 'path=/; SameSite=Lax' |
| 7 | |
| 8 | const hostname = window.location.hostname |
| 9 | const isBrivenCom = hostname === 'supabase.com' || hostname.endsWith('.supabase.com') |
| 10 | return isBrivenCom ? 'path=/; domain=supabase.com; SameSite=Lax' : 'path=/; SameSite=Lax' |
| 11 | } |
| 12 | |
| 13 | // Parse session_id from PostHog cookie since SDK doesn't expose session ID |
| 14 | // (needed to correlate client and server events) |
| 15 | function getPostHogSessionId(): string | null { |
| 16 | if (!isBrowser) return null |
| 17 | |
| 18 | try { |
| 19 | // Parse PostHog cookie to extract session ID |
| 20 | const phCookies = document.cookie.split(';').find((cookie) => cookie.trim().startsWith('ph_')) |
| 21 | |
| 22 | if (phCookies) { |
| 23 | const cookieValue = decodeURIComponent(phCookies.split('=')[1]) |
| 24 | const phData = JSON.parse(cookieValue) |
| 25 | if (phData.$sesid && Array.isArray(phData.$sesid) && phData.$sesid[1]) { |
| 26 | return phData.$sesid[1] |
| 27 | } |
| 28 | } |
| 29 | } catch (error) { |
| 30 | console.warn('Could not extract PostHog session ID:', error) |
| 31 | } |
| 32 | |
| 33 | return null |
| 34 | } |
| 35 | |
| 36 | export function getSharedTelemetryData(pathname?: string) { |
| 37 | const sessionId = getPostHogSessionId() |
| 38 | const pageUrl = (() => { |
| 39 | if (!isBrowser) return '' |
| 40 | |
| 41 | try { |
| 42 | const url = new URL(window.location.href) |
| 43 | url.hash = '' |
| 44 | return url.href |
| 45 | } catch { |
| 46 | return window.location.href.split('#')[0] |
| 47 | } |
| 48 | })() |
| 49 | |
| 50 | return { |
| 51 | page_url: pageUrl, |
| 52 | page_title: isBrowser ? document?.title : '', |
| 53 | pathname: pathname ? pathname : isBrowser ? window.location.pathname : '', |
| 54 | session_id: sessionId, |
| 55 | ph: { |
| 56 | referrer: isBrowser ? document?.referrer : '', |
| 57 | language: navigator.language ?? 'en-US', |
| 58 | user_agent: navigator.userAgent, |
| 59 | search: isBrowser ? window.location.search : '', |
| 60 | viewport_height: isBrowser ? window.innerHeight : 0, |
| 61 | viewport_width: isBrowser ? window.innerWidth : 0, |
| 62 | }, |
| 63 | } |
| 64 | } |