keystone-design-bootstrap 1.0.95 → 1.0.97

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.
@@ -238,4 +238,17 @@ declare function captureEvent<E extends KsEventName>(event: E, ...args: KsEventP
238
238
  */
239
239
  declare function captureCustomEvent(event: string, properties?: Record<string, unknown>): void;
240
240
 
241
- export { GoogleTagManager, type GoogleTagManagerProps, KeystoneAnalyticsTracker, type KsEventName, type KsEventProperties, MetaPixel, type MetaPixelProps, MetaPixelTracker, type PixelEvent, type PixelEventParams, type PixelUserData, PostHogProvider, type PostHogProviderProps, captureCustomEvent, captureEvent, firePixelEvent, setPixelUserData };
241
+ type LogLevel = 'info' | 'warn' | 'error';
242
+ type LogOptions = {
243
+ /** Send this log payload to PostHog Logs product. */
244
+ shipToPostHog?: boolean;
245
+ };
246
+ /**
247
+ * Channel → accent colour. Unregistered channels fall through to gray.
248
+ */
249
+ declare const CHANNEL_COLORS: Record<string, string>;
250
+ declare function log(channel: string, event: string, detail?: Record<string, unknown>, options?: LogOptions): void;
251
+ declare function warn(channel: string, event: string, detail?: Record<string, unknown>, options?: LogOptions): void;
252
+ declare function error(channel: string, event: string, detail?: Record<string, unknown>, options?: LogOptions): void;
253
+
254
+ export { CHANNEL_COLORS, GoogleTagManager, type GoogleTagManagerProps, KeystoneAnalyticsTracker, type KsEventName, type KsEventProperties, type LogLevel, type LogOptions, MetaPixel, type MetaPixelProps, MetaPixelTracker, type PixelEvent, type PixelEventParams, type PixelUserData, PostHogProvider, type PostHogProviderProps, captureCustomEvent, captureEvent, error, firePixelEvent, log, setPixelUserData, warn };
@@ -194,6 +194,159 @@ import posthog from "posthog-js";
194
194
  import { PostHogProvider as PHProvider } from "posthog-js/react";
195
195
  import { useEffect as useEffect2, Suspense } from "react";
196
196
  import { usePathname as usePathname2, useSearchParams } from "next/navigation";
197
+
198
+ // src/tracking/logging.ts
199
+ import { logs } from "@opentelemetry/api-logs";
200
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
201
+ import { resourceFromAttributes } from "@opentelemetry/resources";
202
+ import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
203
+ var BUILD_CONSOLE_DISABLED = process.env.NEXT_PUBLIC_LOGGING_DISABLED === "1";
204
+ var BUILD_POSTHOG_DISABLED = process.env.NEXT_PUBLIC_POSTHOG_LOGGING_DISABLED === "1";
205
+ var otelProvider = null;
206
+ var otelLogger = null;
207
+ var otelInitFingerprint = "";
208
+ var CHANNEL_COLORS = {
209
+ // Shared diagnostics
210
+ "global-client": "#d2a8ff",
211
+ // Section pins (desktop)
212
+ "every-channel-pin": "#9febd7",
213
+ "hero-pin": "#6ecc8b",
214
+ "pricing-pin": "#399587",
215
+ "product-screens-pin": "#4fafa0",
216
+ "social-proof-pin": "#ffbb8a",
217
+ "value-props-pin": "#e0a733",
218
+ "work-pin": "#f57e56",
219
+ // Section pins (mobile)
220
+ "mobile-every-channel-pin": "#7ed9c6",
221
+ "mobile-hero-pin": "#f0eee6",
222
+ "mobile-pricing-pin": "#80d4ff",
223
+ "mobile-product-screens-pin": "#3a9085",
224
+ "mobile-social-proof-pin": "#ffd580",
225
+ "mobile-value-props-pin": "#4fafa0"
226
+ };
227
+ function flattenAttributes(input, prefix = "") {
228
+ const output = {};
229
+ for (const [key, value] of Object.entries(input)) {
230
+ const nextKey = prefix ? `${prefix}.${key}` : key;
231
+ if (value === null || value === void 0) continue;
232
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
233
+ output[nextKey] = value;
234
+ continue;
235
+ }
236
+ if (Array.isArray(value)) {
237
+ output[nextKey] = JSON.stringify(value);
238
+ continue;
239
+ }
240
+ if (typeof value === "object") {
241
+ Object.assign(output, flattenAttributes(value, nextKey));
242
+ continue;
243
+ }
244
+ output[nextKey] = String(value);
245
+ }
246
+ return output;
247
+ }
248
+ function stripTrailingSlash(host) {
249
+ return host.replace(/\/+$/, "");
250
+ }
251
+ function initializePostHogLogging(options) {
252
+ var _a, _b, _c, _d, _e, _f;
253
+ if (typeof window === "undefined") return;
254
+ if (!((_a = options.apiKey) == null ? void 0 : _a.trim())) return;
255
+ const apiHost = stripTrailingSlash(((_b = options.apiHost) == null ? void 0 : _b.trim()) || "https://us.i.posthog.com");
256
+ const serviceName = ((_c = options.serviceName) == null ? void 0 : _c.trim()) || "keystone-customer-site";
257
+ const environment = ((_d = options.environment) == null ? void 0 : _d.trim()) || "production";
258
+ const fingerprint = `${apiHost}|${options.apiKey}|${serviceName}|${environment}|${(_e = options.accountId) != null ? _e : ""}|${(_f = options.accountName) != null ? _f : ""}`;
259
+ if (otelLogger && otelInitFingerprint === fingerprint) return;
260
+ if (otelProvider) {
261
+ void otelProvider.shutdown().catch(() => {
262
+ });
263
+ otelProvider = null;
264
+ otelLogger = null;
265
+ }
266
+ const baseAttributes = {
267
+ "service.name": serviceName,
268
+ environment,
269
+ site_domain: window.location.hostname
270
+ };
271
+ if (options.accountId !== void 0) baseAttributes.account_id = options.accountId;
272
+ if (options.accountName) baseAttributes.account_name = options.accountName;
273
+ const exporter = new OTLPLogExporter({
274
+ url: `${apiHost}/i/v1/logs?token=${encodeURIComponent(options.apiKey)}`,
275
+ headers: {
276
+ // Keep request "simple" to avoid CORS preflight in browser.
277
+ "Content-Type": "text/plain"
278
+ }
279
+ });
280
+ otelProvider = new LoggerProvider({
281
+ resource: resourceFromAttributes(baseAttributes),
282
+ processors: [new BatchLogRecordProcessor(exporter)]
283
+ });
284
+ logs.setGlobalLoggerProvider(otelProvider);
285
+ otelLogger = logs.getLogger(serviceName);
286
+ otelInitFingerprint = fingerprint;
287
+ }
288
+ function isConsoleEnabled() {
289
+ if (BUILD_CONSOLE_DISABLED) return false;
290
+ if (typeof window === "undefined") return true;
291
+ return window.__loggingDisabled !== true;
292
+ }
293
+ function isPostHogShippingEnabled() {
294
+ if (BUILD_POSTHOG_DISABLED) return false;
295
+ if (typeof window === "undefined") return false;
296
+ return window.__posthogLoggingDisabled !== true;
297
+ }
298
+ function formatDetail(detail) {
299
+ return Object.entries(detail).map(([k, v]) => `${k}=${typeof v === "number" ? v.toFixed(4) : String(v)}`).join(" ");
300
+ }
301
+ function emitConsole(level, channel, event, detail) {
302
+ var _a;
303
+ const color = (_a = CHANNEL_COLORS[channel]) != null ? _a : "#aaa";
304
+ const detailStr = formatDetail(detail);
305
+ const message = `%c[${channel}] %c${event}%c ${detailStr}`;
306
+ const channelStyle = `color:${color}; font-weight:bold`;
307
+ const eventStyle = level === "error" ? "color:#e94e4e; font-weight:bold" : level === "warn" ? "color:#f5a623; font-weight:bold" : "color:#fff; font-weight:bold";
308
+ const detailStyle = "color:#999; font-weight:normal";
309
+ if (level === "error") {
310
+ console.error(message, channelStyle, eventStyle, detailStyle);
311
+ return;
312
+ }
313
+ if (level === "warn") {
314
+ console.warn(message, channelStyle, eventStyle, detailStyle);
315
+ return;
316
+ }
317
+ console.log(message, channelStyle, eventStyle, detailStyle);
318
+ }
319
+ function emitToPostHog(level, channel, event, detail) {
320
+ if (!otelLogger) return;
321
+ const severityText = level === "warn" ? "WARNING" : level === "error" ? "ERROR" : "INFO";
322
+ const attributes = flattenAttributes(__spreadValues({ channel }, detail));
323
+ otelLogger.emit({
324
+ severityText,
325
+ body: event,
326
+ attributes
327
+ });
328
+ }
329
+ function emit(level, channel, event, detail, options) {
330
+ var _a;
331
+ const shouldShip = ((_a = options == null ? void 0 : options.shipToPostHog) != null ? _a : level !== "info") && isPostHogShippingEnabled();
332
+ if (level !== "info" || isConsoleEnabled()) {
333
+ emitConsole(level, channel, event, detail);
334
+ }
335
+ if (shouldShip) {
336
+ emitToPostHog(level, channel, event, detail);
337
+ }
338
+ }
339
+ function log(channel, event, detail = {}, options) {
340
+ emit("info", channel, event, detail, options);
341
+ }
342
+ function warn(channel, event, detail = {}, options) {
343
+ emit("warn", channel, event, detail, options);
344
+ }
345
+ function error(channel, event, detail = {}, options) {
346
+ emit("error", channel, event, detail, options);
347
+ }
348
+
349
+ // src/tracking/PostHogProvider.tsx
197
350
  var DEFAULT_HOST = "https://us.i.posthog.com";
198
351
  function resolvePageInfo(pathname) {
199
352
  var _a;
@@ -254,7 +407,42 @@ function PostHogProvider({ apiKey, apiHost, accountId, accountName, environment,
254
407
  posthog.register(__spreadProps(__spreadValues(__spreadValues(__spreadValues({}, accountId !== void 0 && { account_id: accountId }), accountName && { account_name: accountName }), environment && { environment }), {
255
408
  site_domain: window.location.hostname
256
409
  }));
410
+ initializePostHogLogging({
411
+ apiKey,
412
+ apiHost: apiHost != null ? apiHost : DEFAULT_HOST,
413
+ serviceName: "keystone-customer-site",
414
+ environment,
415
+ accountId,
416
+ accountName
417
+ });
257
418
  }, [apiKey, apiHost, accountId, accountName, environment]);
419
+ useEffect2(() => {
420
+ const onWindowError = (event) => {
421
+ error(
422
+ "global-client",
423
+ "WINDOW_ERROR",
424
+ {
425
+ message: event.message || "unknown_error",
426
+ filename: event.filename || "unknown_file",
427
+ lineno: event.lineno || 0,
428
+ colno: event.colno || 0,
429
+ stack: event.error instanceof Error ? event.error.stack || "" : ""
430
+ },
431
+ { shipToPostHog: true }
432
+ );
433
+ };
434
+ const onUnhandledRejection = (event) => {
435
+ const reason = event.reason;
436
+ const payload = reason instanceof Error ? { message: reason.message, stack: reason.stack || "" } : { message: String(reason), stack: "" };
437
+ error("global-client", "UNHANDLED_REJECTION", payload, { shipToPostHog: true });
438
+ };
439
+ window.addEventListener("error", onWindowError);
440
+ window.addEventListener("unhandledrejection", onUnhandledRejection);
441
+ return () => {
442
+ window.removeEventListener("error", onWindowError);
443
+ window.removeEventListener("unhandledrejection", onUnhandledRejection);
444
+ };
445
+ }, []);
258
446
  return /* @__PURE__ */ React.createElement(PHProvider, { client: posthog }, /* @__PURE__ */ React.createElement(Suspense, { fallback: null }, /* @__PURE__ */ React.createElement(PostHogPageviewTracker, null)), children);
259
447
  }
260
448
 
@@ -318,6 +506,7 @@ function GoogleTagManager({ containerId }) {
318
506
  )));
319
507
  }
320
508
  export {
509
+ CHANNEL_COLORS,
321
510
  GoogleTagManager,
322
511
  KeystoneAnalyticsTracker,
323
512
  MetaPixel,
@@ -325,7 +514,10 @@ export {
325
514
  PostHogProvider,
326
515
  captureCustomEvent,
327
516
  captureEvent,
517
+ error,
328
518
  firePixelEvent,
329
- setPixelUserData
519
+ log,
520
+ setPixelUserData,
521
+ warn
330
522
  };
331
523
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/tracking/MetaPixel.tsx","../../src/tracking/MetaPixelTracker.tsx","../../src/tracking/firePixelEvent.ts","../../src/tracking/PostHogProvider.tsx","../../src/tracking/KeystoneAnalyticsTracker.tsx","../../src/tracking/captureEvent.ts","../../src/tracking/GoogleTagManager.tsx"],"sourcesContent":["'use client';\n\nimport Script from 'next/script';\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 fbq('track', 'PageView');\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 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 { 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","type FbqFn = (method: string, ...args: unknown[]) => void;\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 console.debug('[MetaPixel] 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 console.debug('[MetaPixel]', event, normalized, eventId ? { eventID: eventId } : '');\n fbq('track', event, customData, eventData);\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';\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 }, [apiKey, apiHost, accountId, accountName, environment]);\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,OAAO,YAAY;AAEnB,IAAM,eAAe;AAErB,IAAM,eAAe,CAAC,YAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+DAOqB,YAAY;AAAA,iBAC1D,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAAA;AAAA;AAAA,uCAGN,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAAA,kCACjC,QA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;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","usePathname","usePathname","useEffect","useEffect","usePathname","posthog","usePathname","useEffect"]}
1
+ {"version":3,"sources":["../../src/tracking/MetaPixel.tsx","../../src/tracking/MetaPixelTracker.tsx","../../src/tracking/firePixelEvent.ts","../../src/tracking/PostHogProvider.tsx","../../src/tracking/logging.ts","../../src/tracking/KeystoneAnalyticsTracker.tsx","../../src/tracking/captureEvent.ts","../../src/tracking/GoogleTagManager.tsx"],"sourcesContent":["'use client';\n\nimport Script from 'next/script';\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 fbq('track', 'PageView');\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 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 { 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","type FbqFn = (method: string, ...args: unknown[]) => void;\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 console.debug('[MetaPixel] 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 console.debug('[MetaPixel]', event, normalized, eventId ? { eventID: eventId } : '');\n fbq('track', event, customData, eventData);\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 { 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 = '';\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 console.error(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n if (level === 'warn') {\n console.warn(message, channelStyle, eventStyle, detailStyle);\n return;\n }\n console.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","'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,OAAO,YAAY;AAEnB,IAAM,eAAe;AAErB,IAAM,eAAe,CAAC,YAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+DAOqB,YAAY;AAAA,iBAC1D,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAAA;AAAA;AAAA,uCAGN,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAAA,kCACjC,QAAQ,QAAQ,MAAM,KAAK,CAAC;AAAA;AAAA;AAcvD,SAAS,UAAU,EAAE,QAAQ,GAAmB;AACrD,QAAM,MAAM,OAAO,YAAY,WAAW,QAAQ,KAAK,IAAI;AAC3D,QAAM,KAAK,OAAO,QAAQ,UAAU,QAAQ,KAAK,GAAG,IAAI,MAAM;AAC9D,MAAI,CAAC,IAAI;AACP,WAAO;A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AAyB,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","usePathname","usePathname","useEffect","useEffect","usePathname","posthog","usePathname","useEffect"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keystone-design-bootstrap",
3
- "version": "1.0.95",
3
+ "version": "1.0.97",
4
4
  "description": "Keystone Design Bootstrap - Sections, Elements, and Theme System for customer websites",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -67,6 +67,10 @@
67
67
  "@fontsource/montserrat": "^5.2.8",
68
68
  "@fontsource/playfair-display": "^5.2.8",
69
69
  "@fontsource/poppins": "^5.2.7",
70
+ "@opentelemetry/api-logs": "^0.219.0",
71
+ "@opentelemetry/exporter-logs-otlp-http": "^0.219.0",
72
+ "@opentelemetry/resources": "^2.8.0",
73
+ "@opentelemetry/sdk-logs": "^0.219.0",
70
74
  "@rails/actioncable": "^8.1.300",
71
75
  "@untitledui/file-icons": "^0.0.9",
72
76
  "@untitledui/icons": "^0.0.20",
@@ -4,6 +4,7 @@ import posthog from 'posthog-js';
4
4
  import { PostHogProvider as PHProvider } from 'posthog-js/react';
5
5
  import { useEffect, Suspense } from 'react';
6
6
  import { usePathname, useSearchParams } from 'next/navigation';
7
+ import { error as logError, initializePostHogLogging } from './logging';
7
8
 
8
9
  const DEFAULT_HOST = 'https://us.i.posthog.com';
9
10
 
@@ -123,8 +124,51 @@ export function PostHogProvider({ apiKey, apiHost, accountId, accountName, envir
123
124
  ...(environment && { environment }),
124
125
  site_domain: window.location.hostname,
125
126
  });
127
+
128
+ initializePostHogLogging({
129
+ apiKey,
130
+ apiHost: apiHost ?? DEFAULT_HOST,
131
+ serviceName: 'keystone-customer-site',
132
+ environment,
133
+ accountId,
134
+ accountName,
135
+ });
126
136
  }, [apiKey, apiHost, accountId, accountName, environment]);
127
137
 
138
+ useEffect(() => {
139
+ const onWindowError = (event: ErrorEvent) => {
140
+ logError(
141
+ 'global-client',
142
+ 'WINDOW_ERROR',
143
+ {
144
+ message: event.message || 'unknown_error',
145
+ filename: event.filename || 'unknown_file',
146
+ lineno: event.lineno || 0,
147
+ colno: event.colno || 0,
148
+ stack: event.error instanceof Error ? event.error.stack || '' : '',
149
+ },
150
+ { shipToPostHog: true },
151
+ );
152
+ };
153
+
154
+ const onUnhandledRejection = (event: PromiseRejectionEvent) => {
155
+ const reason = event.reason;
156
+ const payload =
157
+ reason instanceof Error
158
+ ? { message: reason.message, stack: reason.stack || '' }
159
+ : { message: String(reason), stack: '' };
160
+
161
+ logError('global-client', 'UNHANDLED_REJECTION', payload, { shipToPostHog: true });
162
+ };
163
+
164
+ window.addEventListener('error', onWindowError);
165
+ window.addEventListener('unhandledrejection', onUnhandledRejection);
166
+ return () => {
167
+ window.removeEventListener('error', onWindowError);
168
+ window.removeEventListener('unhandledrejection', onUnhandledRejection);
169
+ };
170
+ }, []);
171
+
128
172
  return (
129
173
  <PHProvider client={posthog}>
130
174
  <Suspense fallback={null}>
@@ -30,3 +30,5 @@ export { GoogleTagManager } from './GoogleTagManager';
30
30
  export type { GoogleTagManagerProps } from './GoogleTagManager';
31
31
  export { captureEvent, captureCustomEvent } from './captureEvent';
32
32
  export type { KsEventName, KsEventProperties } from './captureEvent';
33
+ export { log, warn, error, CHANNEL_COLORS } from './logging';
34
+ export type { LogLevel, LogOptions } from './logging';
@@ -0,0 +1,214 @@
1
+ 'use client';
2
+
3
+ import { logs } from '@opentelemetry/api-logs';
4
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
5
+ import { resourceFromAttributes } from '@opentelemetry/resources';
6
+ import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs';
7
+
8
+ const BUILD_CONSOLE_DISABLED = process.env.NEXT_PUBLIC_LOGGING_DISABLED === '1';
9
+ const BUILD_POSTHOG_DISABLED = process.env.NEXT_PUBLIC_POSTHOG_LOGGING_DISABLED === '1';
10
+ interface LoggingWindow extends Window {
11
+ __loggingDisabled?: boolean;
12
+ __posthogLoggingDisabled?: boolean;
13
+ }
14
+
15
+ export type LogLevel = 'info' | 'warn' | 'error';
16
+
17
+ export type LogOptions = {
18
+ /** Send this log payload to PostHog Logs product. */
19
+ shipToPostHog?: boolean;
20
+ };
21
+
22
+ type OTelInitOptions = {
23
+ apiKey: string;
24
+ apiHost?: string;
25
+ serviceName?: string;
26
+ environment?: string;
27
+ accountId?: number;
28
+ accountName?: string;
29
+ };
30
+ let otelProvider: LoggerProvider | null = null;
31
+ let otelLogger: ReturnType<typeof logs.getLogger> | null = null;
32
+ let otelInitFingerprint = '';
33
+
34
+ /**
35
+ * Channel → accent colour. Unregistered channels fall through to gray.
36
+ */
37
+ export const CHANNEL_COLORS: Record<string, string> = {
38
+ // Shared diagnostics
39
+ 'global-client': '#d2a8ff',
40
+
41
+ // Section pins (desktop)
42
+ 'every-channel-pin': '#9febd7',
43
+ 'hero-pin': '#6ecc8b',
44
+ 'pricing-pin': '#399587',
45
+ 'product-screens-pin': '#4fafa0',
46
+ 'social-proof-pin': '#ffbb8a',
47
+ 'value-props-pin': '#e0a733',
48
+ 'work-pin': '#f57e56',
49
+
50
+ // Section pins (mobile)
51
+ 'mobile-every-channel-pin': '#7ed9c6',
52
+ 'mobile-hero-pin': '#f0eee6',
53
+ 'mobile-pricing-pin': '#80d4ff',
54
+ 'mobile-product-screens-pin': '#3a9085',
55
+ 'mobile-social-proof-pin': '#ffd580',
56
+ 'mobile-value-props-pin': '#4fafa0',
57
+ };
58
+
59
+ function flattenAttributes(input: Record<string, unknown>, prefix = ''): Record<string, string | number | boolean> {
60
+ const output: Record<string, string | number | boolean> = {};
61
+
62
+ for (const [key, value] of Object.entries(input)) {
63
+ const nextKey = prefix ? `${prefix}.${key}` : key;
64
+ if (value === null || value === undefined) continue;
65
+
66
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
67
+ output[nextKey] = value;
68
+ continue;
69
+ }
70
+
71
+ if (Array.isArray(value)) {
72
+ output[nextKey] = JSON.stringify(value);
73
+ continue;
74
+ }
75
+
76
+ if (typeof value === 'object') {
77
+ Object.assign(output, flattenAttributes(value as Record<string, unknown>, nextKey));
78
+ continue;
79
+ }
80
+
81
+ output[nextKey] = String(value);
82
+ }
83
+
84
+ return output;
85
+ }
86
+
87
+ function stripTrailingSlash(host: string): string {
88
+ return host.replace(/\/+$/, '');
89
+ }
90
+
91
+ export function initializePostHogLogging(options: OTelInitOptions): void {
92
+ if (typeof window === 'undefined') return;
93
+ if (!options.apiKey?.trim()) return;
94
+
95
+ const apiHost = stripTrailingSlash(options.apiHost?.trim() || 'https://us.i.posthog.com');
96
+ const serviceName = options.serviceName?.trim() || 'keystone-customer-site';
97
+ const environment = options.environment?.trim() || 'production';
98
+ const fingerprint = `${apiHost}|${options.apiKey}|${serviceName}|${environment}|${options.accountId ?? ''}|${options.accountName ?? ''}`;
99
+ if (otelLogger && otelInitFingerprint === fingerprint) return;
100
+
101
+ if (otelProvider) {
102
+ // Cleanly replace logger provider when config changes.
103
+ void otelProvider.shutdown().catch(() => {});
104
+ otelProvider = null;
105
+ otelLogger = null;
106
+ }
107
+
108
+ const baseAttributes: Record<string, string | number | boolean> = {
109
+ 'service.name': serviceName,
110
+ environment,
111
+ site_domain: window.location.hostname,
112
+ };
113
+ if (options.accountId !== undefined) baseAttributes.account_id = options.accountId;
114
+ if (options.accountName) baseAttributes.account_name = options.accountName;
115
+
116
+ const exporter = new OTLPLogExporter({
117
+ url: `${apiHost}/i/v1/logs?token=${encodeURIComponent(options.apiKey)}`,
118
+ headers: {
119
+ // Keep request "simple" to avoid CORS preflight in browser.
120
+ 'Content-Type': 'text/plain',
121
+ },
122
+ });
123
+
124
+ otelProvider = new LoggerProvider({
125
+ resource: resourceFromAttributes(baseAttributes),
126
+ processors: [new BatchLogRecordProcessor(exporter)],
127
+ });
128
+
129
+ logs.setGlobalLoggerProvider(otelProvider);
130
+ otelLogger = logs.getLogger(serviceName);
131
+ otelInitFingerprint = fingerprint;
132
+ }
133
+
134
+ function isConsoleEnabled(): boolean {
135
+ if (BUILD_CONSOLE_DISABLED) return false;
136
+ if (typeof window === 'undefined') return true;
137
+ return (window as LoggingWindow).__loggingDisabled !== true;
138
+ }
139
+
140
+ function isPostHogShippingEnabled(): boolean {
141
+ if (BUILD_POSTHOG_DISABLED) return false;
142
+ if (typeof window === 'undefined') return false;
143
+ return (window as LoggingWindow).__posthogLoggingDisabled !== true;
144
+ }
145
+
146
+ function formatDetail(detail: Record<string, unknown>): string {
147
+ return Object.entries(detail)
148
+ .map(([k, v]) => `${k}=${typeof v === 'number' ? v.toFixed(4) : String(v)}`)
149
+ .join(' ');
150
+ }
151
+
152
+ function emitConsole(
153
+ level: LogLevel,
154
+ channel: string,
155
+ event: string,
156
+ detail: Record<string, unknown>,
157
+ ): void {
158
+ const color = CHANNEL_COLORS[channel] ?? '#aaa';
159
+ const detailStr = formatDetail(detail);
160
+ const message = `%c[${channel}] %c${event}%c ${detailStr}`;
161
+ const channelStyle = `color:${color}; font-weight:bold`;
162
+ const eventStyle = level === 'error'
163
+ ? 'color:#e94e4e; font-weight:bold'
164
+ : level === 'warn'
165
+ ? 'color:#f5a623; font-weight:bold'
166
+ : 'color:#fff; font-weight:bold';
167
+ const detailStyle = 'color:#999; font-weight:normal';
168
+
169
+ if (level === 'error') {
170
+ console.error(message, channelStyle, eventStyle, detailStyle);
171
+ return;
172
+ }
173
+ if (level === 'warn') {
174
+ console.warn(message, channelStyle, eventStyle, detailStyle);
175
+ return;
176
+ }
177
+ console.log(message, channelStyle, eventStyle, detailStyle);
178
+ }
179
+
180
+ function emitToPostHog(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>): void {
181
+ if (!otelLogger) return;
182
+
183
+ const severityText = level === 'warn' ? 'WARNING' : level === 'error' ? 'ERROR' : 'INFO';
184
+ const attributes = flattenAttributes({ channel, ...detail });
185
+
186
+ otelLogger.emit({
187
+ severityText,
188
+ body: event,
189
+ attributes,
190
+ });
191
+ }
192
+
193
+ function emit(level: LogLevel, channel: string, event: string, detail: Record<string, unknown>, options?: LogOptions): void {
194
+ const shouldShip = (options?.shipToPostHog ?? level !== 'info') && isPostHogShippingEnabled();
195
+ // Keep warn/error visible even when regular logs are muted.
196
+ if (level !== 'info' || isConsoleEnabled()) {
197
+ emitConsole(level, channel, event, detail);
198
+ }
199
+ if (shouldShip) {
200
+ emitToPostHog(level, channel, event, detail);
201
+ }
202
+ }
203
+
204
+ export function log(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {
205
+ emit('info', channel, event, detail, options);
206
+ }
207
+
208
+ export function warn(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {
209
+ emit('warn', channel, event, detail, options);
210
+ }
211
+
212
+ export function error(channel: string, event: string, detail: Record<string, unknown> = {}, options?: LogOptions): void {
213
+ emit('error', channel, event, detail, options);
214
+ }