keystone-design-bootstrap 1.0.98 → 1.0.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contexts/index.js +14 -2
- package/dist/contexts/index.js.map +1 -1
- package/dist/design_system/components/DynamicFormFields.js +14 -2
- package/dist/design_system/components/DynamicFormFields.js.map +1 -1
- package/dist/design_system/elements/index.js +14 -2
- package/dist/design_system/elements/index.js.map +1 -1
- package/dist/design_system/sections/index.js +14 -2
- package/dist/design_system/sections/index.js.map +1 -1
- package/dist/index.js +14 -2
- package/dist/index.js.map +1 -1
- package/dist/tracking/index.js +23 -2
- package/dist/tracking/index.js.map +1 -1
- package/package.json +1 -1
- package/src/tracking/PostHogProvider.tsx +40 -1
- package/src/tracking/logging.ts +35 -3
package/dist/tracking/index.js
CHANGED
|
@@ -29,9 +29,11 @@ import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
|
29
29
|
import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
|
|
30
30
|
var BUILD_CONSOLE_DISABLED = process.env.NEXT_PUBLIC_LOGGING_DISABLED === "1";
|
|
31
31
|
var BUILD_POSTHOG_DISABLED = process.env.NEXT_PUBLIC_POSTHOG_LOGGING_DISABLED === "1";
|
|
32
|
+
var MAX_PENDING_POSTHOG_LOGS = 500;
|
|
32
33
|
var otelProvider = null;
|
|
33
34
|
var otelLogger = null;
|
|
34
35
|
var otelInitFingerprint = "";
|
|
36
|
+
var pendingPostHogLogs = [];
|
|
35
37
|
var browserConsole = globalThis == null ? void 0 : globalThis["console"];
|
|
36
38
|
var CHANNEL_COLORS = {
|
|
37
39
|
// Shared diagnostics
|
|
@@ -76,6 +78,20 @@ function flattenAttributes(input, prefix = "") {
|
|
|
76
78
|
function stripTrailingSlash(host) {
|
|
77
79
|
return host.replace(/\/+$/, "");
|
|
78
80
|
}
|
|
81
|
+
function enqueuePendingPostHogLog(entry) {
|
|
82
|
+
if (pendingPostHogLogs.length >= MAX_PENDING_POSTHOG_LOGS) {
|
|
83
|
+
pendingPostHogLogs.shift();
|
|
84
|
+
}
|
|
85
|
+
pendingPostHogLogs.push(entry);
|
|
86
|
+
}
|
|
87
|
+
function flushPendingPostHogLogs() {
|
|
88
|
+
if (!otelLogger || pendingPostHogLogs.length === 0) return;
|
|
89
|
+
while (pendingPostHogLogs.length > 0) {
|
|
90
|
+
const entry = pendingPostHogLogs.shift();
|
|
91
|
+
if (!entry) break;
|
|
92
|
+
emitToPostHog(entry.level, entry.channel, entry.event, entry.detail);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
79
95
|
function initializePostHogLogging(options) {
|
|
80
96
|
var _a, _b, _c, _d, _e, _f;
|
|
81
97
|
if (typeof window === "undefined") return;
|
|
@@ -112,6 +128,7 @@ function initializePostHogLogging(options) {
|
|
|
112
128
|
logs.setGlobalLoggerProvider(otelProvider);
|
|
113
129
|
otelLogger = logs.getLogger(serviceName);
|
|
114
130
|
otelInitFingerprint = fingerprint;
|
|
131
|
+
flushPendingPostHogLogs();
|
|
115
132
|
}
|
|
116
133
|
function isConsoleEnabled() {
|
|
117
134
|
if (BUILD_CONSOLE_DISABLED) return false;
|
|
@@ -145,7 +162,7 @@ function emitConsole(level, channel, event, detail) {
|
|
|
145
162
|
(_d = browserConsole == null ? void 0 : browserConsole.log) == null ? void 0 : _d.call(browserConsole, message, channelStyle, eventStyle, detailStyle);
|
|
146
163
|
}
|
|
147
164
|
function emitToPostHog(level, channel, event, detail) {
|
|
148
|
-
if (!otelLogger) return;
|
|
165
|
+
if (!otelLogger) return false;
|
|
149
166
|
const severityText = level === "warn" ? "WARNING" : level === "error" ? "ERROR" : "INFO";
|
|
150
167
|
const attributes = flattenAttributes(__spreadValues({ channel }, detail));
|
|
151
168
|
otelLogger.emit({
|
|
@@ -153,6 +170,7 @@ function emitToPostHog(level, channel, event, detail) {
|
|
|
153
170
|
body: event,
|
|
154
171
|
attributes
|
|
155
172
|
});
|
|
173
|
+
return true;
|
|
156
174
|
}
|
|
157
175
|
function emit(level, channel, event, detail, options) {
|
|
158
176
|
var _a;
|
|
@@ -161,7 +179,10 @@ function emit(level, channel, event, detail, options) {
|
|
|
161
179
|
emitConsole(level, channel, event, detail);
|
|
162
180
|
}
|
|
163
181
|
if (shouldShip) {
|
|
164
|
-
emitToPostHog(level, channel, event, detail);
|
|
182
|
+
const shipped = emitToPostHog(level, channel, event, detail);
|
|
183
|
+
if (!shipped) {
|
|
184
|
+
enqueuePendingPostHogLog({ level, channel, event, detail });
|
|
185
|
+
}
|
|
165
186
|
}
|
|
166
187
|
}
|
|
167
188
|
function log(channel, event, detail = {}, options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/tracking/MetaPixel.tsx","../../src/tracking/logging.ts","../../src/tracking/firePixelEvent.ts","../../src/tracking/MetaPixelTracker.tsx","../../src/tracking/PostHogProvider.tsx","../../src/tracking/KeystoneAnalyticsTracker.tsx","../../src/tracking/captureEvent.ts","../../src/tracking/GoogleTagManager.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport Script from 'next/script';\nimport { firePixelEvent } from './firePixelEvent';\nimport { log } from './logging';\n\nconst FBEVENTS_URL = 'https://connect.facebook.net/en_US/fbevents.js';\n\nconst PIXEL_SCRIPT = (pixelId: string) => `\n !function(f,b,e,v,n,t,s)\n {if(f.fbq)return;n=f.fbq=function(){n.callMethod?\n n.callMethod.apply(n,arguments):n.queue.push(arguments)};\n if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\n n.queue=[];t=b.createElement(e);t.async=!0;\n t.src=v;s=b.getElementsByTagName(e)[0];\n s.parentNode.insertBefore(t,s)}(window, document,'script','${FBEVENTS_URL}');\n fbq('init', '${pixelId.replace(/'/g, \"\\\\'\")}');\n window.__ks_pixel_ids = window.__ks_pixel_ids || [];\n if (window.__ks_pixel_ids.indexOf('${pixelId.replace(/'/g, \"\\\\'\")}') === -1) {\n window.__ks_pixel_ids.push('${pixelId.replace(/'/g, \"\\\\'\")}');\n }\n`;\n\nexport type MetaPixelProps = {\n /** Meta Pixel ID. When null/undefined, nothing is rendered. */\n pixelId: string | null | undefined;\n};\n\n/**\n * Renders the Meta (Facebook) Pixel base code: loads fbevents.js, initializes\n * the pixel, and tracks PageView. Use in the root layout when ads config\n * provides a meta_pixel_id.\n */\nexport function MetaPixel({ pixelId }: MetaPixelProps) {\n const raw = typeof pixelId === 'string' ? pixelId.trim() : '';\n const id = raw && raw !== 'null' && /^\\d+$/.test(raw) ? raw : '';\n\n useEffect(() => {\n if (!id) return;\n log('meta-pixel', 'PIXEL_INIT', { pixelId: id }, { shipToPostHog: true });\n firePixelEvent('PageView');\n }, [id]);\n\n if (!id) {\n return null;\n }\n\n return (\n <>\n <Script\n id=\"meta-pixel\"\n strategy=\"afterInteractive\"\n dangerouslySetInnerHTML={{ __html: PIXEL_SCRIPT(id) }}\n />\n <noscript>\n {/* eslint-disable-next-line @next/next/no-img-element -- 1x1 tracking pixel for no-JS fallback; next/image not applicable in noscript */}\n <img\n height={1}\n width={1}\n style={{ display: 'none' }}\n src={`https://www.facebook.com/tr?id=${id}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n );\n}\n","'use client';\n\nimport { logs } from '@opentelemetry/api-logs';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';\n\nconst BUILD_CONSOLE_DISABLED = process.env.NEXT_PUBLIC_LOGGING_DISABLED === '1';\nconst BUILD_POSTHOG_DISABLED = process.env.NEXT_PUBLIC_POSTHOG_LOGGING_DISABLED === '1';\ninterface LoggingWindow extends Window {\n __loggingDisabled?: boolean;\n __posthogLoggingDisabled?: boolean;\n}\n\nexport type LogLevel = 'info' | 'warn' | 'error';\n\nexport type LogOptions = {\n /** Send this log payload to PostHog Logs product. */\n shipToPostHog?: boolean;\n};\n\ntype OTelInitOptions = {\n apiKey: string;\n apiHost?: string;\n serviceName?: string;\n environment?: string;\n accountId?: number;\n accountName?: string;\n};\nlet otelProvider: LoggerProvider | null = null;\nlet otelLogger: ReturnType<typeof logs.getLogger> | null = null;\nlet otelInitFingerprint = '';\nconst browserConsole = globalThis?.['console'];\n\n/**\n * Channel → accent colour. Unregistered channels fall through to gray.\n */\nexport const CHANNEL_COLORS: Record<string, string> = {\n // Shared diagnostics\n 'global-client': '#d2a8ff',\n\n // Section pins (desktop)\n 'every-channel-pin': '#9febd7',\n 'hero-pin': '#6ecc8b',\n 'pricing-pin': '#399587',\n 'product-screens-pin': '#4fafa0',\n 'social-proof-pin': '#ffbb8a',\n 'value-props-pin': '#e0a733',\n 'work-pin': '#f57e56',\n\n // Section pins (mobile)\n 'mobile-every-channel-pin': '#7ed9c6',\n 'mobile-hero-pin': '#f0eee6',\n 'mobile-pricing-pin': '#80d4ff',\n 'mobile-product-screens-pin': '#3a9085',\n 'mobile-social-proof-pin': '#ffd580',\n 'mobile-value-props-pin': '#4fafa0',\n};\n\nfunction flattenAttributes(input: Record<string, unknown>, prefix = ''): Record<string, string | number | boolean> {\n const output: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(input)) {\n const nextKey = prefix ? `${prefix}.${key}` : key;\n if (value === null || value === undefined) continue;\n\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n output[nextKey] = value;\n continue;\n }\n\n if (Array.isArray(value)) {\n output[nextKey] = JSON.stringify(value);\n continue;\n }\n\n if (typeof value === 'object') {\n Object.assign(output, flattenAttributes(value as Record<string, unknown>, nextKey));\n continue;\n }\n\n output[nextKey] = String(value);\n }\n\n return output;\n}\n\nfunction stripTrailingSlash(host: string): string {\n return host.replace(/\\/+$/, '');\n}\n\nexport function initializePostHogLogging(options: OTelInitOptions): void {\n if (typeof window === 'undefined') return;\n if (!options.apiKey?.trim()) return;\n\n const apiHost = stripTrailingSlash(options.apiHost?.trim() || 'https://us.i.posthog.com');\n const serviceName = options.serviceName?.trim() || 'keystone-customer-site';\n const environment = options.environment?.trim() || 'production';\n const fingerprint = `${apiHost}|${options.apiKey}|${serviceName}|${environment}|${options.accountId ?? ''}|${options.accountName ?? ''}`;\n if (otelLogger && otelInitFingerprint === fingerprint) return;\n\n if (otelProvider) {\n // Cleanly replace logger provider when config changes.\n void otelProvider.shutdown().catch(() => {});\n otelProvider = null;\n otelLogger = null;\n }\n\n const baseAttributes: Record<string, string | number | boolean> = {\n 'service.name': serviceName,\n environment,\n site_domain: window.location.hostname,\n };\n if (options.accountId !== undefined) baseAttributes.account_id = options.accountId;\n if (options.accountName) baseAttributes.account_name = options.accountName;\n\n const exporter = new OTLPLogExporter({\n url: `${apiHost}/i/v1/logs?token=${encodeURIComponent(options.apiKey)}`,\n headers: {\n // Keep request \"simple\" to avoid CORS preflight in browser.\n 'Content-Type': 'text/plain',\n },\n });\n\n otelProvider = new LoggerProvider({\n resource: resourceFromAttributes(baseAttributes),\n processors: [new BatchLogRecordProcessor(exporter)],\n });\n\n logs.setGlobalLoggerProvider(otelProvider);\n otelLogger = logs.getLogger(serviceName);\n otelInitFingerprint = fingerprint;\n}\n\nfunction isConsoleEnabled(): boolean {\n if (BUILD_CONSOLE_DISABLED) return false;\n if (typeof window === 'undefined') return true;\n return (window as LoggingWindow).__loggingDisabled !== true;\n}\n\nfunction isPostHogShippingEnabled(): boolean {\n if (BUILD_POSTHOG_DISABLED) return false;\n if (typeof window === 'undefined') return false;\n return (window as LoggingWindow).__posthogLoggingDisabled !== true;\n}\n\nfunction formatDetail(detail: Record<string, unknown>): string {\n return Object.entries(detail)\n .map(([k, v]) => `${k}=${typeof v === 'number' ? v.toFixed(4) : String(v)}`)\n .join(' ');\n}\n\nfunction emitConsole(\n level: LogLevel,\n channel: string,\n event: string,\n detail: Record<string, unknown>,\n): void {\n const color = CHANNEL_COLORS[channel] ?? '#aaa';\n const detailStr = formatDetail(detail);\n const message = `%c[${channel}] %c${event}%c ${detailStr}`;\n const channelStyle = `color:${color}; font-weight:bold`;\n const eventStyle = level === 'error'\n ? 'color:#e94e4e; font-weight:bold'\n : level === 'warn'\n ? 'color:#f5a623; font-weight:bold'\n : 'color:#fff; font-weight:bold';\n const detailStyle = 'color:#999; font-weight:normal';\n\n if (level === 'error') {\n browserConsole?.error?.(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n if (level === 'warn') {\n browserConsole?.warn?.(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n browserConsole?.log?.(message, channelStyle, eventStyle, detailStyle);\n}\n\nfunction emitToPostHog(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>): void {\n if (!otelLogger) return;\n\n const severityText = level === 'warn' ? 'WARNING' : level === 'error' ? 'ERROR' : 'INFO';\n const attributes = flattenAttributes({ channel, ...detail });\n\n otelLogger.emit({\n severityText,\n body: event,\n attributes,\n });\n}\n\nfunction emit(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>, options?: LogOptions): void {\n const shouldShip = (options?.shipToPostHog ?? level !== 'info') && isPostHogShippingEnabled();\n // Keep warn/error visible even when regular logs are muted.\n if (level !== 'info' || isConsoleEnabled()) {\n emitConsole(level, channel, event, detail);\n }\n if (shouldShip) {\n emitToPostHog(level, channel, event, detail);\n }\n}\n\nexport function log(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('info', channel, event, detail, options);\n}\n\nexport function warn(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('warn', channel, event, detail, options);\n}\n\nexport function error(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('error', channel, event, detail, options);\n}\n","type FbqFn = (method: string, ...args: unknown[]) => void;\nimport { log, warn } from './logging';\n\nexport type PixelEvent = 'PageView' | 'ViewContent' | 'InitiateCheckout' | 'Lead';\n\nexport interface PixelEventParams {\n contentName?: string;\n contentCategory?: string;\n}\n\n/** Raw (unhashed) user identifiers for advanced matching. */\nexport interface PixelUserData {\n email?: string | null;\n phone?: string | null;\n}\n\n// Hashed user data stored in sessionStorage for the duration of the browsing session.\n// Keyed by a short namespace to avoid collisions.\nconst STORAGE_KEY = 'ks_pud';\n\nasync function sha256Hex(str: string): Promise<string> {\n const buffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str));\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nfunction getFbq(): FbqFn | undefined {\n if (typeof window === 'undefined') return undefined;\n return (window as Window & { fbq?: FbqFn }).fbq;\n}\n\n/** Read the pixel IDs registered by MetaPixel via the inline init script. */\nfunction getRegisteredPixelIds(): string[] {\n return (window as Window & { __ks_pixel_ids?: string[] }).__ks_pixel_ids ?? [];\n}\n\n/** Apply stored hashed user data to every configured Meta Pixel. */\nfunction applyStoredUserData(fbq: FbqFn): void {\n try {\n const raw = sessionStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n const hashed = JSON.parse(raw) as Record<string, string>;\n if (Object.keys(hashed).length === 0) return;\n getRegisteredPixelIds().forEach((id) => fbq('init', id, hashed));\n } catch {\n // sessionStorage unavailable or JSON malformed — safe to ignore\n }\n}\n\n/**\n * Hash and store user identifiers so they are automatically included in all\n * subsequent pixel events for this browser session. Call this as soon as\n * identity is known (e.g. contact form submission, portal login step 1).\n */\nexport async function setPixelUserData(userData: PixelUserData): Promise<void> {\n const hashed: Record<string, string> = {};\n\n if (userData.email) {\n hashed.em = await sha256Hex(userData.email.trim().toLowerCase());\n }\n if (userData.phone) {\n const digits = userData.phone.replace(/\\D/g, '');\n if (digits) hashed.ph = await sha256Hex(digits);\n }\n\n if (Object.keys(hashed).length === 0) return;\n\n try {\n sessionStorage.setItem(STORAGE_KEY, JSON.stringify(hashed));\n } catch {\n // sessionStorage unavailable — still apply to fbq for this page load\n }\n\n const fbq = getFbq();\n if (fbq) {\n getRegisteredPixelIds().forEach((id) => fbq('init', id, hashed));\n }\n}\n\n/**\n * Single entry point for all client-side Meta Pixel event fires.\n * Automatically applies any stored user identity before firing so that Meta\n * can match events to known users across the entire session.\n * Silently no-ops if fbq is not loaded (pixel not configured for this site).\n *\n * @param eventId - Optional server-side event ID for browser/server deduplication.\n * Pass the `eventId` returned by the form submission API so Meta can match and\n * deduplicate the browser Lead event against the server-side CAPI Lead event.\n * Format: fbq('track', event, params, { eventID: eventId })\n */\nexport function firePixelEvent(event: PixelEvent, params?: PixelEventParams, eventId?: string): void {\n const fbq = getFbq();\n if (!fbq) {\n warn('meta-pixel', 'PIXEL_EVENT_SKIPPED_FBQ_NOT_LOADED', { event });\n return;\n }\n\n // Re-apply stored identity before every event so user data is included\n // even on events that fire after a client-side navigation (PageView, ViewContent, etc.)\n applyStoredUserData(fbq);\n\n const normalized: Record<string, string> = {};\n if (params?.contentName) normalized.content_name = params.contentName;\n if (params?.contentCategory) normalized.content_category = params.contentCategory;\n\n const customData = Object.keys(normalized).length > 0 ? normalized : undefined;\n const eventData = eventId ? { eventID: eventId } : undefined;\n\n log('meta-pixel', 'PIXEL_EVENT_FIRED', {\n event,\n ...normalized,\n ...(eventId ? { eventId } : {}),\n }, { shipToPostHog: true });\n fbq('track', event, customData, eventData);\n}\n","'use client';\n\nimport { useEffect } from 'react';\nimport { usePathname } from 'next/navigation';\nimport { firePixelEvent } from './firePixelEvent';\n\ntype RouteRule = {\n pattern: RegExp;\n getParams: (match: RegExpMatchArray) => { contentName: string; contentCategory: string };\n};\n\nfunction slugToTitle(slug: string): string {\n return slug\n .split('-')\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n// Checked in order — first match wins. More specific patterns come first.\nconst ROUTE_RULES: RouteRule[] = [\n {\n pattern: /^\\/services\\/(.+)$/,\n getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Service' }),\n },\n {\n pattern: /^\\/locations\\/(.+)$/,\n getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Location' }),\n },\n {\n pattern: /^\\/services$/,\n getParams: () => ({ contentName: 'Services', contentCategory: 'Services' }),\n },\n {\n pattern: /^\\/locations$/,\n getParams: () => ({ contentName: 'Locations', contentCategory: 'Locations' }),\n },\n {\n pattern: /^\\/portal$/,\n getParams: () => ({ contentName: 'Member Portal', contentCategory: 'Pricing' }),\n },\n {\n pattern: /^\\/service-menu$/,\n getParams: () => ({ contentName: 'Service Menu', contentCategory: 'Pricing' }),\n },\n {\n pattern: /^\\/faq$/,\n getParams: () => ({ contentName: 'FAQ', contentCategory: 'FAQ' }),\n },\n {\n pattern: /^\\/contact$/,\n getParams: () => ({ contentName: 'Contact', contentCategory: 'Contact' }),\n },\n];\n\ntype Props = {\n /** External booking URL. When set, fires InitiateCheckout on any click targeting that URL. */\n bookingUrl?: string | null;\n};\n\n/**\n * Single client-side tracker placed once in KeystoneRootLayout.\n * - Fires ViewContent on every route change for known page patterns.\n * - Fires InitiateCheckout whenever a visitor clicks a link to the external booking URL.\n *\n * Portal booking tab tracking is handled directly inside PortalPage via PortalTabTracker\n * since intent is only established when the Booking tab is explicitly opened.\n */\nexport function MetaPixelTracker({ bookingUrl }: Props) {\n const pathname = usePathname();\n\n useEffect(() => {\n for (const rule of ROUTE_RULES) {\n const match = pathname.match(rule.pattern);\n if (match) {\n const { contentName, contentCategory } = rule.getParams(match);\n firePixelEvent('ViewContent', { contentName, contentCategory });\n break;\n }\n }\n }, [pathname]);\n\n useEffect(() => {\n if (!bookingUrl) return;\n\n const handleClick = (e: MouseEvent) => {\n const anchor = (e.target as Element).closest('a');\n if (anchor?.href?.startsWith(bookingUrl)) {\n firePixelEvent('InitiateCheckout');\n }\n };\n\n document.addEventListener('click', handleClick);\n return () => document.removeEventListener('click', handleClick);\n }, [bookingUrl]);\n\n return null;\n}\n","'use client';\n\nimport posthog from 'posthog-js';\nimport { PostHogProvider as PHProvider } from 'posthog-js/react';\nimport { useEffect, Suspense } from 'react';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { error as logError, initializePostHogLogging } from './logging';\n\nconst DEFAULT_HOST = 'https://us.i.posthog.com';\n\nexport type PostHogProviderProps = {\n apiKey: string;\n apiHost?: string;\n /** Keystone account ID — attached to every event as a super property. */\n accountId?: number;\n /** Keystone account name (company_name) — attached to every event as a super property. */\n accountName?: string;\n /**\n * Environment identifier from KEYSTONE_ENV on the Rails server (e.g. \"production\", \"staging\",\n * \"development\"). Registered as a super property so events can be filtered by environment\n * in PostHog and the sync job only imports data for the matching environment.\n */\n environment?: string;\n children: React.ReactNode;\n};\n\n// ---------------------------------------------------------------------------\n// Page name resolution\n// ---------------------------------------------------------------------------\n\ntype PageInfo = { page_name: string; page_slug?: string };\n\nfunction resolvePageInfo(pathname: string): PageInfo {\n if (pathname === '/') return { page_name: 'home' };\n\n const patterns: Array<[RegExp, (m: RegExpMatchArray) => PageInfo]> = [\n [/^\\/services\\/(.+)$/, ([, slug]) => ({ page_name: 'service_detail', page_slug: slug })],\n [/^\\/locations\\/(.+)$/, ([, slug]) => ({ page_name: 'location_detail', page_slug: slug })],\n [/^\\/blog\\/(.+)$/, ([, slug]) => ({ page_name: 'blog_post', page_slug: slug })],\n [/^\\/jobs\\/(.+)$/, ([, slug]) => ({ page_name: 'job_detail', page_slug: slug })],\n [/^\\/packages\\/(.+)$/, ([, slug]) => ({ page_name: 'package_detail', page_slug: slug })],\n ];\n\n for (const [pattern, resolve] of patterns) {\n const match = pathname.match(pattern);\n if (match) return resolve(match);\n }\n\n const staticNames: Record<string, string> = {\n '/services': 'services',\n '/locations': 'locations',\n '/contact': 'contact',\n '/about': 'about',\n '/blog': 'blog',\n '/portal': 'portal',\n '/gallery': 'gallery',\n '/team': 'team',\n '/faq': 'faq',\n '/reviews': 'reviews',\n '/jobs': 'jobs',\n '/packages': 'packages',\n '/service-menu': 'service_menu',\n '/privacy-policy': 'privacy_policy',\n '/terms': 'terms_of_service',\n };\n\n return { page_name: staticNames[pathname] ?? 'unknown' };\n}\n\n// ---------------------------------------------------------------------------\n// Pageview tracker — must be wrapped in <Suspense> (useSearchParams)\n// ---------------------------------------------------------------------------\n\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n\n useEffect(() => {\n if (!pathname) return;\n\n const search = searchParams?.toString();\n const url = window.location.origin + pathname + (search ? `?${search}` : '');\n const { page_name, page_slug } = resolvePageInfo(pathname);\n\n posthog.capture('$pageview', {\n $current_url: url,\n page_name,\n page_path: pathname,\n ...(page_slug && { page_slug }),\n });\n }, [pathname, searchParams]);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\n/**\n * Initialises PostHog, registers account-level super properties, and fires\n * an enriched `$pageview` on every App Router navigation.\n *\n * Super properties attached to every event automatically:\n * - account_id (Keystone account ID)\n * - account_name (company_name)\n * - site_domain (window.location.hostname)\n * - environment (KEYSTONE_ENV — e.g. \"production\", \"staging\", \"local_rahuljaswa\")\n *\n * Mount once in the root layout body. One project key covers all customer\n * sites — filter by account_name or site_domain in the PostHog dashboard.\n */\nexport function PostHogProvider({ apiKey, apiHost, accountId, accountName, environment, children }: PostHogProviderProps) {\n useEffect(() => {\n posthog.init(apiKey, {\n api_host: apiHost ?? DEFAULT_HOST,\n person_profiles: 'identified_only',\n capture_pageview: false,\n });\n\n posthog.register({\n ...(accountId !== undefined && { account_id: accountId }),\n ...(accountName && { account_name: accountName }),\n ...(environment && { environment }),\n site_domain: window.location.hostname,\n });\n\n initializePostHogLogging({\n apiKey,\n apiHost: apiHost ?? DEFAULT_HOST,\n serviceName: 'keystone-customer-site',\n environment,\n accountId,\n accountName,\n });\n }, [apiKey, apiHost, accountId, accountName, environment]);\n\n useEffect(() => {\n const onWindowError = (event: ErrorEvent) => {\n logError(\n 'global-client',\n 'WINDOW_ERROR',\n {\n message: event.message || 'unknown_error',\n filename: event.filename || 'unknown_file',\n lineno: event.lineno || 0,\n colno: event.colno || 0,\n stack: event.error instanceof Error ? event.error.stack || '' : '',\n },\n { shipToPostHog: true },\n );\n };\n\n const onUnhandledRejection = (event: PromiseRejectionEvent) => {\n const reason = event.reason;\n const payload =\n reason instanceof Error\n ? { message: reason.message, stack: reason.stack || '' }\n : { message: String(reason), stack: '' };\n\n logError('global-client', 'UNHANDLED_REJECTION', payload, { shipToPostHog: true });\n };\n\n window.addEventListener('error', onWindowError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n return () => {\n window.removeEventListener('error', onWindowError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n };\n }, []);\n\n return (\n <PHProvider client={posthog}>\n <Suspense fallback={null}>\n <PostHogPageviewTracker />\n </Suspense>\n {children}\n </PHProvider>\n );\n}\n","'use client';\n\nimport { useEffect } from 'react';\nimport { usePathname } from 'next/navigation';\nimport { captureEvent } from './captureEvent';\n\ntype Props = {\n /** External booking / portal URL. When set, fires booking_cta_clicked on any click to that URL. */\n bookingUrl?: string | null;\n};\n\n/**\n * Page-level PostHog event tracker. Mount once inside PostHogProvider in\n * KeystoneRootLayout alongside MetaPixelTracker.\n *\n * Responsibilities:\n * - booking_cta_clicked: fires when any link to the booking URL is clicked,\n * capturing the page the visitor was on when they clicked.\n */\nexport function KeystoneAnalyticsTracker({ bookingUrl }: Props) {\n const pathname = usePathname();\n\n useEffect(() => {\n if (!bookingUrl) return;\n\n const handleClick = (e: MouseEvent) => {\n const anchor = (e.target as Element).closest('a');\n if (anchor?.href?.startsWith(bookingUrl)) {\n captureEvent('booking_cta_clicked', {\n source_path: pathname,\n booking_url: bookingUrl,\n });\n }\n };\n\n document.addEventListener('click', handleClick);\n return () => document.removeEventListener('click', handleClick);\n }, [bookingUrl, pathname]);\n\n return null;\n}\n","/**\n * PostHog event capture — Keystone customer sites.\n *\n * ## Naming convention\n * All events use snake_case `object_action` format.\n * Properties use snake_case as well.\n *\n * ## Event taxonomy\n * Add new events here: define the name in `KsEventName` and its required\n * properties in `KsEventProperties`. Every callsite is then type-checked.\n *\n * ## Usage\n *\n * import { captureEvent } from 'keystone-design-bootstrap/tracking';\n *\n * captureEvent('form_submitted', { form_type: 'lead' });\n * captureEvent('booking_cta_clicked', { source_path: '/services/massage', booking_url: url });\n *\n * All calls are safe no-ops when PostHog has not been initialised (e.g. no\n * POSTHOG_API_KEY configured on the server).\n *\n * ## Super properties\n * account_id, account_name, and site_domain are registered as super properties\n * by PostHogProvider and are automatically attached to every event — you do not\n * need to include them in individual captureEvent calls.\n */\n\nimport posthog from 'posthog-js';\n\n// ---------------------------------------------------------------------------\n// Event taxonomy\n// ---------------------------------------------------------------------------\n\nexport type KsEventName =\n // Booking / conversion\n | 'booking_cta_clicked'\n // Forms\n | 'form_submitted'\n | 'form_failed'\n // Chat widget\n | 'chat_opened'\n | 'chat_message_sent'\n | 'chat_message_failed'\n // Member portal — tab navigation\n | 'portal_tab_viewed'\n // Member portal — authentication flow\n | 'portal_login_started'\n | 'portal_login_step_viewed'\n | 'portal_login_step_submitted'\n | 'portal_login_step_advanced'\n | 'portal_login_back_clicked'\n | 'portal_login_identified'\n | 'portal_login_completed'\n | 'portal_login_failed';\n\nexport type KsEventProperties = {\n /** Fired when a visitor clicks any CTA that links to the external booking URL. */\n booking_cta_clicked: {\n source_path: string;\n booking_url: string;\n };\n\n /** Fired when a Keystone form is successfully submitted. */\n form_submitted: {\n /** One of: lead | job_application | marketing_list_signup */\n form_type: string;\n /** Server-generated event ID for CAPI deduplication (when present). */\n event_id?: string;\n };\n\n /** Fired when a form submission fails (validation error or network error). */\n form_failed: {\n form_type: string;\n error: string;\n };\n\n /** Fired when the chat widget is first opened by the visitor. */\n chat_opened: Record<string, never>;\n\n /** Fired when a chat message is successfully sent. */\n chat_message_sent: {\n /** Whether the visitor is authenticated (contactId present). */\n is_authenticated: boolean;\n };\n\n /** Fired when a chat message fails to send. */\n chat_message_failed: {\n error: string;\n };\n\n /** Fired when a member portal tab is opened. */\n portal_tab_viewed: {\n tab: string;\n };\n\n /** Fired when the portal login modal is opened / login flow starts. */\n portal_login_started: Record<string, never>;\n\n /** Fired whenever a login step becomes visible to the user. */\n portal_login_step_viewed: {\n step: 'identifier' | 'signin' | 'signup';\n };\n\n /** Fired when the user submits a specific login step. */\n portal_login_step_submitted: {\n step: 'identifier' | 'signin' | 'signup';\n };\n\n /** Fired when the flow transitions from one step to another state. */\n portal_login_step_advanced: {\n from_step: 'identifier' | 'signin' | 'signup';\n to_step: 'signin' | 'signup' | 'authenticated';\n reason: string;\n };\n\n /** Fired when the user explicitly navigates back to the identifier step. */\n portal_login_back_clicked: {\n from_step: 'signin' | 'signup';\n to_step: 'identifier';\n };\n\n /**\n * Fired after the identifier step resolves — we know whether the user\n * already has an account.\n */\n portal_login_identified: {\n method: 'email' | 'phone' | 'email_and_phone';\n user_exists: boolean;\n };\n\n /** Fired after the user successfully signs in or creates an account. */\n portal_login_completed: {\n flow: 'signin' | 'signup';\n };\n\n /** Fired when any step of the login flow returns an error. */\n portal_login_failed: {\n step: 'identifier' | 'signin' | 'signup';\n reason: string;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Capture helper\n// ---------------------------------------------------------------------------\n\n/**\n * Captures a typed Keystone analytics event via PostHog.\n * Safe no-op when PostHog has not been initialised.\n */\nexport function captureEvent<E extends KsEventName>(\n event: E,\n ...args: KsEventProperties[E] extends Record<string, never>\n ? []\n : [properties: KsEventProperties[E]]\n): void {\n posthog.capture(event, args[0] as Record<string, unknown>);\n}\n\n/**\n * Captures an app-specific (\"custom\") analytics event via PostHog.\n *\n * Unlike `captureEvent` — which is restricted to the shared, type-checked\n * Keystone taxonomy (`KsEventName`) — this is a thin, open-ended escape hatch\n * for product-specific funnels that don't belong in the shared taxonomy\n * (e.g. the Grader's `grader_scan_started`, or any one-off consumer app event).\n * It keeps those events out of the shared union while still flowing through the\n * same initialised PostHog instance, so account super properties and config are\n * applied identically.\n *\n * Conventions (not enforced, but please follow):\n * - snake_case `object_action` names, prefixed with your app/feature so events\n * are easy to group and never collide with the shared taxonomy\n * (e.g. `grader_scan_started`; `portal_*`, `form_*`, `chat_*`, `booking_*`\n * are reserved by `captureEvent`).\n * - snake_case property keys.\n *\n * `account_id` / `account_name` / `site_domain` super properties are attached\n * automatically by PostHogProvider. Safe no-op when PostHog isn't initialised.\n *\n * For events that are reused across multiple sites, promote them into the typed\n * `KsEventName` taxonomy above and use `captureEvent` instead.\n */\nexport function captureCustomEvent(\n event: string,\n properties?: Record<string, unknown>,\n): void {\n posthog.capture(event, properties);\n}\n","const GTM_SCRIPT = (containerId: string) => `\n (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n })(window,document,'script','dataLayer','${containerId.replace(/'/g, \"\\\\'\")}');\n`;\n\nexport type GoogleTagManagerProps = {\n /** GTM container public ID (e.g. GTM-ABC123). */\n containerId: string | null | undefined;\n};\n\n/**\n * Renders Google Tag Manager script + noscript fallback.\n * Mount once at root layout level when a container is provisioned.\n */\nexport function GoogleTagManager({ containerId }: GoogleTagManagerProps) {\n const raw = typeof containerId === 'string' ? containerId.trim() : '';\n const id = raw && raw !== 'null' && /^GTM-[A-Z0-9]+$/i.test(raw) ? raw : '';\n\n if (!id) {\n return null;\n }\n\n return (\n <>\n <script id=\"google-tag-manager\" dangerouslySetInnerHTML={{ __html: GTM_SCRIPT(id) }} />\n <noscript>\n <iframe\n src={`https://www.googletagmanager.com/ns.html?id=${id}`}\n height=\"0\"\n width=\"0\"\n style={{ display: 'none', visibility: 'hidden' }}\n title=\"google-tag-manager\"\n />\n </noscript>\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAC1B,OAAO,YAAY;;;ACDnB,SAAS,YAAY;AACrB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,sBAAsB;AAExD,IAAM,yBAAyB,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R,mBAAc,WAAW,aAAa;AACxC,qBAAa,uBAAuB;AAAA,UAClC,aAAa;AAAA,UACb,aAAa;AAAA,QACf,CAAC;AAAA,MACH;AAAA,IACF;AAEA,aAAS,iBAAiB,SAAS,WAAW;AAC9C,WAAO,MAAM,SAAS,oBAAoB,SAAS,WAAW;AAAA,EAChE,GAAG,CAAC,YAAY,QAAQ,CAAC;AAEzB,SAAO;AACT;;;AExCA,IAAM,aAAa,CAAC,gBAAwB;AAAA;AAAA;AAAA;AAAA;AAAA,6CAKC,YAAY,QAAQ,MAAM,KAAK,CAAC;AAAA;AAYtE,SAAS,iBAAiB,EAAE,YAAY,GAA0B;AACvE,QAAM,MAAM,OAAO,gBAAgB,WAAW,YAAY,KAAK,IAAI;AACnE,QAAM,KAAK,OAAO,QAAQ,UAAU,mBAAmB,KAAK,GAAG,IAAI,MAAM;AAEzE,MAAI,CAAC,IAAI;AACP,WAAO;AAAA,EACT;AAEA,SACE,0DACE,oCAAC,YAAO,IAAG,sBAAqB,yBAAyB,EAAE,QAAQ,WAAW,EAAE,EAAE,GAAG,GACrF,oCAAC,kBACC;AAAA,IAAC;AAAA;AAAA,MACC,KAAK,+CAA+C,EAAE;AAAA,MACtD,QAAO;AAAA,MACP,OAAM;AAAA,MACN,OAAO,EAAE,SAAS,QAAQ,YAAY,SAAS;AAAA,MAC/C,OAAM;AAAA;AAAA,EACR,CACF,CACF;AAEJ;","names":["useEffect","useEffect","useEffect","usePathname","usePathname","useEffect","useEffect","usePathname","posthog","usePathname","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../../src/tracking/MetaPixel.tsx","../../src/tracking/logging.ts","../../src/tracking/firePixelEvent.ts","../../src/tracking/MetaPixelTracker.tsx","../../src/tracking/PostHogProvider.tsx","../../src/tracking/KeystoneAnalyticsTracker.tsx","../../src/tracking/captureEvent.ts","../../src/tracking/GoogleTagManager.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport Script from 'next/script';\nimport { firePixelEvent } from './firePixelEvent';\nimport { log } from './logging';\n\nconst FBEVENTS_URL = 'https://connect.facebook.net/en_US/fbevents.js';\n\nconst PIXEL_SCRIPT = (pixelId: string) => `\n !function(f,b,e,v,n,t,s)\n {if(f.fbq)return;n=f.fbq=function(){n.callMethod?\n n.callMethod.apply(n,arguments):n.queue.push(arguments)};\n if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\n n.queue=[];t=b.createElement(e);t.async=!0;\n t.src=v;s=b.getElementsByTagName(e)[0];\n s.parentNode.insertBefore(t,s)}(window, document,'script','${FBEVENTS_URL}');\n fbq('init', '${pixelId.replace(/'/g, \"\\\\'\")}');\n window.__ks_pixel_ids = window.__ks_pixel_ids || [];\n if (window.__ks_pixel_ids.indexOf('${pixelId.replace(/'/g, \"\\\\'\")}') === -1) {\n window.__ks_pixel_ids.push('${pixelId.replace(/'/g, \"\\\\'\")}');\n }\n`;\n\nexport type MetaPixelProps = {\n /** Meta Pixel ID. When null/undefined, nothing is rendered. */\n pixelId: string | null | undefined;\n};\n\n/**\n * Renders the Meta (Facebook) Pixel base code: loads fbevents.js, initializes\n * the pixel, and tracks PageView. Use in the root layout when ads config\n * provides a meta_pixel_id.\n */\nexport function MetaPixel({ pixelId }: MetaPixelProps) {\n const raw = typeof pixelId === 'string' ? pixelId.trim() : '';\n const id = raw && raw !== 'null' && /^\\d+$/.test(raw) ? raw : '';\n\n useEffect(() => {\n if (!id) return;\n log('meta-pixel', 'PIXEL_INIT', { pixelId: id }, { shipToPostHog: true });\n firePixelEvent('PageView');\n }, [id]);\n\n if (!id) {\n return null;\n }\n\n return (\n <>\n <Script\n id=\"meta-pixel\"\n strategy=\"afterInteractive\"\n dangerouslySetInnerHTML={{ __html: PIXEL_SCRIPT(id) }}\n />\n <noscript>\n {/* eslint-disable-next-line @next/next/no-img-element -- 1x1 tracking pixel for no-JS fallback; next/image not applicable in noscript */}\n <img\n height={1}\n width={1}\n style={{ display: 'none' }}\n src={`https://www.facebook.com/tr?id=${id}&ev=PageView&noscript=1`}\n alt=\"\"\n />\n </noscript>\n </>\n );\n}\n","'use client';\n\nimport { logs } from '@opentelemetry/api-logs';\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';\nimport { resourceFromAttributes } from '@opentelemetry/resources';\nimport { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';\n\nconst BUILD_CONSOLE_DISABLED = process.env.NEXT_PUBLIC_LOGGING_DISABLED === '1';\nconst BUILD_POSTHOG_DISABLED = process.env.NEXT_PUBLIC_POSTHOG_LOGGING_DISABLED === '1';\ninterface LoggingWindow extends Window {\n __loggingDisabled?: boolean;\n __posthogLoggingDisabled?: boolean;\n}\n\nexport type LogLevel = 'info' | 'warn' | 'error';\n\nexport type LogOptions = {\n /** Send this log payload to PostHog Logs product. */\n shipToPostHog?: boolean;\n};\n\ntype OTelInitOptions = {\n apiKey: string;\n apiHost?: string;\n serviceName?: string;\n environment?: string;\n accountId?: number;\n accountName?: string;\n};\n\ntype PendingShipLog = {\n level: LogLevel;\n channel: string;\n event: string;\n detail: Record<string, unknown>;\n};\n\nconst MAX_PENDING_POSTHOG_LOGS = 500;\nlet otelProvider: LoggerProvider | null = null;\nlet otelLogger: ReturnType<typeof logs.getLogger> | null = null;\nlet otelInitFingerprint = '';\nconst pendingPostHogLogs: PendingShipLog[] = [];\nconst browserConsole = globalThis?.['console'];\n\n/**\n * Channel → accent colour. Unregistered channels fall through to gray.\n */\nexport const CHANNEL_COLORS: Record<string, string> = {\n // Shared diagnostics\n 'global-client': '#d2a8ff',\n\n // Section pins (desktop)\n 'every-channel-pin': '#9febd7',\n 'hero-pin': '#6ecc8b',\n 'pricing-pin': '#399587',\n 'product-screens-pin': '#4fafa0',\n 'social-proof-pin': '#ffbb8a',\n 'value-props-pin': '#e0a733',\n 'work-pin': '#f57e56',\n\n // Section pins (mobile)\n 'mobile-every-channel-pin': '#7ed9c6',\n 'mobile-hero-pin': '#f0eee6',\n 'mobile-pricing-pin': '#80d4ff',\n 'mobile-product-screens-pin': '#3a9085',\n 'mobile-social-proof-pin': '#ffd580',\n 'mobile-value-props-pin': '#4fafa0',\n};\n\nfunction flattenAttributes(input: Record<string, unknown>, prefix = ''): Record<string, string | number | boolean> {\n const output: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(input)) {\n const nextKey = prefix ? `${prefix}.${key}` : key;\n if (value === null || value === undefined) continue;\n\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n output[nextKey] = value;\n continue;\n }\n\n if (Array.isArray(value)) {\n output[nextKey] = JSON.stringify(value);\n continue;\n }\n\n if (typeof value === 'object') {\n Object.assign(output, flattenAttributes(value as Record<string, unknown>, nextKey));\n continue;\n }\n\n output[nextKey] = String(value);\n }\n\n return output;\n}\n\nfunction stripTrailingSlash(host: string): string {\n return host.replace(/\\/+$/, '');\n}\n\nfunction enqueuePendingPostHogLog(entry: PendingShipLog): void {\n if (pendingPostHogLogs.length >= MAX_PENDING_POSTHOG_LOGS) {\n pendingPostHogLogs.shift();\n }\n pendingPostHogLogs.push(entry);\n}\n\nfunction flushPendingPostHogLogs(): void {\n if (!otelLogger || pendingPostHogLogs.length === 0) return;\n\n while (pendingPostHogLogs.length > 0) {\n const entry = pendingPostHogLogs.shift();\n if (!entry) break;\n emitToPostHog(entry.level, entry.channel, entry.event, entry.detail);\n }\n}\n\nexport function initializePostHogLogging(options: OTelInitOptions): void {\n if (typeof window === 'undefined') return;\n if (!options.apiKey?.trim()) return;\n\n const apiHost = stripTrailingSlash(options.apiHost?.trim() || 'https://us.i.posthog.com');\n const serviceName = options.serviceName?.trim() || 'keystone-customer-site';\n const environment = options.environment?.trim() || 'production';\n const fingerprint = `${apiHost}|${options.apiKey}|${serviceName}|${environment}|${options.accountId ?? ''}|${options.accountName ?? ''}`;\n if (otelLogger && otelInitFingerprint === fingerprint) return;\n\n if (otelProvider) {\n // Cleanly replace logger provider when config changes.\n void otelProvider.shutdown().catch(() => {});\n otelProvider = null;\n otelLogger = null;\n }\n\n const baseAttributes: Record<string, string | number | boolean> = {\n 'service.name': serviceName,\n environment,\n site_domain: window.location.hostname,\n };\n if (options.accountId !== undefined) baseAttributes.account_id = options.accountId;\n if (options.accountName) baseAttributes.account_name = options.accountName;\n\n const exporter = new OTLPLogExporter({\n url: `${apiHost}/i/v1/logs?token=${encodeURIComponent(options.apiKey)}`,\n headers: {\n // Keep request \"simple\" to avoid CORS preflight in browser.\n 'Content-Type': 'text/plain',\n },\n });\n\n otelProvider = new LoggerProvider({\n resource: resourceFromAttributes(baseAttributes),\n processors: [new BatchLogRecordProcessor(exporter)],\n });\n\n logs.setGlobalLoggerProvider(otelProvider);\n otelLogger = logs.getLogger(serviceName);\n otelInitFingerprint = fingerprint;\n flushPendingPostHogLogs();\n}\n\nfunction isConsoleEnabled(): boolean {\n if (BUILD_CONSOLE_DISABLED) return false;\n if (typeof window === 'undefined') return true;\n return (window as LoggingWindow).__loggingDisabled !== true;\n}\n\nfunction isPostHogShippingEnabled(): boolean {\n if (BUILD_POSTHOG_DISABLED) return false;\n if (typeof window === 'undefined') return false;\n return (window as LoggingWindow).__posthogLoggingDisabled !== true;\n}\n\nfunction formatDetail(detail: Record<string, unknown>): string {\n return Object.entries(detail)\n .map(([k, v]) => `${k}=${typeof v === 'number' ? v.toFixed(4) : String(v)}`)\n .join(' ');\n}\n\nfunction emitConsole(\n level: LogLevel,\n channel: string,\n event: string,\n detail: Record<string, unknown>,\n): void {\n const color = CHANNEL_COLORS[channel] ?? '#aaa';\n const detailStr = formatDetail(detail);\n const message = `%c[${channel}] %c${event}%c ${detailStr}`;\n const channelStyle = `color:${color}; font-weight:bold`;\n const eventStyle = level === 'error'\n ? 'color:#e94e4e; font-weight:bold'\n : level === 'warn'\n ? 'color:#f5a623; font-weight:bold'\n : 'color:#fff; font-weight:bold';\n const detailStyle = 'color:#999; font-weight:normal';\n\n if (level === 'error') {\n browserConsole?.error?.(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n if (level === 'warn') {\n browserConsole?.warn?.(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n browserConsole?.log?.(message, channelStyle, eventStyle, detailStyle);\n}\n\nfunction emitToPostHog(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>): boolean {\n if (!otelLogger) return false;\n\n const severityText = level === 'warn' ? 'WARNING' : level === 'error' ? 'ERROR' : 'INFO';\n const attributes = flattenAttributes({ channel, ...detail });\n\n otelLogger.emit({\n severityText,\n body: event,\n attributes,\n });\n return true;\n}\n\nfunction emit(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>, options?: LogOptions): void {\n const shouldShip = (options?.shipToPostHog ?? level !== 'info') && isPostHogShippingEnabled();\n // Keep warn/error visible even when regular logs are muted.\n if (level !== 'info' || isConsoleEnabled()) {\n emitConsole(level, channel, event, detail);\n }\n if (shouldShip) {\n const shipped = emitToPostHog(level, channel, event, detail);\n if (!shipped) {\n enqueuePendingPostHogLog({ level, channel, event, detail });\n }\n }\n}\n\nexport function log(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('info', channel, event, detail, options);\n}\n\nexport function warn(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('warn', channel, event, detail, options);\n}\n\nexport function error(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {\n emit('error', channel, event, detail, options);\n}\n","type FbqFn = (method: string, ...args: unknown[]) => void;\nimport { log, warn } from './logging';\n\nexport type PixelEvent = 'PageView' | 'ViewContent' | 'InitiateCheckout' | 'Lead';\n\nexport interface PixelEventParams {\n contentName?: string;\n contentCategory?: string;\n}\n\n/** Raw (unhashed) user identifiers for advanced matching. */\nexport interface PixelUserData {\n email?: string | null;\n phone?: string | null;\n}\n\n// Hashed user data stored in sessionStorage for the duration of the browsing session.\n// Keyed by a short namespace to avoid collisions.\nconst STORAGE_KEY = 'ks_pud';\n\nasync function sha256Hex(str: string): Promise<string> {\n const buffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str));\n return Array.from(new Uint8Array(buffer))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nfunction getFbq(): FbqFn | undefined {\n if (typeof window === 'undefined') return undefined;\n return (window as Window & { fbq?: FbqFn }).fbq;\n}\n\n/** Read the pixel IDs registered by MetaPixel via the inline init script. */\nfunction getRegisteredPixelIds(): string[] {\n return (window as Window & { __ks_pixel_ids?: string[] }).__ks_pixel_ids ?? [];\n}\n\n/** Apply stored hashed user data to every configured Meta Pixel. */\nfunction applyStoredUserData(fbq: FbqFn): void {\n try {\n const raw = sessionStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n const hashed = JSON.parse(raw) as Record<string, string>;\n if (Object.keys(hashed).length === 0) return;\n getRegisteredPixelIds().forEach((id) => fbq('init', id, hashed));\n } catch {\n // sessionStorage unavailable or JSON malformed — safe to ignore\n }\n}\n\n/**\n * Hash and store user identifiers so they are automatically included in all\n * subsequent pixel events for this browser session. Call this as soon as\n * identity is known (e.g. contact form submission, portal login step 1).\n */\nexport async function setPixelUserData(userData: PixelUserData): Promise<void> {\n const hashed: Record<string, string> = {};\n\n if (userData.email) {\n hashed.em = await sha256Hex(userData.email.trim().toLowerCase());\n }\n if (userData.phone) {\n const digits = userData.phone.replace(/\\D/g, '');\n if (digits) hashed.ph = await sha256Hex(digits);\n }\n\n if (Object.keys(hashed).length === 0) return;\n\n try {\n sessionStorage.setItem(STORAGE_KEY, JSON.stringify(hashed));\n } catch {\n // sessionStorage unavailable — still apply to fbq for this page load\n }\n\n const fbq = getFbq();\n if (fbq) {\n getRegisteredPixelIds().forEach((id) => fbq('init', id, hashed));\n }\n}\n\n/**\n * Single entry point for all client-side Meta Pixel event fires.\n * Automatically applies any stored user identity before firing so that Meta\n * can match events to known users across the entire session.\n * Silently no-ops if fbq is not loaded (pixel not configured for this site).\n *\n * @param eventId - Optional server-side event ID for browser/server deduplication.\n * Pass the `eventId` returned by the form submission API so Meta can match and\n * deduplicate the browser Lead event against the server-side CAPI Lead event.\n * Format: fbq('track', event, params, { eventID: eventId })\n */\nexport function firePixelEvent(event: PixelEvent, params?: PixelEventParams, eventId?: string): void {\n const fbq = getFbq();\n if (!fbq) {\n warn('meta-pixel', 'PIXEL_EVENT_SKIPPED_FBQ_NOT_LOADED', { event });\n return;\n }\n\n // Re-apply stored identity before every event so user data is included\n // even on events that fire after a client-side navigation (PageView, ViewContent, etc.)\n applyStoredUserData(fbq);\n\n const normalized: Record<string, string> = {};\n if (params?.contentName) normalized.content_name = params.contentName;\n if (params?.contentCategory) normalized.content_category = params.contentCategory;\n\n const customData = Object.keys(normalized).length > 0 ? normalized : undefined;\n const eventData = eventId ? { eventID: eventId } : undefined;\n\n log('meta-pixel', 'PIXEL_EVENT_FIRED', {\n event,\n ...normalized,\n ...(eventId ? { eventId } : {}),\n }, { shipToPostHog: true });\n fbq('track', event, customData, eventData);\n}\n","'use client';\n\nimport { useEffect } from 'react';\nimport { usePathname } from 'next/navigation';\nimport { firePixelEvent } from './firePixelEvent';\n\ntype RouteRule = {\n pattern: RegExp;\n getParams: (match: RegExpMatchArray) => { contentName: string; contentCategory: string };\n};\n\nfunction slugToTitle(slug: string): string {\n return slug\n .split('-')\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n// Checked in order — first match wins. More specific patterns come first.\nconst ROUTE_RULES: RouteRule[] = [\n {\n pattern: /^\\/services\\/(.+)$/,\n getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Service' }),\n },\n {\n pattern: /^\\/locations\\/(.+)$/,\n getParams: ([, slug]) => ({ contentName: slugToTitle(slug), contentCategory: 'Location' }),\n },\n {\n pattern: /^\\/services$/,\n getParams: () => ({ contentName: 'Services', contentCategory: 'Services' }),\n },\n {\n pattern: /^\\/locations$/,\n getParams: () => ({ contentName: 'Locations', contentCategory: 'Locations' }),\n },\n {\n pattern: /^\\/portal$/,\n getParams: () => ({ contentName: 'Member Portal', contentCategory: 'Pricing' }),\n },\n {\n pattern: /^\\/service-menu$/,\n getParams: () => ({ contentName: 'Service Menu', contentCategory: 'Pricing' }),\n },\n {\n pattern: /^\\/faq$/,\n getParams: () => ({ contentName: 'FAQ', contentCategory: 'FAQ' }),\n },\n {\n pattern: /^\\/contact$/,\n getParams: () => ({ contentName: 'Contact', contentCategory: 'Contact' }),\n },\n];\n\ntype Props = {\n /** External booking URL. When set, fires InitiateCheckout on any click targeting that URL. */\n bookingUrl?: string | null;\n};\n\n/**\n * Single client-side tracker placed once in KeystoneRootLayout.\n * - Fires ViewContent on every route change for known page patterns.\n * - Fires InitiateCheckout whenever a visitor clicks a link to the external booking URL.\n *\n * Portal booking tab tracking is handled directly inside PortalPage via PortalTabTracker\n * since intent is only established when the Booking tab is explicitly opened.\n */\nexport function MetaPixelTracker({ bookingUrl }: Props) {\n const pathname = usePathname();\n\n useEffect(() => {\n for (const rule of ROUTE_RULES) {\n const match = pathname.match(rule.pattern);\n if (match) {\n const { contentName, contentCategory } = rule.getParams(match);\n firePixelEvent('ViewContent', { contentName, contentCategory });\n break;\n }\n }\n }, [pathname]);\n\n useEffect(() => {\n if (!bookingUrl) return;\n\n const handleClick = (e: MouseEvent) => {\n const anchor = (e.target as Element).closest('a');\n if (anchor?.href?.startsWith(bookingUrl)) {\n firePixelEvent('InitiateCheckout');\n }\n };\n\n document.addEventListener('click', handleClick);\n return () => document.removeEventListener('click', handleClick);\n }, [bookingUrl]);\n\n return null;\n}\n","'use client';\n\nimport posthog from 'posthog-js';\nimport { PostHogProvider as PHProvider } from 'posthog-js/react';\nimport { useEffect, Suspense } from 'react';\nimport { usePathname, useSearchParams } from 'next/navigation';\nimport { error as logError, initializePostHogLogging } from './logging';\n\nconst DEFAULT_HOST = 'https://us.i.posthog.com';\n\nexport type PostHogProviderProps = {\n apiKey: string;\n apiHost?: string;\n /** Keystone account ID — attached to every event as a super property. */\n accountId?: number;\n /** Keystone account name (company_name) — attached to every event as a super property. */\n accountName?: string;\n /**\n * Environment identifier from KEYSTONE_ENV on the Rails server (e.g. \"production\", \"staging\",\n * \"development\"). Registered as a super property so events can be filtered by environment\n * in PostHog and the sync job only imports data for the matching environment.\n */\n environment?: string;\n children: React.ReactNode;\n};\n\n// ---------------------------------------------------------------------------\n// Page name resolution\n// ---------------------------------------------------------------------------\n\ntype PageInfo = { page_name: string; page_slug?: string };\n\nfunction resolvePageInfo(pathname: string): PageInfo {\n if (pathname === '/') return { page_name: 'home' };\n\n const patterns: Array<[RegExp, (m: RegExpMatchArray) => PageInfo]> = [\n [/^\\/services\\/(.+)$/, ([, slug]) => ({ page_name: 'service_detail', page_slug: slug })],\n [/^\\/locations\\/(.+)$/, ([, slug]) => ({ page_name: 'location_detail', page_slug: slug })],\n [/^\\/blog\\/(.+)$/, ([, slug]) => ({ page_name: 'blog_post', page_slug: slug })],\n [/^\\/jobs\\/(.+)$/, ([, slug]) => ({ page_name: 'job_detail', page_slug: slug })],\n [/^\\/packages\\/(.+)$/, ([, slug]) => ({ page_name: 'package_detail', page_slug: slug })],\n ];\n\n for (const [pattern, resolve] of patterns) {\n const match = pathname.match(pattern);\n if (match) return resolve(match);\n }\n\n const staticNames: Record<string, string> = {\n '/services': 'services',\n '/locations': 'locations',\n '/contact': 'contact',\n '/about': 'about',\n '/blog': 'blog',\n '/portal': 'portal',\n '/gallery': 'gallery',\n '/team': 'team',\n '/faq': 'faq',\n '/reviews': 'reviews',\n '/jobs': 'jobs',\n '/packages': 'packages',\n '/service-menu': 'service_menu',\n '/privacy-policy': 'privacy_policy',\n '/terms': 'terms_of_service',\n };\n\n return { page_name: staticNames[pathname] ?? 'unknown' };\n}\n\n// ---------------------------------------------------------------------------\n// Pageview tracker — must be wrapped in <Suspense> (useSearchParams)\n// ---------------------------------------------------------------------------\n\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n\n useEffect(() => {\n if (!pathname) return;\n\n const search = searchParams?.toString();\n const url = window.location.origin + pathname + (search ? `?${search}` : '');\n const { page_name, page_slug } = resolvePageInfo(pathname);\n\n posthog.capture('$pageview', {\n $current_url: url,\n page_name,\n page_path: pathname,\n ...(page_slug && { page_slug }),\n });\n }, [pathname, searchParams]);\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\n/**\n * Initialises PostHog, registers account-level super properties, and fires\n * an enriched `$pageview` on every App Router navigation.\n *\n * Super properties attached to every event automatically:\n * - account_id (Keystone account ID)\n * - account_name (company_name)\n * - site_domain (window.location.hostname)\n * - environment (KEYSTONE_ENV — e.g. \"production\", \"staging\", \"local_rahuljaswa\")\n *\n * Mount once in the root layout body. One project key covers all customer\n * sites — filter by account_name or site_domain in the PostHog dashboard.\n */\nexport function PostHogProvider({ apiKey, apiHost, accountId, accountName, environment, children }: PostHogProviderProps) {\n useEffect(() => {\n posthog.init(apiKey, {\n api_host: apiHost ?? DEFAULT_HOST,\n person_profiles: 'identified_only',\n capture_pageview: false,\n });\n\n posthog.register({\n ...(accountId !== undefined && { account_id: accountId }),\n ...(accountName && { account_name: accountName }),\n ...(environment && { environment }),\n site_domain: window.location.hostname,\n });\n\n initializePostHogLogging({\n apiKey,\n apiHost: apiHost ?? DEFAULT_HOST,\n serviceName: 'keystone-customer-site',\n environment,\n accountId,\n accountName,\n });\n }, [apiKey, apiHost, accountId, accountName, environment]);\n\n useEffect(() => {\n const onWindowError = (event: ErrorEvent) => {\n logError(\n 'global-client',\n 'WINDOW_ERROR',\n {\n message: event.message || 'unknown_error',\n filename: event.filename || 'unknown_file',\n lineno: event.lineno || 0,\n colno: event.colno || 0,\n stack: event.error instanceof Error ? event.error.stack || '' : '',\n },\n { shipToPostHog: true },\n );\n };\n\n const onUnhandledRejection = (event: PromiseRejectionEvent) => {\n const reason = event.reason;\n const payload =\n reason instanceof Error\n ? { message: reason.message, stack: reason.stack || '' }\n : { message: String(reason), stack: '' };\n\n logError('global-client', 'UNHANDLED_REJECTION', payload, { shipToPostHog: true });\n };\n\n window.addEventListener('error', onWindowError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n return () => {\n window.removeEventListener('error', onWindowError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n };\n }, []);\n\n return (\n <PHProvider client={posthog}>\n <Suspense fallback={null}>\n <PostHogPageviewTracker />\n </Suspense>\n {children}\n </PHProvider>\n );\n}\n","'use client';\n\nimport { useEffect } from 'react';\nimport { usePathname } from 'next/navigation';\nimport { captureEvent } from './captureEvent';\n\ntype Props = {\n /** External booking / portal URL. When set, fires booking_cta_clicked on any click to that URL. */\n bookingUrl?: string | null;\n};\n\n/**\n * Page-level PostHog event tracker. Mount once inside PostHogProvider in\n * KeystoneRootLayout alongside MetaPixelTracker.\n *\n * Responsibilities:\n * - booking_cta_clicked: fires when any link to the booking URL is clicked,\n * capturing the page the visitor was on when they clicked.\n */\nexport function KeystoneAnalyticsTracker({ bookingUrl }: Props) {\n const pathname = usePathname();\n\n useEffect(() => {\n if (!bookingUrl) return;\n\n const handleClick = (e: MouseEvent) => {\n const anchor = (e.target as Element).closest('a');\n if (anchor?.href?.startsWith(bookingUrl)) {\n captureEvent('booking_cta_clicked', {\n source_path: pathname,\n booking_url: bookingUrl,\n });\n }\n };\n\n document.addEventListener('click', handleClick);\n return () => document.removeEventListener('click', handleClick);\n }, [bookingUrl, pathname]);\n\n return null;\n}\n","/**\n * PostHog event capture — Keystone customer sites.\n *\n * ## Naming convention\n * All events use snake_case `object_action` format.\n * Properties use snake_case as well.\n *\n * ## Event taxonomy\n * Add new events here: define the name in `KsEventName` and its required\n * properties in `KsEventProperties`. Every callsite is then type-checked.\n *\n * ## Usage\n *\n * import { captureEvent } from 'keystone-design-bootstrap/tracking';\n *\n * captureEvent('form_submitted', { form_type: 'lead' });\n * captureEvent('booking_cta_clicked', { source_path: '/services/massage', booking_url: url });\n *\n * All calls are safe no-ops when PostHog has not been initialised (e.g. no\n * POSTHOG_API_KEY configured on the server).\n *\n * ## Super properties\n * account_id, account_name, and site_domain are registered as super properties\n * by PostHogProvider and are automatically attached to every event — you do not\n * need to include them in individual captureEvent calls.\n */\n\nimport posthog from 'posthog-js';\n\n// ---------------------------------------------------------------------------\n// Event taxonomy\n// ---------------------------------------------------------------------------\n\nexport type KsEventName =\n // Booking / conversion\n | 'booking_cta_clicked'\n // Forms\n | 'form_submitted'\n | 'form_failed'\n // Chat widget\n | 'chat_opened'\n | 'chat_message_sent'\n | 'chat_message_failed'\n // Member portal — tab navigation\n | 'portal_tab_viewed'\n // Member portal — authentication flow\n | 'portal_login_started'\n | 'portal_login_step_viewed'\n | 'portal_login_step_submitted'\n | 'portal_login_step_advanced'\n | 'portal_login_back_clicked'\n | 'portal_login_identified'\n | 'portal_login_completed'\n | 'portal_login_failed';\n\nexport type KsEventProperties = {\n /** Fired when a visitor clicks any CTA that links to the external booking URL. */\n booking_cta_clicked: {\n source_path: string;\n booking_url: string;\n };\n\n /** Fired when a Keystone form is successfully submitted. */\n form_submitted: {\n /** One of: lead | job_application | marketing_list_signup */\n form_type: string;\n /** Server-generated event ID for CAPI deduplication (when present). */\n event_id?: string;\n };\n\n /** Fired when a form submission fails (validation error or network error). */\n form_failed: {\n form_type: string;\n error: string;\n };\n\n /** Fired when the chat widget is first opened by the visitor. */\n chat_opened: Record<string, never>;\n\n /** Fired when a chat message is successfully sent. */\n chat_message_sent: {\n /** Whether the visitor is authenticated (contactId present). */\n is_authenticated: boolean;\n };\n\n /** Fired when a chat message fails to send. */\n chat_message_failed: {\n error: string;\n };\n\n /** Fired when a member portal tab is opened. */\n portal_tab_viewed: {\n tab: string;\n };\n\n /** Fired when the portal login modal is opened / login flow starts. */\n portal_login_started: Record<string, never>;\n\n /** Fired whenever a login step becomes visible to the user. */\n portal_login_step_viewed: {\n step: 'identifier' | 'signin' | 'signup';\n };\n\n /** Fired when the user submits a specific login step. */\n portal_login_step_submitted: {\n step: 'identifier' | 'signin' | 'signup';\n };\n\n /** Fired when the flow transitions from one step to another state. */\n portal_login_step_advanced: {\n from_step: 'identifier' | 'signin' | 'signup';\n to_step: 'signin' | 'signup' | 'authenticated';\n reason: string;\n };\n\n /** Fired when the user explicitly navigates back to the identifier step. */\n portal_login_back_clicked: {\n from_step: 'signin' | 'signup';\n to_step: 'identifier';\n };\n\n /**\n * Fired after the identifier step resolves — we know whether the user\n * already has an account.\n */\n portal_login_identified: {\n method: 'email' | 'phone' | 'email_and_phone';\n user_exists: boolean;\n };\n\n /** Fired after the user successfully signs in or creates an account. */\n portal_login_completed: {\n flow: 'signin' | 'signup';\n };\n\n /** Fired when any step of the login flow returns an error. */\n portal_login_failed: {\n step: 'identifier' | 'signin' | 'signup';\n reason: string;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Capture helper\n// ---------------------------------------------------------------------------\n\n/**\n * Captures a typed Keystone analytics event via PostHog.\n * Safe no-op when PostHog has not been initialised.\n */\nexport function captureEvent<E extends KsEventName>(\n event: E,\n ...args: KsEventProperties[E] extends Record<string, never>\n ? []\n : [properties: KsEventProperties[E]]\n): void {\n posthog.capture(event, args[0] as Record<string, unknown>);\n}\n\n/**\n * Captures an app-specific (\"custom\") analytics event via PostHog.\n *\n * Unlike `captureEvent` — which is restricted to the shared, type-checked\n * Keystone taxonomy (`KsEventName`) — this is a thin, open-ended escape hatch\n * for product-specific funnels that don't belong in the shared taxonomy\n * (e.g. the Grader's `grader_scan_started`, or any one-off consumer app event).\n * It keeps those events out of the shared union while still flowing through the\n * same initialised PostHog instance, so account super properties and config are\n * applied identically.\n *\n * Conventions (not enforced, but please follow):\n * - snake_case `object_action` names, prefixed with your app/feature so events\n * are easy to group and never collide with the shared taxonomy\n * (e.g. `grader_scan_started`; `portal_*`, `form_*`, `chat_*`, `booking_*`\n * are reserved by `captureEvent`).\n * - snake_case property keys.\n *\n * `account_id` / `account_name` / `site_domain` super properties are attached\n * automatically by PostHogProvider. Safe no-op when PostHog isn't initialised.\n *\n * For events that are reused across multiple sites, promote them into the typed\n * `KsEventName` taxonomy above and use `captureEvent` instead.\n */\nexport function captureCustomEvent(\n event: string,\n properties?: Record<string, unknown>,\n): void {\n posthog.capture(event, properties);\n}\n","const GTM_SCRIPT = (containerId: string) => `\n (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':\n new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],\n j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=\n 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);\n })(window,document,'script','dataLayer','${containerId.replace(/'/g, \"\\\\'\")}');\n`;\n\nexport type GoogleTagManagerProps = {\n /** GTM container public ID (e.g. GTM-ABC123). */\n containerId: string | null | undefined;\n};\n\n/**\n * Renders Google Tag Manager script + noscript fallback.\n * Mount once at root layout level when a container is provisioned.\n */\nexport function GoogleTagManager({ containerId }: GoogleTagManagerProps) {\n const raw = typeof containerId === 'string' ? containerId.trim() : '';\n const id = raw && raw !== 'null' && /^GTM-[A-Z0-9]+$/i.test(raw) ? raw : '';\n\n if (!id) {\n return null;\n }\n\n return (\n <>\n <script id=\"google-tag-manager\" dangerouslySetInnerHTML={{ __html: GTM_SCRIPT(id) }} />\n <noscript>\n <iframe\n src={`https://www.googletagmanager.com/ns.html?id=${id}`}\n height=\"0\"\n width=\"0\"\n style={{ display: 'none', visibility: 'hidden' }}\n title=\"google-tag-manager\"\n />\n </noscript>\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAC1B,OAAO,YAAY;;;ACDnB,SAAS,YAAY;AACrB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,sBAAsB;AAExD,IAAM,yBAAyB,QAAQ,IAAI,iCAAiC;AAC5E,IAAM,yBAAyB,QAAQ,IAAI,yCAAyC;AA6BpF,IAAM,2BAA2B;AACjC,IAAI,eAAsC;AAC1C,IAAI,aAAuD;AAC3D,IAAI,sBAAsB;AAC1B,IAAM,qBAAuC,CAAC;AAC9C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;","names":["useEffect","useEffect","useEffect","usePathname","usePathname","useEffect","useEffect","usePathname","posthog","usePathname","useEffect"]}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import posthog from 'posthog-js';
|
|
4
4
|
import { PostHogProvider as PHProvider } from 'posthog-js/react';
|
|
5
|
-
import { useEffect, Suspense } from 'react';
|
|
5
|
+
import { useEffect, Suspense, useRef } from 'react';
|
|
6
6
|
import { usePathname, useSearchParams } from 'next/navigation';
|
|
7
7
|
import { error as logError, initializePostHogLogging } from './logging';
|
|
8
8
|
|
|
@@ -74,12 +74,28 @@ function resolvePageInfo(pathname: string): PageInfo {
|
|
|
74
74
|
function PostHogPageviewTracker() {
|
|
75
75
|
const pathname = usePathname();
|
|
76
76
|
const searchParams = useSearchParams();
|
|
77
|
+
const latestUrlRef = useRef<string | null>(null);
|
|
77
78
|
|
|
78
79
|
useEffect(() => {
|
|
79
80
|
if (!pathname) return;
|
|
80
81
|
|
|
81
82
|
const search = searchParams?.toString();
|
|
82
83
|
const url = window.location.origin + pathname + (search ? `?${search}` : '');
|
|
84
|
+
const previousUrl = latestUrlRef.current;
|
|
85
|
+
if (previousUrl && previousUrl !== url) {
|
|
86
|
+
const previousPath = (() => {
|
|
87
|
+
try {
|
|
88
|
+
return new URL(previousUrl).pathname;
|
|
89
|
+
} catch {
|
|
90
|
+
return pathname;
|
|
91
|
+
}
|
|
92
|
+
})();
|
|
93
|
+
posthog.capture('$pageleave', {
|
|
94
|
+
$current_url: previousUrl,
|
|
95
|
+
page_path: previousPath,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
latestUrlRef.current = url;
|
|
83
99
|
const { page_name, page_slug } = resolvePageInfo(pathname);
|
|
84
100
|
|
|
85
101
|
posthog.capture('$pageview', {
|
|
@@ -90,6 +106,29 @@ function PostHogPageviewTracker() {
|
|
|
90
106
|
});
|
|
91
107
|
}, [pathname, searchParams]);
|
|
92
108
|
|
|
109
|
+
useEffect(() => {
|
|
110
|
+
const onPageHide = () => {
|
|
111
|
+
const currentUrl = latestUrlRef.current;
|
|
112
|
+
if (!currentUrl) return;
|
|
113
|
+
const currentPath = (() => {
|
|
114
|
+
try {
|
|
115
|
+
return new URL(currentUrl).pathname;
|
|
116
|
+
} catch {
|
|
117
|
+
return window.location.pathname;
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
posthog.capture('$pageleave', {
|
|
121
|
+
$current_url: currentUrl,
|
|
122
|
+
page_path: currentPath,
|
|
123
|
+
});
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
window.addEventListener('pagehide', onPageHide);
|
|
127
|
+
return () => {
|
|
128
|
+
window.removeEventListener('pagehide', onPageHide);
|
|
129
|
+
};
|
|
130
|
+
}, []);
|
|
131
|
+
|
|
93
132
|
return null;
|
|
94
133
|
}
|
|
95
134
|
|
package/src/tracking/logging.ts
CHANGED
|
@@ -27,9 +27,19 @@ type OTelInitOptions = {
|
|
|
27
27
|
accountId?: number;
|
|
28
28
|
accountName?: string;
|
|
29
29
|
};
|
|
30
|
+
|
|
31
|
+
type PendingShipLog = {
|
|
32
|
+
level: LogLevel;
|
|
33
|
+
channel: string;
|
|
34
|
+
event: string;
|
|
35
|
+
detail: Record<string, unknown>;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const MAX_PENDING_POSTHOG_LOGS = 500;
|
|
30
39
|
let otelProvider: LoggerProvider | null = null;
|
|
31
40
|
let otelLogger: ReturnType<typeof logs.getLogger> | null = null;
|
|
32
41
|
let otelInitFingerprint = '';
|
|
42
|
+
const pendingPostHogLogs: PendingShipLog[] = [];
|
|
33
43
|
const browserConsole = globalThis?.['console'];
|
|
34
44
|
|
|
35
45
|
/**
|
|
@@ -89,6 +99,23 @@ function stripTrailingSlash(host: string): string {
|
|
|
89
99
|
return host.replace(/\/+$/, '');
|
|
90
100
|
}
|
|
91
101
|
|
|
102
|
+
function enqueuePendingPostHogLog(entry: PendingShipLog): void {
|
|
103
|
+
if (pendingPostHogLogs.length >= MAX_PENDING_POSTHOG_LOGS) {
|
|
104
|
+
pendingPostHogLogs.shift();
|
|
105
|
+
}
|
|
106
|
+
pendingPostHogLogs.push(entry);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function flushPendingPostHogLogs(): void {
|
|
110
|
+
if (!otelLogger || pendingPostHogLogs.length === 0) return;
|
|
111
|
+
|
|
112
|
+
while (pendingPostHogLogs.length > 0) {
|
|
113
|
+
const entry = pendingPostHogLogs.shift();
|
|
114
|
+
if (!entry) break;
|
|
115
|
+
emitToPostHog(entry.level, entry.channel, entry.event, entry.detail);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
92
119
|
export function initializePostHogLogging(options: OTelInitOptions): void {
|
|
93
120
|
if (typeof window === 'undefined') return;
|
|
94
121
|
if (!options.apiKey?.trim()) return;
|
|
@@ -130,6 +157,7 @@ export function initializePostHogLogging(options: OTelInitOptions): void {
|
|
|
130
157
|
logs.setGlobalLoggerProvider(otelProvider);
|
|
131
158
|
otelLogger = logs.getLogger(serviceName);
|
|
132
159
|
otelInitFingerprint = fingerprint;
|
|
160
|
+
flushPendingPostHogLogs();
|
|
133
161
|
}
|
|
134
162
|
|
|
135
163
|
function isConsoleEnabled(): boolean {
|
|
@@ -178,8 +206,8 @@ function emitConsole(
|
|
|
178
206
|
browserConsole?.log?.(message, channelStyle, eventStyle, detailStyle);
|
|
179
207
|
}
|
|
180
208
|
|
|
181
|
-
function emitToPostHog(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>):
|
|
182
|
-
if (!otelLogger) return;
|
|
209
|
+
function emitToPostHog(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>): boolean {
|
|
210
|
+
if (!otelLogger) return false;
|
|
183
211
|
|
|
184
212
|
const severityText = level === 'warn' ? 'WARNING' : level === 'error' ? 'ERROR' : 'INFO';
|
|
185
213
|
const attributes = flattenAttributes({ channel, ...detail });
|
|
@@ -189,6 +217,7 @@ function emitToPostHog(level: LogLevel, channel: string, event: string, detail:
|
|
|
189
217
|
body: event,
|
|
190
218
|
attributes,
|
|
191
219
|
});
|
|
220
|
+
return true;
|
|
192
221
|
}
|
|
193
222
|
|
|
194
223
|
function emit(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>, options?: LogOptions): void {
|
|
@@ -198,7 +227,10 @@ function emit(level: LogLevel, channel: string, event: string, detail: Record<st
|
|
|
198
227
|
emitConsole(level, channel, event, detail);
|
|
199
228
|
}
|
|
200
229
|
if (shouldShip) {
|
|
201
|
-
emitToPostHog(level, channel, event, detail);
|
|
230
|
+
const shipped = emitToPostHog(level, channel, event, detail);
|
|
231
|
+
if (!shipped) {
|
|
232
|
+
enqueuePendingPostHogLog({ level, channel, event, detail });
|
|
233
|
+
}
|
|
202
234
|
}
|
|
203
235
|
}
|
|
204
236
|
|